11A. For-Loops

If A, B and C are expressions then

  for(A; B; C)
  {
     body
  }
is equivalent to
  {
    A;
    while(B)
    {
       body
       C;
    }
  }
For example,
  for(i = 0; i < 5; i++)
  {
     printf"%d\n", i);
  }
is equivalent to
  {
    i = 0;
    while(i < 5)
    {
       printf("%d\n", i);
       i++;
    }
  }

An advantage of a for-loop is that the initialization, update and test of one of the control variables are all together in one place, so it is easier to see what the loop is doing and it is less likely that you will make a mistake.


Exercises

  1. Suppose that you have some statements STEP that you want to perform n times. Using a for-loop, write C++ statements to do that. Just write STEP to stand for whatever you want to repeat. Answer