1. Write a program that acts as a simple calculator. It should take two numbers and an operator (+, -, *, /) as input and perform the corresponding operation.
#include <stdio.h>
int main() {
// Declare variables
float num1, num2, result;
char operator;// Input: Get two numbers and an operator from the user
printf(“Enter the first number: “);
scanf(“%f”, &num1);printf(“Enter an operator (+, -, *, /): “);
scanf(” %c”, &operator); // Note the space before %c to consume any previous newline characterprintf(“Enter the second number: “);
scanf(“%f”, &num2);// Process: Perform the corresponding operation
switch (operator) {
case ‘+’:
result = num1 + num2;
break;
case ‘-‘:
result = num1 – num2;
break;
case ‘*’:
result = num1 * num2;
break;
case ‘/’:
if (num2 != 0) {
result = num1 / num2;
} else {
printf(“Error: Division by zero is undefined.n”);
return 1; // Exit the program with an error code
}
break;
default:
printf(“Error: Invalid operator entered.n”);
return 1; // Exit the program with an error code
}// Output: Display the result
printf(“Result: %.2f %c %.2f = %.2fn”, num1, operator, num2, result);return 0; // Exit the program successfully
}