sum will not compute

I need these parameters:

prompt for number input, with 0 being the exit character.

input to print one character per line, like so (as they are entered):
3
4
5
6
9
3
4
5
0

Then, sum the numbers entered and output that sum, indicate the number of entries, and indicate whether the sum was < or > 100.

Everything works... EXCEPT, the sum of numbers entered omits the first entry. For the entries above the output is 36 and should be 39 (the three would be omitted).

I cannot change the while loop, or at least that is a requirement (a while loop, not a 'do while' or any other variation)

Any hints?

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
#include "stdafx.h"
#include <iostream>
#include <iomanip>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	int count = 0;
	int sum = 0;
	int n = 0;  // variable for input
	
	cout << "Enter numbers, one per line. Enter 0 to end: \n";
	cin >> n;

	while (n!=0) {  // Loop to allow repeated entries until '0' is entered
	
	count++; // Increment the number of entries
	
	cin >> n;
	sum +=n; // Add up all entered numbers

	}

	cout << "\n\nThank you. " << " The total was: " << sum << ".\n" << endl;
	cout << "The total number of inputs read: " << count << "\n" << endl;
		
	if(sum < 100) { // is sum > 100
		cout << "The total is less than 100. " << endl;
	}
	else {
		cout << "The total is more than 100. " << endl;
	}
	cout << "\n\nEnter a character and ENTER, to quit. ";
	char c; // Added to allow viewing results
	cin >> c; // Any char + enter to exit, once done

    return 0;
}
Line 14
 
cin >> n;


should be
1
2
cin >> n;
sum += n;


Last edited on
Thanks for the reply.

I actually tried that too but placing the sum statement outside of the while loop then only includes the first entered number in the sum. With it _after the while loop it sums nothing (returns zero).

Craif
hm....try this then
try assigning a value to n as 1 or something but not including it in the sum.

1
2
3
4
5
6
7
8
9
10
......
// no cin command here.
int n = 1;

while ( n != 0 )
{
	cin >> n;
	sum += n;
	count++;
......
Actually it should be a do while loop look closely a do while will save that concept and just add the while loop in it you should review the do while loop in the tutorials on this site is uses that exactg eexample
Excellent! That did the trick.

Thank you for the evaluation, it looks cleaner as well ;-)

Craig
Thanks for the tip, Jackforey. In this case I was required to use only a while loop.
Topic archived. No new replies allowed.