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). What usually goes wrong. What you see What caused it How to fix it --- --- --- ArrayIndexOutOfBoundsException the moment the grid stops being square The outer loop was bounded by grid[0].length and the inner by grid.length The outer bound is grid.length for rows, the inner is grid[r].length for columns The traversal works on a 3 by 3 grid and fails on a 3 by 5 Swapped bounds hide themselve

Challenge: Print Grid in Row-Major Order