The do-while-loop is suitable for situations where the test value is input or calculated in the loop body, often leading to a compact solution. One aspect of the average problem complicates the do-while solution. When the user enters a -1 to end data input, the program increments count and updates sum before the loop ends. The program decrements count and increments sum below the loop, correcting the end-of-loop problem before calculating the average. The program also fails if the user enters a value < -1.
double ave3()
{
double sum = 0;
int count = 0;
int number;
do
{
cout << "Enter a number: ";
cin >> number;
sum += number;
count++;
} while (number >= 0);
if (--count > 0)
return ++sum / count;
else
return -1;
}