FInd the largest number

May 13, 2014 at 6:47pm
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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;
}
May 13, 2014 at 9:49pm
Need help
May 13, 2014 at 11:01pm
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).
May 14, 2014 at 4:31am
Make the following changes in your code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
        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;

        
  
      
May 14, 2014 at 10:39am
In the code posted by anmol2701, instead of
1
2
    int smallest = 0;
    int largest  = 0;

this might be better:
1
2
    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.
May 14, 2014 at 11:29am
Or:
1
2
3
4
5
#include <limits>


  int largest  = std::numeric_limits<int>::min();
  int smallest = std::numeric_limits<int>::max();

Topic archived. No new replies allowed.