C++ do...while loop

C++ Loops

UnlikeforandwhileLoops, they test the loop condition at the top of the loop.do...whileThe loop checks its condition at the end of the loop.

do...whileThe loop is similar to the while loop, but the do...while loop ensures that the loop is executed at least once.

Syntax

In C++do...whileThe syntax of loops:

do
{
   statement(s);

}while( condition );

Note that the condition expression appears at the end of the loop, so the statement(s) in the loop are executed at least once before the condition is tested.

If the condition is true, the control flow jumps back to the do above and re-executes the statement(s) in the loop. This process repeats until the given condition becomes false.

Flowchart

C++ 中的 do...while 循环

Example

Example

#include <iostream>
using namespace std;
 
int main ()
{
   // Local variable declaration
   int a = 10;

   // do loop execution
   do
   {
       cout << "value of a:" << a << endl;
       a = a + 1;
   }while( a < 20 );
 
   return 0;
}

When the above code is compiled and executed, it produces the following result:

a 的值: 10
a 的值: 11
a 的值: 12
a 的值: 13
a 的值: 14
a 的值: 15
a 的值: 16
a 的值: 17
a 的值: 18
a 的值: 19

C++ Loops

other extensions