#include<iostream> #include<iomanip> using namespace std; void print(int[][20],i
ID: 3625151 • Letter: #
Question
#include<iostream>#include<iomanip>
using namespace std;
void print(int[][20],int);
void fill(int[][20],int);
int main()
{int a[20][20],n;
cout<<"Enter the Order of the Magic Square(Odd): ";
cin>>n;
while(n%2==0||n<1||n>20)
{cout<<"Enter the Order of Magic Square(Odd): ";
cin>>n;
}
fill(a,n);
print(a,n);
system("pause");
return 0;
}
void fill(int a[][20],int n)
{int x=0,y,i,j,k=1;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
a[i][j]=0;
y=(n+1)/2-1;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{a[x][y]=k++;
if(k%n==1)
x=++x%n;
else
{y=++y%n;
if(--x<0)
x=n-1;
}
}
}
void print(int a[][20],int n)
{int i,j;
cout<<"The Magic Square... ";
for(i=0;i<n;i++)
{for(j=0;j<n;j++)
cout<<setw(50/n+2)<<a[i][j];
cout<<" ";
}
}
Please add braces to all for loops and make it so the middle row of the right most column contains 1. Thanks!
Explanation / Answer
please rate - thanks
I fixed, and rewrote, and commented it
hopefully it will be clearer
#include<iostream>
#include<iomanip>
using namespace std;
void print(int[][20],int);
void fill(int[][20],int);
int main()
{int a[20][20],n;
cout<<"Enter the Order of the Magic Square(Odd): ";
cin>>n;
while(n%2==0||n<1||n>20)
{cout<<"Enter the Order of Magic Square(Odd): ";
cin>>n;
}
fill(a,n);
print(a,n);
system("pause");
return 0;
}
void fill(int a[][20],int n)
{int r,c,prevr,prevc,k=1;
for(r=0;r<n;r++)
{for(c=0;c<n;c++) //start a
{a[r][c]=0; //start b
} //end b
} //end a
r=(n+1)/2-1;
c=n-1;
while(k<=n*n)
{a[r][c]=k++; //start c
prevr=r; //save row and column so you
prevc=c; // know where you came from for rule 3
r++;
if(r>n-1) //rule 1
{r=0; //start
} //end
c++;
if(c>n-1) //rule 2
{c=0; //start
} //end
if(a[r][c]!=0||r>n-1&&c>n-1) //rule 3
{r=prevr; //start
c=prevc-1; //end
}
} //end c
}
void print(int a[][20],int n)
{int i,j;
cout<<"The Magic Square... ";
for(i=0;i<n;i++)
{for(j=0;j<n;j++)
cout<<setw(50/n+2)<<a[i][j];
cout<<" ";
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.