A function takes values in through parameters, does some work and sends one value back with RETURN. To trace a call, match each argument to its parameter by position, run the body, then replace the call with the returned value.
This lesson is part of programming foundations. It builds on writing loops with correct boundaries, because functions can contain loops.
How do you trace a function call?
Use three moves.
- Match: copy each argument into the parameter in the same position.
- Run: follow the body line by line using those parameter values.
- Return: put the returned value where the call was written, and carry on.
Write the parameter values at the top of your trace table, so you never mix them with the caller’s variables.
Worked example: area of a rectangle
FUNCTION area(length, width)
RETURN length * width
END FUNCTION
SET w = 3
SET result = area(w + 2, 4)
OUTPUT result
| Move | Working |
|---|---|
| Evaluate arguments | w + 2 = 5, and 4 |
| Match | length = 5, width = 4 |
| Run and return | 5 × 4 = 20 |
| Store | result = 20 |
The output is 20. Notice that w stays 3 in the caller, because only its value was used.
What mistake do students make here?
The usual mistake is to match arguments by name or to swap their order. Consider a function that finds a remainder.
FUNCTION remainder(a, b)
RETURN a MOD b
END FUNCTION
| Call | a | b | Result |
|---|---|---|---|
| remainder(17, 5) | 17 | 5 | 17 MOD 5 = 2 |
| remainder(5, 17) | 5 | 17 | 5 MOD 17 = 5 |
Same two numbers, different answer. The position of each argument decides which parameter receives it, so always write the match step.
Check yourself
Trace this and state the output.
FUNCTION bigger(p, q)
IF p > q THEN
RETURN p
ELSE
RETURN q
END IF
END FUNCTION
OUTPUT bigger(7, 12) + bigger(9, 3)
Answer
For bigger(7, 12): p = 7, q = 12, 7 > 12 is false, so it returns 12. For bigger(9, 3): p = 9, q = 3, 9 > 3 is true, so it returns 9.
The expression becomes 12 + 9, so the output is 21.
What to study next
Next, see how to locate faults in whole programs in program structure and debugging. You can practise call tracing with the restricted pseudocode trace trainer.
If you want a teacher to go through your function traces, see online one-to-one Computer Science tuition.