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.


1. For Loops

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:


2. While Loops

Purpose: 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:


3. Do-While Loops

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.


4. String Reversal Using For Loop

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:


5. Nested Loops

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:

Use Cases:


Summary Table

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:


Next Steps:


End of Lesson 4 Review