Learn AP Comp Sci

Problem of the Day

Problem:

Consider the following method which prints out values from the two-dimensional array arr.

public static void output(int[][] arr)
{

/* missing code */

}

An array arr is declared and initialized as shown:

int[][] arr = {{0,1,2,3}, {4,5,6,7}, {8,9,10,11}};

Identify the code that will replace /* missing code */ to produce the output

11 7 3 10 6 2 9 5 1 8 4 0

  1. for (int y = arr.length - 1; y > 0; y--)
    {
    for (int x = arr[0].length - 1; x > 0; x--)
    {
    System.out.print(arr[x][y] + " ");
    }
    }

  2. for (int x = arr[0].length - 1; x > 0; x--)
    {
    for (int y = arr.length - 1; y > 0; y--)
    {
    System.out.print(arr[y][x] + " ");
    }
    }

  3. for (int x = arr[0].length - 1; x >= 0; x--)
    {
    for (int y = arr.length - 1; y >= 0; y--)
    {
    System.out.print(arr[y][x] + " ");
    }
    }

  4. for (int y = arr.length - 1; y >= 0; y--)
    {
    for (int x = arr[0].length - 1; x >= 0; x--)
    {
    System.out.print(arr[y][x] + " ");
    }
    }

Show solution:

The correct answer is b. Answer (a) prints out all the values in reverse order , answer (c) produces an ArrayIndexOutOfBoundsException, and answer (d) doesn't include row 0 and column 0 in the output.