Is my code correct for what I want to do?

Does this look correct? I wanted it to keep looping until the sum of the columns are equal to that of the rows. It keeps printing random numbers in a 3x3 array until it is correct.
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
 #include <iostream>

using namespace std;
int magicSquare[3][3];
int row;
int col;
int rowSum;
int colSum;



int main()
{

 int rowSum1 = 0, rowSum2 = 0, rowSum3 = 0;


    for(int row = 0; row < 3; row++)
    {
            rowSum1 += magicSquare[0][row];
            rowSum2 += magicSquare[1][row];
            rowSum3 += magicSquare[2][row];

    }
    rowSum = rowSum1 + rowSum2 + rowSum3;




int colSum1 = 0, colSum2 = 0, colSum3 = 0;

for(int col = 0; col < 3; col++)
    {
            colSum1 += magicSquare[0][col];
            colSum2 += magicSquare[1][col];
            colSum3 += magicSquare[2][col];

    }
    colSum = colSum1 + colSum2 + colSum3;


while (colSum == rowSum)
{
      for (row = 0; row < 3; row++)
	{
		for (col = 0; col < 3; col++)
		{
			magicSquare[row][col] = rand()%9;
			cout << magicSquare[row][col] << "    ";
		}
        cout << endl;
	}
}

    return 0;
}
Well test it yourself! And tell us if you get any errors and we can help you.

EDIT: Grammar mistake XD
Last edited on
Nope no errors, I'm just concerned that the while loop will never end haha.

Also the only problem I'm having is making sure that each number in the magicSquare array are unique. Because right now there not, could you help?
Maybe i am missing something here. colSum and rowSum are not calculated in the while loop so condition is always true and while will never end.Right?
Thats the exact problem I'm having. How would I calculate them in the while loop?
Topic archived. No new replies allowed.