Working with Columns

Part of: 2D Array

Columns Are Different. A column is a vertical slice of the grid: the cells grid[0][c], grid[1][c], grid[2][c], and so on for a fixed column c. Unlike a row, a column is not a single Java array, there is no grid[][c] shortcut. To process one column you must fix the column index c and loop over the row index r. The Loop Order Flips. The big idea: for column-wise processing the outer loop is the column and the inner loop is the row : the reverse of row-major traversal. - Row-wise: for r { for c { grid[r][c] } } - Column-wise: for c { for r { grid[r][c] } } In both cases the cell access is still grid[r][c], only the loop order changes. The outer bound is grid[0].length (number of columns) and the inner bound is grid.length (number of rows). What usually goes wrong. What you see What caused it How to fix it --- --- --- The column totals are actually the row totals The outer loop walked rows, which is row-wise traversal For column-wise work the outer loop holds c while the inner loop varies r ArrayIndexOutOfBoundsException on any grid that is not square The outer loop over columns used grid.length as its bound The column count is grid[0].length, not grid.length grid[][c] will not compile

Challenge: Largest Column Sum