Printing a 2D array

Nested loops walk the grid. Compare printing the whole matrix, a single row, or a single column.

Programming Beginner 2D arrays · Nested loops ~6 min
The idea

Two indices: row and column

A 2D array is a grid. Each value lives at grid[r][c]. To visit cells you usually nest a column loop inside a row loop (row-major order).

Sometimes you only need one row or one column — fix that index and loop over the other.

TipWhole matrix → two loops. One row → fix r. One column → fix c.
IdeaNested visit
matrix_print.pyPython
for r in range(rows):
    for c in range(cols):
        print(grid[r][c])

Grid: 3×3 · Switch modes to compare row vs column vs all.

Interactive

Run the simulation

Blue cell is current. Green cells are already printed. The tray shows output order.

Step 0 / 0
demo.pyPython
Matrix + outputdemo
Ready
Shortcuts: Space play/pause · → step · ← back · R reset
Remember

How 2D printing works

Order depends on which index you fix and which you loop.

All

Outer row, inner column

Row-major order prints left-to-right, top-to-bottom — the usual default.

Row

Fix r, loop c

One horizontal stripe of the grid — perfect for “print row 1”.

Column

Fix c, loop r

One vertical stripe — same idea, different loop shape.