basics · beginner · ~15 min
Branch on an operator and guard division.
Build a tiny calculator: apply an arithmetic operator chosen at runtime.
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.
Two ints a and b, and an operator character op.
Returns the computed result, or 0 for divide-by-zero or an unknown operator.
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)
Two ints a and b, and an operator char op.
The result, or 0 for divide-by-zero or an unknown operator.
Supported ops: + - * /. Guard division by zero.
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.