C Program to Take Operator as Input
The below example demonstrates the use of scanf function to take an operator as input in C.
#include <stdio.h>
int main()
{
char operator;
double num1, num2, result;
// Prompt the user to enter an operator
printf("Enter an operator (+, -, *, /): ");
scanf(" %c", &operator);
// Prompt the user to enter two operands
printf("Enter two numbers: ");
scanf("%lf %lf", &num1, &num2);
// Perform the operation based on the operator input
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 '/':
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;
}
Output
Enter an operator (+, -, *, /): +
Enter two numbers: 10
20
10.00 + 20.00 = 30.00
We can define more operators in the switch statement and even include the check for binary, unary and ternary operator and then ask the operands accordingly.
Time Complexity: O(1)
Auxiliary Space: O(1)
How to Take Operator as Input in C?
In C, an operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. We may need to take operator as an input in some cases. In this article, we will learn how to take an operator as input in C.