1
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?

6
  • 2
    Do you set answer to 0 before the loops start? Commented Mar 2, 2011 at 6:20
  • How about changing answer = 0; to the start of the bucle? Commented Mar 2, 2011 at 6:21
  • When you say not working, what exactly is not working? compilation error? strange value coming out? etc. also how are answer,row,col declared? Commented Mar 2, 2011 at 6:21
  • Put some example to explain your problem Commented Mar 2, 2011 at 6:22
  • No I did not. Thanks for catching my error haha I forgot to initialize it to zero! Commented Mar 2, 2011 at 6:26

2 Answers 2

4

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);       
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

int answer = 0;

Thanks Gunner and Pedro.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.