logo

AQA A-Level Computer Science practice

Consider this Python function: ```python def total(n): if n == 1: return 1 return n + total(n - 1) ``` Trace the calls made by total(4), give the final result, and explain how the answers from the recursive calls are combined.

Try the question first, then check the answer and practise the same topic again.

At a glance

Question

Type

practice

Style

Topic

Programming

Exam-style question

Try this first

Consider this Python function: ```python def total(n): if n == 1: return 1 return n + total(n - 1) ``` Trace the calls made by total(4), give the final result, and explain how the answers from the recursive calls are combined.

Answer and explanation

Concise answer

The calls are: `total(4)` returns `4 + total(3)`.

Why this is correct

Each general-case call waits for the result of the next recursive call. Once the base case returns 1, the waiting calls finish in reverse order and add their own n value to the returned result.

Use the concise answer above for a quick check, then reveal the full model answer and detailed explanation.

Common mistake

No common mistake is linked to this question yet.

Related flashcards

No flashcards are published for this page yet.

Related practice questions