Home > Software engineering >  Initialize a variable with the sum of the first column
Initialize a variable with the sum of the first column

Time:02-21

I have made a program which finds the column that has the min sum out of a 2d array. To calculate it, I initiated the min variable of the lowestSum function.

Purpose

I am trying to initialize the min variable with the sum of the 1st column instead of giving a specific number. So far only with providing a specific number I made it work. See the code below:

Therefore, how should it store the sum of the first column and then check against the other columns to eventually find the column with the min sum of values? Now it works only by providing the min specifically.

#include<stdio.h>

#define ROWS 4
#define COLS 3

void printnumbers(int arr[][COLS]);
int lowestSum(int MovieRatings[][COLS]);
int main() {
    int arr[ROWS][COLS] = {{1, 2, 3},
                     {2, 3, 4},
                     {3, 4, 5},
                     {5, 15, 6}};
    printnumbers(arr);
    printf("the lowest sum is in column %d\n", lowestSum(arr));
return 0;
}


void printnumbers(int arr[][COLS]){

    int i,j;

    for(i = 0; i<ROWS; i  )
    {
        printf("\n");
        for(j = 0; j<COLS; j  )
        {
            printf("%d\t", arr[i][j]);
        }
    }
}




int lowestSum(int arr[][COLS]){
    int i, j, total, min,min_col;
    min = 20;                   //<------this is is intialization
    for (j = 0; j < COLS; j  ) {
        total = 0;
        for (i = 0; i < ROWS; i  ) {
            total  = arr[i][j];    
            }
        if (min > total) {
            min = total;
            min_col = j 1;
            printf("\n");
        }
    }
    return min_col;
}

CodePudding user response:

After summing up the first column, that one will for the moment have the smallest sum. So if you're on the first iteration of the outer loop, set min.

    if (j == 0 || min > total) {
        min = total;
        min_col = j 1;
        printf("\n");
    }
  • Related