For Loops


For loops

Up to now we have only used one kind of loop, a while-loop. Java has other kinds of loops, and one of them, the for-loop, is particularly useful with arrays.

The heading of a for-loop has three parts, separated by semicolons. The first part initializes (and possibly declares) a variable. The second part is a condition under which the loop keeps going, and the third part tells how to update the variable. For loop

  int k;
  for(k = 0; k < 10; k++)
  {
     A[k] = 1;
  }
is exactly the same as
  int k;
  k = 0;
  while(k < 10)
  {
    A[k] = 1;
    k++;
  }
The three parts in the for-loop heading are just moved around for you. Statement
  for(X; Y; Z)
  {
    S
  }
is converted to
  X;
  while(Y)
  {
    S
    Z
  }
Notice that X is done just once, at the beginning, since it is not inside the while-loop. Also notice that Z is done each time after the body S.


Creating variables in for-loop headings

It is often convenient to create your variable inside the for-loop heading. For example,

  for(int k = 0; k < 10; k++)
  {
     A[k] = 1;
  }
makes A[0] = 1, ..., A[9] = 1. But if you create a variable inside the for-loop heading, then that variable only exists while the program is inside the for-loop, and is destroyed as soon as the for-loop is done. You cannot use k after the above loop.


Short for-loops

The body of a for-loop is any single statement. It is not required to be a compound statement, so you are not required to use braces unless the body involves doing more than one thing. The next section shows an example of a short for-loop.


For loops for arrays

It is quite common for a program to look at every variable in an array, either from the beginning to the end or from the end to the beginning. For-loops are excellent tools for doing that. For example, suppose that nums is an array of 40 integers. Here is a program fragment that makes variable sum hold num[0] + num[1] + ... + num[39].

  int sum = 0;
  for(int k = 0; k < 40; k++) sum = sum + A[k];
That is short and simple.

If you want to do the same thing by sweeping backwards over array A, that is not a problem either. (Of course, it gives the same answer for this problem.) Just be sure to start at 39, not at 40.

  int sum = 0;
  for(int k = 39; k >= 0; k--) sum = sum + A[k];


Why use a for-loop?

Not only does a for-loop have the advantage that it yields shorter programs, but it also tends to help avoid certain kinds of errors. Imagine that you want to add up the 40 values in array nums using a while loop. A correct approach is as follows.

  int sum = 0;
  int k = 0;
  while(k < 40)
  {
    sum = sum + A[k];
    k++;
  }
But it is easy to make mistakes. One of the most common is to forget about adding 1 to k. Then you get the following.
  int sum = 0;
  int k = 0;
  while(k < 40)
  {
    sum = sum + A[k];
  }
That just keeps adding A[0] into sum forever. The for-loop heading has a place for you to tell how to update k, so it is difficult to forget about it. (If you do not put three parts in the for-loop heading, separated by semicolons, the Java compiler will complain about it.)


Additional information

Savitch and Carrano discuss for-loops in Chapter 4-1.

Problems

  1. [solve] Write a definition of the factorial function using a for-loop to accumulate the factorial. Make the argument and the result both have type long. Call the function factorial.

  2. [solve] Write a definition of isPrime(n) using a for-loop, where isPrime(n) returns true if n is a prime number (and returns false if n is not prime).


Summary

A for-loop is a kind of loop that contains information on how to initialize and update a variable, as well as how long to keep going, all in one place. It has the advantage of brevity, and it also makes certain kinds of mistakes less likely.

For-loops are very useful for working with arrays, since it is common to go through an entire array, from beginning to end or from end to beginning, with a loop.

Remember that the three parts of a for-loop heading are separated by semicolons, not by commas.