Error finding the largest and the smallest number

I writed a program in wich you can enter 10 numbers and then calculate the sum and the average of all numbers and also find the largest and the smallest number.
I have and error finding the largest and the smallest number. I don't know what's wrong.

I writed the following 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
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
using namespace std;

int main()
{
	double num[10];
	double sum = 0, largest, smallest, avg;
	int i = 0;
	for (i = 0; i < (sizeof(num) / sizeof(num[0])); i++)
	{
		cout << i+1 << ".Enter a number: ";
		cin >> num[i];
	}
	cout << endl;
	cout << "You entered the following numbers: " << endl;
	for (i = 0; i < (sizeof(num) / sizeof(num[0])); i++)
	{
		cout << num[i] << ' ';

		sum = (num[i]) + sum; //sum
		
		largest = smallest = num[0];

		largest = largest > num[i] ? largest : num[i]; //largest
		
		smallest = smallest < num[i] ? smallest : num[i]; //smallest

		avg = sum / (sizeof(num) / sizeof(num[0])); //average
	}
	cout << endl << endl;
	cout << "SUM:\t\t" << sum << endl;
	cout << "LARGEST:\t" << largest << endl;
	cout << "SMALLEST:\t" << smallest << endl;
	cout << "AVERAGE:\t" << avg << endl;
	cout << endl;
	return 0;
}
Last edited on
Line 22: You're resetting largest and smallest each time through the loop. This line should be after line 15.

Line 28: You're recalculating avg each time through the loop. This is harmless, but should really be after line 29 since you only need to do it once.

Thank you, now everything works fine!
Topic archived. No new replies allowed.