
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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 If Given Matrix Is a Magic Square 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
Advertisements