Search code examples
carraysmathsumdev-c++

Sum of arrays in C


So folks, below is a part of my code, I need to sum what’s in each column and sum what’s in the entire table, could you help me on how to do that, using an array in code? just talking didn't help me, I would like to see it in code to understand it better.

void main(void){
//Matrix Declaration and Initialization with the Production Data of each Branch; 
//Format: productionXX[shift][week];
    int productionSP[3][4] = {{1000, 1030,  900,  990},
                              {1010, 1045, 1100, 1015},
                              {1050, 1065, 1075, 1100}};

Solution

  • You could do it using loops as follows -

    #include <stdio.h>
    
    int main() {
        int productionSP[3][4] = {{1000, 1030,  900,  990},
                                  {1010, 1045, 1100, 1015},
                                  {1050, 1065, 1075, 1100}};
        int column_sum[4]={0};
        int final_sum=0;
    
        // i denotes iterating over each of the rows
        for(int i=0;i<3;i++){
            // j denotes iterating over each column of each row
            for(int j=0;j<4;j++){
                final_sum+=productionSP[i][j];
                column_sum[j] +=  productionSP[i][j];
            }
        }
        printf("column sums - \n");
        for(int i=0;i<4;i++){
            printf("Column #%d - %d\n",i+1,column_sum[i]);
        }
        printf("final_sum = %d",final_sum);
    }
    

    Output :

    column sums -                                                                                                                                                                               
    Column #1 - 3060                                                                                                                                                                            
    Column #2 - 3140                                                                                                                                                                            
    Column #3 - 3075                                                                                                                                                                            
    Column #4 - 3105                                                                                                                                                                            
    final_sum = 12380
    

    You can change the loop break conditions as per your productionSP array. For now it has static 3 rows and 4 columns. You can change your loop condition accordingly when you matrix is of a different size.

    Hope this helps !