Java Loops: for, while, do-while
What Are Loops?
In programming, loops are used to repeat a block of code multiple times.
For example: printing numbers 1 to 10, repeating a game level, checking user input until correct.
Types of Loops in Java
Loop Type | When to Use |
for | When you know how many times to repeat |
while | When you don’t know how many times, but have a condition |
do-while | When the loop should run at least once, no matter what |
for Loop Syntax
for (initialization; condition; update) {
// code to repeat
}Initialization: start value (e.g. int i = 1;)
Condition: loop runs while this is true (i <= 10)
Update: value change after each loop (i++)
Example – Print Numbers 1 to 5
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}1 2 3 4 5
Example – Sum of Numbers
int sum = 0;
for (int i = 1; i <= 5; i++) {
sum = sum + i;
}
System.out.println("Sum = " + sum);Sum = 15
while Loop Syntax
while (condition) {
// code to repeat
}Checks the condition before running the loop.
If condition is false at the start, the loop doesn’t run at all.
Example – while Loop
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}1 2 3 4 5
do-while Loop Syntax
do {
// code to repeat
} while (condition);This loop runs at least once, even if the condition is false.
The condition is checked after the loop runs once.
Example – do-while Loop
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 5);1 2 3 4 5
Example – Condition False but Still Runs Once
int i = 6;
do {
System.out.println("Number: " + i);
i++;
} while (i <= 5);Number: 6
Comparison Table
Feature | for | while | do-while |
Condition checked | Before loop | Before loop | After loop |
Executes at least once? | No | No | Yes |
When to use | When loop count known | When condition-based repetition | When you want code to run once minimum |
Common use | Counting, arrays | Waiting for input | Menu-based programs |
Nested Loops
A loop inside another loop is called a nested loop. Useful for printing patterns or tables.
Multiplication Table
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.println(i + " × " + j + " = " + (i * j));
}
}Infinite Loops
If you forget to change the variable or use the wrong condition, the loop never ends.
while (true) {
System.out.println("This will run forever!");
}Practice Exercises
Print numbers 1–10 using a for loop.
Print even numbers between 1 and 20 using while.
Find the factorial of a number using a for loop.
Use do-while to ask a user for input until they type "exit".
Print a simple triangle pattern using nested loops.