Loop Statements in Java: While, Do-While, and For Loop Explained
Loop Statements in Java
Loop statements in Java are used to execute a block of code repeatedly as long as a given condition is true.
They help reduce code duplication and make programs efficient.
Java provides three types of loop statements:
- While Loop
- Do-While Loop
- For Loop
1. While Loop
✅ Definition
The while loop executes a block of code only if the condition is true.
The condition is checked before executing the loop body.
🔹 Syntax
while (condition) {
// loop body
}
🌍 Real-Life Example
Checking mobile battery level
→ While battery is not full, keep charging.
📊 Flowchart (While Loop)
Start
|
v
Check Condition
(true?)
|
┌──┴──┐
Yes No
| |
Execute End
Body
|
└───↺
🧠 Example Code
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
2. Do-While Loop
✅ Definition
The do-while loop executes the loop body at least once, even if the condition is false.
The condition is checked after the loop body.
🔹 Syntax
do {
// loop body
} while (condition);
🌍 Real-Life Example
ATM transaction screen
→ The menu is shown at least once before checking user choice.
📊 Flowchart (Do-While Loop)
Start
|
v
Execute Body
|
v
Check Condition
(true?)
|
┌──┴──┐
Yes No
| |
↺ End
🧠 Example Code
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 5);
3. For Loop
✅ Definition
The for loop is used when the number of iterations is known in advance.
🔹 Syntax
for (initialization; condition; increment/decrement) {
// loop body
}
🌍 Real-Life Example
Attendance counting in a class
→ Count students from roll number 1 to 50.
📊 Flowchart (For Loop)
Start
|
v
Initialization
|
v
Check Condition
(true?)
|
┌──┴──┐
Yes. No
| |
Execute End
Body
|
Increment
|
└───↺
🧠 Example Code
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
Comments
Post a Comment