The while statement is the simplest of the three loops that C++ provides. It’s definition is very similar to that of an if statement:

while (expression)
    statement;

A while statement is declared using the while keyword. When a while statement is executed, the expression is evaluated. If the expression evaluates to true (non-zero), the 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.

Let’s take a look at a simple while loop. The following program prints all the numbers from 0 and 9:


int iii = 0;
while (iii < 10)
    {
    cout << iii << " ";
    iii++;
    }
cout << "done!";

This outputs:

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

iii is initialized to 0. 0 < 10 evaluates to true, so the statement block executes. The first statement prints 0, and the second increments iii to 1. Control then returns back to the top of the while statement. 1 < 10 evaluates to true, so the code block is executed again. The code block will repeatedly execute until iii == 10, at which point 10 < 10 will evaluate to false, and the loop will exit.

It is possible that a while statement executes 0 times. Consider the following program:


int iii = 15;
while (iii < 10)
    {
    cout << iii << " ";
    i++;
    }
cout << "done!";

The condition 15 < 10 evaluates to false, so the while statement is skipped. The only thing this program prints is done!.

On the other hand, if the expression always evaluates to true, the while loop will execute forever. This is called an infinite loop. Here is an example of an infinite loop:


int iii = 0;
while (iii < 10)
    cout << iii << " ";

Because iii is never incremented in this program, iii < 10 will always be true. Consequently, the loop will never terminate, and the program will hang. We can declare an intentional infinite loop like this:


while (1)
{
  // this loop will execute forever
}

The only way to exit an infinite loop is through a return statement, a break statement, an exception being thrown, or the user killing the program.

Often, we want a loop to execute a certain number of times. To do this, it is common to use a loop variable. A loop variable is an integer variable that is declared for the sole purpose of counting how many times a loop has executed. Loop variables are often given simple names, such as i, j, or k. Hungarian Notation is often ignored for loop variables (though whether it should be is another question altogether).

However, naming variables i, j, or k has one major problem. If you want to know where in your program a loop variable is used, and you use the search function on i, j, or k, the search function will return half your program! Many words have an i, j, or k in them. Consequently, a better idea is to use iii, jjj, or kkk as your loop variable names. Because these names are more unique, this makes searching for loop variables much easier, and helps them stand out as loop variables. An even better idea is to use “real” variable names, such as nCount, nLoop, or a name that gives more detail about what you’re counting.

Each time a loop executes, it is called an iteration. Often, we want to do something every n iterations, such as print a newline. To have something happen every n interations, we can use the modulus operator:


// Loop through every number between 1 and 50
int iii = 1;
while (iii <= 50)
{
    // print the number
    cout << iii << " ";

    // if the loop variable is divisible by 10, print a newline
    if (iii % 10 == 0)
        cout << endl;

    // increment the loop counter
    iii++;
}

This program produces the result:

1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50

It is also possible to nest loops inside of other loops. In the following example, the inner loop and outer loops each have their own counters. However, note that the loop expression for the inner loop makes use of the outer loop’s counter as well!


// Loop between 1 and 5
int iii=1;
while (iii<=5)
{
    // loop between 1 and iii
    int jjj = 1;
    while (jjj <= iii)
        cout << jjj++;

    // print a newline at the end of each row
    cout << endl;
    iii++;
}

This program prints:

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Quiz

1) In the above program, why is jjj declared inside the while block instead of following immediately following the declaration of iii?

2) Write a program that prints out the letters a-z along with their ASCII codes. Hint: to print characters as integers, you have to use a static_cast.

Quiz Answers

1) Show Solution

2) Show Solution

5.6 — Do while statements
Index
5.4 — Goto statements