O'Reilly logo

C++ Primer Plus, Fourth Edition by Stephen Prata

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Introducing the for Loop

Circumstances often call upon a program to perform repetitive tasks, such as adding together the elements of an array one by one or printing some paean to productivity twenty times. The C++ for loop makes such tasks easy to do. Let's look at a loop in Listing 5.1, see what it does, and then discuss how it works.

Listing 5.1. forloop.cpp
// forloop.cpp -- introducing the for loop
#include <iostream>
using namespace std;
int main()
{
    int i;  // create a counter
    //   initialize; test ; update
    for (i = 0; i < 5; i++)
        cout << "C++ knows loops.\n";
    cout << "C++ knows when to stop.\n";
    return 0;
}

Here is the output:

 C++ knows loops. C++ knows loops. C++ knows loops. C++ knows loops. C++ knows loops. C++ knows when to stop. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required