While and do-while Loops
Learn about the while and the do-while loop constructs in C++.
Several programming tasks consist of executing the same code multiple times. Tasks like moving an object across the screen, iterating through a list of items, searching through data, and performing mathematical operations on a stream of numbers all consist of a block of code being executed repeatedly till a termination condition is met. C++ allows executing the same code several times using two different loop constructs:
The
while
loop and its variation, thedo-while
loopThe
for
loop
The while
Loop
The while
loop is really the only necessary repetition construct. The for
loop and the do
- while
loop, coming up shortly, can be replicated using a while loop.
while ( condition ){//body}
Note: A
while
statement doesn't use a semicolon at its end. It's because the semicolon is used to terminate statements, and thewhile
statement itself is a control structure that needs to be followed by a block of code to execute as long as the condition istrue
.
A while
loop continues to run as long as the condition inside the parentheses is true
. If the condition is true
, the code inside the curly braces {}
is executed. After executing the last line inside the braces, the program checks the condition again. If it is still true
, the code inside the curly braces runs again. This cycle repeats as long as the condition remains true
. Once the condition becomes false
, the while
loop stops, and the program proceeds with the code following the closing curly brace }
.
Coding example
Let’s look at a simple while
loop that prints the integers from 1
to 5
.
#include <iostream>using namespace std;int main() {int i = 1; // Initialize the counter variablewhile (i <= 5){cout << " The value of i is:" << i << endl;i = i + 1; // Increment the variable i by 1}return 0; // End of the program}
Explanation
Let’s look at the line-by-line explanation of the above program.
Line 1: We include the
<iostream>
header to use input and output functions.Line 2: We use
using namespace std;
so we don’t have to writestd::
before every standard library object.Line 4: The
main
function is defined, which is the entry point of the program.Line 5: We declare an integer variable
i
and initialize it with the value1
.Line 7: The
while
loop begins, checking the conditioni <= 5
. As long as this condition istrue
, the loop will execute the code inside the curly braces{}
of thewhile
loop.Line 9: Within the loop, we print the current value of
i
followed by a newline.Line 10: Still, within the loop, we increment the value of
i
by1
.Line 11: The loop ends when the condition
i <= 5
becomesfalse
. The program then continues to the next statement.Line 13: The
return 0;
statement ends themain
function and the program. Returning0
typically indicates that the program has been executed successfully.
Workflow
Let’s try to understand the flow of the program using the illustration below:
Infinite loops
Let’s assess your understanding of while
loops with the quiz below.
Consider the following code:
#include <iostream>
using namespace std;
int main() {
int i = 1;
while (i <= 5) {
cout << i << endl;
}
i = i + 1;
return 0;
}
What would be the output of this code? Try running this program in the above widget and see what happens.
The above piece of code demonstrates an infinite loop. An infinite loop is one that either doesn’t have a termination condition, is structured in a manner, or acts on input data such that the termination condition is never met. Because of this, the loop continues to run until the program crashes or is forcefully exited.
Note: A common beginner's mistake is to forget to add code that updates the loop variable such that the loop condition eventually evaluates to
false
. Another common mistake is to add the line of code that updates the loop variable outside of the loop's body because of which the control never reaches that point.
The do-while
loop
The do-while loop is identical to the while loop, but instead of checking the conditional statement before the loop starts, it checks the condition after the first run and then continues on to another iteration. Here’s the syntax of the do-while
loop:
do {// body} while (condition);
As you can see, it will run the loop at least once before checking the condition.
Note: The do-while loop does have a semicolon at the end. Infinite loops can still occur in do-while loops, so exercise the same caution as you would with while loops. Its usefulness is more limited, so use this only when necessary.
Coding example
The playground below shows how to implement the above example using a do-while
loop instead.
#include <iostream>using namespace std;int main() {int i = 1;do {cout << "Value of i is: " << i << endl;i = i + 1;} while (i <= 5); // the condition is being checked after the first runreturn 0;}
Explanation
Let’s have a look at the line-by-line explanation of the above program.
Line 1: We include the
<iostream>
header to use input and output functions.Line 2: We use the
using namespace std;
statement so we don’t have to writestd::
before every standard library object.Line 4: The
main
function is defined, which is the entry point of the program.Line 5: We declare an integer variable
i
and initialize it with the value1
.Line 6: The
do
block begins, printing the value ofi
and then incrementing its value by1
.Line 7: We print the current value of
i
followed by a newline.Line 8: Still within the
do
block, we increment the value ofi
by1
.Line 9: The
while
statement checks if the value ofi
is less than or equal to5
. The loop continues to run as long as the condition istrue
.Line 10: The
return 0;
statement ends themain
function and the program. Returning0
typically indicates that the program has been executed successfully.
Scenario
We have looked at the do-while
loop, but where is it helpful? Let’s consider a scenario where we want to take an integer input from the user until the user has entered a positive number. In this case, we will use a do-while
loop as we have to run the loop at least once because we want input from the user at least once. This loop will continue running until the user enters a positive number. Let’s have a look at the code:
#include <iostream>using namespace std;int main() {int number;do {cout << "Enter a positive number: ";cin >> number;} while (number <= 0); // the condition is being checked after the first runcout << "You entered a positive number: " << number << endl;return 0;}
As you can see, the above code will continue taking input from the user unless the user enters a positive number.
Exercise
Test your understanding by changing the above code such that instead of printing the numbers from 1
to 5
, it prints the number from 5
to 1
.
#include <iostream>using namespace std;int main() {// Write your code herereturn 0;}
If you’re stuck, click the “Show Solution” button.