While Loops

So for this class I'm taking, I have to write a program to ask for integers from the user until 999 is entered and print the average of all numbers
entered before the user typed 999 using while loops. I'm really not understanding the concept and if someone could maybe code this for me to look at that would be really nice.
> if someone could maybe code this for me to look at that would be really nice.

It would be really nice if you look at the code, put in an effort to understand it,
and then (try to) write the program (from scratch) on your own.

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

int main()
{
    const int TERMINAL_NUMBER = 999 ; // this terminates the input

    std::cout << "enter integers one by one. enter " << TERMINAL_NUMBER << " to end input\n" ;

    long long sum = 0 ; // variable to keep track of the sum of all entered numbers
                        // long long since sum of many integers may be outside the
                        // range of values that an int can hold
                        // note: long long is the largest (portable) signed integer type

    unsigned int cnt = 0 ; // count of the numbers to sum up
    int number ; // to hold the current number entered by the user

    while( std::cin >> number && // if an int was successfully read from input and
           number != TERMINAL_NUMBER ) // the number entered does not signal end of input
    {
        ++cnt ; // another number was entered. increment the count of numbers
        sum += number ; // and add the number to the sum
    }

    if( cnt != 0 ) // if at least one number was entered
    {
        // compute the average (sum divided by count)
        const double average = double(sum) / cnt ; // note: avoid integer division
                                                   // double(sum) yields a floating point value equal to sum
                                                   // the division is now floating point division (20.0/8 == 2.5 etc.)

        // print out the results
        std::cout << "sum of numbers: " << sum << '\n'
                  << "      #numbers: " << cnt << '\n'
                  << "       average: " << average << '\n' ;
    }
}
Thanks, I'll take a look at it.
Topic archived. No new replies allowed.