Loops & Control Flow
Loops repeat code blocks as long as a condition remains true. Java features three primary loop constructs: for, while, and do-while.
1 Loop Structures: while, do-while, and for
Different loop configurations suit different tasks:
- while: Evaluates its condition before checking the block. May execute 0 times.
- do-while: Executes the block first, then evaluates the condition. Guaranteed to run at least once!
- for: Best when the iteration count is known beforehand. Declares initializer, condition, and step increment in one line.
2 Iteration Tracing & Loop Control (Break / Continue)
Loop execution can be dynamically controlled:
- break: Terminates the loop structure immediately.
- continue: Skips the remaining statement blocks in the current iteration and jumps to the next condition evaluation.
Java — Loops and Flow Control
▶ Run Code
public class Main {
public static void main(String[] args) {
// Standard For Loop
System.out.print("For iteration: ");
for (int i = 1; i <= 5; i++) {
System.out.print(i + " ");
}
System.out.println();
// While Loop with loop control
System.out.print("While iteration (skipping 3, breaking at 6): ");
int count = 1;
while (count <= 10) {
if (count == 3) {
count++;
continue; // Skip printing 3
}
if (count == 6) {
break; // Exit loop completely
}
System.out.print(count + " ");
count++;
}
System.out.println();
// Do-While loop execution guarantee
int val = 100;
do {
System.out.println("Do-while block runs even though condition is false!");
} while (val < 10);
}
}
3 Code Challenge
Challenge: Write a program that uses a loop to compute the sum of all odd numbers between 1 and 20. Print the final computed sum. Extend it by adding a check inside the loop to skip the number 9 completely using the `continue` keyword.