do while
The
do while loop allows to repeat a statement as long as a certain
expression’s value is or converts to
true. The statement is executed
at least once. For example, the loop reported in the program below
reads grades from the user and sums them into
gradeSum. The loop body executes
at least once, and the loop iterates until a grade equal to 0 is input.
In case the body is a single statement, and not a block, parentheses, just like
for other loops, are unnecessary:
do cout << i++ << endl; // no parenthesis with one statement
while(i <= 10);
Example
#include <iostream>
using namespace std;
int main()
{
int grade;
double gradeSum = 0;
int gradeCount = 0;
do // sums grades input
{
cout << "Enter a grade (0 to quit): ";
cin >> grade;
gradeSum += grade;
gradeCount++;
}
while(grade);
cout << "The grade average is: " << (gradeSum ? gradeSum/--gradeCount : 0) << endl << endl;
int i = 1;
do cout << i++ << endl; // no parentheses with one statement
while(i <= 10);
}
Output
Enter a grade (0 to quit): 5
Enter a grade (0 to quit): 2
Enter a grade (0 to quit): 7
Enter a grade (0 to quit): 0
The grade average is: 4.66667
1
2
3
4
5
6
7
8
9
10