Java Reference
In-Depth Information
The syntax of the
for
loop, which is
for
(initial expression; logical expression; update expression)
statement
is functionally equivalent to the following
while
statement:
initial expression
while
(logical expression)
{
statement
update expression
}
For example, the following
for
and
while
loops are equivalent:
for
(
int
i = 0; i < 10; i++)
int
i = 0;
system.out.print(i + " ");
while
(i < 10)
system.out.println();
{
system.out.print(i + " ");
i++;
}
system.out.println();
If the number of iterations of a loop is known or can be determined in advance, then
typically, programmers use a
for
loop.
EXAMPLE 5-15 (FIBONACCI NUMBER PROGRAM: REVISITED)
The programming example Fibonacci Number given in the previous section uses a
while
loop to determine the desired Fibonacci number. You can replace the
while
loop with an equivalent
for
loop as follows:
for
(counter = 3; counter <= nthFibonacci; counter++)
{
current = previous2 + previous1;
previous1 = previous2;
previous2 = current;
counter++;
}
//end for
The complete program listing of the program that uses a
for
loop to determine the
desired Fibonacci number is given with the Additional Student Files at www.cengagebrain.com.
The program is named
Ch5_FibonacciNumberUsingAForLoop.java
.
Recall that putting one control structure statement inside another is called nesting. The
following programming example demonstrates a simple instance of nesting, and also
nicely demonstrates counting.
Search WWH ::
Custom Search