Find the maximum sum of a column of two dimensional arrays in c
max1
is unintialized, hence the test if (sum > max1)
is meaningless and max1
may not be updated correctly. In your case, max1
happened to have the value 4201200
, but the behavior is undefined and this could have been any value or even a trap value on some systems.
Since all matrix elements are positive, you can initialize max1
to 0
, otherwise you would use INT_MIN
defined in <limits.h>
or add a test for the first column.
Furthermore, the index values i
and j
are swapped in the second loop and the loop test is incorrect too.
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int rows = 3, cols = 5;
int *a = (int *)malloc(rows * cols * sizeof(int));
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
a[i * cols + j] = (rand() % (10 - 1 + 1)) + 1;
}
}
printf("The array elements are:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf(" %2d", a[i * cols + j]);
}
printf("\n");
}
int max_col = 0;
int max_sum = 0;
for (int j = 0; j < cols; j++) {
int sum = 0;
for (int i = 0; i < rows; i++) {
sum += a[i * cols + j];
}
printf("sum of column %i is -> %d\n", j, sum);
if (j == 0 || sum > max_sum) {
printf("max is detected\n");
max_sum = sum;
max_col = j;
}
}
printf("max is %d column %d\n", max_col, max_sum);
free(a);
return 0;
}