In programming, we often need to repeat a task multiple times.
For example, you may want to:
-
Print progress for 7 days
-
Check all completed modules
-
Repeat a menu until the user exits
-
Process multiple test cases
If you write the same statement repeatedly, the code becomes long and difficult to maintain.
This is where loops help.
Loops allow us to execute a block of code repeatedly.
A loop is a control structure that repeats a block of code as long as a condition is satisfied.
Java provides three primary loops:
-
forloop -
whileloop -
do-whileloop
Each loop is useful in different situations.
Loops help in:
-
Reducing repetition
-
Writing shorter code
-
Solving pattern problems
-
Processing arrays and strings
-
Implementing DSA logic
-
Handling repeated input/output
Without loops:
System.out.println(1);
System.out.println(2);
System.out.println(3);
System.out.println(4);
System.out.println(5);This approach is not scalable.
Using a loop is much better.
The for loop is used when the number of iterations is known in advance.
for (initialization; condition; update) {
// code
}Runs only once at the beginning.
int i = 1;Checked before every iteration.
-
If true → loop executes
-
If false → loop stops
Updates the loop variable after each iteration.
i++;public class Main {
public static void main(String[] args) {
for (int day = 1; day <= 5; day++) {
System.out.println(day);
}
}
}1
2
3
4
5
| Iteration | day | Condition | Output |
|---|---|---|---|
| 1 | 1 | True | 1 |
| 2 | 2 | True | 2 |
| 3 | 3 | True | 3 |
| 4 | 4 | True | 4 |
| 5 | 5 | True | 5 |
| 6 | 6 | False | Stop |
for (int value = 2; value <= 10; value += 2) {
System.out.println(value);
}2
4
6
8
10
for (int attempt = 1; attempt <= 3; attempt++) {
System.out.println("Keep practicing");
}Use a for loop when:
-
Number of iterations is known
-
Working with indices
-
Traversing arrays
-
Solving pattern problems
Initialization
↓
Condition Check
↓
Loop Body
↓
Update
↓
Condition Check Again
Repeats until the condition becomes false.
The while loop is used when the number of iterations is not known beforehand.
while (condition) {
// code
}public class Main {
public static void main(String[] args) {
int count = 1;
while (count <= 5) {
System.out.println(count);
count++;
}
}
}1
2
3
4
5
public class Main {
public static void main(String[] args) {
int modulesLeft = 4;
while (modulesLeft >= 1) {
System.out.println("Modules left: " + modulesLeft);
modulesLeft--;
}
}
}Modules left: 4
Modules left: 3
Modules left: 2
Modules left: 1
Use a while loop when:
-
Iterations are unknown
-
Waiting for user input
-
Loop depends on a condition
-
Processing until something becomes false
The do-while loop executes the body at least once.
do {
// code
} while (condition);Notice the semicolon after while(condition).
public class Main {
public static void main(String[] args) {
int revisionRound = 1;
do {
System.out.println("Revision Round: " + revisionRound);
revisionRound++;
} while (revisionRound <= 3);
}
}Revision Round: 1
Revision Round: 2
Revision Round: 3
public class Main {
public static void main(String[] args) {
int score = 10;
do {
System.out.println("This runs once.");
} while (score > 50);
}
}This runs once.
Even though the condition is false, the loop body executes once.
| Feature | while | do-while |
|---|---|---|
| Condition Checked | Before execution | After execution |
| Minimum Executions | 0 | 1 |
| Use Case | Condition-based loops | Menus and prompts |
int x = 10;
while (x > 20) {
System.out.println("Hello");
}Output:
No Output
int x = 10;
do {
System.out.println("Hello");
} while (x > 20);Output:
Hello
Used when you only need the values and not the index.
for (datatype variable : collection) {
// code
}int[] nums = {10, 20, 30};
for (int num : nums) {
System.out.println(num);
}10
20
30
-
Traversing arrays
-
Traversing collections
-
When index is not required
If a loop condition never becomes false, the loop runs forever.
This is called an infinite loop.
while (true) {
System.out.println("This keeps running forever");
}for (;;) {
System.out.println("Infinite loop");
}-
Missing update statement
-
Incorrect condition
-
Variable not changing
Example:
int num = 1;
while (num <= 5) {
System.out.println(num);
}This loop never ends because num++ is missing.
A loop inside another loop is called a nested loop.
Used in:
-
Pattern problems
-
Matrices
-
Grids
-
Table generation
public class Main {
public static void main(String[] args) {
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 3; col++) {
System.out.print("* ");
}
System.out.println();
}
}
}* * *
* * *
* * *
-
Outer loop → Rows
-
Inner loop → Columns
Java provides:
-
break -
continue
Stops the loop immediately.
for (int testCase = 1; testCase <= 6; testCase++) {
if (testCase == 4) {
break;
}
System.out.println(testCase);
}1
2
3
Skips the current iteration and moves to the next one.
for (int day = 1; day <= 5; day++) {
if (day == 3) {
continue;
}
System.out.println(day);
}1
2
4
5
| Situation | Loop |
|---|---|
| Known iterations | for |
| Unknown iterations | while |
| Must execute once | do-while |
| Pattern problems | for |
| Array traversal | for |
| Menu systems | do-while |
Loops are closely related to Time Complexity.
for (int i = 0; i < n; i++)Time Complexity:
O(n)
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)Time Complexity:
O(n²)
for (int i = n; i > 1; i /= 2)Time Complexity:
O(log n)
int i = 1;
while (i <= 5) {
System.out.println(i);
}Results in an infinite loop.
for (int i = 1; i >= 5; i++) {
System.out.println(i);
}Loop never runs.
for (int i = 1; i <= 5; i++);
{
System.out.println("Hello");
}The semicolon ends the loop.
Remember:
while → checks first
do-while → runs first
Prefer:
row
col
i
j
index
countinstead of unclear names.
Loops are used in:
-
Arrays
-
Strings
-
Searching
-
Sorting
-
Pattern Problems
-
Dynamic Programming
-
Matrix Traversal
Strong loop fundamentals make DSA significantly easier.
-
Print numbers from 1 to 10 using a for loop.
-
Print numbers from 10 to 1 using a while loop.
-
Print the first 5 even numbers.
-
Print the multiplication table of 7.
-
Create a menu using do-while.
-
Find the sum of numbers from 1 to n.
-
Print an n × n square pattern.
-
Print odd numbers from 1 to 20 using continue.
-
Stop a loop when the value becomes 6 using break.
Java provides three primary loops:
-
for→ Fixed repetitions -
while→ Condition-based repetitions -
do-while→ At least one execution
Also remember:
-
breakstops a loop -
continueskips an iteration -
Nested loops are used for patterns and grids
-
Missing updates can create infinite loops
Loops are not just another Java topic.
They are one of the strongest foundations of programming.
If conditionals teach your program how to decide,
then loops teach your program how to repeat logic efficiently.
This is why loops appear everywhere:
-
Beginner programs
-
Pattern problems
-
DSA
-
Real-world software systems
Mastering loops forms the bridge between:
Basic Syntax
↓
Logical Programming
↓
Problem Solving
↓
Data Structures & Algorithms