Unit 2 Cycle 1 Day 15: For Loop Counting Pattern
Share
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.
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.