Next: Example Program: Valid Input
Up: The do-while statement
Previous: The do-while statement
The following loop produces the sum 1+2+3+
...+n
,
where a value for n
is entered by the user:
cout << "Enter a value for n: "; cin >> n; sum = 0; i = 1; do { sum += i; i++; } while (i <= n);
Download program.
If the user entered a value of 0 for n
then the value of 1
would be returned as the value of sum
. This is obviously
incorrect and, as noted above, is because the loop statement of a
do-while
loop is always executed at least once. In this case if
the entered value of n
is zero then the loop statement should not
be entered at all! Thus if there is any possibility that some valid
data may require that a loop be executed zero times then a
while
statement should be used rather than a do-while
statement.