Unit 2 Cycle 1 Day 15: For Loop Counting Pattern

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

For Loop Counting Pattern

Section 2.10 — Loop Algorithms

Key Concept

Counting with for loops requires careful attention to the start value, condition, and update. To count from 1 to n: for (int i = 1; i <= n; i++). To count by twos: for (int i = 0; i < n; i += 2). To count backward: for (int i = n; i > 0; i--). The AP exam tests boundary values: how many times does the loop execute? The formula is (end - start) / step for simple cases, but always verify by tracing the first and last iterations.

Consider the following code segment.

int count = 0; for (int i = 1; i <= 100; i++) { if (i % 3 == 0 && i % 5 == 0) { count++; } } System.out.println(count);

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

Answer: (A) 6

The condition checks for numbers divisible by BOTH 3 AND 5, which means divisible by 15. Multiples of 15 from 1 to 100: 15, 30, 45, 60, 75, 90. That is 6 numbers.

Why Not the Others?

(B) 33 is the count of multiples of 3 alone (from 1-100), ignoring the AND with 5.

(C) 20 is the count of multiples of 5 alone (from 1-100), ignoring the AND with 3.

(D) 47 is the count divisible by 3 OR 5 (using inclusion-exclusion: 33+20-6=47).

Common Mistake

Divisible by both 3 AND 5 means divisible by their LCM (15). Do not add the counts of multiples of 3 and multiples of 5 separately.

AP Exam Tip

When you see % a == 0 && % b == 0, think LCM. Divisible by both a and b means divisible by their least common multiple.

Review this topic: Section 2.10 — Loop Algorithms • 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.