Simple Calculator Using Switch Statement

Introduction
  • In this blog, I am going to explain how to do simple calculations by using a calculator. 
Software Requirements
  • Turbo C++ or C. 
Programming
  1. #include < stdio.h >   
  2. int main()  
  3. {  
  4.     char operator;  
  5.     double firstNumber, secondNumber;  
  6.     printf("Enter an operator (+, -, *,): ");  
  7.     scanf("%c", & operator);  
  8.     printf("Enter two operands: ");  
  9.     scanf("%lf %lf", & firstNumber, & secondNumber);  
  10.     switch (operator)  
  11.     {  
  12.         case '+':  
  13.             printf("%.1lf + %.1lf = %.1lf", firstNumber, secondNumber, firstNumber + secondNumber);  
  14.             break;  
  15.         case '-':  
  16.             printf("%.1lf - %.1lf = %.1lf", firstNumber, secondNumber, firstNumber - secondNumber);  
  17.             break;  
  18.         case '*':  
  19.             printf("%.1lf * %.1lf = %.1lf", firstNumber, secondNumber, firstNumber * secondNumber);  
  20.             break;  
  21.         case '/':  
  22.             printf("%.1lf / %.1lf = %.1lf", firstNumber, secondNumber, firstNumber / firstNumber);  
  23.             break;  
  24.         default:  
  25.             printf("Error! operator is not correct");  
  26.     }  
  27.     return 0;  
  28. }  
Explanation
  • By the programming given above, the calculations of addition, subtraction, multiplication and division can be done and explained in a simple manner.

     programming

    programming
Output

Output
 
Conclusion: Thus the simple calculator can get created successfully.
Ebook Download
View all
Learn
View all