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

C++ while Loop

C++ while Loop

C++ Loops C++ Loops

As long as the given condition is true,while the loop statement repeatedly executes a target statement.

Syntax

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


while(condition)
{
   statement(s);
}

Here,statement(s) can be a single statement or a block of several statements.condition can be any expression; it is true when it evaluates to any non-zero value. The loop executes while the condition is true.

When the condition is false, program flow continues to the next statement immediately following the loop.

Flowchart

while Loop in C++

Here,while The key point about the loop is that it may not execute even once. When the condition is tested and the result is false, the loop body is skipped, and the statement immediately following the while loop is executed directly.

Example

Example

#include

using

namespace

std

;

 

int

main

(

)

{

   

// local variable declaration

   

int

a

=

10

;

   

// while loop execution

   

while

(

a

<
20
)
{
cout
<<

"Value of a: "

<<

a

<<

endl

;

       a

++

;

   

}

 

   

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