Java Reference
In-Depth Information
3. Calculate the next Fibonacci number by adding the previous two
elements of the Fibonacci sequence.
4. Repeat Step 3 until the nth Fibonacci number is found.
5. Output the nth Fibonacci number.
Note that the program assumes that the first number of the Fibonacci sequence is
less than or equal to the second number of the Fibonacci sequence, and both
numbers are non-negative. Moreover, the program also assumes that the user enters
a valid value for the position of the desired number in the Fibonacci sequence; that
is, it is a positive integer. (See Programming Exercise 12 at the end of this chapter.)
Because you must know the last two numbers to find the current Fibonacci number,
you need the following variables: two variables—say, previous1 and previous2
to hold the previous two numbers of the Fibonacci sequence, and one variable—say,
current —to hold the current Fibonacci number. The number of times that Step 2
of the algorithm repeats depends on the position of the Fibonacci number you are
calculating. For example, if you want to calculate the 10 th Fibonacci number, you
must execute Step 3 eight times. (Remember, the user gives the first two numbers of
the Fibonacci sequence.) Therefore, you need a variable to store the number of times
that Step 3 should execute. You also need a variable—the loop control variable—to
track the number of times that Step 3 has executed. Therefore, you need five
variables for the data manipulation:
int previous1; //Variable to store the first
//Fibonacci number
int previous2; //Variable to store the second
//Fibonacci number
int current; //Variable to store the current
//Fibonacci number
int counter; //Loop control variable
int nthFibonacci; //Variable to store the desired
//Fibonacci number
VARIABLES
To calculate the third Fibonacci number, add the value of previous1 and previous2
and store the result in current . To calculate the fourth Fibonacci number, add the
value of the second Fibonacci number (that is, previous2 ) and the value of the third
Fibonacci number (that is, current ). Thus, when the fourth Fibonacci number is
calculated, you no longer need the first Fibonacci number. Instead of declaring
additional variables, which could be several, after calculating a Fibonacci number to
determine the next Fibonacci number, current becomes previous2 and previous2
becomes previous1 . Therefore, you can again use the variable current to store the
next Fibonacci number. This process is repeated until the desired Fibonacci number is
calculated. Initially, previous1 and previous2 are the first two numbers of the
sequence, supplied by the user. From the preceding discussion, it follows that you
need five variables.
 
Search WWH ::




Custom Search