Write a program in c++ to perform a mini calculator using switch state...
**Mini Calculator using Switch Statement in C**
Switch statements are used to select one of the several blocks of code to be executed. In this program, we are going to perform a mini calculator using switch statement in C.
**Steps to Perform Mini Calculator using Switch Statement in C**
1. First, we need to declare the variables to store the values of two operands and the operator.
2. Then, we need to display a menu of options for the user to select the operation they want to perform.
3. We can use scanf() function to take the input from the user for the operands and the operator.
4. Now, we can use switch statement to execute the required operation based on the selected option.
5. We can use printf() function to display the result of the operation.
**Code Implementation**
Here is the code for performing a mini calculator using switch statement in C.
```
#include
int main()
{
float num1, num2, result;
char operator;
printf("Enter two operands: ");
scanf("%f %f", &num1, &num2);
printf("Enter an operator (+, -, *, /): ");
scanf(" %c", &operator);
switch (operator)
{
case '+':
result = num1 + num2;
printf("%.2f + %.2f = %.2f", num1, num2, result);
break;
case '-':
result = num1 - num2;
printf("%.2f - %.2f = %.2f", num1, num2, result);
break;
case '*':
result = num1 * num2;
printf("%.2f * %.2f = %.2f", num1, num2, result);
break;
case '/':
result = num1 / num2;
printf("%.2f / %.2f = %.2f", num1, num2, result);
break;
default:
printf("Invalid operator");
break;
}
return 0;
}
```
**Explanation of Code**
- In the first line of the code, we have included the header file stdio.h which contains the standard input/output functions.
- Then, we have declared the variables num1, num2, result, and operator of type float and char respectively.
- We have used printf() function to display the message to the user to enter the two operands.
- We have used scanf() function to take the input from the user for the two operands.
- Then, we have used printf() function to display the message to the user to enter the operator.
- We have used scanf() function to take the input from the user for the operator.
- We have used switch statement to execute the required operation based on the selected operator.
- We have used printf() function to display the result of the operation.
- In the end, we have returned 0 to the operating system to indicate that the program has executed successfully.