8.8 — Introduction to loops and while statements

Introduction to loops

And now the real fun begins -- in the next set of lessons, we’ll cover loops. Loops are control flow constructs that allow a piece of code to execute repeatedly until some condition is met. Loops add a significant amount of flexibility into your programming toolkit, allowing you to do many things that would otherwise be difficult.

For example, let’s say you wanted to print all the numbers between 1 and 10. Without loops, you might try something like this:

#include <iostream>

int main()
{
    std::cout << "1 2 3 4 5 6 7 8 9 10";
    std::cout << " done!\n";
    return 0;
}

While that’s doable, it becomes increasingly less so as you want to print more numbers: what if you wanted to print all the numbers between 1 and 1000? That would be quite a bit of typing! But such a program is writable in this way because we know at compile time how many numbers we want to print.

Now, let’s change the parameters a bit. What if we wanted to ask the user to enter a number and then print all the numbers between 1 and the number the user entered? The number the user will enter isn’t knowable at compile-time. So how might we go about solving this?

While statements

The while statement (also called a while loop) is the simplest of the three loop types that C++ provides, and it has a definition very similar to that of an if-statement:

while (condition)
    statement;

A while statement is declared using the while keyword. When a while-statement is executed, the expression condition is evaluated. If the condition evaluates to true, the associated statement executes.

However, unlike an if-statement, once the statement has finished executing, control returns to the top of the while-statement and the process is repeated. This means a while-statement will keep looping as long as the condition continues to evaluate to true.

Let’s take a look at a simple while loop that prints all the numbers from 1 to 10:

#include <iostream>

int main()
{
    int count{ 1 };
    while (count <= 10)
    {
        std::cout << count << ' ';
        ++count;
    }

    std::cout << "done!\n";

    return 0;
}

This outputs:

1 2 3 4 5 6 7 8 9 10 done!

Let’s take a closer look at what this program is doing.

First, we define a variable named count and set it to 1. The condition count <= 10 is true, so the statement executes. In this case, our statement is a block, so all the statements in the block will execute. The first statement in the block prints 1 and a space, and the second increments count to 2. Control now returns back to the top of the while-statement, and the condition is evaluated again.