Level: BeginnerGo Programs

Go Matrix Programs: Addition, Multiplication, Transpose, Rotate

Updated 18 min read
Go Matrix Programs featured image: matrix add, multiply and rotate output

Go matrix programs work with rows and columns of numbers, like a spreadsheet, a game board or the pixels of an image. In this post, you will write fourteen matrix programs with their exact output, including addition, multiplication, transpose, rotation and spiral order. Then you will practice the matrix questions that come up in coding rounds, where index mistakes are very common.

This post closes Level 3 of our Go programs series. It uses the 2D slices from our Go slice programs and the 2D arrays from our Go array programs. It also uses the nested loops from our Go pattern programs. All programs were tested on Go 1.27.

What are Go Matrix Programs?

Go matrix programs store numbers in a grid with rows and columns. In Go, a matrix is usually a slice of slices, [][]int, or a fixed 2D array such as [3][3]int. You reach one cell with two indexes: m[row][col].

Think of a cinema seating chart. Each row has a number, and each seat in that row has a number. To find your seat, you need both. A matrix works the same way, with the row first and the column second.

Why Go Matrix Programs Matter

Grids appear in many real problems. For example, a chess or tic-tac-toe board is a grid, an image is a grid of pixels and a timetable is a grid of days and periods. Interviewers like Go matrix programs because they test careful loops and index maths.

  • Interviews: rotate a matrix, spiral order and search a 2D grid are classic questions.
  • Games and maps: boards, mazes and tile maps all use 2D grids.
  • Maths and data: tables, images and machine learning use matrix operations.

How Go Matrix Programs Work

Most Go matrix programs use two nested loops. The outer loop walks the rows, and the inner loop walks the columns of the current row. You get the number of rows with len(m) and the number of columns with len(m[0]).

Go matrix programs diagram showing rows, columns and the m row col index
Each cell is found with m[row

The table below shows the common ways to create a matrix in Go.

WayExampleWhen to use
2D arrayvar board [3][3]intFixed size known at compile time
Slice literalm := [][]int{{1, 2}, {3, 4}}Small known data
make in a loopm[i] = make([]int, cols)Size known at run time
One flat slicedata[r*cols+c]Big grids, best speed

Basic Go Matrix Programs

These first Go matrix programs create, print and add matrices. If you are new to grids, start with Program 1.

Program 1: Your First Matrix and m[row][col]

This easy program reads one cell, then prints every cell with two loops, just like the diagram above.

package main

import "fmt"

func main() {
    // m is a matrix: a slice of rows, and each row is a slice of numbers.
    m := [][]int{ // := creates the variable and sets its value
        {1, 2, 3}, // row 0
        {4, 5, 6}, // row 1
    }

    // Step 1: read one cell. The row comes first, then the column.
    fmt.Println("Cell at row 1, col 2:", m[1][2])

    // Step 2: visit every cell with two loops.
    for row := 0; row < len(m); row++ { // len(m) is the number of rows
        for col := 0; col < len(m[row]); col++ { // len(m[row]) is the number of columns
            fmt.Print(m[row][col], " ")
        }
        fmt.Println() // start a new line after each row
    }
}
Cell at row 1, col 2: 6
1 2 3
4 5 6

Indexes start at 0, so m[1][2] means the second row and the third column. That cell holds 6. The outer loop picks a row, and the inner loop prints each number in that row. After each row, fmt.Println() moves to the next line.

Program 2: Create and Print a Matrix

We write a helper that makes a matrix of any size, filled with zeros.

package main

import "fmt"

// newMatrix makes a grid with the given rows and columns, all set to 0.
func newMatrix(rows, cols int) [][]int {
    // Step 1: make the outer slice that will hold the rows.
    matrix := make([][]int, rows) // make creates a slice of the given length
    // Step 2: make each row separately.
    for i := range matrix { // range gives each index 0, 1, 2 ...
        matrix[i] = make([]int, cols)
    }
    return matrix
}

func main() {
    matrix := newMatrix(2, 3)
    matrix[0][1] = 5
    matrix[1][2] = 9
    for _, row := range matrix { // _ ignores the index, row is each row slice
        fmt.Println(row)
    }
    fmt.Println("Rows:", len(matrix), "Cols:", len(matrix[0]))
}
[0 5 0]
[0 0 9]
Rows: 2 Cols: 3

First, make([][]int, rows) creates the list of rows, but each row is still empty. Then the loop gives each row its own make call with room for the columns. If you skip that step, the rows stay nil and writing to them panics.

Program 3: Matrix Addition

Two matrices can be added only if they have the same size. Each cell adds the matching cells.

package main

import "fmt"

func main() {
    first := [][]int{{1, 2, 3}, {4, 5, 6}}
    second := [][]int{{10, 20, 30}, {40, 50, 60}}

    // Step 1: make the result with the same number of rows.
    sum := make([][]int, len(first))
    for i := range first {
        // Step 2: make this row of the result.
        sum[i] = make([]int, len(first[i]))
        // Step 3: add the matching cells.
        for j := range first[i] {
            sum[i][j] = first[i][j] + second[i][j]
        }
    }
    fmt.Println(sum)
}
[[11 22 33] [44 55 66]]

The loop uses i for the row and j for the column. For each position, it adds the cell from first and the cell from second. Subtraction works exactly the same way with - instead of +.

Program 4: Row Sums and Column Sums

package main

import "fmt"

func main() {
    // Each row is a shop, each column is a day.
    sales := [][]int{
        {120, 80, 95},
        {60, 150, 70},
        {90, 40, 110},
    }

    // One running total for each column.
    columnTotals := make([]int, len(sales[0]))

    for i, row := range sales {
        rowTotal := 0 // starts again at 0 for every row
        for j, value := range row {
            rowTotal += value
            columnTotals[j] += value // keeps adding across all rows
        }
        fmt.Println("Row", i, "total:", rowTotal)
    }
    fmt.Println("Column totals:", columnTotals)
}
Row 0 total: 295
Row 1 total: 280
Row 2 total: 240
Column totals: [270 270 275]

One pass fills both totals. The row total resets to 0 for each row, so it prints after the inner loop. The column totals keep adding across all rows, so we print them at the very end.

Classic Go Matrix Programs

These Go matrix programs cover the operations from school maths.

Program 5: Multiply Every Cell by a Number

This is the easiest maths operation on a matrix. It is called scalar multiplication.

package main

import "fmt"

func main() {
    prices := [][]int{{10, 20}, {30, 40}}

    // Double every price, one cell at a time.
    for i := range prices {
        for j := range prices[i] {
            prices[i][j] = prices[i][j] * 2
        }
    }
    fmt.Println(prices)
}
[[20 40] [60 80]]

The two loops visit every cell once. Each cell is read, multiplied by 2 and written back in the same place. This warm-up uses the same loop shape as the bigger programs below.

Program 6: Matrix Multiplication

A 2×3 matrix times a 3×2 matrix gives a 2×2 result. The columns of the first must equal the rows of the second.

package main

import (
    "errors"
    "fmt"
)

// multiply returns first x second, or an error if the sizes do not fit.
func multiply(first, second [][]int) ([][]int, error) {
    // Step 1: check the sizes.
    if len(first[0]) != len(second) {
        return nil, errors.New("columns of first must equal rows of second")
    }
    // Step 2: make the result, rows of first by columns of second.
    result := make([][]int, len(first))
    for i := range first {
        result[i] = make([]int, len(second[0]))
        // Step 3: each cell is a row of first times a column of second.
        for j := range second[0] {
            for k := range second {
                result[i][j] += first[i][k] * second[k][j]
            }
        }
    }
    return result, nil // nil means "no error"
}

func main() {
    first := [][]int{{1, 2, 3}, {4, 5, 6}}
    second := [][]int{{7, 8}, {9, 10}, {11, 12}}
    fmt.Println(multiply(first, second)) // prints both return values
    fmt.Println(multiply(first, first))
}
[[58 64] [139 154]] <nil>
[] columns of first must equal rows of second

This function returns two things: the result and an error value. The first call works, so the error prints as <nil>. Each result cell is the sum of a row times a column, so 58 is 1×7 + 2×9 + 3×11. The second call has the wrong sizes, so it returns the error message.

Program 7: Transpose a Matrix

The transpose turns rows into columns.

package main

import "fmt"

func main() {
    matrix := [][]int{{1, 2, 3}, {4, 5, 6}}

    // The result has as many rows as matrix has columns.
    transposed := make([][]int, len(matrix[0]))
    for j := range transposed {
        transposed[j] = make([]int, len(matrix))
        for i := range matrix {
            transposed[j][i] = matrix[i][j] // row i, column j moves to row j, column i
        }
    }
    fmt.Println(transposed)
}
[[1 4] [2 5] [3 6]]

A 2×3 matrix becomes 3×2. We build each new row by reading one column of the old matrix. The cell at row i, column j moves to row j, column i.

Program 8: Diagonal Sums

package main

import "fmt"

func main() {
    matrix := [3][3]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} // a fixed 3x3 array
    size := len(matrix)
    primary, secondary := 0, 0
    for i := 0; i < size; i++ {
        primary += matrix[i][i]          // top left to bottom right
        secondary += matrix[i][size-1-i] // top right to bottom left
    }
    fmt.Println("Primary:", primary, "Secondary:", secondary)
}
Primary: 15 Secondary: 15

On the main diagonal, the row and column numbers are equal, so we read matrix[i][i]. The other diagonal uses column size-1-i, which runs from right to left. One loop adds both totals.

Program 9: Identity Matrix Check

An identity matrix has 1 on the main diagonal and 0 everywhere else.

package main

import "fmt"

// isIdentity reports whether matrix has 1 on the diagonal and 0 elsewhere.
func isIdentity(matrix [][]int) bool {
    for i := range matrix {
        for j := range matrix[i] {
            // Step 1: work out what this cell should hold.
            want := 0
            if i == j {
                want = 1
            }
            // Step 2: stop early if the cell is wrong.
            if matrix[i][j] != want {
                return false
            }
        }
    }
    return true
}

func main() {
    fmt.Println(isIdentity([][]int{{1, 0}, {0, 1}}))
    fmt.Println(isIdentity([][]int{{1, 2}, {0, 1}}))
}
true
false

For every cell, we decide the expected value first. A cell on the diagonal should be 1, and every other cell should be 0. The function returns false at the first wrong cell, and true only if all cells pass.

Program 10: Symmetric Matrix Check

A matrix is symmetric when it equals its own transpose.

package main

import "fmt"

func main() {
    matrix := [][]int{{2, 7, 3}, {7, 4, 5}, {3, 5, 6}}
    symmetric := true
    for i := range matrix {
        // Start j at i + 1, so we only look above the diagonal.
        for j := i + 1; j < len(matrix); j++ {
            if matrix[i][j] != matrix[j][i] {
                symmetric = false
            }
        }
    }
    fmt.Println("Symmetric:", symmetric)
}
Symmetric: true

Each cell above the diagonal must match its mirror cell below it. So we compare matrix[i][j] with matrix[j][i]. We only check cells above the diagonal, because each pair needs one comparison.

Interview Go Matrix Programs

These Go matrix programs show up often in coding rounds.

Program 11: Rotate a Matrix 90 Degrees Clockwise

The trick is to transpose the matrix, then reverse each row.

package main

import (
    "fmt"
    "slices"
)

// rotate turns a square matrix 90 degrees clockwise, in place.
func rotate(matrix [][]int) {
    size := len(matrix)
    // Step 1: transpose by swapping cells across the diagonal.
    for i := 0; i < size; i++ {
        for j := i + 1; j < size; j++ {
            // Swap the two cells in one line: each side gets the other's old value.
            matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
        }
    }
    // Step 2: reverse each row.
    for _, row := range matrix {
        slices.Reverse(row)
    }
}

func main() {
    matrix := [][]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
    rotate(matrix)
    for _, row := range matrix {
        fmt.Println(row)
    }
}
[7 4 1]
[8 5 2]
[9 6 3]

After step 1, the first row is 1 4 7. Reversing it gives 7 4 1, which is the first row of the rotated matrix. This works in place, with no second matrix. For anticlockwise, reverse each row first and then transpose.

Program 12: Spiral Order

We walk the outer ring, then shrink the edges and repeat.

package main

import "fmt"

// spiral returns the cells of matrix in clockwise spiral order.
func spiral(matrix [][]int) []int {
    var result []int
    // The four edges of the part we have not visited yet.
    top, bottom := 0, len(matrix)-1
    left, right := 0, len(matrix[0])-1
    for top <= bottom && left <= right {
        // Step 1: go right along the top row.
        for col := left; col <= right; col++ {
            result = append(result, matrix[top][col]) // append adds to the end
        }
        top++
        // Step 2: go down the right column.
        for row := top; row <= bottom; row++ {
            result = append(result, matrix[row][right])
        }
        right--
        // Step 3: go left along the bottom row, if one is left.
        if top <= bottom {
            for col := right; col >= left; col-- {
                result = append(result, matrix[bottom][col])
            }
            bottom--
        }
        // Step 4: go up the left column, if one is left.
        if left <= right {
            for row := bottom; row >= top; row-- {
                result = append(result, matrix[row][left])
            }
            left++
        }
    }
    return result
}

func main() {
    matrix := [][]int{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}
    fmt.Println(spiral(matrix))
}
[1 2 3 4 8 12 11 10 9 5 6 7]

Four edge markers track the unvisited part of the grid. After walking each side, we move that edge one step inward. The two if checks stop us from reading a row or column twice when the matrix is not square.

Program 13: Largest Value and Its Position

package main

import "fmt"

func main() {
    scores := [][]int{{45, 78, 62}, {91, 55, 88}, {70, 99, 64}}

    // Step 1: start by guessing the first cell is the biggest.
    best := scores[0][0]
    bestRow := 0
    bestCol := 0

    // Step 2: check every cell and remember a bigger one.
    for row, cells := range scores {
        for col, value := range cells {
            if value > best {
                best = value
                bestRow = row
                bestCol = col
            }
        }
    }
    fmt.Printf("Max %d at row %d, column %d\n", best, bestRow, bestCol) // %d prints a whole number
}
Max 99 at row 2, column 1

We start with the first cell as our best guess. Whenever we find a bigger value, we save it with its row and column. After both loops finish, the saved values point to 99.

Program 14: Count Zeros in a Sparse Matrix

A sparse matrix has mostly zeros. Counting them tells you whether a special storage format would save memory.

package main

import "fmt"

func main() {
    matrix := [][]int{
        {0, 0, 3, 0},
        {0, 0, 0, 0},
        {5, 0, 0, 1},
    }

    // Step 1: count all cells and the zero cells.
    zeros, total := 0, 0
    for _, row := range matrix {
        for _, value := range row {
            total++
            if value == 0 {
                zeros++
            }
        }
    }

    // Step 2: work out the percentage. float64 turns whole numbers into decimals.
    percent := float64(zeros) / float64(total) * 100
    fmt.Printf("Zeros: %d of %d (%.0f%%)\n", zeros, total, percent) // %% prints a % sign
}
Zeros: 9 of 12 (75%)

The loops count every cell and every zero. Then we turn both counts into decimals with float64, so the division does not drop the fraction. Here 9 out of 12 cells are zero, which is 75 percent.

2D Array vs Slice of Slices in Go Matrix Programs

Go gives you two main ways to store a grid. The diagram and table below compare them.

Go matrix programs comparison of 2D arrays and slices of slices
A 2D array has a fixed size in one block of memory, while a slice of slices can be any size at run time.
Feature2D array [3][3]intSlice of slices [][]int
SizeFixed at compile timeChosen at run time
MemoryOne blockOne block per row
Copy on assignYes, full copyNo, shares rows
Rows can differ in lengthNoYes
Best forBoards, small fixed gridsInput data, any size

In short, use a 2D array for fixed boards like tic-tac-toe. Use a slice of slices for data whose size you only know when the program runs.

Common Mistakes in Go Matrix Programs

  • Forgetting to make each row: make([][]int, n) only makes the outer slice, so each row starts as nil.
  • Mixing up rows and columns: len(m) is rows and len(m[0]) is columns, so check both.
  • Sharing one row: reusing the same row slice for every row means all rows change together.
  • Wrong sizes for multiplication: the columns of the first must equal the rows of the second.
  • Empty matrix: m[0] panics when there are no rows, so check len(m) > 0 first.

Best Practices for Go Matrix Programs

  • Write a newMatrix helper, so every row is created the right way.
  • Return errors for size problems, instead of letting the program panic.
  • Use range for reading, and indexes only when you need the positions.
  • Consider one flat slice with r*cols + c for very large grids, since it is faster.
  • Draw a small example before you code rotations or spirals.

Go Matrix Programs Interview Questions and Answers

Interviewers use short Go matrix programs to test index rules and memory. Each program is complete, with real output from Go 1.27.

Go Matrix Programs Index and Size Questions

Q1. What does this program print?

package main

import "fmt"

func main() {
    matrix := [][]int{{1, 2, 3}, {4, 5, 6}}
    // rows, columns, row 1 col 0, row 0 col 2
    fmt.Println(len(matrix), len(matrix[0]), matrix[1][0], matrix[0][2])
}
2 3 4 3

There are 2 rows and 3 columns. matrix[1][0] is row 1, column 0, which holds 4.

Q2. Why does this program panic?

package main

func main() {
    matrix := make([][]int, 2) // two rows, but each row is still nil
    matrix[0][0] = 1           // row 0 has length 0, so index 0 does not exist
}
panic: runtime error: index out of range [0] with length 0

make([][]int, 2) creates two nil rows. Each row has length 0, so index 0 does not exist yet.

Q3. What does this program print?

package main

import "fmt"

func main() {
    row := make([]int, 3)
    grid := [][]int{row, row} // both rows are the SAME slice
    grid[0][0] = 7
    fmt.Println(grid)
}
[[7 0 0] [7 0 0]]

Both rows point to the same slice. So a change through one row shows in the other, which is a common bug.

Q4. What does this program print?

package main

import "fmt"

func main() {
    board := [2][2]int{{1, 2}, {3, 4}}
    copyBoard := board // arrays are values, so this copies every cell
    copyBoard[0][0] = 100
    fmt.Println(board[0][0], copyBoard[0][0])
}
1 100

A 2D array is a value, so copyBoard := board copies every cell. With a slice of slices, the same code would change both.

Algorithm Questions

Q5. What is the time complexity of multiplying two n x n matrices?

The simple three-loop method is O(n cubed). Faster methods exist, such as Strassen’s algorithm, but they are rarely needed in normal Go code.

Q6. What does this program print?

package main

import "fmt"

func main() {
    size := 4
    for i := 0; i < size; i++ {
        for j := 0; j < size; j++ {
            // || means "or": print X on either diagonal.
            if i == j || i+j == size-1 {
                fmt.Print("X ")
            } else {
                fmt.Print(". ")
            }
        }
        fmt.Println()
    }
}
X . . X
. X X .
. X X .
X . . X

i == j marks the main diagonal, and i + j == size - 1 marks the other one. Together they draw a big X.

Q7. How do you rotate a matrix anticlockwise?

Reverse each row, then transpose. Or transpose first and reverse each column. Draw a 3×3 example to check, because the order of steps matters.

Q8. What does this program print?

package main

import "fmt"

func main() {
    rows, cols := 2, 3
    flat := make([]int, rows*cols) // one slice holds all 6 cells
    for row := 0; row < rows; row++ {
        for col := 0; col < cols; col++ {
            flat[row*cols+col] = row*10 + col // row*cols+col finds the cell's place
        }
    }
    fmt.Println(flat, flat[1*cols+2])
}
[0 1 2 10 11 12] 12

A flat slice stores the grid row after row. The cell at row r, column c sits at index r*cols + c.

Q9. How do you search a matrix where every row is sorted?

Run a binary search on each row, which costs O(rows x log cols). If the columns are also sorted, start at the top right corner and step left or down, which costs O(rows + cols). We wrote this staircase search in our Go searching programs.

Q10. What does this program print?

package main

import "fmt"

func main() {
    jagged := [][]int{{1}, {2, 3}, {4, 5, 6}} // rows of different lengths
    total := 0
    for _, row := range jagged {
        total += len(row)
    }
    fmt.Println(total, len(jagged[2]))
}
6 3

Rows of a slice of slices can have different lengths. This shape is called a jagged matrix.

Practice Task

A tic-tac-toe checker is a fun way to practise Go matrix programs. Write a program that checks a 3×3 board stored as [3][3]string and prints the winner, or “draw” if nobody has won. Hint: check all rows, all columns and both diagonals with the index rules from this post.

Official Resources

Quick Recap

  • Go matrix programs use [][]int for any size or [N][M]int for fixed grids.
  • len(m) gives the rows and len(m[0]) gives the columns.
  • Create every row with make, or writes will panic.
  • Rotate 90 degrees clockwise by transposing and then reversing each row.
  • A 2D array copies on assignment, while a slice of slices shares its rows.

What’s Next?

That completes Level 3 of our Go programs series. Coming soon: Level 4, starting with Go function programs such as variadic functions, multiple returns and closures. Until then, test yourself with the Go slice interview questions.