Prev Main Next

For Loops

A for loop is a convenient abbreviation for a while loop that is useful for special purposes, such as counting, or other very simple loops.

Advantage. Normally, a loop needs some initialization, a condition that tells when to keep looping, and some update code to update the values of some variables. It is easy to forget one or more of those parts. A for loop has a place for each one, so that you are less likely to forget them.


General form

A for loop has the form

  for(init; cond; update)
  {
    body
  }
where init is the initialization, cond is the condition to do another iteration of the loop, and update does the update. This loop has the same meaning as
  init
  while(cond)
  {
    body
    update
  }


Important things to note



Example

The following prints the numbers from 1 to 20, one per line.

  int k;
  for(k = 1; k <= 20; k++) 
  {
    System.out.println(k);
  }


Example

The following makes variable sum hold 1 + 2 + ... + n, where n is a variable that has already been given a value earlier.

  int k, sum;
  sum = 0;
  for(k = 0; k <= n; k++)
  {
    sum = sum + k;
  }


Questions.

  1. Suppose that you use the following to compute the sum 1 + 2 + ... + n. Does it work for every nonnegative integer value of n? If not, give a counterexample.

      int k, sum;
      sum = 0;
      for(k = 1; k <= n; k++)
      {
        sum = sum + k;
      }
    
    Answer[25]

  2. What is wrong with the following?

      int i;
      for(i = 0, i <= 10, i++)
      {
        s += i;
      }
      
    Answer[26]

  3. What is wrong with the following?

      int j;
      for(j <= 10)
      {
        s += i;
        j++;
      }
      
    Answer[27]


Prev Main Next