A C++ while loop repeatedly executes a statement or block while its condition evaluates to true. Because the condition is checked before the loop body, a while loop can run zero times. This tutorial covers the syntax, execution flow, flowchart, examples, break, continue, multiple conditions, infinite loops, and nested while loops.
C++ While Loop
Use a while loop when a block of code should repeat as long as a condition remains true, especially when the number of iterations is not known in advance.
The while statement is an entry-controlled loop: C++ evaluates the condition before each iteration. If the condition is false on the first check, the loop body is skipped completely.
C++ While Loop Syntax
Following is the syntax of while loop in C++.
while (condition) {
// statement(s)
}
At the start of while loop execution, the condition is checked. If the condition is true, statement(s) inside while block are executed. The condition is checked again. If it evaluates to true, the statement(s) inside the while loop are executed. This cycle goes on. If at all, the condition evaluates to false, execution comes out of while loop, meaning while loop is completed. And the program continues with the execution of statements after while loop if any.
In ordinary use, the condition is an expression that can be converted to bool. For example, i <= 5 is true while i is at most 5, and becomes false after i increases beyond that value.
How a C++ While Loop Executes
The execution sequence of a typical counter-controlled while loop is:
- Initialize the variable or state used by the loop.
- Evaluate the
whilecondition. - If the condition is false, leave the loop.
- If the condition is true, execute the loop body.
- Update the loop-control variable or other state.
- Return to the condition check.
The update step is important. If the variables used by the condition never change in a way that can make the condition false, the loop can continue indefinitely.
C++ While Loop Algorithm
Following would be the algorithm of while loop.
- Start.
- Check the condition. If the condition is false, go to step 4.
- Execute statement(s). Go to step 2.
- Stop.
You have to take care of the initialization and update of the variables present in condition. And make sure that the condition would break after a definite number of iterations. If the condition is never going to be false, then the while loop is going to execute indefinitely.
C++ While Loop Flowchart
The following flowchart shows the condition-first execution of a C++ while loop.
C++ While Loop Examples
1. Basic While loop example
In this example, we shall write a while loop that prints numbers from 1 to 5. The while loop contains statement to print a number, and the condition checks if the number is within the limits.
C++ Program
#include <iostream>
using namespace std;
int main() {
int n = 5;
int i = 1;
while (i<=n) {
cout << i << "\n";
i++;
}
}
Output
1
2
3
4
5
Here, i starts at 1. After each iteration, i++ increases it by one. When i becomes 6, the condition i <= n is false and the loop stops.
2. While loop to compute factorial
In this example, we shall use while loop to compute factorial of a number.
C++ Program
#include <iostream>
using namespace std;
int main() {
int n = 5;
int factorial = 1;
int i = 1;
while (i<=n) {
factorial *= i;
i++;
}
cout << factorial;
}
Output
120
The variable factorial is multiplied by each integer from 1 through 5, so the final value is 1 × 2 × 3 × 4 × 5 = 120.
3. While loop to compute sum of first N natural numbers
In this example, we shall use while loop to compute the sum of first N natural numbers. We shall write a while loop with condition that it is true until it reaches given number, and during each iteration, we shall add this number to the sum.
C++ Program
#include <iostream>
using namespace std;
int main() {
int n = 5;
int sum = 0;
int i = 1;
while (i<=n) {
sum += i;
i++;
}
cout << sum;
}
Output
15
C++ While Loop with Multiple Conditions
A while condition can combine comparisons with logical operators such as && (AND) and || (OR). With &&, all combined conditions must be true for another iteration to run.
The following loop continues only while i is at most 10 and sum is less than 20.
#include <iostream>
using namespace std;
int main() {
int i = 1;
int sum = 0;
while (i <= 10 && sum < 20) {
sum += i;
i++;
}
cout << "i = " << i << '\n';
cout << "sum = " << sum;
}
Output
i = 7
sum = 21
The iteration that starts with i == 6 is allowed because sum is still below 20. That iteration raises sum to 21. On the next condition check, sum < 20 is false, so the loop ends.
C++ While Loop with break Statement
You can break the while loop abruptly using break statement. break statement ends the execution of the wrapping loop.
In the following example, we shall write a while loop that prints numbers from 1 to 10. But, then we include a break statement such that when i is 4, we break the while loop.
C++ Program
#include <iostream>
using namespace std;
int main() {
int i = 1;
while (i <= 10) {
if (i == 4) {
break;
}
cout << i << "\n";
i++;
}
}
Output
1
2
3
When i becomes 4, break terminates the nearest enclosing loop immediately. Control continues with the first statement after that loop.
C++ While Loop with continue Statement
You can skip the execution of statements in a while loop during an iteration using continue statement. continue statement takes the control to the condition without executing further statements in the loop.
In the following example, we shall write a while loop that prints numbers from 1 to 7. We include a continue statement so that when i is 4, the remaining statements in that iteration are skipped.
C++ Program
#include <iostream>
using namespace std;
int main() {
int i = 1;
while (i <= 7) {
if (i == 4) {
i++;
continue;
}
cout << i << "\n";
i++;
}
}
Output
1
2
3
5
6
7
Notice that i is incremented before continue when i == 4. Without that update, the loop would keep returning to the same condition with i still equal to 4.
Infinite While Loop in C++
If the condition in while loop is going to be always true, then this loop runs indefinitely. This kind of loop is called infinite while loop.
Just a simple condition like 1==1 or true, will make the while loop to run indefinitely.
C++ Program
#include <iostream>
using namespace std;
int main() {
while (true) {
cout << "hello";
}
}
Output
The string “hello” is printed to the terminal indefinitely, until you interrupt and stop the program execution.
An intentional infinite loop is sometimes paired with a break condition inside the body. Accidental infinite loops commonly happen when the loop-control variable is never updated or is updated in the wrong direction.
C++ While Loop with Update in the Condition
You can update the loop control variable in the condition itself.
In the following example, we shall print the numbers from 1 to 5.
C++ Program
#include <iostream>
using namespace std;
int main() {
int i = 0;
while (++i<=5) {
cout << i << "\n";
}
}
Output
1
2
3
4
5
Because this condition uses the prefix increment operator, ++i increments i before comparing it with 5. This compact style is valid, but a separate update statement is often easier to read when the loop logic is more complex.
Nested While Loop in C++
While is just like another statement in C++. So, you can include a while loop inside the body a while loop, just like a statement.
In the following example program, we shall print a pattern that resembles a triangle, using nested while loop.
C++ Program
#include <iostream>
using namespace std;
int main() {
int i = 1;
while (i <= 5) {
int j = 1;
while (j <= i) {
cout << " *";
j++;
}
cout << "\n";
i++;
}
}
Output
*
* *
* * *
* * * *
* * * * *
Outer while loop is used to traverse the rows, and inner while loop is used to traverse the columns.
C++ While Loop vs Do-While Loop vs For Loop
C++ commonly uses while, do-while, and for for repetition. They differ mainly in where the condition is checked and how loop-control logic is organized.
| Loop | Condition check | Minimum executions | Typical use |
|---|---|---|---|
while | Before the body | 0 | Repeat while a condition remains true, especially when the iteration count is not known beforehand. |
do-while | After the body | 1 | Run the body at least once, then decide whether to repeat. |
for | Before the body | 0 | Keep initialization, condition, and update together when iterating with a counter or a similar progression. |
The key difference between while and do-while is therefore the first condition check. A false initial condition skips a while body, but a do-while body still runs once before its condition is tested.
Common C++ While Loop Mistakes
- Forgetting the update: if the condition depends on
ibutinever changes, the loop may never terminate. - Updating in the wrong direction: increasing a variable when the condition requires it to decrease can keep the condition true indefinitely.
- Placing
continuebefore the update: the skipped update can leave the loop stuck on the same value. - Using the wrong boundary:
i < nandi <= ndiffer by one iteration, so choose the comparison that matches the required range. - Adding an accidental semicolon: writing
while (condition);creates an empty loop body. The following block is then not controlled by thatwhilestatement.
When to Use a While Loop in C++
A while loop is a good fit when repetition depends on a changing condition rather than a fixed count. Examples include reading input until a sentinel value appears, repeating a menu until the user chooses to exit, retrying an operation while a condition holds, or processing data until no more valid items remain.
If the number of repetitions is naturally expressed by initialization, a test, and a counter update, a for loop may be more concise. If the body must run at least once before the condition is checked, use a do-while loop instead.
C++ While Loop Practice Exercises
- Use a
whileloop to print the integers from10down to1. - Read a positive integer and use a
whileloop to count its digits. - Use a
whileloop to print only the even numbers from2through20. - Keep reading integers until the user enters
0, then print the sum of all previously entered values. - Write a loop with two conditions that stops when either a counter exceeds a limit or an accumulated total reaches a target.
C++ While Loop Summary
In this C++ Tutorial, we learned the syntax of while loop in C++, its algorithm, flowchart, and usage with the help of example C++ programs.
A C++ while loop checks its condition before every iteration, so the body may execute zero or more times. Correct initialization, a condition that can eventually become false, and an appropriate update are the main pieces to verify when writing or debugging a while loop.
TutorialKart.com