Latest web development tutorials

C ++ while loop

C ++ loop C ++ loop

As long as the given condition istrue, while loop will repeat a target statement.

grammar

In C ++while loop syntax:

while(condition)
{
   statement(s);
}

Here, statement (s) may be a single statement, it can also be a block composed of a few statements.condition can be any expression, any non-zero when the values are true. Conditions for the execution of the loop when true.

When the condition is false, program flow will continue with the next statement followed the loop.

flow chart

In C ++ while loop

Here, the key pointswhileloop is a loop may not execute. When the condition is tested and the result is false, the loop body will skip directly to the next statement immediately while loop.

Examples

#include <iostream>
using namespace std;
 
int main ()
{
   // 局部变量声明
   int a = 10;

   // while 循环执行
   while( a < 20 )
   {
       cout << "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 ++ loop C ++ loop