L7: Iteration in Java
Overview of Iteration
- Iteration allows repeating a block of code multiple times with minimal duplication.
- Loops execute a single block of code multiple times, making programs more flexible and efficient.
The while Loop
Definition: Executes a block of code as long as the specified condition is
true.Syntax:
while (condition) { // bodyStatement(s); }How It Works:
- Checks the condition at the start. If
true, executes the loop body. - After executing the body, it checks the condition again.
- If the condition becomes
false, the loop exits, and the program moves to the code following the loop.
- Checks the condition at the start. If
Example:
int count = 0; while (count < 5) { System.out.println("Count: " + count); count++; }Notes:
- Curly braces
{}are only necessary if the loop body has more than one statement. - Be cautious of infinite loops if the condition never becomes
false.
- Curly braces
The do-while Loop
Definition: Similar to the
whileloop, but guarantees at least one execution of the loop body since the condition is evaluated after the body.Syntax:
do { // bodyStatement(s); } while (condition);How It Works:
- Executes the loop body first.
- Then, it checks the condition. If
true, it repeats the body. - If
false, the loop ends, and the program continues with the code after thedo-whileloop.
Example:
int count = 0; do { System.out.println("Count: " + count); count++; } while (count < 5);Notes:
- The loop body runs at least once, regardless of the condition.
- Curly braces
{}are only required for multiple statements in the loop body.
The for Loop
Definition: Combines initialization, condition, and update in a single line, providing a concise way to iterate.
Syntax:
for (initialization; condition; update) { // bodyStatement(s); }How It Works:
- Initialization: Runs once at the start of the loop.
- Condition: Evaluated before each iteration. If
true, the loop body executes. - Update: Executes after the loop body, typically used to modify the loop counter.
- Repeats until the condition becomes
false.
Example:
for (int count = 0; count < 5; count++) { System.out.println("Count: " + count); }Notes:
- Not all parts (
initialization,condition,update) are required. For example, you can have an infinite loop withfor (;;) { ... }. - Curly braces
{}are only necessary if the loop body has more than one statement.
- Not all parts (
The for-each Loop
Definition: Designed to iterate over arrays or collections, accessing each element without using an index.
Syntax:
for (type element : collection) { // bodyStatement(s); }How It Works:
- Directly accesses each element in the array or collection.
- Useful when you don’t need to modify the collection or need to keep track of the index.
Example:
int[] numbers = {1, 2, 3, 4, 5}; for (int num : numbers) { System.out.println(num); }Notes:
- Works with arrays,
ArrayList, and other collections. - Cannot modify the collection (e.g., cannot change elements of an array) in a
for-eachloop.
- Works with arrays,
Nested Loops
A loop inside another loop is known as a nested loop.
How It Works:
- The outer loop runs once, then the inner loop completes all its iterations.
- Total iterations = (Outer loop iterations) × (Inner loop iterations).
Example:
for (int i = 0; i < 3; i++) { for (int j = 0; j < 2; j++) { System.out.println("i: " + i + ", j: " + j); } }
Difference Between break and continue
break: Exits the loop immediately, regardless of the loop’s condition. Useful for terminating the loop when a specific condition is met.for (int i = 0; i < 10; i++) { if (i == 5) { break; // Exits the loop when i equals 5 } System.out.println(i); }continue: Skips the remaining statements in the current iteration and jumps to the next iteration of the loop.for (int i = 0; i < 10; i++) { if (i == 5) { continue; // Skips the rest of the loop body when i equals 5 } System.out.println(i); }
Converting Between while and for Loops
A
whileloop can be converted to aforloop by placing initialization, condition, and update in the loop’s header.// while loop int i = 0; while (i < 5) { System.out.println(i); i++; } // Equivalent for loop for (int i = 0; i < 5; i++) { System.out.println(i); }Conversely, a
forloop can be converted to awhileloop by moving initialization outside the loop and update statements inside the loop body.// for loop for (int i = 0; i < 5; i++) { System.out.println(i); } // Equivalent while loop int i = 0; while (i < 5) { System.out.println(i); i++; }
Tracing Loops
- Tracing: Following the execution of a loop to understand its flow.
- For
whileanddo-whileloops, check the condition before (or after, fordo-while) each iteration. - For
forloops, follow the sequence: initialization → condition check → body execution → update → condition check. - For
for-eachloops, iterate over each element in the collection sequentially.
Key Points to Remember
- Initialization Statement: Sets up the loop counter (e.g.,
int i = 0in aforloop). - Condition: Decides whether to continue executing the loop.
- Update Statement: Changes the loop counter (e.g.,
i++). breakvs.continue:breakterminates the loop;continueskips to the next iteration.for-eachLoop: Ideal for iterating over collections when you do not need to modify elements or track indices.