C++ while loop

C++ Loops

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

Syntax

In C++whileSyntax for loops:

while(condition)
{
   statement(s);
}

Here,statement(s)It can be a single statement, or a block of code composed of several statements.conditionIt can be any expression, and it is true when it is any non-zero value. When the condition is true, the loop is executed.

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

Flowchart

C++ 中的 while 循环

Here,whileThe key point of a loop is that the loop may not execute even once. When the condition is tested and the result is false, the loop body is skipped, and execution proceeds directly to the next statement following the while loop.

Example

Example

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

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

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

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

C++ Loops

other extensions