C Program to Make a Simple Calculator Using switch case
C Programming Language / Decision Making of C Language
1420Program:
// Performs addition, subtraction, multiplication or division depending the input from user # include int main() { char operator; double firstNumber,secondNumber; printf("Enter an operator (+, -, *,): "); scanf("%c", &operator); printf("Enter two operands: "); scanf("%lf %lf",&firstNumber, &secondNumber); switch(operator) { case '+': printf("%.1lf + %.1lf = %.1lf",firstNumber, secondNumber, firstNumber + secondNumber); break; case '-': printf("%.1lf - %.1lf = %.1lf",firstNumber, secondNumber, firstNumber - secondNumber); break; case '*': printf("%.1lf * %.1lf = %.1lf",firstNumber, secondNumber, firstNumber * secondNumber); break; case '/': printf("%.1lf / %.1lf = %.1lf",firstNumber, secondNumber, firstNumber / secondNumber); break; // operator doesn't match any case constant (+, -, *, /) default: printf("Error! operator is not correct"); } return 0; }
Output:
Enter an operator (+, -, *,): * Enter two operands: 1.5 4.5 1.5 * 4.5 = 6.8
Explanation:
The *
operator entered by the user is stored in the operator variable. And, the two operands, 1.5 and 4.5 are stored in variables firstNumber and secondNumber respectively.
Since, the operator *
matches the case case '*':
, the control of the program jumps to
printf("%.1lf * %.1lf = %.1lf",firstNumber, secondNumber, firstNumber * secondNumber);
This statement calculates the product and displays it on the screen.
Finally, the break
; statement ends the switch statement.
This Particular section is dedicated to Programs only. If you want learn more about C Programming Language. Then you can visit below links to get more depth on this subject.
# C Tutorials
# JAVA Tutorials
# HTML Tutorials
# Computer Fundamental
# Data Structure
# DBMS Tutorials
SQL
# C# Language
# R Language
# PHP
# Python
# Vue JS