简体   繁体   中英

How to find the smallest sum of rows(2D array) C programming

This one is good for finding the largest number and his row but i dont know how to find the smallest sum. I tried to compare it like mat[i][j] < sum of row but it doesnt work. If u can help me a bit

 #include <stdio.h>
#include <stdlib.h>

int main()

{
    int i, j,n, sum_row, min_row;

printf("Enter the size of an array: ");
scanf("%d", &n);
int mat[n][n];

printf("\nEnter numbers in array:");
for(i=0;i<n; i++){
    for (j=0;j<n;j++){
        scanf("%d", &mat[i][j]);
    }
}



min_row=mat[0][0];
for(i=0;i<n;i++){
        sum_row=0;
    for (j=0;j<n;j++){
            sum_row +=mat[i][j];


       if(mat[i][j]<sum_row)
            sum row=mat[i][j];
           /*  min_row=i; */

    }
}
printf("The smallest sum in rows is: %d, and row looks like", sum_row);


/*for(j=0;j<n;j++){
    printf(" %3d", min_row);
}*/





    return 0;
}

I think the comments provided by a few people already point you to the direction. I just sums up all the changes needed for you to check.

#include <stdio.h>
#include <stdlib.h>

int main()

{
    int i, j,n, sum_row, min_row;

    printf("Enter the size of an array: ");
    scanf("%d", &n);
    int mat[n][n];

    printf("\nEnter numbers in array:");
    for(i=0;i<n; i++){
        for (j=0;j<n;j++){
            scanf("%d", &mat[i][j]);
        }
    }

    min_row = - 1;        // row index
    int row_min = 1<<31; // some large number, here I assume int is 32 bit on your machine.  this var saves the min value of row sum

    for(i=0;i<n;i++){
        sum_row = 0;

        for (j=0;j<n;j++){
            sum_row += mat[i][j];


            if(sum_row < row_min) {
                row_min = sum_row;
                min_row = i;
            }

        }
    }

    printf("The smallest sum in rows is: %d, and row looks like %d", row_min, min_row);
}

I suppose n >= 1

int min_row =0;
int i, j;

// min_row is first the sum for first row
for (j=0;j<n;j++)
  min_row +=mat[0][j];

// look at other rows
for (i=1; i<n; i++) {
  // compute current row sum
  int sum_row = 0;

  for (j=0;j<n;j++)
    sum_row +=mat[i][j];

  // look at who is the smallest
  if(sum_row < min_row)
    min_row = sum_row;
}

printf("The smallest sum in rows is: %d", min_row);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM