while Loops in C++ - dummies

By Stephen R. Davis

A fundamental feature in C++ programming is the ability to loop. C++ offers three looping constructs in C++. The while loop has the following format:

while (expression)
    // stuff to do in a loop
// continue here once expression is false

When a program comes upon a while loop, it first evaluates the expression in the parentheses. If this expression is true, then control passes to the first line inside the {. When control reaches the }, the program returns back to the expression and starts over. Control continues to cycle through the code in the braces until expression evaluates to false (or until something else breaks the loop).

The following Factorial program demonstrates the while loop:

Factorial(N) = N * (N-1) * (N-2) * ... * 1
//  Factorial - calculate factorial using the while
//              construct.
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int nNumberofArgs, char* pszArgs[])
    // enter the number to calculate the factorial of
    int nTarget;
    cout << "This program calculates factorial.n"
         << "Enter a number to take factorial of: ";
    cin  >> nTarget;
    // start with an accumulator that's initialized to 1
    int nAccumulator = 1;
    int nValue = 1;
    while (nValue <= nTarget)
        cout << nAccumulator << " * "
             << nValue << " equals ";
        nAccumulator = nAccumulator * nValue;
        cout << nAccumulator << endl;
    // display the result
    cout << nTarget << " factorial is "
         << nAccumulator << endl;
    // wait until user is ready before terminating program
    // to allow the user to see the program results
    cout << "Press Enter to continue..." << endl;
    cin.ignore(10, 'n');
    return 0;

The program starts by prompting the user for a target value. The program reads this value into nTarget. The program then initializes both nAccumulator and nValue to 1 before entering the loop.

(Pay attention — this is the interesting part.) The program compares nValue to nTarget. Assume that the user had entered a target value of 5. On the first loop, the question becomes, “Is 1 less than or equal to 5?” The answer is obviously true, so control flows into the loop.

The program outputs the value of nAccumulator (1) and nValue (also 1) before multiplying nAccumulator by nValue and storing the result back into nAccumulator.

The last statement in the loop increments nValue from 1 to 2.

That done, control passes back up to the while statement where nValue (now 2) is compared to nTarget (still 5). “Is 2 less than or equal to 5?” Clearly, true; so control flows back into the loop. nAccumulator is now set to the result of nAccumulator (1) times nValue (2). The last statement increments nValue to 3.

This cycle of fun continues until nValue reaches the value 6, which is no longer less than or equal to 5. At that point, control passes to the first statement beyond the closed brace }. This is shown graphically here.


The actual output from the program appears as follows for an input value of 5:

This program calculates factorial.
Enter a number to take factorial of: 5
1 * 1 equals 1
1 * 2 equals 2
2 * 3 equals 6
6 * 4 equals 24
24 * 5 equals 120
5 factorial is 120
Press Enter to continue . . .

You are not guaranteed that the code within the braces of a while loop is executed at all: If the conditional expression is false the first time it’s evaluated, control passes around the braces without ever diving in. Consider, for example, the output from the Factorial program when the user enters a target value of 0:

This program calculates factorial.
Enter a number to take factorial of: 0
0 factorial is 1
Press Enter to continue . . .

No lines of output are generated from within the loop because the condition “Is nValue less than or equal to 0” was false even for the initial value of 1. The body of the while loop was never executed.