5. if and for Statements

More About for Loops

If you remember, we ended the second chapter of this book with a quick look at the main C++ iteration statement, for. We will conclude this chapter by presenting several more examples that demonstrate how useful a for loop can be.

First, let us solve a simple problem: Write a program that writes out the first six natural numbers (i.e. the first six positive whole numbers). Then write a program that writes out the first 1000 natural numbers.

Just to remind you, the text of the program is also called the source code.

We would like to make as little effort when solving the first part of the problem as when solving the second part. Thus, we have no intention to type in those 6 numbers into the text of our program; and the same certainly goes for a thousand of them.

Fortunately, a little help from a for loop can make life so much easier:

#include <iostream>
using namespace std;

int main() 
    for(double i=1; i<=6; i++)
        cout << i << endl;

Type in and execute this program. You should see the following on the standard output:


The purpose of a for statement is to repeat a statement (or a statement block) a certain number of times. In our example, the cout statement will be repeated for a total of six times. However, in each iteration of the for statement, the variable i will be assigned a different value. In the first iteration, the variable i has the value 1, in the second the value 2, in the third the value 3, and so on. The cout statement here simply prints out the current value of the variable i and by doing so it prints out each one of the first six natural numbers.

When reading out the text of a program, being able to pronounce the "sentences" that the program is made of may be helpful. The for statement from this program could be read like this: "For every i from one to six". The entire construction, including the part repeated by the for statement, is called a for loop.

We will leave the task of solving the second part of the stated problem to you.

Warning! Do not terminate for statements[*] by semicolons! Although doing it will not result in a compile-time error, it will likely result in unintended program behavior. To be more specific, if you terminate a for statement by a semicolon, what you are actually ordering to be repeated is not the following statement, but rather the semicolon itself! Since a semicolon itself represents the so-called empty statement, such a for loop will be repeating —nothing.