C Program if else : "Calculator Example Using Else if" with output
int main() {
char operator;
double num1, num2, result;
printf("Enter an operator (+, -, *, /): ");
scanf(" %c", &operator);
printf("Enter two numbers: ");
scanf("%lf %lf", &num1, &num2);
if (operator == '+') {
result = num1 + num2;
} else if (operator == '-') {
result = num1 - num2;
} else if (operator == '*') {
result = num1 * num2;
} else if (operator == '/') {
if (num2 != 0) {
result = num1 / num2;
} else {
printf("Division by zero is not allowed.\n");
return 1; // Exit the program with an error code
}
} else {
printf("Invalid operator! Please use +, -, *, or /.\n");
return 1; // Exit the program with an error code
}
printf("Result: %lf %c %lf = %lf\n", num1, operator, num2, result);
return 0; // Exit the program with a success code
}
Enter an operator (+, -, *, /): * Enter two numbers: 5 3 Result: 5.000000 * 3.000000 = 15.000000
Comments
Post a Comment