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.
#include<iostream>
int main()
{
constint TERMINAL_NUMBER = 999 ; // this terminates the input
std::cout << "enter integers one by one. enter " << TERMINAL_NUMBER << " to end input\n" ;
longlong 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
unsignedint 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)
constdouble 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' ;
}
}