Unit 2 Cycle 1 Day 13: Spotting the Infinite Loop

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

Spotting the Infinite Loop

Section 2.8 — While Loops

Key Concept

An infinite loop occurs when the loop condition never becomes false. Common causes include: forgetting to increment a counter, modifying the wrong variable, or using a condition that is always true (like while (x > 0) when x only increases). The AP exam tests your ability to identify which code segment produces an infinite loop versus one that terminates. Check each loop by asking: does the body change a variable in the condition, and does that change move toward making the condition false?

A student writes the following code segment. What happens when it executes?

int x = 10; while (x > 0) { System.out.println(x); x++; }

What is the result of executing the code segment?

Answer: (C) It runs forever (infinite loop).

The loop condition is x > 0, but x++ increases x each iteration (10, 11, 12, ...). x will always be greater than 0, so the condition is always true. The loop never terminates.

Why Not the Others?

(A) The loop increments x instead of decrementing it. x never reaches 0.

(B) The loop body has no break statement and the condition never becomes false.

(D) x starts at 10, which is greater than 0, so the loop body executes at least once.

Common Mistake

An infinite loop occurs when the loop variable changes in the wrong direction. Here, the condition requires x to eventually reach 0, but x increases. The fix: change x++ to x--.

AP Exam Tip

When analyzing loops, check: (1) Does the condition start as true? (2) Does the loop body change the variable toward making the condition false? If not, it is infinite.

Review this topic: Section 2.8 — While Loops • 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.