In C++, while
loop causes a program to repeat a group of statements or code block as long a starting condition remains true. They are executed repeatedly until the expression is false. Note that the condition is only checked at the start of each iteration (loop).
The while
keyword is followed by an expression in parentheses. If the expression is true, the statements inside the loop block are executed.
while(condition){ //code to be executed }
Let's see a simple example of while loop to print table of 1.
#include <iostream> using namespace std; int main() { int i=1; while(i<=10) { cout<<i <<"\n"; i++; } }
In C++, we can use while loop inside the body of another while loop, it is known as nested while loop. The nested while loop is executed fully when outer loop is executed once.
Let's see a simple example of nested while loop in C++ programming language.
#include <iostream> using namespace std; int main () { int i=1; while(i<=3) { int j = 1; while (j <= 3) { cout<<i<<" "<<j<<"\n"; j++; } i++; } }
A while
loop executes as long as its condition is true. We can also create infinite while loop by passing true as the test condition.
#include <iostream> using namespace std; int main () { while(true) { cout<<"Infinitive While Loop"; } }