- To print N x N magic matrix
User Input: 3
Output:
8 1 6 3 5 7 4 9 2
#include <iostream>
using namespace std;
int main() {
int n;
cout<<"Enter your magic matrix size <Must be odd> : ";
cin>>n;
if(n%2==0)cout<<"Magic matrix size must be an odd";
else {
int m[n][n],r=n,c=n/2-1,k=1;
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
r=(r+n)%n;
c++;
c%=n;
m[r][c]=k;
k++;
if(k%n==1){ r++; c--;}
else{ r--;}
}
}
cout<<"Your Magic Matrix :\n";
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
cout<<m[i][j];
if(m[i][j]<10)cout<<" ";
else if(m[i][j]<100)cout<<" ";
else if(m[i][j]<1000)cout<<" ";
else cout<<" ";
}
cout<<"\n\n";
}
}
return 0;
}
Enter your magic matrix size <Must be odd> : 5 Your Magic Matrix : 17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9Program
Remember : Magic matrix are always odd value matrix
like : 3x3,5x5,7x7,.....
So, you must first check it for an Odd value
Main Logic :
/*n: size of matrix
m: Matrix used to save,
r: holds row position, c: holds column position,
k: value to put every time in matrix */
int m[n][n],r=n,c=n/2-1,k=1;
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
r=(r+n)%n;
c++;
c%=n;
m[r][c]=k;
k++;
if(k%n==1){ r++; c--;}
else{ r--;}
}
}
To print your magic matrix
for(int i=0;i<n;i++){
for(int j=0;j<n;j++) {
cout<<m[i][j];
//To prettify Matrix size of upto 99
if(m[i][j]<10)cout<<" ";
else if(m[i][j]<100)cout<<" ";
else if(m[i][j]<1000)cout<<" ";
else cout<<" ";
}
cout<<"\n\n";
}
How to write Magic Matrix Always Put value in every step(Increment value by 1 every time) ================================================================ 0. Start from 'top mid' 1. Now Follow the direction 'right top' 2. If you found any number multiple of Matrix Size then Follow the next direction 'down' 3. continue from step 1 ============================================================== Example in 3x3 Magic Matrix Step 0: Start from 'top mid' _ 1 _ _ _ _ _ _ _ Step 1: Follow the direction 'right top' _ 1 _ _ _ _ _ _ 2 Step 2: Follow the direction 'right top'(Not Multiple of 3, continue with rule 1) _ 1 _ 3 _ _ _ _ 2 Step 3: Follow the direction 'down'(Found Multiple of 3, rule 2) _ 1 _ 3 _ _ 4 _ 2 Step 4: Follow the direction 'right top'(Not Multiple of 3, continue with rule 1) _ 1 _ 3 5 _ 4 _ 2 Step 5: Follow the direction 'right top'(Not Multiple of 3, continue with rule 1) _ 1 6 3 5 _ 4 _ 2 Step 6: Follow the direction 'down'(Found Multiple of 3, rule 2) _ 1 6 3 5 7 4 _ 2 Step 7: Follow the direction 'right top'(Not Multiple of 3, continue with rule 1) 8 1 6 3 5 7 4 _ 2 Step 7: Follow the direction 'right top'(Not Multiple of 3, continue with rule 1) 8 1 6 3 5 7 4 9 2Concept
Coming Soon !
QuickPractice isn’t the thing you do once you’re good. It’s the thing you do that makes you good.