Multiplication Grid (Nested Loops)

easy Programming Basics

Problem

Read n and print an n by n grid. The number in row r and column c is r * c. Separate the numbers in a row with one space.

Constraints

  • 1 <= n <= 12

Examples

Input

4

Output

1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16

Solutions

Best approachTime O(n^2)Space O(n)

The inner loop runs completely for each step of the outer loop, so we get n * n numbers. Row and column are the two loop counters.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Print a multiplication grid.
 * Input   : One integer n.
 * Output  : n lines of n numbers.
 * Approach: A loop inside a loop.
 * Time    : O(n^2)
 * Space   : O(n)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int n = new Scanner(System.in).nextInt();

        // Step 1: The outer loop goes through the rows.
        for (int row = 1; row <= n; row++) {
            StringBuilder line = new StringBuilder();

            // Step 2: The inner loop goes through the columns. It runs completely for every row.
            for (int column = 1; column <= n; column++) {
                // Step 3: Put a space before every number except the first one in the row.
                if (column > 1) {
                    line.append(" ");
                }

                // Step 4: The number is row times column. Example: row 3, column 4 -> 12.
                line.append(row * column);
            }

            // Step 5: Print the finished row.
            System.out.println(line);
        }
    }
}
Hints (1)
  1. What do the two loop counters mean?