Computer >> Computer tutorials >  >> Programming >> C programming

How to write a simple calculator program using C language?


Begin by writing the C code to create a simple calculator. Then, follow the algorithm given below to write a C program.

Algorithm

Step 1: Declare variables
Step 2: Enter any operator at runtime
Step 3: Enter any two integer values at runtime
Step 4: Apply switch case to select the operator:
        // case '+': result = num1 + num2;
               break;
           case '-': result = num1 - num2;
               break;
           case '*': result = num1 * num2;
               break;
           case '/': result = num1 / num2;
               break;
           default: printf("\n Invalid Operator ");
Step 5: Print the result

Example

Following is the C program for calculator by using the Switch Case −

#include <stdio.h>
int main(){
   char Operator;
   float num1, num2, result = 0;
   printf("\n Enter any one operator like +, -, *, / : ");
   scanf("%c", &Operator);
   printf("Enter the values of Operands num1 and num2 \n : ");
   scanf("%f%f", &num1, &num2);
   switch(Operator){
      case '+': result = num1 + num2;
         break;
      case '-': result = num1 - num2;
         break;
      case '*': result = num1 * num2;
         break;
      case '/': result = num1 / num2;
         break;
      default: printf("\n Invalid Operator ");
   }
   printf("The value = %f", result);
   return 0;
}

Output

When the above program is executed, it produces the following result −

Enter any one operator: +
Enter values of Operands num1 and num2:
23
45
The value = 68.000000