β What Are Loops?
Loops let you repeat a block of code multiple times.
They are used when you want to run the same code until a condition is false.
π for Loop
Used when the number of iterations is known.
πΈ Syntax:
for(initialization; condition; update) {
// code to repeat
}πΈ Code Example:
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}Count: 1
Count: 2
Count: 3
Count: 4
Count: 5π Why use it?
When you know exactly how many times you want to loop.
β³ while Loop
Used when the condition is checked before every iteration.
Ideal for situations where you donβt know how many times you'll loop.
πΈ Code Example:
int i = 1;
while (i <= 3) {
System.out.println("i = " + i);
i++;
}i = 1
i = 2
i = 3π Why use it?
When you want to loop based on a condition being true.
π do-while Loop
Same as while loop, but it runs at least once, even if the condition is false.
πΈ Code Example:
int i = 1;
do {
System.out.println("Value is: " + i);
i++;
} while (i <= 2);Value is: 1
Value is: 2π Why use it?
Use when the code should execute at least once, no matter what.
π Comparison Table: for, while, do-while Loops in Java
Feature |
|
|
|
|---|---|---|---|
Control Type | β Entry-controlled | β Entry-controlled | β Exit-controlled |
When condition is checked? | β Before the loop starts | β Before the loop starts | β After the loop executes once |
Minimum executions | 0 times (may not run at all) | 0 times (may not run at all) | At least once (even if condition is false) |
Use case | When number of iterations is known | When number of iterations is unknown | When loop must run at least once |
Syntax |
|
|
|
Entry-controlled = Condition first, body later β may not run at all.
Exit-controlled = Body first, condition later β runs at least once.