Function Pointer Array
C
Hard
4 views
Problem Description
Create array of different math functions (add, sub, mul, div) using function pointers. Make a call by selecting from the index. Menu-driven calculator.
Official Solution
#include <stdio.h>
/* Function prototypes */
int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
int mul(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() {
int choice, x, y;
/* Array of function pointers */
int (*operations[4])(int, int) = {add, sub, mul, divide};
char *op_names[4] = {"+", "-", "*", "/"};
printf("Menu-driven calculatorn");
printf("0: Add (+)n1: Subtract (-)n2: Multiply (*)n3: Divide (/)n");
printf("Enter choice (0-3): ");
scanf("%d", &choice);
if (choice < 0 || choice > 3) {
printf("Invalid choice!n");
return 1;
}
printf("Enter two numbers: ");
scanf("%d %d", &x, &y);
int result = operations[choice](x, y); // call function via pointer
printf("Result: %d %s %d = %dn", x, op_names[choice], y, result);
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!