I am really frustrated , I tried all day to make it works but never figured it out. I need to find 2 largest
and 2 smalllest
numbers from arr[11]
.
Here is what I have been done so far :
int main(){
float arr[11] ,max = 0, max2, min, min2;
int i = 0;
for (i = 0; i < 11; i++){
scanf("%f", &arr[i]);
}
max = arr[0];
max2 = arr[0];
min = arr[0];
min2 = arr[0];
for (i = 1; i < 11; i++){
if (arr[i] > max)
max = arr[i];
if (arr[i] < min)
min = arr[i];
}
while (min == min2){
min2 = arr[1 + i];
i++;
}
for (i = 10; i > 0; i--){
if (arr[i] > max2 && arr[i] < max)
max2 = arr[i];
if (arr[i] < min2 && arr[i] > min)
min2 = arr[i];
}
printf("Max = %.2f\nMax2 = %.2f\nMin = %.2f\nMin2 = %.2f", max, max2, min, min2);
getch();
return 0;
}
You could sort it, but that will be O(n log n) if the array gets any larger. It's pretty irrelevant for 11 elements, though, and if you're certain it'll always be 11, then sorting would be the easiest method.
Failing that, the simplest way, from the perspective of understanding the code, would be:
In terms of the code you have, the problem is here:
while (min == min2){
min2 = arr[1 + i];
i++;
}
This is after your first loop, where i
ran from 1 to 10. At the end of the loop, the value of i
would have been 11. But now you're keeping scanning, and i
is still increasing... you've run past the end of the array!
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments