0

[I tried two ways, one is with line 14 and the other is with line 15.Why does line 14 pass the compiler but line 15 does not?]

I did it in two separate steps, the first with a 14-line method alone, and the second with a 15-line approach.

#include<stdio.h>

int main() {
    int matrix[][4] = 
        {{14, 10, 6, 4}, {3, 7, 18, 11}, {13, 9, 5, 17}, {19, 12, 2, 1}}; 
  

  // Checkpoint 1 code goes here.

    int rowDimension=sizeof(matrix)/sizeof(matrix[0]);
    int columDimension=sizeof(matrix[0])/sizeof(int);
  // Checkpoint 2 code goes here.
    
    for(int i=0;i<rowDimension;i++){
      for(int j=0;j<columDimension;j++){
        int sum = sum+matrix[i][j]; //line 14
        int sum +=matrix[i][j]; //line 15
        printf("%d\n",sum);
    }
  }
    
}
justin103
  • 3
  • 2

1 Answers1

3

This is a declaration:

 int x = matrix[i][j];

This is an expression statement:

 x += matrix[i][j];

This is not valid C code:

 int sum += matrix[i][j];

It is not a declaration because a declaration cannot have += after the thing being declared. It is not an expression statement because an expression statement cannot begin with a type.

This compiles

 int sum = sum+matrix[i][j];

but only if you ignore compiler warnings. Don't. More info.

The way to add up values in an array is this:

  1. Declare the sum before the loop and initialise it to zero.

      int sum = 0;
    
  2. Add values to the sum inside the loop:

      for (... whatever...) {
          sum += ... whatever ...;
      }
    
n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243