CS 051 Fall 2012

Lecture 21

Counting and For loops

For loops in Java capture a very common pattern found in while
loops. While loops are often used for counting. Let's look at some
examples. In our falling leaves example we had code something like
(this is slightly simplified):

      int treeCount = 0;	// # of leaves generated so far

      while (treeCount < NUM_LEAVES ) {
         new FallingLeaf( aCanvas, nextLeaf,
                          leafLocGen.nextValue(),         // x coordinate
                          leafLocGen.nextValue()*2/aScreenWidth+2, // y speed
                          aScreenHeight);

         treeCount++;
         pause( 900);
      }

If we carefully examine the loop in the falling leaves example above,
we can see that it has the following structure:

    int counter = 0;
    while (counter < stopVal) {
        // do stuff
        counter++;     
    }

It turns out that we can use a different construct that localizes the
code dealing with counting so that it is easier to understand. This
construct is called a for loop. You would use it for
counting by saying the following:

    for (int counter = 0; counter < stopVal; counter++) {
       // do stuff - but omit counter++ at end
    }

The code in the parentheses consists of 3 parts; it is not just a
condition as in if or while statements. The parts
are separated by semicolons. The first part is executed once when we
first reach the for loop. It is used to declare and
initialize the counter. The second part is a condition, just as in
while statements. It is evaluated before we enter the loop and before
each subsequent iteration of the loop. It defines the stopping
condition for the loop, comparing the counter to the upper limit. The
third part performs an update. It is executed at the end of
each iteration of the for loop, just before testing the
condition again. It is used to update the counter.

How would we rewrite the falling leaves example to use a for loop?

      for (int treeCount = 0; treeCount < NUM_LEAVES; treeCount++ ) {
         new FallingLeaf( aCanvas, nextLeaf,
                          leafLocGen.nextValue(),         // x coordinate
                          leafLocGen.nextValue()*2/aScreenWidth+2, // y speed
                          aScreenHeight);

         pause( 900);
      }

Nested For loops

We can rewrite the knitting example from earlier in the term,
replacing the while loops with nested for loops as follows:

Demo: Knitting

Calculating Interest Example

Let's see another example with nested for loops. Suppose that we wanted to
determine how much money we would have if we invested it for 10
years, gaining 5% interest each year (compounded annually). Suppose
amount represents the amount of money we have invested. After one
year, we would have:

    amount + amount * 5/100.0;

Our class example Demo: Interest rates shows how to calculate 10 years worth
of interest for many possible interest rates. The outer for loop controls
what interest rate we are currently calculating, and the inner loop does
the interest rate calculation for that particular rate.

Other variations

The interest example showed us incrementing on each loop, but we
didn't start at 0 or 1.

Other variations are possible. We could count down instead of up:

    for (int countdown = 10; countdown >= 1; countdown--) {
        System.out.println(countdown);
    }
    System.out.println ("Blast off!");

We could increment by a value other than 1. For example, we could
have kept our interest rate as a double and then incremented by .01.

    private double amount = startInvestment;  // value of investment

    private static final double START_RATE = .02;   // interest rates
    private static final double END_RATE = .12;
    private static final double RATE_INCREMENT = .01;

    private static final int YEARS = 10;      // number of years for investment

    for (double rate = START_RATE; rate <= END_RATE; 
                       rate = rate + RATE_INCREMENT) {
        amount = startInvestment;
        for (int yearNum = 1; yearNum <= YEARS; yearNum++)
        {
            amount = amount + amount * rate;
        }
        System.out.println("At "+ (rate * 100) +"%, the amount is: "+amount);
    }

Warning: Note that you need to be very careful when testing for equality of
floating point numbers. Due to roundoff errors, your numbers might not
be what you expect.

Summary of for loops

The general structure of a for statement is the following:

    for ( <initialization>; <condition>; <update>) {
      <code to repeat>
    }

When should you use a for loop instead of a while loop:

Look over section on common loop errors!