Rolando Andrade
Back to Content

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.

· 10 min read
Matrices in Programming: Rows, Columns, Nested Loops and Diagonals: Programming Fundamentals (11)

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.

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 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.
columns (j) rows (i) 1 1 2 2 3 3 4 4 [1,1] [1,2] [1,3] [1,4] [2,1] [2,2] [2,3] [2,4] [3,1] [3,2] [3,3] [3,4] [4,1] [4,2] [4,3] [4,4] main diagonal: i = j secondary diagonal: i + j = n + 1
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. 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.

columns (j) 1 1 2 2 3 3 1 2 3 4 5 6 7 8 9

Outer loop: i (rows). Inner loop: j (columns).

Output: 1 2 3 4 5 6 7 8 9

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.

Edit the code and press Run to try it.

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.

Edit the code and press Run to try it.

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.

Edit the code and press Run to try it.

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.

t: 3 rows, 2 columns

t[j, i] <- a[i, j];

Row 1 of a (1 2 3) is now column 1 of t. Row 2 (4 5 6) is column 2.

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.
Edit the code and press Run to try it.

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.

Edit the code and press Run to try it.

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:

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
Edit the code and press Run to try it.

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. That needs a third loop inside the other two.

A is a 2 by 2 matrix with rows 1 2 and 3 4. B is a 2 by 4 matrix with rows 1 2 3 4 and 5 6 7 8. Their product C has rows 11 14 17 20 and 23 30 37 44. Each box c[i, j] is row i of A times column j of B: for example c[1, 1] = 1×1 + 2×5 = 11.

C

c[1, 1] = row 1 of A × column 1 of B = 1×1 + 2×5 = 11

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 
Edit the code and press Run to try it.

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 
Edit the code and press Run to try it.

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, 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, you give a name to a block of code and reuse it, so you write the loading loop once and call it everywhere.