Function Pointer Dispatch Table

Code

#include <stdio.h>

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) { return a / b; }

int execute_command(int a, int b, int cmd) {
    // Your logic here using function pointer array
    int (*operations[])(int , int) = {add, sub, mul, divide};
    int result = operations[cmd](a,b);
    return result;
}

int main() {
    int a, b, cmd;
    scanf("%d %d %d", &a, &b, &cmd);

    int result = execute_command(a, b, cmd);
    printf("%d", result);

    return 0;
}

Solving Approach

  • Define separate functions for Add, Subtract, Multiply, Divide.
  • Create a function pointer array → each element points to one of these functions.
  • Take input for a, b, and command.
  • Use operations[command](a, b) to directly call the required function.
  • Print the result.

 

 

Upvote
Downvote
Loading...

Input

10 5 0

Expected Output

15