### FInd the largest number

im trying to write a source code that find the smallest, largest and average of numbers in array. the code runs fine, but it is not giving the highest number and the the average should include only four number excluding highest and smallest number from the array.
 ``123456789101112131415161718192021222324252627282930`` ``````void OlympicJudging() // Olympic Judging { int numbers [6]; double average, sum = 0; int temp; for(int i = 0; i < 6; i++){ cout << "Please type a value for scores: "; cin >> numbers[i]; } for(int i = 0; i < 6 ; i++){ for(int j = 0; j < 6 + 1; j++){ if(numbers[i] < numbers[j]) { temp = numbers[i]; numbers[i] = numbers[j]; numbers[j] = temp; } } } for(int k = 0; k < 6;k++) { sum = sum + numbers[k]; } average = sum / 6; cout << "\nHighest Score: " << numbers[6] << endl; cout << "Lowest Score: " << numbers[0] << endl; cout << fixed; cout << setprecision(1) << "Olympic Average: " << average << endl; } ``````
Need help
This looks wrong: `for(int j = 0; j < 6 + 1; j++)`
On the next line `numbers[j]` will be accessing numbers[6] which is the non-existent seventh element of the array.

(Actually it isn't necessary to sort the array if all you need is the highest, lowest and total, you can get those values in a single pass through the array - or indeed get rid of the array and capture them during the user input process).
Make the following changes in your code
 ``123456789101112131415161718192021222324`` `````` int smallest=0; int largest=0; // find the largest and smallest element for(int i = 0; i < 6 ; i++){ if(numbers[i] < smallest) { smallest=numbers[i]; } if(numbers[i]>largest) { largest=numbers[i]; } } // average for(int i = 0; i < 6 ; i++){ sum=sum+numbers[i]; } average=(sum-largest-smallest)/4; ``````
In the code posted by anmol2701, instead of
 ``12`` `````` int smallest = 0; int largest = 0;``````

this might be better:
 ``12`` `````` int smallest = numbers[0]; int largest = numbers[0];``````

Also it's possible to use just a single for loop, accumulate the sum within the first loop.
Or:
 ``12345`` ``````#include int largest = std::numeric_limits::min(); int smallest = std::numeric_limits::max();``````

Topic archived. No new replies allowed.