Unit 2 Cycle 1 Day 14: For Loop Tracing

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

For Loop Tracing

Section 2.9 — For Loops

Key Concept

A for loop combines initialization, condition, and update into a single line: for (init; condition; update). The initialization runs once before the loop starts, the condition is checked before each iteration, and the update runs after each iteration's body completes. A standard counting loop for (int i = 0; i < n; i++) executes exactly n times, with i taking values 0 through n - 1. The variable i is only in scope within the loop.

Consider the following code segment.

int result = 0; for (int i = 1; i <= 4; i++) { result += i * i; } System.out.println(result);

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

Answer: (B) 30

Trace: i=1: result=1. i=2: result=1+4=5. i=3: result=5+9=14. i=4: result=14+16=30. Sum of squares: 1+4+9+16=30.

Why Not the Others?

(A) 16 is just i*i when i=4, not the accumulated sum.

(C) 10 would be the sum of 1+2+3+4 (sum of i, not i*i).

(D) 20 is not the sum of any standard pattern with these values.

Common Mistake

Trace each iteration carefully. The accumulator adds i * i, not i. Sum of squares (1+4+9+16) differs from sum of integers (1+2+3+4).

AP Exam Tip

For accumulator loops, write a table with columns for i and result. Update after each iteration. This prevents arithmetic errors on multi-step traces.

Review this topic: Section 2.9 — For 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.