Official Solution
#include <stdio.h>
/* Function prototypes */
int add(int a, int b) { return a + b; }
int subtract(int a, int b) { return a - b; }
int multiply(int a, int b) { return a * b; }
int divide(int a, int b) {
if (b == 0) {
printf("Error: Division by zero!n");
return 0;
}
return a / b;
}
int main() {
char op;
int x, y;
/* Array of function pointers */
int (*funcPtr[4])(int, int) = {add, subtract, multiply, divide};
char operators[4] = {'+', '-', '*', '/'};
printf("Enter two numbers: ");
scanf("%d %d", &x, &y);
printf("Enter operator (+, -, *, /): ");
scanf(" %c", &op);
int i, found = 0;
for (i = 0; i < 4; i++) {
if (op == operators[i]) {
int result = funcPtr[i](x, y); // Call corresponding function
printf("Result: %d %c %d = %dn", x, op, y, result);
found = 1;
break;
}
}
if (!found) {
printf("Error: Invalid operator!n");
}
return 0;
}
No comments yet. Start the discussion!