This program builds a simple calculator that performs addition, subtraction, multiplication, and division based on the user’s menu choice, using a switch statement.
C Program
#include <stdio.h>
int main() {
int choice;
float num1, num2, result;
printf("Enter two numbers: ");
scanf("%f %f", &num1, &num2);
printf("Choose an operation:\n");
printf("1. Addition\n2. Subtraction\n3. Multiplication\n4. Division\n");
printf("Enter your choice (1-4): ");
scanf("%d", &choice);
switch (choice) {
case 1:
result = num1 + num2;
printf("Result: %.2f\n", result);
break;
case 2:
result = num1 - num2;
printf("Result: %.2f\n", result);
break;
case 3:
result = num1 * num2;
printf("Result: %.2f\n", result);
break;
case 4:
if (num2 != 0) {
result = num1 / num2;
printf("Result: %.2f\n", result);
} else {
printf("Error: Division by zero is not allowed.\n");
}
break;
default:
printf("Invalid choice.\n");
}
return 0;
}
Explanation
- The user enters two numbers and picks an operation number from a menu.
- The
switchstatement matcheschoiceagainst eachcaseand executes only the matching block. breakafter each case prevents “fall-through” into the next case.- Division includes a check for
num2 != 0to avoid division by zero. - The
defaultcase handles any input outside 1–4.
Sample Output
Enter two numbers: 10 5
Choose an operation:
1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter your choice (1-4): 3
Result: 50.00