How to check whether a matrix is a square matrix in C++

1 Answer

0 votes
#include <iostream>
#include <vector>

bool isSquareMatrix(const std::vector<std::vector<int>>& matrix) {
    // Get the number of rows
    int rows = matrix.size();

    // Check if the matrix is empty
    if (rows == 0) {
        return false; // An empty matrix is not a square matrix
    }

    // Get the number of columns in the first row
    int cols = matrix[0].size();

    // Check if the number of rows equals the number of columns
    return rows == cols;
}

int main() {
     std::vector<std::vector<int>> matrix = {
      {5, 8, 9, 10},
      {1, 4, 6, 13},
      {7, 3, 0, 18},
      {6, 8, 9, 20},
    };

    // Check if the matrix is a square matrix
    if (isSquareMatrix(matrix)) {
        std::cout << "The matrix is a square matrix." << std::endl;
    } else {
        std::cout << "The matrix is not a square matrix." << std::endl;
    }
}



/*
run:

The matrix is a square matrix.

*/

 



answered Oct 6, 2025 by avibootz
...