Have students make a multiplication table to practice working with 2D arrays, nested loops, and abstraction using a data construct they’re already familiar with.

  • Activity:

    • Ask students to make a 10-by-10 multiplication table.

      • For example:

int maxValue = 11; // holds table from 0 to 10.
int[][] multiplicationTable = new int[maxValue][maxValue];
for (int row = 0; row < maxValue; row++){
    for (int column = 0; column < maxValue; column++){
        multiplicationTable[row][column] = row * column;
    }
}


  • Ask students to expand their multiplication table to include more values. Here’s code that makes a multiplication table for numbers 0 to 100.

    • For example:

int maxValue = 101; // holds table from 0 to 100.
int[][] multiplicationTable = new int[maxValue][maxValue];
for (int row = 0; row < maxValue; row++){
    for (int column = 0; column < maxValue; column++){
        multiplicationTable[row][column] = row * column;
    }
}
  • Ask students how big they could make their multiplication table?

    • and how hard it would be to make it that big?

  • Point out how the abstraction of the loop allowed them to make really big multiplication tables with very little code changed.

  • Ask students what would happen if you could rewrite the following line, switching the placement of variables in the 2D indices:

    • multiplicationTable[row][column] = row * column;
    • as: multiplicationTable[column][row] = row * column;
    • Use this to introduce the idea that there isn’t a "right" order to put row and column, you just need to make sure that you’re consistent!

  • Extend this activity by having students write code for a multiplication table that isn’t a square.

    • The goal is to get students paying attention to the bounds of the array.

public static int[][] timesTable(int r, int c){
    int [][] mult = new int[r][c];
    for (int row = 0; row < mult.length ; row++){
        for (int column = 0; column < mult[row].length; column++){
            mult[row][column] = (row+1)*(column+1);
        }
    }
    return mult;
}

More about this tip

External Source

Interview with Tammy Pirmann.