Calculator Program in C

Learn via video course
FREE
View all courses
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
1000
5
Start Learning
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
1000
5
Start Learning
Topics Covered

You might already know what a calculator is. It is a device that performs arithmetic operations such as +, -, *, /. It makes the calculations faster and our lives easier. Have you ever wondered if we can write a calculator program in C?

Algorithm of Calculator Program

  1. Declare 4 variables - num1, num2, result, opt. The variables num1 and num2 are for storing the values or operands, for storing the calculation result, and opt to take the operator as inputs.
  2. Take inputs of the operands, operator.
  3. Use switch case or conditional statements to check the operator.
  4. Display the result according to the operator.
  5. Exit the program

Calculator Program in C Using the Switch Statement

Here is a program that uses a switch statement to write a Calculator program in C:

Output

Explanation

  • Declare the variables opt, num1, num2, and result to store the required values.
  • Take the operator and the values of two operands.
  • Use a switch case to check which operator is given as input.
  • If the following operators: +, -, *, / were found, print the result and come out of the switch case; otherwise, print the default statement.

Calculator Program in C Using if else if Statement

Here is a program using if else if statement to write a Calculator program in C:

Output

Explanation

  • We declare the variables as opt, num1, num2, and result to store the required values.
  • We then take the operator as input from the user and two other inputs for operating.
  • Next, we use the if else if statement to check which operator is given as input and display accordingly.

Conclusion

  • We can perform Calculator Program in C using:

    • switch statement
    • if-else if statement
  • While performing the division operation, make sure you check the divisor is not equal to zero.

See More