ITPEC IP April 2024 Question 6
Topic: Algorithm and ProgrammingAlso asked in April 2019 and October 2022
The procedure described below is sequentially performed for two (2) variables x and y, starting with step (1). When the procedure is completed, what is the resulting value of x?
[Procedure](1)Assign 2 to x and 3 to y.(2)Subtract 1 from the value of y, and assign the resulting value to y.(3)Add the values of x and y, and assign the resulting value to x.(4)If the value of y is 1, complete the procedure. Otherwise, return to step (2).
Explanation
5 — the loop runs twice, adding y = 2 and then y = 1 to x.
Trace the procedure, checking y at step (4) after each pass:
Answer (b)
Why not others:
- •(a) 4 — the value after the first pass, stopping before the loop has finished
- •(c) 7 — performs step (3) before step (2), adding y before it is decremented: 2 + 3 + 2
- •(d) 8 — adds every value y takes, the starting 3 included, 2 + 3 + 2 + 1; y is decremented before each addition, so 3 is never added
Key rule: Trace a loop in a table, one row per step in the stated order, and test the exit condition only where the procedure tests it, with the values updated so far.
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.