Row-Major Order and Dimensions

Part of: 2D Array

Row-Major Order Java stores and processes 2D arrays in row-major order : you finish all the columns of row 0 before moving to row 1, then row 2, and so on. When you traverse a grid with nested loops, the outer loop walks the rows and the inner loop walks the columns of the current row. The values come out in the order 1 2 3 4 5 6, row 0 first, then row 1. That ordering is exactly what row-major means. Finding the Dimensions You rarely hard-code the size. Instead you ask the array for its dimensions: - arr.length is the number of rows (length of the outer array). - arr[0].length is the number of columns (length of a single row). Why This Matters Using .length makes your loops work for any size grid: - The outer bound is m.length (rows). - The inner bound is m[r].length or m[0].length (columns). A frequent mistake is swapping these bounds, which throws an ArrayIndexOutOfBoundsException whenever the grid is not square. Because the AP exam uses only rectangular arrays, m[0].length always equals m[r].length, but writing m[r].length is the most robust habit. Remember: outer = rows, inner = columns, row-major = rows first.

Challenge: Print Grid in Row-Major Order