Unit 2 Cycle 1 Day 21: Nested Loop with Accumulator

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

Nested Loop with Accumulator

Section 2.12 — Nested Loops

Key Concept

A nested loop with an accumulator combines the counting pattern with nested iteration. The accumulator might track a running sum, count, or constructed string. The key is that the inner loop's behavior may depend on the outer loop's current variable. For example, when the inner loop runs from 1 to i (where i is the outer variable), the number of inner iterations changes each time. Trace these carefully by writing the accumulator value at the end of each complete inner loop execution.

Consider the following code segment.

int sum = 0; for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { if (i == j) { sum += i; } } } System.out.println(sum);

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

Answer: (B) 6

The condition i == j is true when: (1,1), (2,2), (3,3). Sum = 1 + 2 + 3 = 6. This sums the "diagonal" values.

Why Not the Others?

(A) 9 = 3*3, which would be the sum if the condition were always true and each added 1.

(C) 3 is the number of times the condition is true, not the sum of i values.

(D) 18 = sum of all i*j products, not the sum when i equals j.

Common Mistake

When nested loops have a conditional, do not just multiply iterations. Identify which (i, j) pairs satisfy the condition and sum only those values.

AP Exam Tip

For nested loop questions with conditionals, list out the pairs that satisfy the condition. This is more reliable than trying to reason abstractly.

Review this topic: Section 2.12 — Nested 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.