Recursive Program to find out nth Fibonacci number
Fibonacci series numbers are generated by adding two previous numbers of the series. Two starting numbers of this series are 1 and 0. so the next numbers are 1,2,3,5,8,13,21,34,55 and so on.
This series is can be generated using looping methods as well as recursion. First of all, we are going to present its looping method and then its recursive method.
The Fibonacci number using Looping
a = 0 b = 1 for i in range(1, 20): if i == 1: print(a, end=" ") if i == 2: print(b, end=" ") if i > 2: c = a+b print(c, end=" ") a = b b = c
The above program checks if it is the first term or second term, if it is the first term then it prints the zero()( or one(1) otherwise add previous two numbers and display on the screen.
Recursive program to find out the nth Fibonacci number
# User defined recursive function to find out nth fibonacci number # and its implementation in a python program def fab(n): if(n == 1): return 0 elif(n == 2): return 1 else: return fab(n-1)+fab(n-2) if __name__ == "__main__": for x in range(1, 21): print(fab(x), end=" ")
The output of the above python program is as follows
rakesh@folio MINGW64 /e/python (master) $ python -u "e:\python\Loops\fibonacci.py" 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584
I hope you like this recursive program. Please check out other recursive programs suggested for class 12 computer science student’s for their practical assignments by the CBSE.