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?

[Output]
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
[Program]
○ draw(integer: n)
integer: i, k
i ← 1
while (i ≤ n) /* The while loop is skipped if n is zero. */
A
while (k ≤ i)
output the value of k and a space
B
endwhile
output the line break
i ← i + 1
endwhile
OptionAB

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 ← 1 resets the outer counter on every line, and B increments i instead of k; k is never set or changed, so k ≤ i never becomes false
  • •(c) — A i ← i + 1 skips line lengths and leaves k unset; B i ← k changes i instead of k, so k ≤ i stays true forever
  • •(d) — A k ← k + 1 never resets k to 1, and B k ← i + 1 ends 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.