What does fact(4) return if fact(n) = 1 when n = 0, else n * fact(n − 1)?
- fact(4) = 4 × fact(3) = 4 × 3 × fact(2).
- = 4 × 3 × 2 × 1 × fact(0).
- = 24.
Answer 24
A-level Computer Science revision · Programming
A recursive subroutine calls itself. It must have a base case that stops the recursion, and each call must move towards it. Each call adds a frame to the call stack, so deep recursion can cause a stack overflow. Recursion can be elegant for problems like tree traversal, but iteration often uses less memory.
Watch out Without a base case, recursion never stops and causes a stack overflow.
What does fact(4) return if fact(n) = 1 when n = 0, else n * fact(n − 1)?
Answer 24
f(n) returns 0 if n = 0, else n + f(n − 1). What does f(5) return?
What causes a stack overflow in a recursive program?
Give one advantage of recursion over iteration.
Answer Recursive code can be shorter and closer to the problem's natural definition, such as traversing a tree.
A-level Computer Science Pro, OCR H446
£119 once
Price rises to £199 on 1 January. Save £80 by joining before then.
At least 12 months of access
No VAT is charged.