A while loop executes a code block as long as some condition remains true. The program evaluates the condition before every execution of the block.
If the condition is initially false, the block will never be executed.
int count{0};
while (count < 5)
{
std::cout << count << '\n';
// Increment the value before the expression uses it
++count;
}
As usual, the loop starts with some variable to determine how long it runs. The condition tests that variable, and the body of the loop has the job of updating it so that the loop eventually terminates.
The condition can be any expression that returns a Boolean value, either true or false.
Tests and logical operators are the most common conditions to use because they check whether a specific criterion, or group of criteria, is satisfied and allow the loop to continue only as long as that situation persists.
int remaining{10};
// Require both conditions joined by logical AND to be true
while (remaining > 0 && remaining != 3)
{
std::cout << remaining << '\n';
--remaining;
}
If two conditions are joined by logical AND, both tests must return a true value in order for the code block to be executed. The next time through, if either test returns a false value, the loop will stop.
Since the condition is checked before the first statement of the loop is executed, there's nothing to stop a while loop from executing zero times.
Something inside the loop body will eventually have to change the outcome of the condition. Otherwise, it will continue forever.
The usual way to do this is to update a variable used in the condition, such as by incrementing or decrementing it, or otherwise changing it in a way that will eventually cause the condition to evaluate to false.
Failure to update one of the variables used in the loop condition will often result in an infinite loop. It will repeatedly run the same statements because the condition will always evaluate to true.
int n{0};
while (n < 10)
{
std::cout << n << '\n';
// n never changes
}
Placing an update where it is easy to see will facilitate the reading of the loop as it executes.
Although you can intentionally write an infinite loop, you should make it clear from context when the loop is meant to run indefinitely.
You are permitted to omit curly braces from the controlled portion of a while loop if it contains only a single statement.
However, the same caveat given for an if statement applies here. If at a later point you add another statement without adding curly braces, it will not be executed as part of the loop's body.
Using curly braces from the beginning makes it clear what has been included in the loop.
You are even permitted to use an empty loop body. Some writers achieve this by following the condition with a semicolon.
while (condition)
;
Since a semicolon often goes unnoticed at the end of the line, an empty pair of curly braces is usually clearer when writing an empty loop body intentionally.
while (condition)
{
}
You are allowed to place a while loop inside another while loop.
When the computer reaches the inner loop from within the outer loop, it continues until the inner loop finishes all of its iterations. Only then do the remaining instructions within the body of the outer loop continue.
int outer{0};
while (outer < 3)
{
int inner{0};
while (inner < 2)
{
std::cout << outer << "," << inner << '\n';
++inner;
}
++outer;
}
Make sure that each loop has its own relevant, separately determined controlling variable. Reusing the same variable can cause one loop to interfere with the progress of the other.
You may also have to consider resetting the inner variable during each outer iteration. Otherwise, it may retain its final value from the last time the inner loop ran.
The while loop can serve a variety of useful purposes, such as moving through a set of numbers and carrying out instructions once for each step.
One use might be to print a statement for each value within a certain range.
Another might be to find the total sum of all the numbers within the range.
You might even adjust the rate at which you increment or decrement numbers, such as by two in order to print only the even numbers.
#include <iostream>
int main()
{
int n{1};
while (n <= 5)
{
std::cout << "Square of " << n << " is " << n * n << '\n';
++n;
}
int sum{0};
int value{1};
while (value <= 10)
{
// Add the value and store the result back in the same variable
sum += value;
++value;
}
std::cout << "Sum of 1 to 10 is " << sum << '\n';
int limit{20};
int current{2};
while (current < limit)
{
std::cout << current << '\n';
current += 2;
}
}
With every pass through the loop, the program must compare the given condition to determine whether or not to proceed. It must then execute the instructions within the loop and finally modify a value so that the condition will eventually evaluate to false, causing the loop to terminate.
The while loop is used when an uncertain number of operations are to be carried out. The condition determines whether the loop should continue, the body shows what is to be done during each iteration, and an update moves the loop toward its next test and eventual termination.
Exercise: while LoopsStarter code, hints and solutionOpenClose
Practice: while Loops
Work through the mission, reveal hints only when needed, and compare your result with the model solution.
Your challenge
Extend only the first while loop so it prints one additional square. Preserve its starting value and update; predict the last new line.
Mission checklist
- Run the starter as a baseline, then predict the change requested in Your challenge.
- Make that change in your editor; use the lesson-specific hints if you need help.
- Compile and run your answer, then compare with the worked solution and explain the result.
Starter program
This is the working baseline, not the completed answer. Compile as C++20, then make the change described above.
#include <iostream>
int main()
{
int n{1};
while (n <= 5)
{
std::cout << "Square of " << n << " is " << n * n << '\n';
++n;
}
int sum{0};
int value{1};
while (value <= 10)
{
// Add the value and store the result back in the same variable
sum += value;
++value;
}
std::cout << "Sum of 1 to 10 is " << sum << '\n';
int limit{20};
int current{2};
while (current < limit)
{
std::cout << current << '\n';
current += 2;
}
}Hints
The first loop tests n <= 5 before printing n * n, then increments n. Increasing that bound by one gives one extra square.
Increase the inclusive bound in the first while condition by one. Leave the even-number loop alone and keep the increment that makes the square loop progress.
Worked solution
Only the first loop bound changes from n <= 5 to n <= 6. It now performs six iterations and adds Square of 6 is 36; its increment still guarantees progress.
#include <iostream>
int main()
{
int n{1};
while (n <= 6)
{
std::cout << "Square of " << n << " is " << n * n << '\n';
++n;
}
int sum{0};
int value{1};
while (value <= 10)
{
// Add the value and store the result back in the same variable
sum += value;
++value;
}
std::cout << "Sum of 1 to 10 is " << sum << '\n';
int limit{20};
int current{2};
while (current < limit)
{
std::cout << current << '\n';
current += 2;
}
}
Example output
Square of 1 is 1
Square of 2 is 4
Square of 3 is 9
Square of 4 is 16
Square of 5 is 25
Square of 6 is 36
Sum of 1 to 10 is 55
2
4
6
8
10
12
14
16
18
0 comments
No comments yet. Be the first.