---
title: "Matrices in Programming: Rows, Columns, Nested Loops and Diagonals: Programming Fundamentals (11)"
date: "2026-10-25"
description: "Learn two dimensional arrays: declare a matrix, load and print it with nested loops, add two matrices, sum its diagonals and build its transpose."
tags: ["Programming Fundamentals", "Tutorials"]
url: "https://rolandoandrade.me/blog/programming-fundamentals-matrices/"
author: "Rolando Andrade"
---

# Matrices in Programming: Rows, Columns, Nested Loops and Diagonals: Programming Fundamentals (11)

> Learn two dimensional arrays: declare a matrix, load and print it with nested loops, add two matrices, sum its diagonals and build its transpose.

A matrix is an array with two dimensions: rows and columns, like a table. You pick one box with two indexes, the row first and then the column, like `grid[2, 3]`. In this lesson you declare a matrix, fill it and print it with two nested loops, add two matrices, sum the diagonals of a square matrix and turn rows into columns.

In this lesson you will:

- Declare a matrix with `Dimension grid[10, 10]` and use two indexes.
- Load and print a matrix with nested `For` loops.
- Add two matrices box by box.
- Walk the main and secondary diagonals with a single loop.
- Build the transpose of a matrix and check if it is symmetric.

It takes about 35 minutes. You need a browser. Every example runs in the page. You should already know [arrays](/blog/programming-fundamentals-arrays/).

## Why two dimensions

Some data has rows and columns by nature. A class has students, and each student has grades in several subjects. A chessboard has 8 rows and 8 columns. A spreadsheet is rows and columns. A digital photo is a grid of pixels, one color value in each box.

You could flatten all of that into one long array, but then you must calculate positions by hand. Where does row 3 start? A matrix keeps the shape. The row and the column are the address, so the code reads like the problem. The [final project](/blog/programming-fundamentals-final-project/) uses a 4 by 4 matrix as the board of a game.

Matrix code is easy to get almost right, whether a person or an AI agent writes it. Swap `i` and `j` in one line and a program still runs on a square matrix. It only breaks when the rows and columns differ, or it silently returns the wrong box. To review that code, you need to see the grid in your head and know which index moves in which loop.

## How a matrix works

The course describes a multidimensional array as an array of arrays: a set of elements where order matters and you need one index per dimension to find each one. A matrix has two dimensions, so it needs two indexes.

You declare it like an array, with two sizes inside the brackets: `Define grid As Integer;` and then `Dimension grid[10, 10];`. This reserves 10 rows and 10 columns, 100 boxes in total, all of type `Integer`.

- The **first index** is the row. Rows are counted from top to bottom, and the course calls this index `i`.
- The **second index** is the column. Columns are counted from left to right, and the course calls this index `j`.
- `grid[i, j]` is the box in row `i` and column `j`. In StepCode both start at 1.

A matrix with `m` rows and `n` columns is called an `m` by `n` matrix. When `m` equals `n`, it is a **square** matrix. Square matrices have two diagonals:

- The **main diagonal** goes from the top left to the bottom right. Its boxes have `i = j`.
- The **secondary diagonal** goes from the top right to the bottom left. Its boxes have `i + j = n + 1`.

*Figure: A 4 by 4 matrix. The row index i goes down and the column index j goes across. The main diagonal has i = j, and the secondary diagonal has i + j = n + 1. Move i to see one loop reach a box of each diagonal.*

To visit every box you need **nested loops**: a loop inside another loop, like the mosaic in [Loops](/blog/programming-fundamentals-loops/#nested-loops). The outer loop picks a row. For each row, the inner loop visits every column. So the inner loop runs completely once for every iteration of the outer loop.

*Figure: Row by row, the outer loop picks the row and the inner loop walks it. Switch the order to see how swapping the loops, or changing their direction, changes the output.*

## Build programs with matrices

Each part below is a complete program. Press Run, type the inputs shown, and compare your output.

### 1. Fill a square matrix in order

This activity comes from the course slides. The program creates an `n` by `n` matrix, up to 10 by 10, and fills it with 1, 2, 3 and so on, row by row. Then it prints it as a grid. `WriteNoNewline` keeps the numbers of one row on the same line, and the empty `Write ""` ends the row.

**Part 1: fill in order** (StepCode)

```stepcode
Program FillInOrder
    Define grid As Integer;
    Dimension grid[10, 10];
    Define n, row, column, counter As Integer;

    Write "Enter n (max 10):";
    Read n;

    counter <- 1;
    For row <- 1 To n Step 1 Do
        For column <- 1 To n Step 1 Do
            grid[row, column] <- counter;
            counter <- counter + 1;
        EndFor
    EndFor

    For row <- 1 To n Step 1 Do
        For column <- 1 To n Step 1 Do
            WriteNoNewline grid[row, column], " ";
        EndFor
        Write "";
    EndFor
EndProgram
```

Type `3`.

You should see:

```
Enter n (max 10):
1 2 3 
4 5 6 
7 8 9 
```

Read the first pair of loops slowly. When `row` is 1, `column` goes 1, 2, 3. Only then does `row` become 2, and `column` starts again at 1. That is why the numbers fill the first row before the second.

### 2. Add two matrices

This exercise comes from the course practice guide. Two matrices of the same size add box by box: the result in row `i` and column `j` is `a[i, j] + b[i, j]`. The program reads the size, loads both matrices, adds them and prints the result.

**Part 2: add two matrices** (StepCode)

```stepcode
Program AddMatrices
    Define a, b, total As Integer;
    Dimension a[10, 10];
    Dimension b[10, 10];
    Dimension total[10, 10];
    Define m, n, i, j As Integer;

    Write "Enter m (rows):";
    Read m;
    Write "Enter n (columns):";
    Read n;

    For i <- 1 To m Step 1 Do
        For j <- 1 To n Step 1 Do
            Write "a[", i, ",", j, "]:";
            Read a[i, j];
        EndFor
    EndFor
    For i <- 1 To m Step 1 Do
        For j <- 1 To n Step 1 Do
            Write "b[", i, ",", j, "]:";
            Read b[i, j];
        EndFor
    EndFor

    For i <- 1 To m Step 1 Do
        For j <- 1 To n Step 1 Do
            total[i, j] <- a[i, j] + b[i, j];
        EndFor
    EndFor

    Write "The sum is:";
    For i <- 1 To m Step 1 Do
        For j <- 1 To n Step 1 Do
            WriteNoNewline total[i, j], " ";
        EndFor
        Write "";
    EndFor
EndProgram
```

Type `2` and `2` for the size. Then type `1`, `2`, `3`, `4` for matrix a and `5`, `6`, `5`, `6` for matrix b.

You should see:

```
Enter m (rows):
Enter n (columns):
a[1,1]:
a[1,2]:
a[2,1]:
a[2,2]:
b[1,1]:
b[1,2]:
b[2,1]:
b[2,2]:
The sum is:
6 8 
8 10 
```

The prompts show the order of the loops. The program asks for `a[1,1]`, then `a[1,2]`, and only then moves to row 2.

### 3. Sum both diagonals

You do not need two loops to walk a diagonal. On the main diagonal the row and the column are the same number, so one loop with `grid[i, i]` visits it. On the secondary diagonal the column is `n - i + 1`, which comes from `i + j = n + 1`.

**Part 3: diagonals** (StepCode)

```stepcode
Program Diagonals
    Define grid As Integer;
    Dimension grid[10, 10];
    Define n, i, j, main, secondary As Integer;

    Write "Enter n (max 10):";
    Read n;
    For i <- 1 To n Step 1 Do
        For j <- 1 To n Step 1 Do
            Write "a[", i, ",", j, "]:";
            Read grid[i, j];
        EndFor
    EndFor

    main <- 0;
    secondary <- 0;
    For i <- 1 To n Step 1 Do
        main <- main + grid[i, i];
        secondary <- secondary + grid[i, n - i + 1];
    EndFor

    Write "Main diagonal sum: ", main;
    Write "Secondary diagonal sum: ", secondary;
EndProgram
```

Type `3`, then `2`, `0`, `1`, `4`, `5`, `6`, `3`, `8`, `9`. That is the matrix with rows `2 0 1`, `4 5 6` and `3 8 9`.

You should see:

```
Enter n (max 10):
a[1,1]:
a[1,2]:
a[1,3]:
a[2,1]:
a[2,2]:
a[2,3]:
a[3,1]:
a[3,2]:
a[3,3]:
Main diagonal sum: 16
Secondary diagonal sum: 9
```

The main diagonal is 2 + 5 + 9 = 16. The secondary diagonal is 1 + 5 + 3 = 9. In an odd sized matrix, the center box belongs to both.

### 4. Transpose a matrix and check symmetry

The **transpose** of a matrix swaps rows and columns: row 1 becomes column 1, row 2 becomes column 2, and so on. An `m` by `n` matrix becomes an `n` by `m` matrix. The whole trick is one line, `t[j, i] <- a[i, j];`. A matrix is **symmetric** when it equals its transpose, which is only possible when it is square. Both exercises come from the course practice guide.

*Figure: Each box a[i, j] slides across the dashed diagonal to t[j, i]. Row 1 becomes column 1, and the 2 by 3 matrix becomes 3 by 2.*

**Part 4: transpose and symmetry** (StepCode)

```stepcode
Program Transpose
    Define a, t As Integer;
    Dimension a[10, 10];
    Dimension t[10, 10];
    Define m, n, i, j As Integer;
    Define symmetric As Boolean;

    Write "Enter m (rows):";
    Read m;
    Write "Enter n (columns):";
    Read n;
    For i <- 1 To m Step 1 Do
        For j <- 1 To n Step 1 Do
            Write "a[", i, ",", j, "]:";
            Read a[i, j];
        EndFor
    EndFor

    For i <- 1 To m Step 1 Do
        For j <- 1 To n Step 1 Do
            t[j, i] <- a[i, j];
        EndFor
    EndFor

    Write "Transpose:";
    For i <- 1 To n Step 1 Do
        For j <- 1 To m Step 1 Do
            WriteNoNewline t[i, j], " ";
        EndFor
        Write "";
    EndFor

    symmetric <- m = n;
    If symmetric Then
        For i <- 1 To m Step 1 Do
            For j <- 1 To n Step 1 Do
                If a[i, j] <> t[i, j] Then
                    symmetric <- False;
                EndIf
            EndFor
        EndFor
    EndIf

    If symmetric Then
        Write "The matrix is symmetric";
    Else
        Write "The matrix is not symmetric";
    EndIf
EndProgram
```

Type `2` and `3` for the size, then `1`, `2`, `3`, `4`, `5`, `6`. That is the matrix with rows `1 2 3` and `4 5 6`.

You should see:

```
Enter m (rows):
Enter n (columns):
a[1,1]:
a[1,2]:
a[1,3]:
a[2,1]:
a[2,2]:
a[2,3]:
Transpose:
1 4 
2 5 
3 6 
The matrix is not symmetric
```

Run it again with `2`, `2`, then `1`, `2`, `2`, `1`. The transpose is the same matrix, and you should see `The matrix is symmetric`. Notice that the printing loop uses `n` for the rows and `m` for the columns, because the transpose has the opposite shape.

### 5. Traverse a matrix in zig zag

The loops do not always have to go left to right. This activity from the course slides prints a matrix in a zig zag: the first row left to right, the second row right to left, and so on. The outer loop checks if the row is odd or even and picks the direction of the inner loop.

**Part 5: zig zag** (StepCode)

```stepcode
Program ZigZag
    Define grid As Integer;
    Dimension grid[3, 3];
    Define i, j, counter As Integer;

    counter <- 1;
    For i <- 1 To 3 Step 1 Do
        For j <- 1 To 3 Step 1 Do
            grid[i, j] <- counter;
            counter <- counter + 1;
        EndFor
    EndFor

    For i <- 1 To 3 Step 1 Do
        If i Mod 2 = 1 Then
            For j <- 1 To 3 Step 1 Do
                WriteNoNewline grid[i, j], " ";
            EndFor
        Else
            For j <- 3 To 1 Step -1 Do
                WriteNoNewline grid[i, j], " ";
            EndFor
        EndIf
    EndFor
    Write "";
EndProgram
```

Press Run. This program needs no input.

You should see:

```
1 2 3 6 5 4 7 8 9 
```

The matrix holds `1 2 3`, `4 5 6`, `7 8 9`. Row 2 comes out as `6 5 4` because its inner loop counts down.

## Common mistakes

If you see `Index 3 is outside "grid": its positions run from 1 to 2.`, you probably swapped rows and columns. With `Dimension grid[2, 3]`, the first index only goes up to 2. Check that the loop over `i` uses the number of rows and the loop over `j` uses the number of columns.

If you see `This array needs 2 indices and you gave it 1.`, you wrote something like `grid[1]`. Every box of a matrix needs a row and a column: `grid[1, 1]`.

If every number prints on one long line, the `Write ""` after the inner loop is missing. If every number prints on its own line, you used `Write` instead of `WriteNoNewline` inside the inner loop.

If a program works on a 3 by 3 matrix but fails on a 2 by 3 one, test it with a matrix that is not square. Square matrices hide swapped indexes, because both sizes are equal. This is the first test to run on matrix code that someone else wrote, including an AI agent.

## Matrices in other places

The same board can have different addresses depending on who counts. The course slides used a chessboard to show it.

| Who counts | Rows | Columns | Top left box |
| --- | --- | --- | --- |
| Chess notation | 8 down to 1 | A to H | A8 |
| Pseudocode in this course | 1 to 8 | 1 to 8 | `[1, 1]` |
| Python | 0 to 7 | 0 to 7 | `[0][0]` |

In Python, a matrix is usually a list of lists. Each inner list is one row, and you use two pairs of brackets:

```python
grid = [[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]]
print(grid[1][2])   # 6: row 1, column 2, counting from 0
for row in grid:
    print(row)
```

For big numeric work, Python programs use the NumPy library, which stores matrices in a compact way and adds or multiplies whole matrices in one call. The ideas stay the same: rows, columns and two indexes.

## Practice exercises

These exercises come from the course practice guide for matrices. Try each one in an empty editor first. Then compare with the solution.

### Show the even numbers

Given a matrix of up to 10 by 10, show its even numbers from left to right and from top to bottom.

Inputs `2` and `3`, then `5`, `6`, `2`, `2`, `9`, `6` give:

```
Enter m (rows):
Enter n (columns):
a[1,1]:
a[1,2]:
a[1,3]:
a[2,1]:
a[2,2]:
a[2,3]:
Result:
6
2
2
6
```

**Solution: even numbers** (StepCode)

```stepcode
Program EvenNumbers
    Define a As Integer;
    Dimension a[10, 10];
    Define m, n, i, j As Integer;

    Write "Enter m (rows):";
    Read m;
    Write "Enter n (columns):";
    Read n;
    For i <- 1 To m Step 1 Do
        For j <- 1 To n Step 1 Do
            Write "a[", i, ",", j, "]:";
            Read a[i, j];
        EndFor
    EndFor

    Write "Result:";
    For i <- 1 To m Step 1 Do
        For j <- 1 To n Step 1 Do
            If a[i, j] Mod 2 = 0 Then
                Write a[i, j];
            EndIf
        EndFor
    EndFor
EndProgram
```

### Multiply two matrices

Multiply an `m` by `n` matrix A by an `n` by `p` matrix B. The rules from the course guide are:

- The number of columns of A must equal the number of rows of B.
- The box in row `i` and column `j` of the result is the sum of the products of row `i` of A and column `j` of B.
- The result has `m` rows and `p` columns.

Each box of the result is a weighted sum, like the neuron in the [arrays lesson](/blog/programming-fundamentals-arrays/). That needs a third loop inside the other two.

*Figure: Press a box of C. It is row i of A times column j of B: multiply the pairs and add them up.*

Inputs `2`, `2`, `4`, then `1`, `2`, `3`, `4` for A and `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8` for B give:

```
Enter m:
Enter n:
Enter p:
a[1,1]:
a[1,2]:
a[2,1]:
a[2,2]:
b[1,1]:
b[1,2]:
b[1,3]:
b[1,4]:
b[2,1]:
b[2,2]:
b[2,3]:
b[2,4]:
The product is:
11 14 17 20 
23 30 37 44 
```

**Solution: matrix product** (StepCode)

```stepcode
Program MatrixProduct
    Define a, b, c As Integer;
    Dimension a[10, 10];
    Dimension b[10, 10];
    Dimension c[10, 10];
    Define m, n, p, i, j, k As Integer;

    Write "Enter m:";
    Read m;
    Write "Enter n:";
    Read n;
    Write "Enter p:";
    Read p;
    For i <- 1 To m Step 1 Do
        For k <- 1 To n Step 1 Do
            Write "a[", i, ",", k, "]:";
            Read a[i, k];
        EndFor
    EndFor
    For k <- 1 To n Step 1 Do
        For j <- 1 To p Step 1 Do
            Write "b[", k, ",", j, "]:";
            Read b[k, j];
        EndFor
    EndFor

    For i <- 1 To m Step 1 Do
        For j <- 1 To p Step 1 Do
            c[i, j] <- 0;
            For k <- 1 To n Step 1 Do
                c[i, j] <- c[i, j] + a[i, k] * b[k, j];
            EndFor
        EndFor
    EndFor

    Write "The product is:";
    For i <- 1 To m Step 1 Do
        For j <- 1 To p Step 1 Do
            WriteNoNewline c[i, j], " ";
        EndFor
        Write "";
    EndFor
EndProgram
```

Check the first box by hand: row 1 of A is `1 2` and column 1 of B is `1 5`, so the result is 1×1 + 2×5 = 11.

### Challenge: spiral

The course slides end with a harder traversal. Print a 3 by 3 matrix in a spiral, going around the edges toward the center. The matrix `1 2 3`, `4 5 6`, `7 8 9` gives `1 2 3 6 9 8 7 4 5`. Hint: keep four limits, the top row, the bottom row, the left column and the right column, and move each one inward after you walk its side.

Press Run on the solution. It needs no input.

```
1 2 3 6 9 8 7 4 5 
```

**Solution: spiral** (StepCode)

```stepcode
Program Spiral
    Define grid As Integer;
    Dimension grid[3, 3];
    Define i, j, counter, top, bottom, left, right As Integer;

    counter <- 1;
    For i <- 1 To 3 Step 1 Do
        For j <- 1 To 3 Step 1 Do
            grid[i, j] <- counter;
            counter <- counter + 1;
        EndFor
    EndFor

    top <- 1;
    bottom <- 3;
    left <- 1;
    right <- 3;
    While top <= bottom And left <= right Do
        For j <- left To right Step 1 Do
            WriteNoNewline grid[top, j], " ";
        EndFor
        top <- top + 1;
        For i <- top To bottom Step 1 Do
            WriteNoNewline grid[i, right], " ";
        EndFor
        right <- right - 1;
        If top <= bottom Then
            For j <- right To left Step -1 Do
                WriteNoNewline grid[bottom, j], " ";
            EndFor
            bottom <- bottom - 1;
        EndIf
        If left <= right Then
            For i <- bottom To top Step -1 Do
                WriteNoNewline grid[i, left], " ";
            EndFor
            left <- left + 1;
        EndIf
    EndWhile
    Write "";
EndProgram
```

The two `If` checks stop the walk from visiting the center twice when the limits meet. Change the size to 4 by 4 and every 3 to 4, and the same code prints `1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10`.

All the editors on this page run on [StepCode](/projects/stepcode/), the pseudocode language I built for my students at UCAB.

## What you learned

- A matrix is an array with two dimensions. `Dimension grid[10, 10]` reserves 10 rows and 10 columns.
- `grid[i, j]` is the box in row `i` and column `j`. The row always comes first.
- Nested loops visit every box: the outer loop picks the row and the inner loop walks its columns.
- On a square matrix, the main diagonal has `i = j` and the secondary diagonal has `i + j = n + 1`, so one loop is enough to walk each.
- Test matrix code with a matrix that is not square. It is the fastest way to find swapped indexes.

## Next steps

Your programs are getting longer, and some code repeats: the loops that load and print a matrix appear in almost every example here. In the next lesson, [procedures and functions](/blog/programming-fundamentals-procedures-and-functions/), you give a name to a block of code and reuse it, so you write the loading loop once and call it everywhere.
