Java Loops (for, while, do while)
A loop allows a block of code to be executed repeatedly as long as a certain condition is true. Instead of writing the same code multiple times, loops automate repetitive tasks. Java provides three main types of loops: for, while, and do-while.
1. The for Loop
The for loop is best used when the number of iterations (repetitions) is known in advance. It combines the initialization, condition, and update all in one line.
Syntax
for (initialization; condition; update) {
// code to repeat
}- initialization: Runs once at the start. Usually declares and initializes a counter variable.
- condition: Checked before each iteration. The loop runs as long as this is true.
- update: Runs after each iteration. Usually increments or decrements the counter.
Example – Print Numbers 1 to 5
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5Example – Sum of First 10 Numbers
int sum = 0;
for (int i = 1; i <= 10; i++) {
sum += i;
}
System.out.println("Sum = " + sum); // Sum = 55Example – Loop Backwards
for (int i = 5; i >= 1; i--) {
System.out.print(i + " ");
}Output:
5 4 3 2 1 2. The while Loop
The while loop is best used when the number of iterations is not known in advance. It keeps repeating as long as the condition remains true. The condition is checked before each iteration.
Syntax
while (condition) {
// code to repeat
}Example – Count Down from 5
int count = 5;
while (count > 0) {
System.out.println("Count: " + count);
count--;
}Output:
Count: 5
Count: 4
Count: 3
Count: 2
Count: 1Example – Read Input Until User Types "exit"
import java.util.Scanner;
public class WhileInput {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = "";
while (!input.equals("exit")) {
System.out.print("Enter a word (or 'exit' to stop): ");
input = sc.nextLine();
System.out.println("You entered: " + input);
}
System.out.println("Loop ended.");
sc.close();
}
}Infinite Loop Warning
If the condition in a while loop never becomes false, the loop runs forever. This is called an infinite loop.
// Dangerous: infinite loop
while (true) {
System.out.println("This never stops...");
}Always make sure the condition will eventually become false, or use a break statement.
3. The do-while Loop
The do-while loop is similar to the while loop, but with one key difference: the body of the loop runs at least once regardless of the condition, because the condition is checked after each iteration.
Syntax
do {
// code to repeat
} while (condition);Example – Ask for a Valid Number
import java.util.Scanner;
public class DoWhileDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int number;
do {
System.out.print("Enter a positive number: ");
number = sc.nextInt();
} while (number <= 0);
System.out.println("You entered: " + number);
sc.close();
}
}Sample Interaction:
Enter a positive number: -3
Enter a positive number: 0
Enter a positive number: 7
You entered: 7The loop keeps asking until a valid (positive) number is entered.
The Enhanced for Loop (for-each)
Java provides a simplified loop for iterating over arrays and collections. It is called the enhanced for loop or for-each loop.
Syntax
for (dataType element : arrayOrCollection) {
// use element
}Example
int[] numbers = {10, 20, 30, 40, 50};
for (int num : numbers) {
System.out.println(num);
}Output:
10
20
30
40
50Loop Control Statements
break
The break statement immediately exits the loop, even if the condition is still true.
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // stop the loop when i reaches 5
}
System.out.print(i + " ");
}Output:
1 2 3 4 continue
The continue statement skips the current iteration and moves to the next one.
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // skip even numbers
}
System.out.print(i + " ");
}Output:
1 3 5 7 9 Nested Loops
A loop inside another loop is called a nested loop. The inner loop completes all its iterations for each single iteration of the outer loop.
Example – Multiplication Table
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.print(i * j + "\t");
}
System.out.println();
}Output:
1 2 3
2 4 6
3 6 9 Comparison of Loops
| Loop Type | Use When | Condition Checked |
|---|---|---|
| for | Number of iterations is known | Before each iteration |
| while | Number of iterations is unknown | Before each iteration |
| do-while | Loop must run at least once | After each iteration |
| for-each | Iterating over arrays or collections | Internally managed |
Summary
- Loops repeat a block of code multiple times.
- The
forloop is ideal when the number of repetitions is known. - The
whileloop continues as long as a condition is true, with the condition checked first. - The
do-whileloop runs at least once because the condition is checked after the body. - The enhanced
for-eachloop simplifies iteration over arrays and collections. breakexits the loop early;continueskips to the next iteration.
