Introduction to 2D Arrays and Printing Values

  • A 2D array is a matrix with rows and columns.
  • In programming, 2D arrays are often used to represent tables of values.

Row-Major Order:

  • In row-major order, elements in each row are stored together in memory.
  • Rows are stored consecutively, making it efficient for row-wise access.

Column-Major Order:

  • In column-major order, elements in each column are stored together in memory.
  • Columns are stored consecutively, making it efficient for column-wise access.

The choice between row-major and column-major order depends on the specific requirements of the program.

Printing Values in Row-Major Order:

public class RowMajor {
    public static void rowMajor(int[][] array) {
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[0].length; j++) {
                System.out.print(array[i][j] + " ");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        int[][] myArray = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };
        rowMajor(myArray);
    }
}

Printing Values in Column-Major Order:

public class ColumnMajor {
    public static void columnMajor(int[][] array) {
        for (int j = 0; j < array[0].length; j++) {
            for (int i = 0; i < array.length; i++) {
                System.out.print(array[i][j] + " ");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        int[][] myArray = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };
        columnMajor(myArray);
    }
}

Hacks

  • Practice printing values in a 2D array using both rowmajor and columnmajor order in Java.

  • Create a 2D array using the following values

{ {71, 72, 73}, {81, 82, 83}, {91, 92, 93} }

  • Modify the printRowMajor and printColumnMajor methods to print the values in both row-major and column-major order for this new array.
//Add 2D array HACK here