Java Reference
In-Depth Information
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 initializ-
ation 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 mechan-
ism: 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 state-
ment 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