ITPEC FE Subject A April 2024 Question 6

The flowchart below shows an algorithm that determines the sum (i.e. “1 +3+ 5+ … + (2N−1)”) of the first N odd integers from 1 through 2N−1 (where N ≥ 1) and inserts the result into variable x. Which of the following is an expression to be inserted in blank A ?

Startx0i1AYesNoxx + iii + 2End

Explanation

i ≥ 2N + 1 — the loop may stop only after the last odd number, 2N − 1, has been added.

The decision is tested before each addition. The counter takes 1, 3, 5, …; once 2N − 1 has been added, it becomes 2N − 1 + 2 = 2N + 1, and that is the first value at which the loop should exit.

Trace for N = 3, expecting 1 + 3 + 5 = 9: i = 1, 3, 5 are added, giving x = 9, and i = 7 = 2N + 1 ends the loop.

Answer (b)

Why not others:

  • •(a) — i ≥ 2N − 1 exits as soon as i reaches 2N − 1, before that last term is added; for N = 3 it stops at x = 4
  • •(c) — x ≥ 2N − 1 tests the sum instead of the counter; it happens to work for N ≤ 3, but for N = 4 it stops at x = 9 instead of 16
  • •(d) — x ≥ 2N + 1 also tests the sum; for N = 1 it runs on to x = 4 instead of 1

Key rule: In a loop that tests before the body, the exit condition must first become true at the counter value just past the last one to process; trace the smallest cases to confirm it.

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 FE past-paper collection or Report an issue.