LOOPS...

I have trouble with this, a program to enter 15 numbers and calculate the summation and average of number less than 20. i successfully found the sum but for the average part i cant seem to figure it out. lets say 5 of the 15 numbers are less than 20 i want the sum of the 5 entered numbers divided on 5...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int main()
{
	int i, n;
	float sum = 0, avg;
	for (i = 1; i <= 15; i++)
	{
		cin >> n;
		if (n < 20)
		{
			sum = sum + n;
			avg = sum /n  ;
		}
		
	}
        cout << "sum = " << sum << endl;
		cout << "average = " << avg << endl;
		

	return 0;
}
Last edited on
Just to be clear you want to divide the sum by 5 to get the average? And do you always want to divide the sum by 5?
Also what if the user enters a number that is > than 20 you should include an else if statement so that if (n>20) cout something like "Error, please enter a number less than 20" also inside the for loop you should have a cout statement prompting the user to enter a number less than 20 if thats what you want. However, if you're the only one using this program then you're fine.
Not always by 5 but for the entered numbers that are less than 20. lets say 8 of the 15 numbers are less than 20 e.g. (2,3,1,4,5,4,4,3)their sum is 26 i want the 26 divided by 8. sorry if my question was unclear. #GhostCas
A couple of comments. You need to maintain a count of how many number are less than 20. Declare a variable at the start, initialise it to zero. Each time you encounter a number less than 20, increment that count.

The other comment is - don't calculate the average inside the loop - that's just wasted effort as all the previous values don't matter. After the loop has ended, calculate the average as sum/count.
Chervil, wonderful suggesstion i will work on it now.
it works :)))) thank you both.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int main()
{
	int i, n;
	float sum = 0, avg,count=0;
	cout << "enter numbers less than 20"<<endl;
	for (i = 1; i <= 15; i++)
	{
		
		cin >> n;
		if (n < 20)
		{
			sum = sum + n;
			count++;
		}
		else
			cout << "error" << endl;
	}
                       cout << "sum = " << sum << endl;
		cout << "average = " << sum/count << endl;
		

	return 0;
}
Last edited on
Topic archived. No new replies allowed.