I need to sum and output the rows, columns, and main diagonals. Can someone please tell me what I'm doing wrong? This is the code I was given to use but I can't seem to get it to output my sums. I put a comment in the code below where I beleive my problem exist, where it starts summing and where it stops. I would appreciate any help as I am having trouble figuring this out on my own. The output should a 3 x 3 matrix with the sums of the rows, columns and diagonals in a fourth row and column to equal 15. My output is not summing the rows, columns, and diagonls.
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main()
{
int n = 3;
int row, col, r, c, i, j, k, diag=0;
int magic[19][19];
ofstream fout;
fout.open("p4-out.txt");
for(j=0 ; j<n+1 ; j++){
for(k=0 ; k<n+1 ; k++)
magic[j][k] = 0;}
row=1; col=(n+1)/2;
magic[row-1][col-1]=1;
for(i=2 ; i<=(n*n) ; i++){
row-=1; col-=1;
if(row==0 && col==0){col++; row+=2;}
else if(row==0) row=n;
else if(col==0) col=n;
else if(magic[row-1][col-1]!=0)
{col++; row+=2;}
magic[row-1][col-1]=i;}
for(r=0; r<n; r++){
for(c=0; c<n; c++)
magic[r][n]+=magic[r][c];}
for(c=0; c<n; c++){
for(r=0; r<n; r++)
magic[n][c]+=magic[r][c];}
for(r=0; r<n; r++){
magic[n][n]+=magic[r][r];}
for(r=1; r<(n-1); r++){
c = n - r + 1;
diag+=magic[r][c];}
for(r=0; r<(n+1) ; r++){
fout << endl;
for(c=0; c<(n+1) ; c++)
{fout << setw (5) << magic[r][c];}
fout << endl;}
return 0;
}
// This my output.
15 <---// I need this 15 to go
6 1 8 15 |
|
7 5 3 15 |
|
2 9 4 15 |
|
[15] 15 15 15 15 |
^-------------<------------<----------<-------|
here
Using proper indexing would fill up your sum
rows and columns too, try:
for(r=0; r<n; r++){ //Where it should start summing
for(c=0; c<n; c++){
magic[r][n]+=magic[r][c];}
}
for(c=0; c<n; c++){
for(r=0; r<n; r++){
magic[n][c]+=magic[r][c];}
}
for(r=0; r<n; r++){
magic[n][n]+=magic[r][r];
}
for(r=0; r<n; r++){
c = n - r + 1;
diag+=magic[r][c];} //where it should stop summing