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.

  • The initializer does not have to be zero

  • The loop can terminate using any boolean expression that makes sense

  • The 'incrementor' does not need to increase by one each step. Decrementing and dividing by 2 are very common alternatives.

while loop

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

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

Example for_loops_AC_1
 1#include <iostream>
 2#include <string>
 3
 4int main() {
 5    // print words in reverse
 6    std::string words = "The rain in Spain falls mainly on the plain.";
 7
 8    size_t i = words.size();
 9    while (i > 0) {
10      std::cout << words[i-1];
11      --i;
12    }
13    return 0;
14}

for loop

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

Example for_loops_AC_2
 1#include <iostream>
 2#include <string>
 3
 4int main() {
 5    // print words in reverse
 6    std::string words = "The rain in Spain falls mainly on the plain.";
 7    for (size_t i = words.size(); i > 0; --i) {
 8      std::cout << words[i-1];
 9    }
10    return 0;
11}

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
}

range for loop

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.

Example for_loops_AC_3
1#include <iostream>
2#include <string>
3
4int main() {
5std::string words = "The rain in Spain falls mainly on the plain.";
6    for (char letter : words) {
7        std::cout << letter << ' ';
8    }
9}

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.

Q1

How many times would the following loop execute? for (int i = 1; i < 4; i++)

Q2

Where are the incrementors in for loops and while?

Q3

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

  1.    }
    }
  2. cout << new_amount << '\n';
  3. for (int i = 0; i &#60; num; ++i) {
  4. for (int i = 0; i &#60;= num; ++i) {
  5. int half_life(int initial_amount, int num) {
  6. int new_amount = initial_amount;
  7. new_amount / 2;
  8. new_amount = new_amount / 2;
  9. return new_amount;                         #distractor
  10. void half_life(int initial_amount, int num) {


More to Explore