Skip to content
Tutorials Center
My learning

Topics

Lesson 165 of 171 ยท Practice and Review

C++ Programs: Matrix Problems

C++ matrix programs with output: trace, normal, rotate 90 degrees, spiral order, boundary sum, symmetry checks, row swap, determinant and 2D prefix sums.

A matrix is a grid of numbers, and in C++ a grid is most naturally a std::vector<std::vector<int>>: a vector of rows. Matrix problems are popular exercises because they mix indexing, nested loops and a little arithmetic, and because the interesting ones have a trick: the spiral walk shrinks four boundaries, a rotation is a transpose plus a reversal, and a prefix-sum table answers any rectangle query in constant time.

The programs on this page are complete and runnable. They share a tiny using Matrix = std::vector<std::vector<int>> alias and a show helper that prints a matrix with aligned columns. If the 2D containers are new to you, read multidimensional arrays and vectors first; for a full class with operators, see the matrix library project.

All programs index rows with r and columns with c, and use std::size_t or int consistently. When a loop compares an index with .size(), we cast to int once at the top (int n = m.size();) so negative-looking arithmetic such as n - 1 - c stays signed.

Sums and properties

1. Trace and normal of a square matrix

The trace is the sum of the main diagonal. The normal (Frobenius norm) is the square root of the sum of the squares of all elements. Both need one pass.

C++ 1. Trace and normal

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

2. Boundary and diagonal sums

The border is every cell on the first or last row or column. The two diagonals are m[i][i] and m[i][n - 1 - i]; for an odd size the center cell belongs to both, so subtract it once.

C++ 2. Boundary and diagonal sums

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

3. Is it symmetric, diagonal, identity or upper triangular?

Each property is a rule about positions. A matrix is symmetric when m[r][c] == m[c][r], diagonal when every off-diagonal cell is zero, the identity when it is diagonal with ones, and upper triangular when everything below the diagonal is zero. Small predicate functions keep main readable.

C++ 3. Matrix properties

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Rearranging a matrix

4. Rotate a square matrix by 90 degrees

Rotating clockwise is two simple steps: transpose (swap m[r][c] with m[c][r] above the diagonal), then reverse each row. This works in place, with no second matrix.

C++ 4. Rotate 90 degrees

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

To rotate counter-clockwise, reverse each row first and then transpose, or reverse the order of the rows (std::reverse(m.begin(), m.end())) after transposing.

5. Swap two rows or two columns

Rows are whole vectors, so std::swap(m[a], m[b]) swaps them in constant time without copying elements (the vectors just trade their internals). Columns have no such shortcut: loop over the rows and swap one element in each.

C++ 5. Swap rows and columns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

6. Print a matrix in spiral order

Keep four boundaries: top, bottom, left and right. Walk the top row left to right, then the right column downwards, then the bottom row right to left, then the left column upwards, shrinking one boundary after each side. The two if guards stop the walk from repeating a row or column when the matrix is not square.

C++ 6. Spiral order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Arithmetic on matrices

7. Determinant by cofactor expansion

The determinant of a 1x1 matrix is its only element. For a larger matrix, expand along the first row: each element is multiplied by the determinant of the smaller matrix left after deleting its row and column (the minor), with alternating signs. The recursion is easy to read but costs factorial time, so it is only fine for small matrices; real libraries use Gaussian elimination.

C++ 7. Determinant

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

8. Prefix sums: any rectangle sum in constant time

Build a table P where P[r][c] is the sum of the rectangle from the top-left corner to (r - 1, c - 1). The extra leading row and column of zeros remove edge cases. Any sub-rectangle sum then needs just four lookups: add the big corner, subtract the two strips, and add back the overlap that was subtracted twice (inclusion-exclusion).

C++ 8. 2D prefix sum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Common mistakes

  • Mixing up rows and cols in a non-square matrix. Write them as two named variables and use them in the loop bounds.
  • Comparing a signed index with .size(). Convert once, or use std::size_t for the loop variable and avoid subtracting from it.
  • Rotating with a second matrix and forgetting that a non-square matrix changes shape; the in-place transpose trick only works for squares.
  • Forgetting that the recursion in the determinant is exponential: it is a teaching tool, not a production routine.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which two steps rotate a square matrix 90 degrees clockwise in place?

    Transposing turns rows into columns, and reversing each row then puts the columns in clockwise order.
  2. 2. In the 2D prefix-sum table, why does it have one extra row and column of zeros?

    With the zero border, p[r1][c1] and the neighbouring terms always exist, even when r1 or c1 is 0.
  3. 3. Why does the spiral program check top <= bottom and left <= right before the last two sides?

    After shrinking top and right, the remaining block may be empty or a single line; the guards stop the walk from revisiting cells.
  4. 4. How is the determinant of an n x n matrix computed in the recursive program?

    Cofactor expansion along the first row: det = sum of (-1)^c * m[0][c] * det(minor c).

Summary

  • A matrix is a vector of rows; name rows and cols separately so non-square cases stay correct.
  • Trace is the diagonal sum; the Frobenius normal is the root of the sum of squares.
  • Symmetry, triangular and identity checks are rules about cell positions.
  • Rotate 90 degrees clockwise = transpose + reverse each row.
  • Spiral order shrinks four boundaries and guards the last two sides.
  • Cofactor expansion computes determinants recursively (factorial cost); a 2D prefix sum answers rectangle sums in O(1) after O(rows * cols) setup.

Next: C++ Programs: Array and Searching Puzzles.