What is a Loop?
A loop is a programming structure that repeats a sequence of instructions until a specific condition is met. It saves time, reduces errors, and makes the code more readable.
1. The For Loop
The For Loop is best used when you know the exact number of iterations required.
Syntax: for (initialization; condition; update) { // body }
for (int i = 1; i <= 3; i++) {
System.out.println("Counting: " + i);
}
// Output:
Counting: 1
Counting: 2
Counting: 3
2. The While Loop
The While Loop checks the condition before executing the code block. If the condition is false at the start, the code never runs.
Syntax: while (condition) { // code; update; }
int count = 10;
while (count > 7) {
System.out.println("Countdown: " + count);
count--;
}
The Do-While Loop is unique because it executes the body first, and then checks the condition. This guarantees the loop runs at least once.
Syntax: do { // code } while (condition);
int x = 100;
do {
System.out.println("Value of x: " + x);
x++;
} while (x < 10);
// Output:
Value of x: 100
Key Difference: Use while when the condition is primary. Use for when the counter is primary. Use do-while when the action must happen at least once (like showing a menu).