Task: Show a menu for +, −, ×, ÷; read two operands and the user’s choice. Perform the operation with a switch and guard division by zero.
/*
Program: Menu-driven Calculator using switch (U2)
What it does:
- Reads two operands (double) and an operator choice (+, -, *, /).
- Uses switch to perform the chosen operation; guards division by zero.
*/
#include <stdio.h>
int main(void) {
double a, b, result;
char op;
printf("Enter two numbers (a b): ");
if (scanf("%lf %lf", &a, &b) != 2) {
printf("Invalid numbers.
");
return 0;
}
printf("Choose operation (+ - * /): ");
scanf(" %c", &op);
switch (op) {
case '+': result = a + b; printf("Result = %.6f
", result); break;
case '-': result = a - b; printf("Result = %.6f
", result); break;
case '*': result = a * b; printf("Result = %.6f
", result); break;
case '/':
if (b == 0.0) {
printf("Error: Division by zero.
");
} else {
result = a / b; printf("Result = %.6f
", result);
}
break;
default:
printf("Unknown operation. Use + - * /.
");
}
return 0;
}