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>
usingnamespace 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.
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.
#include <iostream>
usingnamespace 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;