C++ while loop



In C++, a while loop is used to repeatedly execute a block of code as long as a certain condition is true.

 The basic syntax of a while loop in C++ is as follows:


vbnet code


while (condition) 

// code to be executed while condition is true

 } 


Here, condition is the expression that is evaluated before each iteration of the loop. If the condition is true, the block of code inside the loop is executed. 

If the condition is false, the loop is exited and program execution continues with the statement immediately following the loop.


Here is an example of a simple while loop in C++ that prints the numbers 1 to 10:


c code


int i = 1; 

while (i <= 10) { std::cout << i << " "; 

i++; 


In this example, the condition i <= 10 is evaluated before each iteration of the loop. 


As long as i is less than or equal to 10, the block of code inside the loop is executed.


 Inside the loop, the value of i is printed to the console using std::cout, and then incremented using the i++ operator. 


This process continues until i is greater than 10, at which point the loop is exited and program execution continues with the statement immediately following the loop.