Last Updated : 12 Dec, 2024
In C++, the while loop is an entry-controlled loop that repeatedly executes a block of code as long as the given condition remains true. Unlike the for loop, while loop is used in situations where we do not know the exact number of iterations of the loop beforehand as the loop execution is terminated on the basis of the test condition.
Let's take a look at an example:
C++
#include <iostream>
using namespace std;
int main() {
// while loop to print numbers from 1 to 5
int i = 0;
while (i < 5) {
cout << "Hi" << endl;
i++;
}
return 0;
}
Explanation: The above loop prints the text "Hi" till the given condition is true i.e. i is less than 5. In each execution of the loop's statement, it increments i till i is less than 5.
Syntax of while Loopwhile (condition) {
// Body of the loop
update expression
}
Though the above is the formal syntax of the while loop, we need to declare the loop variable beforehand and update it in the body of the loop. The various parts of the While loop are:
The working of the while loop can be understood using the above image:
The below examples demonstrate how to use while loop in our C++ programs:
Printing Numbers from 1 to 5 C++
#include <bits/stdc++.h>
using namespace std;
int main() {
// Declaration and Initialization of loop variable
int i = 1;
// while loop to print numbers from 1 to 5
while (i <= 5) {
cout << i << " ";
// Updating loop varialbe
i++;
}
return 0;
}
Calculating the Sum of Natural Numbers C++
#include <iostream>
using namespace std;
int main() {
int n = 5;
int sum = 0;
// while loop to calculate the sum
while (n > 0) {
sum += n;
n--;
}
cout << sum;
return 0;
}
Print a Square Pattern using Nested Loops
Just like other loops, we can also nest one while loop into another while loop.
C++
#include <iostream>
using namespace std;
int main()
{
int i = 0;
// Outer loop to print each row
while (i < 4) {
int j = 0;
// Inner loop to print each character
// in each row
while (j < 4) {
cout << "* ";
j++;
}
cout << endl;
i++;
}
return 0;
}
* * * * * * * * * * * * * * * *Infinite while Loop
We can create an infinite loop using a while loop by defining a condition that is always true.
C++
#include <iostream>
using namespace std;
int main() {
// Infinite loop
while (true) {
cout << "gfg" << endl;
}
return 0;
}
Output
gfg gfg . . . infinite times
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4