Counters

Apr 2, 2017 at 10:59am
closed account (2z7fGNh0)
Hey, I have confusion regarding counters and how to differentiate them from initialized values. I have to write a program that prints the average and sum of all numbers from 20 to 50. My confusion is with the "20-50" part specifically. The user does not input anything. Everything must be done by the program.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;
int main()
{
	int sum = 0;
	float av;
	int count;

	for (count= 20; count <=50; ++count)
	{
		sum += count;
	}
	av = sum / ; //Here's the apparent problem. Don't know what to divide the sum by.
	cout << "Sum=" << sum << endl << "Average=" << av << endl;


Now if the numbers had been from 0-50, the counter initialization would have been the same as the actual number value, so no problem. But since the numbers start from 20, it's confusing.
Apr 2, 2017 at 11:08am
Imagine you would have to sum up the numbers between 1 and 3.
Obviously this would be 3 numbers, 1,2,3.
The formular is max - min + 1. So for your problem it would be 50 - 20 + 1.
Apr 2, 2017 at 11:10am
closed account (48T7M4Gy)
To avoid duplicating the 20's and 50's try this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;
int main()
{
	int sum = 0;
	float av;
	int count;

        int start = 20;
        int finish = 50

	for (count = start; count <= finish; ++count)
	{
		sum += count;
	}
	av = sum / (finish - start + 1); //Here's the apparent problem. Don't know what to divide the sum by.
	cout << "Sum=" << sum << endl << "Average=" << av << endl;
Last edited on Apr 2, 2017 at 12:26pm
Topic archived. No new replies allowed.