Unit 4: Iteration – AP Computer Science A
🔑 Key Concepts
for
loopswhile
loopsdo-while
loops- Infinite loops and off-by-one errors
- Nested loops
- Loop control:
break
andcontinue
🔁 for
Loop
Best for when the number of iterations is known.
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
// prints 0 to 4
🔁 while
Loop
Best for when the number of iterations is unknown.
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
🔁 do-while
Loop
Runs the loop at least once before checking the condition.
int i = 0;
do {
System.out.println(i);
i++;
} while (i < 5);
⚠️ Infinite Loops
Loops that never terminate due to a condition that never becomes false.
while (true) {
// endless loop
}
🧠 Common Pitfall: Off-by-One Errors
Be careful with loop conditions using <
, <=
, etc.
for (int i = 0; i <= 5; i++) { // runs 6 times: 0 to 5
🔂 Nested Loops
A loop inside another loop, often used with 2D arrays.
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
System.out.println("[" + row + "," + col + "]");
}
}
⛔ Loop Control Statements
break
— exits the loopcontinue
— skips the current iteration
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) continue;
System.out.print(i + " "); // prints odd numbers
}
🧪 Practice Multiple Choice (5 Questions)
1. What will the following code print?
for (int i = 0; i < 3; i++) {
System.out.print(i + " ");
}
(A) 0 1 2
(B) 1 2 3
(C) 0 1 2 3
(D) 1 2
✅ Answer: (A)
2. How many times will this loop run?
for (int i = 0; i <= 4; i++) {
System.out.println("Loop");
}
(A) 4
(B) 5
(C) 6
(D) Infinite
✅ Answer: (B)
3. What is true about a do-while
loop?
(A) It may never run
(B) It always runs at least once
(C) It always runs exactly once
(D) It runs forever
✅ Answer: (B)
4. Which loop will print all even numbers from 0 to 10?
for (int i = 0; i <= 10; i += 2)
System.out.println(i);
(A) Correct
(B) Skips 0
(C) Prints odd numbers
(D) Infinite loop
✅ Answer: (A)
5. What does continue
do in a loop?
(A) Ends the loop
(B) Restarts the loop
(C) Skips the current iteration
(D) Pauses the loop
✅ Answer: (C)