AP Computer Science A - Unit 4 Review: Lesson 4
Overview
This lesson explores the three main types of loops in Java: for
, while
, and do-while
. It also demonstrates practical applications such as reversing a string using a for
loop and introduces the concept of nested loops, which are especially useful when working with multi-dimensional data structures.
Purpose: Repeat a block of code a specific number of times.
Structure:
for (initialization; test; update) {
// body of loop
}
Example: Printing 0 to 3
for (int i = 0; i < 4; i++) {
System.out.println(i);
}
Execution Steps:
i = 0
i < 4
: If true, execute bodyi
i++
i < 4
is falsePurpose: Repeat a block of code while a condition is true.
Structure:
while (condition) {
// body of loop
}
Example: Countdown from 4
int i = 4;
while (i > 0) {
System.out.println(i);
i--;
}
Notes:
i
is never changed inside the loop, it runs forever.while
loop may never run if the initial condition is false.Purpose: Like a while
loop, but guarantees the body executes at least once.
Structure:
do {
// body of loop
} while (condition);
Example:
int i = -2;
do {
System.out.println(i);
i--;
} while (i > 0);
Note: Ends with a semicolon after the condition.
Goal: Reverse the characters in a string.
Example Code:
String original = "pupils";
String reverse = "";
for (int i = original.length() - 1; i >= 0; i--) {
reverse += original.substring(i, i + 1);
}
System.out.println(reverse); // Output: slipup
Key Concepts:
substring(i, i + 1)
extracts one character at a time.length - 1
.Definition: A loop inside another loop.
Example:
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
System.out.println("i = " + i + ", j = " + j);
}
}
Execution:
i = 0
and i = 1
)j = 0, 1, 2
)Use Cases:
Loop Type | Condition Location | Runs at Least Once? | Best For |
---|---|---|---|
For | Beginning | No | Known iteration counts |
While | Beginning | No | Condition-based repeats |
Do-While | End | Yes | At least one execution |
Nested Loop | Varies | Varies | 2D arrays or grids |
Key Terms:
i
, j
)substring(start, end)
retrieves part of a string (exclusive of end
)Next Steps:
End of Lesson 4 Review