C++ program to Check if Matrix is Magic Matrix or Not

Write C++ program to Check if Matrix is Magic Matrix or Not

// CPP program to Check if Matrix is Magic Matrix or Not

//magic matrix is that matrix having sum of all the elements in the row and column as well as diagonal as same values

#include <iostream>
#include <math.h>
#include <stdbool.h>

using namespace std;

bool isMagicSquare(int A[3][3])
{
	int n = sizeof(A) / sizeof(A[0]), i , j;
	int sumd1 = 0, sumd2 = 0;
	for(i = 0;i < n; i++)
	{
		sumd1 += A[i][i];
		sumd2 += A[i][n-1-i];
	}
	if(sumd1 != sumd2)
		return false;


	for(i = 0; i < n; i++)
    {
        int sumr = 0,sumc = 0;
		for(j = 0;j < n; j++)
		{
			sumr += A[i][j];
			sumc += A[j][i];
		}
		if(sumr != sumc || sumr != sumd1)
			return false;
    }
	return true;
}
int main()
{

	int A[3][3] = { {2, 1, 6}, {9, 5, 1}, {4, 3, 8} }, i, j;

        cout << "Matrix A :--> \n";
	for(i = 0;i < 3; i++)
	{
		for( j = 0; j < 3; j++)
		{
			cout << A[i][j] << " ";
		}
		cout << endl;
	}

    if (isMagicSquare(A))
        cout << "\nGiven Matrix is Magic Matrix";
    else
        cout << "\nGiven Matrix is Not Magic Matrix";

    return 0;

}

Output:

Matrix A :-->
2  1  6
9  5  1
4  3  8

Given Matrix is Magic Matrix

≪ Previous | Next ≫