LearnFrenzy
Sign in Take a free test

Control Flow · Lesson 11 of 42

Loops: for, while, do-while and for-each

5 min read Updated Nov 7, 2026 Saurabh Samir

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 for loop and its three parts
  • while and do-while
  • The enhanced for-each loop
  • 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);
        }
    }
}

Output

7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35

for (init; condition; update)

  1. int i = 1runs once, before the loop
  2. i <= 5 ?checked before every pass; false ends the loop
  3. bodythe statements in { }
  4. 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);
    }
}

Output

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);
    }
}

Output

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());
        }
    }
}

Output

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?

LoopBest when…
foryou know the number of passes or need an index
for-eachyou visit every element of an array or collection
whileyou repeat until a condition changes
do-whilethe 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();
        }
    }
}

Output

*
* *
* * *
* * * *
   *
  ***
 *****
*******
1
12
123
1234

Practice

Try it yourself

  1. 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;
            }
        }
    }

    Output

    0 1 1 2 3 5 8 13 21 34
  2. 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"));
        }
    }

    Output

    97 is prime
  3. 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();
            }
        }
    }

    Output

    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

  • for for counted loops, for-each for collections, while for unknown counts, do-while for 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.

Next lesson

Popular