5.6. The for statement

The loops we have written so far have a number of elements in common. All of them start by initializing a variable; they have a test, or condition, that depends on that variable; and inside the loop they do something to that variable, like increment it.

This type of loop is so common that there is an alternate loop statement, called for, that expresses it more concisely. The general syntax looks like this:

for (INITIALIZER; CONDITION; INCREMENTOR) {
  BODY
}

This statement is exactly equivalent to

INITIALIZER;
while (CONDITION) {
  BODY
  INCREMENTOR
}

except that it is more concise and, since it puts all the loop-related statements in one place, it is easier to read. For example:

// print words 1 character at a time, with a space
string words = "The rain in Spain falls mainly on the plain.";
for (size_t i = 0; i < words.size(); ++i) {
  cout << words[i] << ' ';
}

is equivalent to

size_t i = 0;
while (i < words.size()) {
  cout << count[i] << ' ';
  ++i;
}

The main advantage of the for loop is that the loop variable i is only accessible inside the for loop.

Often the loops we write start at the beginning and increment one element at a time until the end is reached. For loops are more general purpose than that.

Run the active code below, which uses a while loop.

We have been using these for a while – no suprises here.

Run the active code below, which uses a for loop.

When are loops are of the simple sort: - The data source is an array or container - and we want to start at the beginning and step forward until the end

Then C++ offers an even simpler syntax starting in C++11:

for (VARIABLE : CONTAINER) {
  BODY
}

In C++, this is called a range-for loop. In other languages, this is sometimes called a for each loop. The idea is that the for loop knows how to get each element out of the provided container one at a time and assign it to a variable.

Try This!

In the code lens, change the range-for syntax to a traditional loop and see what changes.

Can you remember what happens if you change char letter` to ``int letter? Try it out.

The range-for loop introduced in C++11 was a great addition to the language. It improves readability and simplifies code. It is less error prone and does not require a separate index variable.

The range-for loop, while convenient, has limitations.

Any situation in which you do not need or want to visit every element requires a traditional loop:

for (int i=max; i>0; i/=2) {
  // do something with i . . .
}

Similarly, if you need to iterate through multiple containers in a single loop, possibly at different rates, then you need a traditional for loop:

for (int i=max, j=0; i>0; i/=2, j++) {
  // do something with i and j . . .
}

These special cases excepted, range-for loops are preferred in cases where they make sense.

Construct the <code>half_life()</code> function that prints the first num half lives of the initial amount.


More to Explore

You have attempted of activities on this page