vector magic square program

Hello, I am writing a program that adds the rows, columns, and diagonals of a matrix to see if they are equal, but for some reason no matter what I input the output is always magic, and I can not figure out why. Thanks!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#include <iostream>
#include <iomanip>
#include <cstdlib>	
#include <math.h>
#include <algorithm>
#include <vector>
using namespace std;

void fillSquare(vector<vector<int> > &mat, int nrows, int col);

void printSquare(vector<vector<int> > &mat);

bool isMagic(vector<vector<int> > &mat, int n);

void fillSquare(vector<vector<int> > &mat, int nrows, int col)
{
	cout<<"Enter Data in square"<<endl;
    for(int i = 0; i < nrows; i++)
    {
        for(int j = 0; j < col; j++)
        {
            cout<<"Enter row ["<<i<<"]: ";
            
            cin>>mat[i][j];
        }
    }	

}

bool isMagic(vector<vector<int> > &mat,int n)
{
	bool status = true;
	int frwdDiagSum = 0;
	int bkwrdDiagSum = 0;
	int num, num2;
	
	for (int i = 0; i < n; i++)
	{
		frwdDiagSum += mat[i][i];
		bkwrdDiagSum += mat[i][n-1-i];
	}
	
	if (frwdDiagSum == bkwrdDiagSum)
	{
		num = frwdDiagSum;
	}
	else 
		status = false;
		
	int rowTotal[4] = {0};
	for (int r = 0; r < n; r++)
	{
		for (int c = 0; c < n; c++)
			rowTotal[r] += mat[r][c];
	}

	int colTotal[4] = {0};
	for (int c = 0; c < n; c++)
	{
		for (int r = 0; r < n; r++)
			colTotal[c] += mat[r][c];
	}
	
	for (int i = 0; rowTotal[i] && colTotal[i]; ++i)
	{
		if (rowTotal[i] != colTotal[i])
		{
			status = false;
		}
		else if (rowTotal[i] == colTotal[i])
		{
			num2 = rowTotal[i];
		}
		
		
	}
		
	if (num == num2)
	{
			status = true;
	}
	else
			status = false;
	


	return status; 
}

void printSquare(vector<vector<int> > &mat)
{
	for(int i = 0; i < mat.size(); i++)
	{
		for(int j = 0; j < mat[i].size(); j++)
		{
			cout << mat[i][j] << "   ";
		}
		
		cout << endl;
	}
}

int main()
{
	int nrows, ncol;
	bool magic;
		
	cout << "Enter # of rows for the matrix: ";
	cin >> nrows;
	cout << endl;
	cout << "Enter # of columns for the matrix: ";
	cin >> ncol;
	cout << endl;

	vector<vector<int> > mat(nrows, vector<int>(ncol));
	const int n = ncol;
	
	fillSquare(mat, nrows, ncol);
	
	printSquare(mat);
	
	cout << "Sum of any row, any column or either diagonal: 15" << endl;

	magic = isMagic(mat, n);

	if (magic == true)
		cout << endl << "Magic" << endl;
	else 
		cout << endl << "Not magic" << endl;
	
	return 0;
}
Topic archived. No new replies allowed.