The C++Course provides a general introduction to programming in C++. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.


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:

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

is equivalent to

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


Last Update: 2005-12-05