TOPIC 8.1.1
Advanced Features of For Loops


Note: The examples on this page are intended to help students see how flexible C++ can be. These less common uses of the for loop should be used only when the benefits of doing so outweigh the confusion that may be caused.

The following examples and text will illustrate the flexibility of the for loop. Although the for loop can be used in many different ways, some of these are not considered good programming practice. As we saw in Chapter 8, the for loop did not have to use an initialization expression. The for loop also does not have to use the control expression nor the step expression. When the for loop does not use any of the three expressions, it is called a open loop. When using an open loop there are only three ways to exit the loop, break, exit, and return. The following code illistrates the use of an open for loop.

#include <iostream.h>

int main()
{
  long i;

  cin >> i;

  for(;;)
  {

     i *= 2;
     if(i > 1000) break;

  }

  cout << i/2 << '\n';
  return (0);
}

We have now seen the use of a for loop as an open loop. We will now see how to use the comma operator to include multiple statements in the expressions. The following example illustrates the use of the comma operator and the use of functions in a for loop. The example shows how the expressions in the for loop can actually call other functions. The following example is not ideal for readability.

#include <iostream.h>

int isLessThanTen(int i);

int main() 
{

  for(int i = 0; isLessThanTen(i); cout << i << " ", cout << 10-i << endl)
     i++;

  return (0);

} 

int isLessThanTen(int i)
{

  return(i<10);

}


Output of the for loop:

0 10
1 9
2 8
3 7
4 6
5 5
6 4
7 3
8 2
9 1