Tuesday, 15 April 2014

c - How could I print the max and min values in a 2D array? -



c - How could I print the max and min values in a 2D array? -

here code, working prints min value , prints negative. wrong code ?

#include <stdio.h> int main(void) { double x[5][5],max, min; int i, j; (i = 0; i<5; i++) { (j = 0; j<5; j++) scanf("%lf", &x[i][j]); } max = x[0][0]; min = x[0][0]; if (x[i][j] > x[0][0]) printf("max= %f\n", x[i][j]); else if (x[i][j] < x[0][0]) printf("min = %f\n", x[i][j]); homecoming 0; }

you never iterate through arrays after receiving inputs, because outside for loops. do:

max = x[0][0]; min = x[0][0]; for(i = 0; < 5; ++i) { for(j = 0; j < 5; ++j) { if (x[i][j] < min) // current element smaller min? min = x[i][j]; // if so, update min if (x[i][j] > max) // current element greater max? max = x[i][j]; // if so, update max } } printf("max= %f\n", max); printf("min= %f\n", min);

c max min

No comments:

Post a Comment