Consider the following pseudocode x := 1; i := 1; while (x ≤ 1000) begin x :=…
2007
Consider the following pseudocode x := 1; i := 1; while (x ≤ 1000) begin x := 2^x; i := i + 1; end;
What is the value of i at the end of the pseudocode?
- A.
4
- B.
5
- C.
6
- D.
7
Attempted by 157 students.
Show answer & explanation
Correct answer: B
Tracing a while-loop means evaluating the guard condition before every pass and updating every variable using the values already computed so far. A self-referential assignment like x := 2^x always uses the OLD value of x to compute the NEW value of x. The loop terminates the first time the guard evaluates to false, checked at the top of each pass before any further update happens.
Initial values: x = 1, i = 1.
Guard check: x = 1 ≤ 1000 is true, so the loop runs. Update: x := 2^1 = 2; i := 1 + 1 = 2.
Guard check: x = 2 ≤ 1000 is true. Update: x := 2^2 = 4; i := 2 + 1 = 3.
Guard check: x = 4 ≤ 1000 is true. Update: x := 2^4 = 16; i := 3 + 1 = 4.
Guard check: x = 16 ≤ 1000 is true. Update: x := 2^16 = 65,536; i := 4 + 1 = 5.
Guard check: x = 65,536 ≤ 1000 is false, so the loop exits without any further update.
The pseudocode ends with i = 5.
The jump from x = 16 to x = 65,536 vastly overshoots the threshold in a single step, so the same trace still ends at i = 5 even for nearby threshold variants (for example, x ≤ 500 or x ≤ 2000) — the result depends only on the doubly-exponential growth of the sequence 1, 2, 4, 16, 65536, not on the exact limit value.