In this C programming tutorial, we are going to learn how to create a simple calculator to perform simple arithmetic calculations like +, - x, and / between two operands given by the user. Here we are going to use the switch statement to create our basic calculator.
Calculator using Switch statement in C program.
//C calculator using switch statement #include <stdio.h> int main() { char operator; double num1, num2, result; // Input the operator and two numbers printf("Enter an operator (+, -, *, /): "); scanf("%c", &operator); printf("Enter two numbers: "); scanf("%lf %lf", &num1, &num2); // Perform the calculation based on the operator switch (operator) { case '+': result = num1 + num2; printf("Result: %lf\n", result); break; case '-': result = num1 - num2; printf("Result: %lf\n", result); break; case '*': result = num1 * num2; printf("Result: %lf\n", result); break; case '/': result = num1 / num2; printf("Result: %lf\n", result); break; default: printf("Error: Invalid operator.\n"); } return 0; }
Enter an operator (+, -, *, /): +
Enter two numbers: 23 12
Result: 35.000000
Output:
Enter an operator (+, -, *, /): %
Enter two numbers: 23 43
ERROR!
Error: Invalid operator.
Explanation:
In this program, the user is prompted to enter an operator (+, -, *, /) and two numbers. Then, using the switch statement, the program performs the corresponding calculation based on the operator.
No comments:
Post a Comment