

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check given matrix is magic square or not in C++
Here we will see, if a matrix is magic square or not, a magic square is a square matrix, where the sum of each row, each column, and each diagonal are same.
Suppose a matrix is like below −
6 | 1 | 8 |
7 | 5 | 3 |
2 | 9 | 4 |
This is a magic square, if we see, the sum of each row, column and diagonals are 15.
To check whether a matrix is magic square or not, we have to find the major diagonal sum and the secondary diagonal sum, if they are same, then that is magic square, otherwise not.
Example
#include <iostream> #define N 3 using namespace std; bool isMagicSquare(int mat[][N]) { int sum_diag = 0,sum_diag_second=0; for (int i = 0; i < N; i++) sum_diag = sum_diag + mat[i][i]; for (int i = 0; i < N; i++) sum_diag_second = sum_diag_second + mat[i][N-1-i]; if(sum_diag!=sum_diag_second) return false; for (int i = 0; i < N; i++) { int rowSum = 0; for (int j = 0; j < N; j++) rowSum += mat[i][j]; if (rowSum != sum_diag) return false; } for (int i = 0; i < N; i++) { int colSum = 0; for (int j = 0; j < N; j++) colSum += mat[j][i]; if (sum_diag != colSum) return false; } return true; } int main() { int mat[][N] = {{ 6, 1, 8 }, { 7, 5, 3 }, { 2, 9, 4 }}; if (isMagicSquare(mat)) cout << "It is Magic Square"; else cout << "It is Not a magic Square"; }
Output
It is Magic Square
- Related Questions & Answers
- Check Perfect Square or Not
- C++ code to check given matrix is good or not
- Magic Square
- Program to check whether given matrix is Toeplitz Matrix or not in Python
- Check if a given matrix is Hankel or not in C++
- Check if a given matrix is sparse or not in C++
- Find if given matrix is Toeplitz or not in C++
- Program to check if a matrix is Binary matrix or not in C++
- C Program to check if matrix is singular or not
- Check if a given graph is tree or not
- C Program To Check whether Matrix is Skew Symmetric or not?
- C++ code to check given flag is stripped or not
- How to check if a matrix is invertible or not in R?
- Check if a given number is sparse or not in C++
- Program to check given string is pangram or not in Python
Advertisements