Comparing in 2d Arrays


Here's part of my code:
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
bool isMagic (int magic [][4], const int row, const int col)
{
int originalSum = 0, currentSum;
     bool result = true;

	 // Add first row
     for (int row = 0; row < 4; row ++) 
	 {
		originalSum += magic[4][4]; 
	 }
	 

	 // Add rows and compare to originalSum
     for (int row = 1; row < 4; row ++) 
      { 
		  currentSum = 0;

          for ( int col = 0; col < 4; col ++)
		  {
			    
				currentSum += magic[row][col]; 
		  }
        
		  cout << currentSum << endl;
		  if ( currentSum != originalSum)  
            return (false);  
      }
     
	 //Add columns and compare to originalSum
     for ( int col = 0; col < 4; col ++)   
       { 
		  currentSum = 0;

          for (int row = 0; row < 4; row ++)
		  {
             currentSum += magic [row][col];   
		  }
             if ( currentSum != originalSum) 
			 {
				return (false); 
			 }
        }

// compare diagonal front
     currentSum = 0;
     for (int row = 0; row < 4; row ++)  
	 {
			currentSum += magic[row][row];  

			if ( currentSum != originalSum) 
			{
				return (false);  
			}
	 }

// diagonal back
    currentSum = 0;
    for (int row = 0; row < 4; row ++) 
	{
        currentSum += magic [row] [row - 1];

      if ( currentSum != originalSum)  
       {
		   return (false);  
	  }
    else
        return (true);

	}
}


My program is not adding and comparing the results right. The point is to see if the sum of each row, column, and middle diagonal are the same. I'm not sure if there is a mistake in my program or if I'm missing something apparant, but the numbers and comparisons aren't summing correctly. I was going to do comparisons using a while loop, but I am not totally sure how to implement that with the bool statement. Any help is appreciated. (:
Line 9 could be off. U say 'add first row' but u are only adding the same element 4 times.
Line 60. The first time this goes through u are accessing the element magic[0][-1] which will surely cause an out of range exception...
Last edited on
how would I go about making it add just the first row as a comparison tool?
line 30: originalSum += magic[row][4];
1
2
3
4
5
6
7
8
int i;
int sumr0 = 0, sumc0 = 0, sumd = 0;
for (i = 0; i < 4; i++)
{
	sumr0 += magic[0][i];	// sum of elements in row 0
	sumc0 += magic[i][0];   // sum of elements in col 0
	sumd  += magic[i][i];	// trace of the array
}
Topic archived. No new replies allowed.