Home > Software engineering >  Calculating sum of columns C
Calculating sum of columns C

Time:11-02

I am new to programming in c, on a question I received the code below and was asked to add a code block that would calculate the sum of each column in the array(which is given by the user) and return the index of column that has the biggest sum in it. My best attempt was to create 4 sums and add each column's numbers to its sum, but it seemed too messy and I couldn't make it work, added the code below. Would love to see an example of how it can be done, ty.

#include <stdio.h>   
#define ROW 3   
#define COL 4
void input(int m[][COL]) ;
int sumAllMat(int m[][COL]) ;

int main(){
    int mat[ROW][COL],sum;
    input(mat);
    sum =sumAllMat(mat);
    printf("sum = %d\n", sum);
}
void input(int m[][COL]) {
    int r,c;
for (r=0 ; r<ROW ; r  ){
    printf("\n Enter values into row #%d : \n", r);
    for (c=0 ; c<COL ; c  )
        scanf("%d", &m[r][c]);
}
}
int sumAllMat(int m[][COL]) {
    int r,c,s=0;
    for (c=0 ; c<COL ; c  ) 
        for (r=0 ; r<ROW ; r  )
           s  = m[r][c];
    return(s);
}

.............................

void test(int m[][COL]){
        int a,b,c,d,i,j;
        for(i=0;i<COL;i  ){
            for(j=0;j<ROW;j  ){
                if(i=0){
                    a =m[i][j];
                }
                if(i=1){
                    b =m[i][j];
                }
                if(i=2){
                    c =m[i][j];
                }
                else{
                    d =m[i][j];
                }
            }
        }
        if(a>b>c>d){
            printf("The column with the biggest sum is column 0");
        }
        if(b>a>c>d){
            printf("The column with the biggest sum is column 1");;
        }
        if(c>a>b>d){
            printf("The column with the biggest sum is column 2");;
        }
        if(d>a>b>c){
            printf("The column with the biggest sum is column 3");;
        }
        else{
            printf("The sum of all columns is even");
        }
    }

CodePudding user response:

You can solve this by creating three variables

  • prevSum: the best sum so far
  • sum: current sum
  • prevIndex the best known sum's index

and then:

void test(int m[][COL]){
        int prevSum = -1;
        int prevIndex = -1;
        int sum = 0;
        for(i=0;i<COL;i  ){
            sum = 0;
            for(j=0;j<ROW;j  ){
                sum  = m[j][i];
            }
            if ((prevIndex < 0) || (sum > prevSum)) {
                prevIndex = i;
                prevSum = sum;
            }
        }
        printf("The column with the biggest sum is column %d", prevIndex);
    }

Simple solution and much more dynamic than the one you have started working with.

  • Related