Course contentsShow
← Java
Lesson 170 of 2,8704. Control Flow StructuresFree lesson

Nested for Loops: Processing Multidimensional Data

Write nested loops to iterate over 2D arrays and understand iteration order.

Nested for Loops: Processing Multidimensional Data

You'll learn how to use one loop inside another to work through rows and columns of 2D arrays.

The Core Idea

A nested for loop is simply a loop inside another loop. When you have data organized in rows and columns (like a grid or table), you use the outer loop to move through each row, and the inner loop to move through each item within that row. Think of it like reading a book: the outer loop picks each page (row), and the inner loop reads each line (column) on that page.

Understanding Iteration Order

The outer loop runs completely through the inner loop for each of its iterations. If your outer loop runs 3 times and your inner loop runs 4 times, you'll have 3 × 4 = 12 total iterations.

for (int row = 0; row < 3; row++) {          // Outer loop: rows
    for (int col = 0; col < 4; col++) {      // Inner loop: columns
        System.out.println("Position: row " + row + ", col " + col);
    }
}

This prints positions in order: (0,0), (0,1), (0,2), (0,3), then (1,0), (1,1), and so on. The inner loop completes all its iterations before the outer loop advances once.

Working with 2D Arrays

When processing a 2D array, you use the outer loop index for rows and the inner loop index for columns:

int[][] grid = {{1, 2, 3}, {4, 5, 6}};

for (int i = 0; i < 2; i++) {           // 2 rows
    for (int j = 0; j < 3; j++) {       // 3 columns
        System.out.print(grid[i][j] + " ");
    }
    System.out.println();                // New line after each row
}

Key Takeaway: Nested for loops let you systematically visit every element in multidimensional data by using the outer loop for one dimension and the inner loop for another, always completing all inner iterations before the outer loop advances.