basics · beginner · ~15 min

Apply an operator

Branch on an operator and guard division.

Challenge

Build a tiny calculator: apply an arithmetic operator chosen at runtime.

Task

Implement int apply_op(int a, int b, char op) that returns the result of applying op to a and b. Support '+', '-', '*', and '/' (integer division). Return 0 for division by zero or for any unrecognised operator. No main — the grader calls it.

Input

Two ints a and b, and an operator character op.

Output

Returns the computed result, or 0 for divide-by-zero or an unknown operator.

Example

apply_op(2, 3, '+')   ->   5
apply_op(4, 5, '*')   ->   20
apply_op(9, 3, '/')   ->   3
apply_op(1, 0, '/')   ->   0     (division by zero)
apply_op(1, 2, '?')   ->   0     (unknown operator)

Edge cases

  • Dividing by zero returns 0 (never perform the division — it is undefined behaviour).
  • An unrecognised operator returns 0.

Input format

Two ints a and b, and an operator char op.

Output format

The result, or 0 for divide-by-zero or an unknown operator.

Constraints

Supported ops: + - * /. Guard division by zero.

Starter code

int apply_op(int a, int b, char op) {
    /* TODO */
    return 0;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.