C++ While Loop

In C++, while loop is employed to iterate a neighborhood of the program several times. If the amount of iteration isn't fixed, it's recommended to use while loop than for loop.

A while loop statement over and over executes a target statement as long as a given condition is valid.

Flow Chart: -
c++ while loop
while loop

C++ While Loop

Syntax: -

while (condition)
{
//Code going to be executed
}

Example: -

#include <iostream>
using namespace std;

int main() {
int i=1; while (i <= 5)
{
cout << i <<"\n";
i++;
}
return 0;
}

When the above code is compiled and executed, it produces the subsequent Output −

Output:
1
2
3
4
5

C++ Nested While Loop

In C++, we will use while loop inside another while loop, it's referred to as nested while loop. The nested while loop is executed fully when outer loop is executed once.



Syntax: -

while (condition){
while (condition){
//Code going to be executed
}
}

Example: -

#include <iostream>
using namespace std;

int main() {
int i=1;
while (i <= 2)
{
int j=1;
while (j <= 2)
{
cout << i <<" "<< j <<"\n";
j++;
}
i++;
}
return 0;
}

When the above code is compiled and executed, it produces the subsequent Output −

Output:
1 1
1 2
2 1
2 2

C++ Infinite While Loop

If we use true keyword within the condition a part of while loop then it'll become infinite while loop.


Syntax: -

while (true){
//Code going to be executed
}

Example: -

#include <iostream>
using namespace std;

int main() {
while (true)
{
cout << "Infinite While Loop";
}
return 0;
}

When the above code is compiled and executed, it produces the subsequent Output −

Output:
Infinite While Loop
Infinite While Loop
Infinite While Loop
Infinite While Loop
Infinite While Loop
.
.
.