find average of numbers generated by for loop

Hi so I have to output all numbers between 2 numbers a user inputs. I used a for loop to do so but now I need to figure out how to use those numbers from the for loop and find the average.

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
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

void main()
{
	//define variables
	int Width;
	int Height;

	//define output variables
	int Average;
		
	//prompt user for height
	cout << "Enter a box height(between 3 and 10):";
	cin >> Height;

	//prompt user for width
	cout << "Enter a box width (between" << Height <<" and 20):";
	cin >> Width;

	//prompt user to repeat height if out of bounds
	while(Height  < 3 || Height > 10)
	{
		cout << "That number is out of bounds: Try height again: ";
		cin >> Height;
	}

	//prompt user to repeat height if out of bounds
	while(Width < Height || Width > 20)
	{
		cout << "That number is out of bounds: Try width again: ";
		cin >> Width;
	}

	cout << "\nThe integers between " << Height << " and " << Width
	<< " are:" << endl <<"\t";

	//for loop output integer between height and width
	for (Height; Height <= Width; Height ++)
	{
		cout << Height << " ";
	}
}
Last edited on
If I understand what you are saying correctly, the difference between your high number and low number is the amount of inputs that will occur. So sum up all the numbers in that range and divide by the input number and that should produce the average. I hope that helps.
Right but what I can't figure out is how to find sum of the numbers from the for loop. it outputs all the numbers between the high and low but I need to figure out how to get it to add them all together, then I can just divide by the difference of the input numbers
You just need to create another variable, call it sum and put it in the for loop. Then sum += the low number and you should be able to get the total sum.
sorry I'm not sure if I understand. Would I make another for loop nested inside the first? If I make the sum += low number it will add them all up for me? what do you think about using a while loop?
No you shouldn't have to nest another loop. Just the sum variable inside the for loop. sum += height if that is your low number. Then of course you can sum/input # outside of the loop and there is your avg.
Thanks for the help man, I finally got it figured out

1
2
3
4
5
6
7
8
9
10
11
12

//calculate the number of numbers between height and width
	NumCount = (Width - Height) + 1;

	//calculate integers between height and width and sum of those
	for (Height; Height <= Width; Height++)
	{
		cout << Height << " ";
		NumSum = NumSum + Height;
	}
	cout << endl;
Topic archived. No new replies allowed.