How to Use the For Loop in C++

By Stephen R. Davis

The most common form of loop in C++ is the for loop. The for loop is preferred over the more basic while loop because it’s generally easier to read (there’s really no other advantage).

The for loop has the following format:

for (initialization; conditional; increment)
{
    // ...body of the loop
}

The for loop is equivalent to the following while loop:

{
    initialization;
    while(conditional)
    { 
        {
             // ...body of the loop
        }
        increment;
    }
}

Execution of the for loop begins with the initialization clause, which got its name because it’s normally where counting variables are initialized. The initialization clause is executed only once, when the for loop is first encountered.

Execution continues with the conditional clause. This clause works just like the while loop: As long as the conditional clause is true, the for loop continues to execute.

After the code in the body of the loop finishes executing, control passes to the increment clause before returning to check the conditional clause — thereby repeating the process. The increment clause normally houses the autoincrement or autodecrement statements used to update the counting variables.

The for loop is best understood by example. The following ForDemo1 program is nothing more than the WhileDemo converted to use the for loop construct:

// ForDemo1 - input a loop count. Loop while
//           outputting astring arg number of times.
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int nNumberofArgs, char* pszArgs[])
{
    // input the loop count
    int nLoopCount;
    cout << "Enter loop count: ";
    cin  >> nLoopCount;
    // count up to the loop count limit
    for (; nLoopCount > 0;)
    {
        nLoopCount = nLoopCount - 1;
        cout << "Only " << nLoopCount
             << " loops to go" << 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');
    cin.get();
    return 0;
}

The program reads a value from the keyboard into the variable nloopCount. The for starts out comparing nloopCount to 0. Control passes into the for loop if nloopCount is greater than 0. Once inside the for loop, the program decrements nloopCount and displays the result. That done, the program returns to the for loop control.

Control skips to the next line after the for loop as soon as nloopCount has been decremented to 0.

All three sections of a for loop may be empty. An empty initialization or increment section does nothing. An empty comparison section is treated like a comparison that returns true.

This for loop has two small problems. First, it’s destructive, in the sense that it changes the value of nloopCount, “destroying” the original value. Second, this for loop counts backward from large values down to smaller values. These two problems are addressed by adding a dedicated counting variable to the for loop. Here’s what it looks like:

// ForDemo2 - input a loop count. Loop while
//            outputting astring arg number of times.
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int nNumberofArgs, char* pszArgs[])
{
    // input the loop count
    int nLoopCount;
    cout << "Enter loop count: ";
    cin  >> nLoopCount;
    // count up to the loop count limit
    for (int i = 1; i <= nLoopCount; i++)
    {
        cout << "We've finished " << i
             << " loops" << 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');
    cin.get();
    return 0;
}

This modified version of ForDemo loops the same as it did before. Instead of modifying the value of nLoopCount, however, this ForDemo2 version uses a new counter variable.

This for loop declares a counter variable i and initializes it to 0. It then compares this counter variable to nLoopCount. If i is less than nLoopCount, control passes to the output statement within the body of the for loop. Once the body has completed executing, control passes to the increment clause where i is incremented and compared to nLoopCount again, and so it goes.

The following shows example output from the program:

Enter loop count: 5
We've finished 1 loops
We've finished 2 loops
We've finished 3 loops
We've finished 4 loops
We've finished 5 loops
Press Enter to continue...

When declared within the initialization portion of the for loop, the index variable is known only within the for loop itself. Nerdy C++ programmers say that the scope of the variable is limited to the for loop. In the ForDemo2 example just given, the variable i is not accessible from the return statement because that statement is not within the loop.