Unit 2 Cycle 2 Day 20: I/II/III: Loop Behavior
Share
I/II/III: Loop Behavior
Section 2.8 — While Loops
Key Concept
I/II/III loop behavior questions present three statements about a loop and ask which are true. Statements might claim: the loop always terminates, the loop executes at least once, a specific variable has a certain final value, or the loop body executes exactly n times. For while loops, verify the initial condition (does the body execute at all?), the progression (does it move toward termination?), and the final state (what are the variable values when the condition becomes false?). Test edge cases like initial values that skip the loop entirely.
Consider the following loops.
Which of the statements are correct?
Answer: (B) II and III only
I: INCORRECT. The loop variable i declared in the for header is scoped to the loop. It is NOT accessible after.
II: CORRECT. j starts at 0, increments to 5, then 5 < 5 is false. j = 5 after.
III: CORRECT. k: 10, 7, 4, 1. Next would be -2 which fails > 0. Body executes 4 times.
Why Not the Others?
(A) Statement III is also correct. k takes values 10, 7, 4, 1 (4 iterations).
(C) Statement I is incorrect. For-loop variables declared in the header go out of scope after the loop.
(D) Statement I is incorrect due to variable scope rules.
Common Mistake
Variables declared in a for-loop header (for (int i = ...)) are scoped to the loop. Variables declared before a while loop persist after it. This is a key scope difference.
AP Exam Tip
For-loop scope: int i declared in the header dies after the loop. While-loop variable: declared outside, survives after the loop. The AP exam tests this distinction.