Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,851 questions

51,772 answers

573 users

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

2 Answers

0 votes
#include <stdio.h>
#include <stdbool.h>

#define COLS 4

bool isSquareMatrix(int matrix[][COLS], int rows, int cols) {
    // Check if the matrix is empty
    if (rows == 0 || cols == 0) {
        return false; // An empty matrix is not a square matrix
    }

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

int main() {
    // Initialize the matrix
    int matrix[][COLS] = {
        {5, 8, 9, 10},
        {1, 4, 6, 13},
        {7, 3, 0, 18},
        {6, 8, 9, 20}
    };
    
    // Calculate the total size of the matrix in bytes
    size_t totalSize = sizeof(matrix);

    // Calculate the size of one row
    size_t rowSize = sizeof(matrix[0]); 

    // Calculate the number of rows and columns
    size_t rows = totalSize / rowSize;

    if (isSquareMatrix(matrix, rows, COLS)) {
        printf("The matrix is a square matrix.\n");
    } else {
        printf("The matrix is not a square matrix.\n");
    }

    return 0;
}


/*
run:

The matrix is not a square matrix.

*/

 



answered Oct 6, 2025 by avibootz
0 votes
#include <stdio.h>
#include <stdbool.h>

#define COLS 4

bool isSquareMatrix(int matrix[][COLS], int totalSize, int cols) {
    // Calculate the size of one row
    size_t rowSize = sizeof(matrix[0]);

    // Calculate the number of rows and columns
    size_t rows = totalSize / rowSize;
    
    // Check if the matrix is empty
    if (rows == 0 || cols == 0) {
        return false; // An empty matrix is not a square matrix
    }

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

int main() {
    // Initialize the matrix
    int matrix[][COLS] = {
        {5, 8, 9, 10},
        {1, 4, 6, 13},
        {7, 3, 0, 18},
        {6, 8, 9, 20}
    };
    
    if (isSquareMatrix(matrix, sizeof(matrix), COLS)) {
        printf("The matrix is a square matrix.\n");
    } else {
        printf("The matrix is not a square matrix.\n");
    }

    return 0;
}


/*
run:

The matrix is a square matrix.

*/

 



answered Oct 6, 2025 by avibootz
...