THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

mark = "";
System.out.println(i + ": " + hi + mark);
hi = lo + hi;
lo = hi - lo;
}
}
}


Here is the new output:


1: 1
2: 1
3: 2
4: 3
5: 5
6: 8

7: 13
8: 21
9: 34 *


To number the elements of the sequence, we used a for loop instead of a while loop. A for loop is
shorthand for a while loop, with an initialization and increment section added. The for loop in
ImprovedFibonacci is equivalent to this while loop:


int i = 2; // define and initialize loop index
while (i <= MAX_INDEX) {
// ...generate the next Fibonacci number and print it...
i++; // increment loop index
}


The use of the for loop introduces a new variable declaration mechanism: the declaration of the loop variable
in the initialization section. This is a convenient way of defining loop variables that need exist only while the
loop is executing, but it applies only to for loopsnone of the other control-flow statements allow variables to
be declared within the statement itself. The loop variable i is available only within the body of the for
statement. A loop variable declared in this manner disappears when the loop terminates, which means you can
reuse that variable name in subsequent for statements.


The ++ operator in this code fragment may be unfamiliar if you're new to C-derived programming languages.
The ++ operator increments by one the value of any variable it abutsthe contents of variable i in this case.
The ++ operator is a prefix operator when it comes before its operand, and postfix when it comes after. The
two forms have slightly different semantics but we defer that discussion until Chapter 9. Similarly,
minus-minus (--) decrements by one the value of any variable it abuts and can also be prefix or postfix. In
the context of the previous example, a statement like


i++;


is equivalent to


i = i + 1;

Free download pdf