C++ what is a while loop to allow the user accept values until a limit is reached?

The result should be:

Accepting donations till we reach $100
Enter donation, or zero for no donation: 12
Enter donation, or zero for no donation: 10
Enter donation, or zero for no donation: 15
Enter donation, or zero for no donation: 0
Enter donation, or zero for no donation: 18
Enter donation, or zero for no donation: 0
Enter donation, or zero for no donation: 20
Enter donation, or zero for no donation: 27
Total amount donated: $102.00
Number of donors: 6
Average donation: $17.00

What I have so far: I'm looking for examples to compare - if that makes sense
------------
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

int main()
{
	int donation;
	double sum = 0;

	while (sum < 100)
	{
		cout << "Enter donation or zero for none: ";
		cin >> donation;
		
		cout << "Sum of Donation: " << sum << endl;
		sum += donation;
	}
	system("pause");
	return 0;
}
Last edited on
It seems to me that your code answers you question. Can you rephrase it?
do
{
things;
} while(something != somethingelse)


Some thoughts...
1) for can emulate a while loop, but its abuse of the language. EG for(; x !=y;) is same as while
2) whiles like this need a seed: eg x = 0; while (x != 0) { stuff that can eventually set x to zero to exit} but you can code these so the loop can execute 0 to any times, it does not have to execute once
3) do-while eliminates the seed, but assumes you want to execute the loop at least once.
Last edited on
You need a variable to count the number of donors. Initialise it to 0 and increment it by 1 each time through the loop. Use it (and sum) to calculate the average at the end.

Your donation is an int, whilst your sum is a double. That's not strictly wrong, but looks a bit inconsistent.

If you want your output to match what you posted then you should adjust your cout statements accordingly. On this basis, outputting sum will be done after the looping has finished, as will reporting the number of donors and computing and outputting the average.

closed account (48T7M4Gy)
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
#include <iostream>

using namespace std;

int main()
{
    int donation = 0;
    double sum = 0;
    int count = 0;
    
    while (
           cout << "Enter donation or zero for none: " &&
           cin >> donation &&
           donation >= 0 &&
           (sum += donation) &&
           sum < 100
           )
    {
        count++;
    }
    
    if(donation < 0)
        cout << "Start again\n";
    else
    {
        int no_donors = count + 1;
        
        cout
        << "Total amount donated: $" << sum << '\n'
        << "    Number of donors: " << no_donors << '\n'
        << "    Average donation: $" << sum/no_donors << '\n';
    }
    
    return 0;
}
Topic archived. No new replies allowed.