Exercise:
Write a C Program to make a simple calculator using switch statement.
Click Here to View the Solution!
#include <stdio.h>
int main() {
char operator;
double first, second;
printf("Select Operator (+, -, *,): ");
scanf("%c", &operator);
printf("Enter two operands: ");
scanf("%lf %lf", &first, &second);
switch (operator) {
case '+':
printf("%.1lf + %.1lf = %.1lf", first, second, first + second);
break;
case '-':
printf("%.1lf - %.1lf = %.1lf", first, second, first - second);
break;
case '*':
printf("%.1lf * %.1lf = %.1lf", first, second, first * second);
break;
case '/':
printf("%.1lf / %.1lf = %.1lf", first, second, first / second);
break;
// operator doesn't match any case constant
default:
printf("Error! operator is not correct");
}
return 0;
}
Click Here to View the Output!
Select Operator (+, -, *,): +
Enter two operands: 5 8
5.0 + 8.0 = 13.0
Click Here to View the Explanation!
- This program is used to from a simple calculator by using the
switch…case statement
. - The program requests the user to enter a character from a given options of operators (+, -, *, /) and stored it in the character variable
operator
. And two values for the operands which are stored in the variablesfirst
andsecond
using thescanf() function
. - A
switch operator
is initialized taking operator as its parameter. - The cases are set each with an operator. When a user enters an operator, the program matches it with all the cases until the corresponding case is found and shifts the control to that case.
- The respective case executes its statement, calculates the corresponding operation upon the operands and prints the output.
- Finally, the
break statement
will end theswitch statement
. - If the user enters any character besides the operators, an error message will be displayed.