Unit 2 Cycle 1 Day 25: For Loop Boundary Analysis

Unit 2 Foundation (Cycle 1) Day 25 of 28 Foundation

For Loop Boundary Analysis

Section Mixed — Review: Loop Patterns

Key Concept

For loop boundary analysis focuses on the exact first and last values of the loop variable and the total iteration count. For for (int i = a; i < b; i += c), the first value is a, the last value is the largest a + n*c that is still less than b, and the count is ceil((b - a) / c). The AP exam frequently tests boundary conditions where changing < to <= or i++ to i += 2 changes the count by exactly one. Always verify by testing with specific values.

Consider the following code segment.

for (int i = 10; i > 0; i -= 3) { System.out.print(i + " "); }

What is printed as a result of executing the code segment?

Answer: (A) 10 7 4 1

i=10: print 10. i=7: print 7. i=4: print 4. i=1: print 1. Next: i=-2, condition -2 > 0 is false, loop ends. Output: 10 7 4 1.

Why Not the Others?

(B) i=1 still satisfies i > 0, so 1 is printed before the loop ends.

(C) -2 is never printed because the condition is checked before the body executes.

(D) The loop starts at i=10, which is the first value printed.

Common Mistake

When a loop decrements by a value other than 1, the final iteration may not land exactly on the boundary. Here i goes 10, 7, 4, 1, -2. Since -2 is not > 0, the loop stops after printing 1.

AP Exam Tip

For non-standard decrements, list out the sequence of loop variable values until the condition fails. Do not assume the last printed value will be exactly 1 or 0.

Review this topic: Section Mixed — Review: Loop Patterns • Unit 2 Study Guide

More Practice

Related FRQs

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.