include
int main() {
char operation;
float num1, num2, result;
// User input
printf("Enter first number: ");
scanf("%f", &num1);
printf("Enter second number: ");
scanf("%f", &num2);
printf("Enter operation (+, -, *, /): ");
scanf(" %c", &operation); // Notice the space before %c to consume any whitespace
// Switch-case for operations
switch (operation) {
case '+':
result = num1 + num2;
printf("Result: %.2f + %.2f = %.2f\n", num1, num2, result);
break;
case '-':
result = num1 - num2;
printf("Result: %.2f - %.2f = %.2f\n", num1, num2, result);
break;
case '*':
result = num1 * num2;
printf("Result: %.2f * %.2f = %.2f\n", num1, num2, result);
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
printf("Result: %.2f / %.2f = %.2f\n", num1, num2, result);
} else {
printf("Error: Division by zero!\n");
}
break;
default:
printf("Error: Invalid operation!\n");
break;
}
return 0;
}
Explanation :
- Input Section:
- The program prompts the user to enter two numbers and the desired operation.
- Switch-Case Structure:
- The
switchstatement checks the operation input by the user. - Each case corresponds to an arithmetic operation:
- Addition: For
+, it adds the two numbers. - Subtraction: For
-, it subtracts the second number from the first. - Multiplication: For
*, it multiplies the two numbers. - Division: For
/, it checks for division by zero before performing the operation.
- Addition: For
- The
- Output:
- The result is printed in a formatted manner using
printf.
- The result is printed in a formatted manner using
Examples :
- Example 1:
- Input:
num1 = 10,num2 = 5,operation = '+' - Output:
Result: 10.00 + 5.00 = 15.00
- Input:
- Example 2:
- Input:
num1 = 10,num2 = 5,operation = '-' - Output:
Result: 10.00 - 5.00 = 5.00
- Input: