A calculator using switch case in c perform basic arithmetic operations like addition, subtraction, multiplication, and division. In C programming, we can efficiently implement a simple calculator using the switch-case statement. This approach allows for a structured and organized way of handling multiple operations based on user input.
Why Use Switch Case?
The switch statement is useful when we have multiple conditions to check and execute different blocks of code accordingly. Instead of using multiple if-else statements, switch-case enhances readability and performance in scenarios like a calculator.
Implementation Steps
Take two numbers as input from the user.
Ask the user to select an operation (+, -, *, /).
Use a switch-case to perform the selected operation.
Display the result.
Code Example
c
Copy
Edit
#include <stdio.h>
int main() {
char operator;
double num1, num2, result;
// Taking input from the user
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &operator);
printf("Enter two numbers: ");
scanf("%lf %lf", &num1, &num2);
// Using switch case to perform operations
switch(operator) {
case '+':
result = num1 + num2;
printf("Result: %.2lf\n", result);
break;
case '-':
result = num1 - num2;
printf("Result: %.2lf\n", result);
break;
case '*':
result = num1 * num2;
printf("Result: %.2lf\n", result);
break;
case '/':
if (num2 != 0)
printf("Result: %.2lf\n", num1 / num2);
else
printf("Error! Division by zero is not allowed.\n");
break;
default:
printf("Invalid operator!\n");
}
return 0;
}
Explanation of Code
The user is prompted to enter an arithmetic operator.
Two numbers are taken as input.
The switch-case structure evaluates the operator and performs the respective operation.
If the user enters an invalid operator, a default case handles the error.
Division is checked to prevent division by zero errors.
Output Example
vbnet
Copy
Edit
Enter an operator (+, -, *, /): +
Enter two numbers: 10 5
Result: 15.00
Enhancements & Further Improvements
Implement a loop to allow multiple calculations.
Use functions to modularize the code.
Extend the program to support more operations like modulus (%).