here is my code, it is working but it prints only the min value and prints it as negative. what is wrong with this code ?
#include <stdio.h>
int main(void) {
double x[5][5],Max, Min;
int i, j;
for (i = 0; i<5; i++)
{
for (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]);
return 0;
}
You never iterate through your arrays after receiving the inputs, because you are outside the for
loops. You could do:
Max = x[0][0];
Min = x[0][0];
for(i = 0; i < 5; ++i)
{
for(j = 0; j < 5; ++j)
{
if (x[i][j] < Min) // Is current element smaller than Min?
Min = x[i][j]; // If so, update Min
if (x[i][j] > Max) // Is current element greater than Max?
Max = x[i][j]; // If so, update Max
}
}
printf("Max= %f\n", Max);
printf("Min= %f\n", Min);
You forgot to enclose the search of the minimum and the maximum in a loop.:)
Try the following
for (i = 0; i<5; i++)
{
for (j = 0; j<5; j++)
scanf("%lf", &x[i][j]);
}
Max = x[0][0];
Min = x[0][0];
for (i = 0; i<5; i++)
{
for (j = 0; j<5; j++)
{
if ( Max < x[i][j] )
{
Max = x[i][j];
}
else if ( x[i][j] < Min )
{
Min = x[i][j];
}
}
}
printf( "Max = %f\n", Max );
printf( "Min = %f\n", Min );
You need to iterate through all the values in the 2D array to check all the values of the 2D array and set the max
and min
variable accordingly:
Max = x[0][0]; //set max as the first element
Min = x[0][0]; //set min as the first element
for (i = 0; i<5; i++) //loop through each row
{
for (j = 0; j<5; j++) //loop through each column
{
if (x[i][j] > Max) //if current value is more than max
Max=x[i][j];
if (x[i][j] < Min) //if current value is less than min
Min=x[i][j];
}
}
printf("Max= %f\n", Max);
printf("Min = %f\n", Min);
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.