Lab 8: Two-dimensional Arrays

Instructions: Follow the steps given in each section below. For each question, click the radio button next to the most correct answer. When you are finished, type your name and your partner at the end of the document, write down your answers for your records, then press the Submit button. You may submit just one lab response. If you submit more than one, only the first one counts for a grade.

Contents

A. Purpose

The purpose of this lab is to become familiar with two-dimensional arrays. By the end of the lab, you should be able to define and use a two-dimensional array in a Java program.

B. What is a Two-dimensional Array?

  1. A two-dimensional array is an array in with both rows and columns. In contrast, gave one dimensional array is simply a linear sequence of elements.

  2. When we define or use a two-dimensional array, we must supply both the row and column numbers. Two-dimensional arrays are good for modeling flat surfaces, for example, the screen of a computer, the layout of a warehouse, or a map. Capital flat surface has two dimensions, and so a two-dimensional array can easily model it.

  3. Java has the ability to define and use arrays with dimensions higher than 2. For example, you can define an array with three dimensions to model physical space, or for dimensions to model physical space with a time dimension. Higher dimensional arrays are common in some applications, such as engineering and physics. However, most applications that use arrays only need one or two-dimensional arrays.

C. Defining a Two-dimensional Array

  1. Defining a two-dimensional array is very similar to defining a one-dimensional array. You simply need to use an extra pair of brackets for the additional dimension. Here's an example.

    int [][] myArray = new int [4][5];
    

  2. This example defines an array of integers. When defining (or using) a two-dimensional array, the first subscript is always the row number, and the second subscript is always the column number.

    Question
    1
    The array myArray has ____ rows and ____ columns.

    1. 4, 5
    2. 4, 4
    3. 5, 4
    4. 5, 5
    5. (not possible to tell)

    Question
    2
    Which of the following is not a valid two-dimensional array definition?

    1. Date [][] ex = new Date [2][100];
    2. long [] yo = new long [3][4];
    3. String [][] thing = new String [10][10];
    4. float [][] why = new float [1][1];
    5. double [][] d = new double [1][2];

  3. Just as we can initialize a one dimensional array, we can also initialize a two-dimensional array. We simply list the values for the array in place of the arrays definition. We must use braces around the values of each row, as well as around all the rows. For example, suppose we want to store this table of floating point numbers in an array.

    3.46.28.19.37.2
    5.52.98.59.81.1

  4. This table has to rows and five columns. We could define and initialize the table with 10 assignment statements like this:

    double [][] array = new double [2][5];
    array[0][0] = 3.4;
    array[0][1] = 6.2;
    array[0][2] = 8.1;
    array[0][3] = 9.3;
    array[0][4] = 7.2;
    array[1][0] = 5.5;
    array[1][1] = 2.9;
    array[1][2] = 8.5;
    array[1][3] = 9.8;
    array[1][4] = 1.1;
    

  5. But an easier and faster way is to initialize the array in its definition, like this:

    double [][] array = {{3.4, 6.2, 8.1, 9.3, 7.2},
                         {5.5, 2.9, 8.5, 9.8, 1.1}};
    

  6. Notice that the first row has its own braces, and the second row has its own braces. We also need braces around both rows.

    Question
    3
    Which of the following array definitions defines an array with three rows and two columns?

    1. int [][] x = {{5, 5}, {5, 5}};
    2. int [][] x = {{5, 5, 5}, {5, 5, 5}};
    3. int [][] x = {{5, 5}, {5, 5}, {5, 5}};
    4. int [][] x = {5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5};
    5. int [][] x = {{5, 5, 5}, {5, 5, 5}, {5, 5, 5}};

D. Accessing Elements of a Two-dimensional Array

  1. We can access an element in a two-dimensional array in much the same way that we access an element in a one dimensional array, but instead of using just one subscript, we must use two.

  2. In this section we'll use the following array definition.

    double [][] array = {{3.4, 6.2, 8.1, 9.3, 7.2},
                         {5.5, 2.9, 8.5, 9.8, 1.1}};
    

  3. Here's what the array looks like conceptually. The row numbers and column numbers are shown in bold font.

    01234
    03.46.28.19.37.2
    15.52.98.59.81.1

  4. Remember that, in a two-dimensional array, the first subscript is always the row number, and the second subscript is always the column number.

  5. Let's change the value of row 0, column 3 to 9.9. Here's how.

    array[0][3] = 9.9;
    

  6. Now let's display the value of row 1, column 2.

    System.out.println(array[1][2]);
    

    Pretty simple, right?

    Question
    4
    Which of the following statements copies the value in the upper left corner of the array to the lower right corner of the array?

    1. array[0][0] = array[4][1];
    2. array[1][4] = array[0][0];
    3. array[4][1] = array[4][0];
    4. array[1][1] = array[1][4];
    5. array[0][4] = array[0][4];

    Question
    5
    Which of the following statements displays the right most value in the first row of the array?

    1. System.out.println(array[4][0]);
    2. System.out.println(array[4][4]);
    3. System.out.println(array[1][5]);
    4. System.out.println(array[0][4]);
    5. System.out.println(array[0][1]);

E. Traversing a Two-dimensional Array

  1. To traverse an array means to visit all the elements of that array. There are several popular traversal techniques:

    • Traversing a single row
    • Traversing a single column
    • Traversing all rows
    • Traversing all columns

  2. As before, we'll use this array in the examples in this section.

    double [][] array = {{3.4, 6.2, 8.1, 9.3, 7.2},
                         {5.5, 2.9, 8.5, 9.8, 1.1}};
    

  3. Here's what the array looks like conceptually. The row numbers and column numbers are shown in bold font.

    01234
    03.46.28.19.37.2
    15.52.98.59.81.1

  4. To traverse a single row, we hold the row number constant, and vary the column number. Here's an example that displays all the values in row 0.

    for (int col = 0; col < array[0].length; col++)
    {
      System.out.print(array[0][col] + " ");
    }
    

  5. Notice that we use array[0].length get the number of columns in row 0.

    Question
    6
    What is array[1].length?

    1. The number of columns in row 1.
    2. The number of rows in the array.
    3. An error.
    4. The number of columns in the array.
    5. The number of columns in row 0.

    Question
    7
    What is array.length?

    1. The number of columns in row 1.
    2. The number of rows in the array.
    3. The number of columns in the array.
    4. The number of columns in row 0.
    5. An error.

    Question
    8
    Which of the following displays the contents of column 2 of the array?

    1. for (int row = 0; row < array[2].length; row++)
      {
        System.out.print(array[2][row] + " ");
      }

    2. for (int row = 0; row < array[2].length; row++)
      {
        System.out.print(array[row][2] + " ");
      }

    3. for (int col = 0; col < 2; row++)
      {
        System.out.print(array[row][col] + " ");
      }

    4. for (int row = 0; row < array.length; row++)
      {
        System.out.print(array[2][col] + " ");
      }

    5. for (int row = 0; row < array.length; row++)
      {
        System.out.print(array[row][2] + " ");
      }

  6. To traverse all the rows of an array, we must use two for statements -- one nested inside the other. The outer for statement controls the row number, and the inner for statement controls the column number.

  7. This example shows how to display the contents of each row of the array.

    for (int row = 0; row < array.length; row++)
    {
      for (int col = 0; col < array[row].length; col++)
      {
        System.out.print(array[row][col] + " ");
      }
      System.out.println();
    }
    

    Question
    9
    How can you change this example so it displays the array column by column, like this?
    3.4 5.5
    6.2 2.9
    8.1 8.5
    9.3 9.8
    7.2 1.1

    1. Switch the order of the for statements
    2. Change the second for statement so it goes from 0 to array[col].length
    3. Change the first for statement so it goes from 0 to array[row].length - 1
    4. Change the first for statement so it goes from 0 to array[col].length
    5. Change from System.out.print(array[row][col] + " "); to System.out.print(array[col][row] + " ");

F. Passing a Two-dimensional Array to a Method

  1. You can pass a two-dimensional array to a method just like any other object type, such as a string. Here's an example of a method that displays the contents of a two-dimensional array of double values.

    static void display(int [][] array)
    {
      for (int row = 0; row < array.length; row++)
      {
        for (int col = 0; col < array[row].length; col++)
        {
          System.out.print(array[row][col] + " ");
        }
        System.out.println();
      }
    }
    

  2. Here's an example of a method that changes all the elements in an array to 9999.

    static void changeArray(int [][] x)
    {
      for (int row = 0; row < x.length; row++)
      {
        for (int col = 0; col < x[row].length; col++)
        {
          x[row][col] = 9999;
        }
      }
    }
    

    Question
    10
    If main() calls this method (changeArray()) on an array, what happens to the array in main() after this method returns?

    1. All the elements of the array have 9999.
    2. The array is completely erased.
    3. There is no change to the array in main().
    4. This code gives a compile-time error.
    5. This code gives a run-time error.

    Sometimes, you'll want to change the array object itself inside a method. Here's an example that tries to do this.

    static void changeArray2(int [][] x)
    {
      x = new int[30][3];
    

    for (int row = 0; row < x.length; row++) { for (int col = 0; col < x[row].length; col++) { x[row][col] = -1; } } }

    Question
    11
    If main() calls this method (changeArray2()) on an array, what happens to the array in main() after this method returns?

    1. There is no change to the array in main().
    2. The array is completely erased.
    3. All the elements of the array have -1.
    4. This code gives a compile-time error.
    5. This code gives a run-time error.

    Question
    12
    How can you change method changeArray2() so main() gets the new array after changeArray2() finishes?

    1. Add a return statement and change the return type to int.
    2. Add a return statement and change the return type to int [][].
    3. No change is necessary.
    4. Change the return type to int [][].
    5. Change the return type to int.

G. Copying an Array

  1. There are several ways to copy an array. One way to copy an array is to assign the array to another array variable. Here's an example.
  2. // The original array
    int[] original = {5, 3, 7, 6, 1, 2};
    

    // Copy the original int[] copy = original; ...

  3. Copying an array like this is simple -- almost too good to be true! Well, it is too good to be true. The result is not two arrays with the same values, but one array with two names. (Some languages, such as Pascal, do allow copying an array like this, but it doesn't work with Java.) Program CopyArrayWithAssignment.java contains the same code as above, but is fleshed out with some System.out.println() statements and a couple of assignments to show what's going on.
  4. CopyArrayWithAssignment.javaDownload (Help)
    // Assign one array to another with assignment operator
    
    public class CopyArrayWithAssignment
    {
      public static void main(String[] args)
      {
        // The original array
        int[] original = {5, 3, 7, 6, 1, 2};
    
        // Display the original
        System.out.print("Contents of original array: ");
        for (int i = 0; i < original.length; i++)
        {
          System.out.print(original[i] + " ");
        }
        System.out.println();
    
        // Copy the original
        int[] copy = original;
    
        // Verify that we have a copy
        System.out.print("Contents of copy: ");
        for (int i = 0; i < copy.length; i++)
        {
          System.out.print(copy[i] + " ");
        }
        System.out.println();
    
        System.out.println("Changing contents of both arrays");
        // Change a value in the original array
        original[0] = 12345;
    
        // Change a value in the copy
        copy[1] = 67890;
    
        // Display the original
        System.out.print("New contents of original array: ");
        for (int i = 0; i < original.length; i++)
        {
          System.out.print(original[i] + " ");
        }
        System.out.println();
    
        // Display the copy
        System.out.print("New contents of copy: ");
        for (int i = 0; i < copy.length; i++)
        {
          System.out.print(copy[i] + " ");
        }
        System.out.println();
      }
    }
    CopyArrayWithAssignment.javaDownload (Help)

  5. Download program CopyArrayWithAssignment.java, then compile and run the program..
  6. Question
    13
    After assigning one array to another (with the assignment operator), what happens if we change a value in the original array?

    1. The change appears in the copy as well.
    2. The change doesn't affect the copy.

  7. The first two lines of the output of CopyArrayWithAssignment.java show that the copy was apparently successful. The copy has the same array contents as the original. However, the last two lines show what's really going on -- the "two" arrays are actually the same array! Changing a value in either original or copy changes the other one as well. Both original and copy are names referring to the same array object.
  8.          +------+      +------+------+------+------+------+------+
    original |   ---+----> |   5  |   3  |   7  |   6  |   1  |   2  |
             +------+  +-> +------+------+------+------+------+------+
                       |       0      1      2      3      4      5
             +------+  |
        copy |   ---+--+
             +------+

  9. Assigning an array object to another variable simply makes that variable refer to the same array object. It doesn't make a copy of the array.
  10. The easiest way to copy an array is to use the System.arraycopy() method. This method takes 5 arguments:
  11. Here's how to make a copy of the original array in CopyArrayWithAssignment.java. First, allocate enough space for the copy.
  12. int[] copy = new int[original.length];

    Question
    14
    What is original.length in the example above?

    1. The number of elements in the array original.
    2. The size of each element in the array original.
    3. The number of values retrieved from the array original.
    4. The number of values assigned to the array original.
    5. 19

  13. Next, use System.arraycopy() to copy the contents of original to copy. The source is original, starting at location 0. The destination is copy, also starting at location 0. The number of elements we want to copy is original.length.
  14. System.arraycopy(original, 0, copy, 0, original.length);

    Question
    15
    What would happen if we wrote the previous statement as
    System.arraycopy(copy, 0, original, 0, copy.length);

    1. There would be no change -- either way works the same.
    2. The program would stop with a run-time error.
    3. The computer would copy the values from the array copy to the array original, destroying the values in original.
    4. The computer would copy the values from the array original to the array copy, destroying the values in copy.
    5. The program would not compile.

  15. Make these two changes to CopyArrayWithAssignment.java, then compile and run the program.
  16. Question
    16
    After making these two changes to CopyArrayWithAssignment.java, did the program make a complete (and separate) copy of the original array?

    1. No
    2. Yes


Turn in this Assignment

First name:
Last name:
Partner's last name:

Write down your answers for your records, then press the Submit button below to turn in the lab assignment.