Menu
Coddy logo textTech

Recap: Calculator Dispatch

Part of the Object Oriented Programming section of Coddy's C journey — lesson 37 of 61.

challenge icon

Challenge

Easy

Build a calculator using a dispatch table. You'll create an array of function pointers that maps operation codes to their corresponding functions, then use it to perform calculations.

Write a program that:

  1. Creates a typedef called Operation for a function pointer that takes two int parameters and returns an int
  2. Defines four arithmetic functions:
    • add — returns a + b
    • sub — returns a - b
    • mul — returns a * b
    • divide — returns a / b (integer division)
  3. In main, creates a dispatch table: an array of 4 Operation function pointers, where index 0 is add, index 1 is sub, index 2 is mul, and index 3 is divide
  4. Reads three inputs: two integers and an operation code (0-3)
  5. Uses the operation code to index into the dispatch table and call the appropriate function
  6. Prints the result

You will receive three inputs: the first number, the second number, and the operation code (0 for add, 1 for sub, 2 for mul, 3 for divide).

Your output should be a single integer—the result of the operation:

7

In this example with inputs 10, 3, 1: the operation code 1 selects sub from the dispatch table, so we compute 10 - 3 = 7.

The key here is using array indexing to select the function—no if or switch statements needed. Your dispatch table should look like:

Operation ops[4] = {add, sub, mul, divide};

Then call the function using: ops[code](a, b)

Try it yourself

#include <stdio.h>

// TODO: Create a typedef called 'Operation' for a function pointer
// that takes two int parameters and returns an int


// TODO: Define the four arithmetic functions: add, sub, mul, divide


int main() {
    // Read input
    int a, b, code;
    scanf("%d", &a);
    scanf("%d", &b);
    scanf("%d", &code);
    
    // TODO: Create the dispatch table (array of 4 Operation function pointers)
    // Operation ops[4] = { ... };
    
    // TODO: Use the operation code to call the appropriate function
    // and store the result
    int result;
    
    // Output the result
    printf("%d\n", result);
    
    return 0;
}

All lessons in Object Oriented Programming