Chapter 3 · Data

Nested loops and 2D arrays

You are reading the whole lesson on one page. Back to one step at a time

Step 1 of 18 · Concept

A loop inside a loop

A loop's block can hold another loop. The inner loop then runs all its rounds for each round of the outer loop.

for (int row = 1; row <= 2; row++) {
    for (int col = 1; col <= 3; col++) {
        System.out.print(row * col + " ");
    }
    System.out.println();
}

Rows and columns are the classic case: the outer loop goes down the rows, the inner loop along one row.

public class Table {
    public static void main(String[] args) {
        for (int row = 1; row <= 5; row++) {
            for (int col = 1; col <= 5; col++) {
                System.out.printf("%4d", row * col);
            }
            System.out.println();
        }
    }
}
public class Table {
    public static void main(String[] args) {
        for (int row = 1; row <= 5; row++) {
            for (int col = 1; col <= 5; col++) {
                System.out.printf("%4d", row * col);
            }
            System.out.println();
        }
    }
}
public class Triangle {
    static void triangle(int n) {
        // n rows; row 1 has one *, row n has n
    }

    public static void main(String[] args) {
        triangle(2);
        System.out.println();
        triangle(3);
    }
}
public class Grid {
    public static void main(String[] args) {
        int[][] grid = {
            {1, 2, 3, 4},
            {5, 6, 7, 8},
            {9, 10, 11, 12}
        };
        System.out.println("Rows: " + grid.length);
        System.out.println("Columns: " + grid[0].length);
        System.out.println("Row 1, column 2: " + grid[1][2]);

        for (int r = 0; r < grid.length; r++) {
            for (int c = 0; c < grid[0].length; c++) {
                System.out.printf("%4d", grid[r][c]);
            }
            System.out.println();
        }

        int[][] empty = new int[2][3];
        System.out.print(empty.length + " rows of ");
        System.out.println(empty[0].length + " zeros");
    }
}
public class Totals {
    // the sum of the numbers in one row
    static int rowTotal(int[][] grid, int row) {
        return 0;
    }

    // the sum of the numbers in one column
    static int columnTotal(int[][] grid, int col) {
        return 0;
    }

    public static void main(String[] args) {
        int[][] sales = {
            {3, 5, 2},
            {4, 0, 6},
            {1, 7, 3},
            {2, 2, 2}
        };
        for (int r = 0; r < sales.length; r++) {
            int week = r + 1;
            int total = rowTotal(sales, r);
            System.out.println("Week " + week + ": " + total);
        }
        for (int c = 0; c < sales[0].length; c++) {
            int shop = c + 1;
            int total = columnTotal(sales, c);
            System.out.println("Shop " + shop + ": " + total);
        }
    }
}
public class Board {
    static void print(char[][] board) {
        for (int r = 0; r < board.length; r++) {
            for (int c = 0; c < board[0].length; c++) {
                System.out.print(board[r][c]);
                if (c < board[0].length - 1) {
                    System.out.print("|");
                }
            }
            System.out.println();
            if (r < board.length - 1) {
                System.out.println("-+-+-");
            }
        }
    }

    public static void main(String[] args) {
        char[][] board = {
            {'X', 'O', ' '},
            {' ', 'X', ' '},
            {'O', ' ', ' '}
        };
        board[2][2] = 'X';
        print(board);
    }
}
public class Winner {
    // true when mark fills a whole row, a whole
    // column, or one of the two diagonals
    static boolean wins(char[][] board, char mark) {
        return false;
    }

    // "X wins", "O wins" or "No winner"
    static String result(char[][] board) {
        return "";
    }

    public static void main(String[] args) {
        char[][] a = {{'X', 'X', 'X'},
                      {'O', 'O', ' '},
                      {' ', ' ', ' '}};
        char[][] b = {{'O', 'X', ' '},
                      {'O', 'X', ' '},
                      {'O', ' ', 'X'}};
        char[][] c = {{'X', 'O', 'O'},
                      {' ', 'X', ' '},
                      {'O', ' ', 'X'}};
        char[][] d = {{' ', 'O', 'X'},
                      {' ', 'X', 'O'},
                      {'X', ' ', 'O'}};
        char[][] e = {{'X', 'O', 'X'},
                      {'X', 'O', 'O'},
                      {'O', 'X', 'X'}};
        System.out.println(result(a));
        System.out.println(result(b));
        System.out.println(result(c));
        System.out.println(result(d));
        System.out.println(result(e));
    }
}
public class Rows {
    public static void main(String[] args) {
        int[][] scores = {
            {7, 9},
            {4},
            {8, 6, 10}
        };
        for (int r = 0; r < scores.length; r++) {
            int sum = 0;
            for (int c = 0; c < scores[0].length; c++) {
                sum += scores[r][c];
            }
            System.out.println("Row " + r + ": " + sum);
        }
    }
}
Terminal
Step 1 of 8A multiplication table

Keyboard shortcuts

The step

ContinueEnter
Previous / next stepAlt+[ · Alt+]
Move along the steps bar← → Home End, then Enter
From a quiz's title to its answers↓
Skip to the stepTab, then Enter (first on the page)
Course outlineAlt+O
These shortcuts?

The workspace

Run the stepCtrl+Enter (⌘↵ on a Mac)
Lesson → editor → consoleF6 (Shift+F6 back)
Output ↔ TerminalCtrl+`
Focus the editorCtrl+. (⌘. on a Mac)
Hide or show the lessonAlt+L
Restore, close a messageEsc (outside the editor and the terminal)

The editor

Leave the editorF6 (Shift+F6 back); or Ctrl+M (⌃⇧M on a Mac), then Tab moves the focus (not in the vim mode)
Open a file by nameCtrl+P (⌘P on a Mac)
All commandsCtrl+Shift+P (⌘⇧P on a Mac) or F1
Go to a lineCtrl+G (⌃G on a Mac)
Show or hide the filesCtrl+B (⌘B on a Mac)
Previous / next file tabCtrl+Shift+[ · Ctrl+Shift+] (⌘⇧[ · ⌘⇧] on a Mac)
The file tabs← → Home End on a tab; Delete closes it
Save the files nowCtrl+S (⌘S on a Mac)
Go to a symbol in the fileCtrl+Shift+O (⌘⇧O on a Mac)
Go to the definitionF12
Format the fileCtrl+Shift+F (⌘⇧F on a Mac), or Shift+Alt+F
Go back / forward after a jumpAlt+← · Alt+→ (⌃- · ⌃⇧- on a Mac)