10.4. for loops

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:

int i;
for (i = 0; i < 4; i++) {
  cout << count[i] << endl;
}

is equivalent to

int i = 0;
while (i < 4) {
  cout << count[i] << endl;
  i++;
}

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

Before you keep reading...

Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.

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

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

Run the active code below, which uses a for loop with a negative change in the “INCREMENTOR”.

You have attempted 1 of 7 activities on this page