Home › Learn › Java › Loops

Nested loops

Lesson 14 of 40. A loop inside a loop covers every combination.

A loop inside a loop runs the inner loop completely for every round of the outer one: two loops of 3 and 4 rounds run the inner body 12 times. That is the shape of tables, grids, and "every pair": rows outside, columns inside.

To count pairs without counting each twice, start the inner loop one past the outer index: for (int j = i + 1; ...). Building text row by row, add a newline at the end of each row with "\n".

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

Your task

Write static String grid(int rows, int cols) returning rows lines of cols hash characters, each line ended by \n, so grid(2, 3) is "###\n###\n". Then write static int countPairs(int limit, int target) returning how many pairs of whole numbers i < j, both between 1 and limit, add up to target.

Hint 1

Outer loop over rows, inner over cols adding "#", then result += "\n" after the inner loop.

Hint 2

for (int i = 1; i <= limit; i++) for (int j = i + 1; j <= limit; j++) if (i + j == target) count++;

Show the solution
public class Main {
    static String grid(int rows, int cols) {
        String result = "";
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < cols; c++) {
                result += "#";
            }
            result += "\n";
        }
        return result;
    }

    static int countPairs(int limit, int target) {
        int count = 0;
        for (int i = 1; i <= limit; i++) {
            for (int j = i + 1; j <= limit; j++) {
                if (i + j == target) {
                    count++;
                }
            }
        }
        return count;
    }

    public static void main(String[] args) {
        System.out.print(grid(2, 3));
        System.out.println(countPairs(10, 11));
    }
}

    Compiles with OpenJDK javac and TeaVM, both compiled to WebAssembly (7 MB download the first time, then cached), and runs in this tab; nothing is sent anywhere.