5.6.3.3. 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 the same as
  {
    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.

Declaring a variable in a for-loop heading

The first part of a for-loop heading can create a new variable. But a variable created there can only be used in the for-loop heading and body. For example
  for(int i = 0; i < 5; i++)
  {
     printf("%d\n", i);
  }
creates variable i that can only be used in this for-loop. You are not allowed to say
  for(int i = 0; i < 5; i++)
  {
     printf("%d\n", i);
  }
  printf("%d\n", i);
since that tries to use i outside of the for-loop.

Omitting part of a for-loop heading

Every for-loop heading has exactly two semicolons. But you can omit any (or all) of the three parts that are separated by semicolons.
  • If the first part is empty, no initialization is done.

  • If the second part is empty, it is assumed to be true, so the loop keeps going until stopped some other way.

  • If the third part is empty, no update is added to the end of the body.

For example,
  for(; k < n; k++)
  {
    ...
  }
assumes that k has already been initialized. Only omit parts of the heading with good reason. For example,
  int k = 0;
  for(; k < n; k++)
  {
    ...
  }
does not make sensible use of the for-loop. If there is initialization to be done, do it in the heading where possible, as in
  int k;
  for(k = 0; k < n; k++)
  {
    ...
  }

Watch out: semicolons

Be careful not to end the heading of a for-loop with a semicolon.
  for(int n = 0; n < 4; n++);
  {
    printf("%i\n", n);
    n++;
  }
writes
  4
because the body of the for-loop is an empty statement.


Standards

Do not change the value of a for-loop control variable in the loop body

The intent of a for-loop is that one control variable is managed in the loop heading. For example,
  for(int k = 0; k < n; k++)
  {
    …
  }
shows that k steps from 0 up to n−1.

Do not change the value of k (or whatever the control variable is called) in the loop body. If you do, then you make a lie out of what the loop heading suggests. See the link for an example.


Do not engage in other sneaky ways to make a lie out of the loop heading

Don't make a lie out of the loop heading in other ways. For example,
  for(i = 1; i < n; i++) 
  {
    ...
    if(condition)
    {
      n = 0;
    }
    ...
  }
is not a good way to cause the loop to end. If you want to exit a for-loop, use break or return.


Exercises

  1. Solve question 1 from the page on while loops, but this time use a for-loop. Answer

  2. Solve question 2 from the page on while loops, but this time use a for-loop. Answer

  3. Solve question 3 from the page on while loops, but this time use a for-loop. Answer

  4. Suppose that n is a positive integer. A proper divisior of n is an integer k where 0 < k < n and k is a divisor (or factor) of n. For example, 2 is a proper divisor of 6.

    Say that n is perfect if n is equal to the sum of all of its proper divisors. For example, 6 is perfect because the proper divisors of 6 are 1, 2 and 3 and 1 + 2 + 3 = 6.

    Write C++ definition of function isPerfect(n) that returns true if n is perfect and returns false if n is not perfect.

    Answer

  5. We use positional notation to write numbers. In base 10, there is a position for 1's, a position for 10's, a position for 100's, etc., with a position for each power of 10.

    Computers also use positional notation, but they use base 2 instead of 10 (binary notation). There is a position for 1's, a position for 2's, a position for 4's, etc., with a position for each power of 2.

    Write a C++ program that reads a binary number from the standard input and writes the equivalent decimal (base 10) number on the standard output. Assume that the binary number has no more than 50 digits.

    Hints.

    1. Statement

        scanf("%s", binary);
      
      reads a string and stores the string into character array binary as a null-terminated string. (You don't add & to binary because it is already a pointer to the array where you want scanf to store the string.)

    2. To convert the binary string to an integer, loop over the null-terminated string, from beginning to end. For each bit, multiply your current number by 2 and add the next digit. That is based on the following ideas. Suppose that num(str) is the function that converts a binary string to an integer.

        num("1")   + 1 = num("11").
        num("11")  + 0 = num("110").
        num("110") + 0 = num("1100").
      

    3. Use type long for numbers so that you can handle 50-bit integers (on a 64-bit machine).

    Answer