Arsel Doe
Arsel Doe

Reputation: 21

How to turn this C program into a function which calculates the sum of each row and their total sums?

My Solution: I am running this program in CodeBlocks. It is not working and it shows:

       //error: array type has incomplete elements type 'int[]'
      //warning: return type of 'main' is not 'int'

I want to function which calculates the sum of each row and their total. This solution doesn't work because it shows an error in function declaration.

   //function declaration
  void findSumEachRowAndTotalSum(int a[][], int c, int r){
     int i, j, rowSum, totalSum;
     //ask the user to give elements of rows
     for(i=0; i<c; i++){
       printf("\nGive elements of row %d:\n", i+1);
        for(j=0; j<r; j++)
        scanf("%d", &a[i][j]);
     }
   totalSum = 0;
   for(i=0; i<c; i++){
     rowSum = 0;
     for(j=0; j<r; j++){
     //calculates the sum of each row and total sums
      rowSum = rowSum + a[i][j];
      totalSum = totalSum + a[i][j];
   }
   //displays sum of each row on the screen
  printf("\nSum of row %d is %d", i+1, rowSum);
 }
  //displays the total sum of all rows on the screen
printf("\nTotal sum is %d\n", totalSum);
}

//main function
void main(void){
  int col, row, m[50][50], i, j;
  //...
  //function call
  findSumEachRowAndTotalSum(a,c,r);

}

Upvotes: 0

Views: 95

Answers (2)

Harshith Rai
Harshith Rai

Reputation: 3066

@Osiris, you must post your comment as an answer. You are right, @ArselDoe might have mistakenly overlooked what name was given to the array in main().

@ArselDoe, you have declared the array with the identifier as m[][], but have passed a as the parameter to the function call. Changing this should fix the error.

Upvotes: 0

dbush
dbush

Reputation: 223872

The error is due to the definition of the parameter a to the function findSumEachRowAndTotalSum:

void findSumEachRowAndTotalSum(int a[][], int c, int r){

When an array of more than one dimension is a parameter to a function, only the first dimension is allowed to be left blank. All others must be specified.

Since you seem to be using c and r as the dimensions, you need to give those parameters first and subsequently use them as the dimensions of the array:

void findSumEachRowAndTotalSum(int c, int r, int a[c][r]){

Then you would call the function like this:

findSumEachRowAndTotalSum(50, 50, m);

Regarding the warning, the main function must be defined to return type int, and you need to subsequently return a value:

int main(void){
   ...
   return 0;    
}

Upvotes: 3

Related Questions