Two Dimensional Arrays

This chapter expands our discussion on one-dimensional arrays to two dimensional arrays. A two dimensional array is a data structure that contains a collection of cells laid out in a two dimensional grid, similar to a table with rows and columns although the values are still stored linearly in memory. Each cell in a two dimensional array can be accessed through two indexes that specify the row number and column number respectively. Like s one dimensional array, the range of each index is from zero to the size of the row or column minus one. A nested for loop is commonly used to initialize, manipulate, and access the values in a two dimensional array.

14. Printing a 2D Array


Answer:

  • How many rows must be printed?
    • 3
  • How many cells in each row must be printed?
    • 3 for row 0
    • 2 for row 1
    • 5 for row 3

Printing a 2D Array

Here is a program that creates a 2D array, then prints it out.

The nested loops are written to print out the correct number of cells for each row. The expression uneven[row].length evaluates to a different integer for each row of the array.


Annotation 2020-03-26 211728class unevenExample3 { public static void main( String[] arg ) { // declare and construct a 2D array int[][] uneven = { { 1, 9, 4 }, { 0, 2}, { 0, 1, 2, 3, 4 } }; // print out the array for ( int row=0; row < uneven.length; row++ ) { System.out.print("Row " + row + ": "); for ( int col=0; col < uneven[row].length; col++ ) System.out.print( uneven[row][col] + " "); System.out.println(); } } }


Question 14:

For the print method to work, must every row of uneven be non-null?