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 snow 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); }
Counting and For loops |