int main() {
char operator;
double num1, num2, result;
// Prompt the user for input
printf("Enter first number: ");
scanf("%lf", &num1);
printf("Enter an operator (+, -, *, /): ");
scanf(" %c", &operator); // Notice the space before %c to consume any newline character
printf("Enter second number: ");
scanf("%lf", &num2);
// Perform calculation based on operator
switch (operator) {
case '+':
result = num1 + num2;
printf("%.2lf + %.2lf = %.2lf\n", num1, num2, result);
break;
case '-':
result = num1 - num2;
printf("%.2lf - %.2lf = %.2lf\n", num1, num2, result);
break;
case '*':
result = num1 * num2;
printf("%.2lf * %.2lf = %.2lf\n", num1, num2, result);
break;
case '/':
// Check for division by zero
if (num2 != 0) {
result = num1 / num2;
printf("%.2lf / %.2lf = %.2lf\n", num1, num2, result);
} else {
printf("Error: Division by zero is not allowed.\n");
}
break;
default:
printf("Error: Invalid operator.\n");
break;
}
return 0;
}
Explanation:-
Headers and Main Function: The code begins by including the standard input-output library (<stdio.h>) and defining the main function.
Variables Declaration: Four variables are declared:
operator: to store the arithmetic operator entered by the user.num1andnum2: to store the two numbers on which the operation will be performed.result: to store the result of the operation.
User Input:
- The program prompts the user to enter the first number, the operator, and the second number. The
scanffunction is used to read these inputs.
Switch Case Statement: This statement evaluates the operator variable:
- For each case (
+,-,*,/), it performs the corresponding arithmetic operation and prints the result. - If the operator is
/, it checks if the second number is zero to prevent division by zero. If it is zero, an error message is displayed.
Default Case: If the user enters an invalid operator, the program outputs an error message.
Example:
Suppose a user runs the program and enters the following:
Enter first number: 10
Enter an operator (+, -, *, /): +
Enter second number: 5
10.00 + 5.00 = 15.00