Worked solution from the Programming Paper 2 Problem-solving and Programming booklet, Part 3 of 3.
Return -1 for negative numbers. Otherwise multiply 1 by each number from the parameter down to 1. Factorial of 0 stays 1.
FUNCTION Factorial(ThisNum : INTEGER) RETURNS INTEGER
DECLARE Value : INTEGER
IF ThisNum < 0 THEN
Value ← -1
ELSE
Value ← 1
WHILE ThisNum <> 0
Value ← Value * ThisNum
ThisNum ← ThisNum - 1
ENDWHILE
ENDIF
RETURN Value
ENDFUNCTIONFunction heading and ending with parameter and return type [1]
Declare Value and set it to 1 [1]
Check for a negative number (< 0) [1]
A loop that runs while ThisNum is not 0 (or ThisNum times) [1]
Form the answer by repeated multiplication, completely correct [1]
Return the INTEGER value correctly for both negative and other numbers [1]
A correct recursive version also scores.
Follow the flowchart: A is the loop test, B is the YES exit to END, C is the NO path to the call.
| Label | Text |
|---|---|
| A | Is Num > 9? |
| B | YES |
| C | NO |
| D | Set Result to Factorial(Num) |
| E | OUTPUT "Factorial of ", Num, " is ", Result |
| F | Set Num to Num + 1 |
A, B and C all correct [1]
D correct (any identifier) [1]
E correct [1]
F correct [1]
▶ Whole paper
Video solution of the whole paper · by Digify ID. Tap the picture to open it on YouTube.
Solutions follow the official Cambridge mark schemes; marks are shown in grey. Videos are from other YouTube channels. Paper codes read component / series / year: M/J = May/June, O/N = October/November. Past-paper questions © UCLES, reproduced for classroom practice.