Stuck... on a while loop! Help please!

Write a loop that will accept numbers from a user as long as he wishes to enter numbers. Calculate the sum of all numbers that were entered and when the user exits the loop, display the sum and average of the numbers entered.

Here's what I've got.

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
#include <iostream>
#include <iomanip>

using namespace std;

int main ()
{

	float xNum= 1;
	float sum= 0.0;
	int n= 0;
	float average= 0.0;

	while ( xNum != 0)//0 as sentine
	{
		cout << "Enter a number (enter 0 to stop): ";
		cin >> xNum;

		sum+=xNum;

		n++;
	}	

	average=(sum+=xNum)/(n-1);

	cout << "Sum: " << sum << endl;
	cout << "Average: " << average << endl;


system ("pause");
return 0;
}


It will only display the sum and for some reason my sentinel value (-1) is also calculated with it!
Last edited on
average=(sum+=xNum)/n

Missing a semi-colon. On a note on this code, the operation you used for sum and xNum creates an incorrect result for sum at the end. Might want to take a look at that.

As for taking the final -1 into account, you could throw in an if statement right under cin >> xNum; to break; if (xNum == -1);. The program still runs after you enter an input for xNum, there must be a way to stop the program from executing:

1
2
3
n= n + 1;
sum+=xNum;
average=(sum+=xNum)/n


Or you could try this, while (cin >> xNum), which runs the while loop as long as the input matches the type of xNum (conversion applies).

The loop stops when you hit end-of file (ctrl+z enter), or when a condition within the loop explicitly stops the loop (an if statement perhaps).
Last edited on
Alright I put the semi-colon in.

I would use a another loop the the prompt states use "a" loop and my instructor is pretty strict with us doing it verbatim.

I switched some things around as well and now i can get it to at least 'calculate an average even if it's not correct. I call that progress.

Please re-evaluate if you may. I'll update the code.
Go through the loop and think about what happens.

1. Program prompts for a number.
2. User enters -1.
3. Program reads -1 into xNum.
4. The sum is incremented by xNum (so sum = sum - 1).
5. N is incremented by 1.
6. Loop condition fails, exit the loop.

Also, average=(sum+=xNum)/(n-1); is not right.
Okay. I see.

So I just changed the condition to now be ( xNum != 0) and then changed float xNum= 1;

And for the average=(sum+=xNum)/(n-1);, its for it to not include the sentinel value as another number input. That's why there's the (n-1)

Now it works perfectly. Thank you and I updated the code again.
Topic archived. No new replies allowed.