Unit 2 Day 16 Algorithm Analysis
Share
Unit 2: Selection and Iteration
Day 16 PracticeHard
Focus: Counting loop iterations
Today's Question
How many times does the inner loop body execute?
for (int i = 0; i < 4; i++) {
for (int j = 0; j <= i; j++) {
System.out.print(class="apcs-string">"*");
}
}
When i=0: j goes 0 (1 time). When i=1: j goes 0,1 (2 times). When i=2: j goes 0,1,2 (3 times). When i=3: j goes 0,1,2,3 (4 times). Total: 1+2+3+4 = 10.
Key Concept
Nested loops where the inner loop depends on the outer loop variable create a triangular pattern of iterations.