Control Flow · Lesson 11 of 42
Loops: for, while, do-while and for-each
Loops let a program repeat work: process every order, retry a payment, print a report row for each student. Java has four loops, and choosing the right one makes code clearer. This lesson also covers the nested-loop patterns that appear in nearly every fresher coding test.
In this lesson
- The
forloop and its three parts whileanddo-while- The enhanced
for-eachloop - Nested loops and pattern programs
The for loop
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("7 x " + i + " = " + 7 * i);
}
}
}
7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35
for (init; condition; update)
- int i = 1runs once, before the loop
- i <= 5 ?checked before every pass; false ends the loop
- bodythe statements in { }
- i++runs after each pass, then back to the check
Any part can be different: count down with i--, step by 2 with i += 2, or use two variables for (int i = 0, j = n - 1; i < j; i++, j--) – the two-pointer technique used in many interview problems.
The while loop
Use while when you don't know in advance how many passes you need – you only know when to stop:
public class Main {
public static void main(String[] args) {
double savings = 10000;
int months = 0;
while (savings < 20000) {
savings *= 1.01; // 1% per month
months++;
}
System.out.printf("Doubled in %d months (₹%.0f)%n", months, savings);
}
}
Doubled in 70 months (₹20068)
Common mistake: the infinite loop
If nothing inside the loop changes the condition, it never ends. Forgetting months++ or i++ is the usual cause. In an IDE press the red stop button; in a terminal press Ctrl+C.
The do-while loop
do-while checks the condition after the body, so the body always runs at least once. It fits menus and "ask until valid" input:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int choice;
do {
System.out.print("1) Balance 2) Deposit 3) Exit > ");
choice = sc.nextInt();
switch (choice) {
case 1 -> System.out.println("Balance: ₹5000");
case 2 -> System.out.println("Deposited");
case 3 -> System.out.println("Goodbye");
default -> System.out.println("Invalid option");
}
} while (choice != 3);
}
}
1) Balance 2) Deposit 3) Exit > 1 Balance: ₹5000 1) Balance 2) Deposit 3) Exit > 9 Invalid option 1) Balance 2) Deposit 3) Exit > 3 Goodbye
The for-each loop
For walking through every element of an array or collection, the enhanced for is cleaner and avoids index mistakes:
import java.util.List;
public class Main {
public static void main(String[] args) {
int[] marks = {78, 92, 65, 88};
int total = 0;
for (int m : marks) {
total += m;
}
System.out.println("Average: " + (double) total / marks.length);
List<String> cities = List.of("Pune", "Delhi", "Chennai");
for (String city : cities) {
System.out.println(city.toUpperCase());
}
}
}
Average: 80.75 PUNE DELHI CHENNAI
Use a classic for instead when you need the index, want to go backwards, or need to modify array elements by position.
Which loop?
| Loop | Best when… |
|---|---|
for | you know the number of passes or need an index |
for-each | you visit every element of an array or collection |
while | you repeat until a condition changes |
do-while | the body must run at least once (menus, retries) |
Nested loops and patterns
The inner loop completes fully for every pass of the outer loop. Pattern questions test whether you can turn a picture into rules: what does row r contain?
public class Main {
public static void main(String[] args) {
int n = 4;
// Right triangle
for (int r = 1; r <= n; r++) {
for (int c = 1; c <= r; c++) System.out.print("* ");
System.out.println();
}
// Pyramid: n - r spaces, then 2r - 1 stars
for (int r = 1; r <= n; r++) {
System.out.println(" ".repeat(n - r) + "*".repeat(2 * r - 1));
}
// Number triangle
for (int r = 1; r <= n; r++) {
for (int c = 1; c <= r; c++) System.out.print(c);
System.out.println();
}
}
}
* * * * * * * * * * * *** ***** ******* 1 12 123 1234
Practice
Try it yourself
Print the first 10 Fibonacci numbers.
Show solution
public class Main { public static void main(String[] args) { long a = 0, b = 1; for (int i = 0; i < 10; i++) { System.out.print(a + " "); long next = a + b; a = b; b = next; } } }0 1 1 2 3 5 8 13 21 34
Check whether 97 is prime using a loop up to its square root.
Show solution
public class Main { public static void main(String[] args) { int n = 97; boolean prime = n > 1; for (int d = 2; (long) d * d <= n; d++) { if (n % d == 0) { prime = false; break; } } System.out.println(n + (prime ? " is prime" : " is not prime")); } }97 is prime
Print Floyd's triangle with 4 rows (1 / 2 3 / 4 5 6 / 7 8 9 10).
Show solution
public class Main { public static void main(String[] args) { int num = 1; for (int r = 1; r <= 4; r++) { for (int c = 1; c <= r; c++) System.out.print(num++ + " "); System.out.println(); } } }1 2 3 4 5 6 7 8 9 10
Quick check
How many times does do { … } while (false); run its body?
Once – do-while checks the condition after the body.
Can you change array elements through a for-each variable?
No. The loop variable is a copy of each element; use an index-based for loop to modify the array.
How many lines does for (int i = 0; i < 3; i++) for (int j = 0; j < 4; j++) System.out.println(); print?
12 (3 × 4).
Summary
forfor counted loops,for-eachfor collections,whilefor unknown counts,do-whilefor at-least-once.- Make sure something inside the loop moves it towards the end.
- For patterns, describe each row as a formula of the row number.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.