ITPEC FE Subject B April 2024 Question 7
From the answer group below, select the correct combination of answers to be inserted into A and B in the program.
The Fibonacci sequence is a sequence in which each number is equal to the sum of the two preceding numbers. In this question, the sequence starts with 0 and 1. The first 10 values in the sequence are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34. For example, the 8-th number 13 is the sum of the two preceding numbers 5 and 8.
The function fibo takes an integer value n as the argument and returns the value at the n-th position. Here, n reflects the position of the number in the sequence, starting with 1 (one). When n is 9, the function returns 21.
Answer group
Explanation
A: (n = 1) or (n = 2), B: fibo(n-1) + fibo(n-2) — the first two positions are returned directly as n − 1, and every later one is the sum of the two before it.
- •The base branch returns
n - 1, which is right for position 1 (0) and position 2 (1) only; position 3 would give 2 instead of 1. So A must catch exactlyn = 1andn = 2. - •From position 3 on, each number is the sum of the two preceding ones: B is
fibo(.n-1) + fibo( n-2) - •Every chain of calls ends at position 1 or 2:
fibo(calls3) fibo(and2) fibo(, so the recursion always stops.1)
Check: fibo( is fibo( + fibo( = 13 + 8 = 21, as the question states.
Answer (i)
Why not others:
- •(c) — A
n = 1alone letsfibo(call2) fibo(, which no base case catches, so the recursion runs on through negative n without end0) - •(d), (e) and (f) — A
n > 1inverts the test: every n from 2 up returns n − 1 directly (fibo(gives 8), and9) fibo(recurses into1) fibo(without end0) - •(a) and (g) — B
fibo(adds 1 per step, so every position returns n − 1:n-1) + 1 fibo(gives 3 instead of 2, and4) fibo(gives 89) - •(b) and (h) — B
fibo(adds the position instead of a sequence value:n-1) + n fibo(gives 44 in (b) and 43 in (h)9)
Key rule: A recursion that looks back k steps needs k base cases, and the base-case test must hold exactly where the direct formula is valid.
Math & Numbers · AI-written, may contain errors
This question comes from an official ITPEC past paper. ITPEC Practice is an independent study tool and is not affiliated with ITPEC. See the official FE past-paper collection or Report an issue.