Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C++ do...while Loop

C++ do...while Loop

C++ Loops C++ Loops

Unlike for and while loops, which test the loop condition at the top of the loop.do...while The do...while loop checks its condition at the bottom of the loop.

do...while The do...while loop is similar to the while loop, but it guarantees the loop body executes at least once.

Syntax

In C++ do...while The syntax of the do...while loop:


do
{
   statement(s);

}while( condition );

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

If the condition is true, 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

Example

Example

#include

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 code above 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 C++ Loops