Loading your workspace…
Loading your workspace…
Read two numbers and an operator (+, -, *, /) and print the result, handling division by zero and unknown operators.
#include <stdio.h>
int main(void) {
double left, right, result;
char op;
printf("Enter expression (number operator number):\n");
if (scanf("%lf %c %lf", &left, &op, &right) != 3) {
printf("Error: invalid input\n");
return 1;
}
switch (op) {
case '+':
result = left + right;
break;
case '-':
result = left - right;
break;
case '*':
result = left * right;
break;
case '/':
if (right == 0) {
printf("Error: division by zero\n");
return 1;
}
result = left / right;
break;
default:
printf("Error: unknown operator %c\n", op);
return 1;
}
printf("Result: %.2f\n", result);
return 0;
}
Input
7 / 2Output
Enter expression (number operator number):
Result: 3.50Input
9 / 0Output
Enter expression (number operator number):
Error: division by zeroThe format string "%lf %c %lf" reads a decimal number, one operator character and another decimal number. Each space in the format skips zero or more whitespace characters, so the input can be written as 7 / 2 or 7/2 and both parse the same way.
The division case is the one that needs a guard. Dividing a double by zero does not stop the program in C; it produces infinity, which is almost never what a calculator should show. Checking the divisor first lets the program report the problem clearly.
Edit the program and press Run. It is free and needs no sign-in.
Copy a sample and paste it into the STDIN box in the editor before you press Run.
7 / 2
Expected output
Enter expression (number operator number): Result: 3.50
9 / 0
Expected output
Enter expression (number operator number): Error: division by zero
A double keeps fractional parts, so 7 / 2 gives 3.5 instead of the truncated integer 3.
scanf returns the number of items it converted. Checking for 3 detects missing or malformed input before the program uses uninitialised variables.
return leaves main immediately, so no break is needed; the switch never falls through to the printf below.
The result is infinity or NaN according to IEEE 754. Integer division by zero, by contrast, is undefined behaviour and may crash.
It handles any value that no case matches, here an unsupported operator such as %.
Back to all VTU BPOPS103 lab programs.