Flowchart to display n th fibonacci number has been shown below.
1. Flowchart to Display N th Fibonacci Number
- At first, the value of n is taken as input. Here n is the positional index of the desired Fibonacci number in the Fibonacci sequence (0, 1, 1, 2, 3, 5, ... ).
- Check whether n > 2 or not.
- If n = 1, print 0 as the output and stop the process because the first Fibonacci number is 0.
- If n = 2, print 1 as the output and stop the process because the second Fibonacci number is 1.
- If n > 2, initialize count = 2, a = 0 and b = 1. Here count variable is used to keep track of the index of the last calculated Fibonacci. a and b are used to store two consecutive Fibonacci numbers.
- The next Fibonacci is calculated by performing a + b and is stored into t. Both a and b are updated with new values. The value of count is incremented by 1 as the new Fibonacci t is already calculated.
- Check whether count = n or not. If yes, then stop the process and print t as the n th Fibonacci. If no, then go back to the previous step.
- For an example, let n = 5 i.e. the target is to print the 5 th fibonacci number. As n > 2 condition satisfies, the control flow follows the path at right side.
- Now, the initialization of the variables are done as count = 2, a = 0 and b = 1
- Compute t = a + b = 1, a = 1, b = 1 and count = count + 1 = 3
- Check whether count = 5 or not. As count = 3, go to previous step.
- Compute t = a + b = 2, a = 1, b = 2 and count = count + 1 = 4
- Check whether count = 5 or not. As count = 4, go to previous step.
- Compute t = a + b = 3, a = 2, b = 3 and count = count + 1 = 5
- Check whether count = 5 or not. As count = 5, print 3 as 5 th fibonacci number and stop the process.