ITPEC IP October 2024 Question 8
The procedure draw receives a non-negative integer number n for input. When the value of n is 6, the procedure outputs the six lines shown below. Which of the following is an appropriate combination of pieces of code to be inserted in A and B in the program?
Explanation
A: k ← 1, B: k ← k + 1 — the inner counter restarts at 1 on every line and counts up to the line number i.
The outer loop runs i from 1 to n, and line i must show 1 through i. So before the inner loop, k is reset to 1 (blank A), and each pass of the inner loop outputs k and then advances it by one (blank B) until k exceeds i.
Trace for i = 3: k = 1, 2, 3 are output, then k = 4 fails k ≤ i, the line break is output and i becomes 4.
Answer (b)
Why not others:
- •(a) — A
i ← 1resets the outer counter on every line, and B increments i instead of k; k is never set or changed, sok ≤ inever becomes false - •(c) — A
i ← i + 1skips line lengths and leaves k unset; Bi ← kchanges i instead of k, sok ≤ istays true forever - •(d) — A
k ← k + 1never resets k to 1, and Bk ← i + 1ends the inner loop after one value, so each line would show at most one number
Key rule: In nested loops, initialise the inner counter just before the inner loop and advance that same counter inside it; leave the outer counter to the outer loop.
Algorithm and Programming · 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 IP past-paper collection or Report an issue.