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.
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.
for (initialization; condition; update) { for (initialization; condition; update) { // inner loop code } // outer loop code }
for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 2; j++) { System.out.println("i=" + i + ", j=" + j); } }
for (int row = 1; row <= 4; row++) { for (int col = 1; col <= 4; col++) { System.out.print("* "); } System.out.println(); }
This program prints a 3x3 multiplication table. Each row shows multiples of the row number.
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(); } } }
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.
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.
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
// code
}
}for (int i = 1; i <= 2; i++) {
for (int j = 1; j <= 3; j++) {
System.out.print(i * j + " ");
}
System.out.println();
}for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
System.out.println(i + j);
}
}Pass the test and this pattern moves unknown