Tutorial#29 - Programming Example-6 | Fibonacci Number | While Loop

Fibonacci Number | While Loop



Programming Example-6: Fibonacci Number:

Following is a C++ program that uses a while loop to find a Fibonacci number.
Consider the following sequence of numbers:
1, 1, 2, 3, 5, 8, 13, 21, 34, ....
This sequence is called the Fibonacci sequence.
The following algorithm is defined this program:
  1. Get the first two Fibonacci numbers.
  2. Get the desired Fibonacci position. That is, get the position, n, of the Fibonacci number in the sequence.
  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.
--> Main Algorithm:
1. Prompt the user for the first two numbers—that is, previous1 and previous2.
2. Read (input) the first two numbers into previous1 and previous2.
3. Output the first two Fibonacci numbers. (Echo input.)
4. Prompt the user for the position of the desired Fibonacci number.
5. Read the position of the desired Fibonacci number into nthFibonacci.
6. a. if (nthFibonacci == 1)
The desired Fibonacci number is the first Fibonacci number. Copy the value of previous1 into current.
   b. else if (nthFibonacci == 2)
The desired Fibonacci number is the second Fibonacci number. Copy the value of previous2 into current.
   c. else calculate the desired Fibonacci number as follows:
Because you already know the first two Fibonacci numbers of the sequence, start by determining the third Fibonacci number.
   c.1. Initialize counter to 3 to keep track of the calculated Fibonacci numbers.
   c.2. Calculate the next Fibonacci number, as follows: current = previous2 + previous1;
   c.3. Assign the value of previous2 to previous1.
   c.4. Assign the value of current to previous2.
   c.5. Increment counter by 1.
Repeat Steps c.2 through c.5 until the Fibonacci number you want is calculated.
The following while loop executes Steps c.2 through c.5 and determines the nth Fibonacci number.
while (counter <= nthFibonacci)
{
current = previous2 + previous1;
previous1 = previous2;
previous2 = current;
counter++;
}
7. Output the nthFibonacci number, which is stored in the variable current.

Sample Runs: In these sample runs, the user input is shaded.
--> Sample Run 1:
Enter the first two Fibonacci numbers: 12 16
The first two Fibonacci numbers are 12 and 16
Enter the position of the desired Fibonacci number: 10
The Fibonacci number at position 10 is 796

--> Sample Run 2:
Enter the first two Fibonacci numbers: 1 1
The first two Fibonacci numbers are 1 and 1
Enter the position of the desired Fibonacci number: 15
The Fibonacci number at position 15 is 610

Comments