Kyle
Kyle

Reputation: 3042

Adding 2 dimensional array rows

for (row=0; row<8; row++)
    {
        for (col=0; col<8; col++)
        {
            answer+=my_data[row][col];
        }
        printf("The sum of row %i is: %i\n", row,answer);
        answer = 0;//to reset answer back to zero for next row sum 
    }

I have an 8x8 array and I'm adding each row and resetting the answer back to zero so you get the exact answer for each row. However it's not working... What is wrong?

Upvotes: 1

Views: 2941

Answers (2)

Kyle
Kyle

Reputation: 3042

Forgot to initialize answer to zero in the beginning of the program.

int answer = 0;

Thanks Gunner and Pedro.

Upvotes: 0

codaddict
codaddict

Reputation: 454920

How is answer declared ?

If it is declared without an initial value then your existing code will fail as answer will have junk value for 1st row. To fix this :

for (row=0; row<8; row++) {
        answer = 0; // clear the running sum.
        for (col=0; col<8; col++) {
            answer+=my_data[row][col];
        }
        printf("The sum of row %i is: %i\n", row,answer);       
}

Upvotes: 4

Related Questions