Skip to content

Column Major

  • Lesson
  • 2 min read
  • 4 of 4 in this chapter

What is Column Major?

Column Major is a way to iterate through 2D Arrays, allowing us to iterate by the arrays inside a 2D Array. We iterate by the row, as seen in the image below.

image

This is how it works:

  • Open column 0, then arrays [0],[1],[2]
  • Open column 1, then arrays [0],[1],[2]
  • Open column 2, then arrays [0],[1],[2]
  • Open column 3, then arrays [0],[1],[2]
  • Open column 4, then arrays [0],[1],[2]

It goes one array at a time, going into the traditional iteration we know.

Here's how we would do it in Java:

Java
int[][] values = {{-34,17,25,16,-2},{13,-4,12,8,15},{-21,6,2,3,14}};

for (int col = 0 ; col < values[0].length; col++) {
  System.out.println("Column " + col); // prints the column
  for (int row = 0; row < values.length; row++) {
    System.out.println(values[row][col]); // prints the item
  }
}

In Column Major, we use the first for loop to iterate through the indexes of the items in the arrays. In values[0], values[1], and values[2] we have 5.

Next, we use another for loop to iterate through the arrays and print the values/items in each array.

When you run the program, you will see 5 columns, each with 3 values. That matches the picture above but differs from Row Major.

Row Major printed 3 rows, each with 5 values.