0
0
Javaprogramming~5 mins

Nested for loop in Java

Choose your learning style9 modes available
Introduction

A nested for loop lets you repeat actions inside another repeated action. It helps when you want to work with rows and columns or pairs of items.

When printing a table of numbers with rows and columns.
When checking every pair of items in a list.
When drawing patterns like squares or triangles with characters.
When working with grids, like a chessboard or pixel art.
Syntax
Java
for (initialization; condition; update) {
    for (initialization; condition; update) {
        // inner loop code
    }
    // outer loop code
}
The outer loop runs first, then the inner loop runs completely each time the outer loop runs once.
Use different variable names for each loop to avoid confusion.
Examples
This prints pairs of i and j values. The inner loop runs fully for each i.
Java
for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 2; j++) {
        System.out.println("i=" + i + ", j=" + j);
    }
}
This prints a 4x4 square of stars.
Java
for (int row = 1; row <= 4; row++) {
    for (int col = 1; col <= 4; col++) {
        System.out.print("* ");
    }
    System.out.println();
}
Sample Program

This program prints a 3x3 multiplication table. Each row shows multiples of the row number.

Java
public class NestedLoopExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= 3; j++) {
                System.out.print(i * j + " ");
            }
            System.out.println();
        }
    }
}
OutputSuccess
Important Notes

Remember the inner loop finishes all its cycles before the outer loop moves to the next step.

Nested loops can slow down your program if they run many times, so use them wisely.

Summary

Nested for loops run one loop inside another to handle multi-level repetition.

They are useful for working with tables, grids, and pairs of data.

Always keep track of loop variables and their ranges to avoid mistakes.