By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
449,370 Members | 1,534 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,370 IT Pros & Developers. It's quick & easy.

Print number of times an input was given, and take the average of the inputs

P: 2
Hello, and thanks for any help in advance!

Basically, as the title says, I am looking for a way to print the number of times the user gave the program an input, and then also print the average of all the inputs.

So far, I have initialized three variables as follows:

Expand|Select|Wrap|Line Numbers
  1. int counter=0;
  2. int sum=0;
  3. float average=0;
Do I need to use a loop to do this? I have also written the expressions for the three variables:

Expand|Select|Wrap|Line Numbers
  1. sum = sum + size;
  2. counter = counter + 1;
  3. average = sum/counter;
I have tried printing the values of counter and average, and I get a negative counter value and a nonense average value.

So, in summary, do I need a loop to print the number of inputs and their average? Also, using a loop or not, how do I get the second three lines of code to work correctly?

Thank you in advance for any help!!
Apr 6 '08 #1
Share this Question
Share on Google+
3 Replies

P: 542
Yes you need to declare size and since you are keeping track of sum, count and average you need to control with a loop. You also need to input something with cin>>.At the moment the three variable = 0 and you are also dividing by 0
Apr 6 '08 #2

P: 2
I already have declared size, and have an input already set for size, and the program, which prints squares, works perfectly except for this part. I just didn't want to post too much code.

But how do I actually set up the loop using them? That is the problem I am having.
Apr 6 '08 #3

P: 542
You could do something like this:
Expand|Select|Wrap|Line Numbers
  1. cout<<"Enter an integer";
  2. for(int i=0;i<20;i++)
  3. {cin>>integer;
  4. numberIntegersEntered+=1;
  5. sum+=integer;
  6. averageSum=sum / numberIntegersEntered;
  7. cout<<"The average of the integers entered is: "<<averageSum<<endl;
  8. //if this was a function you could add:
  9. return numberIntegersEntered;//and display this value
Apr 10 '08 #4

Post your reply

Sign in to post your reply or Sign up for a free account.