Skip to content

Commit 2c3c20e

Browse files
committed
Fibonacci using Recursion
1 parent 249d722 commit 2c3c20e

File tree

2 files changed

+65
-24
lines changed

2 files changed

+65
-24
lines changed

.idea/workspace.xml

Lines changed: 44 additions & 24 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

8_MiniPrograms/14_Recursion.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# We will find the sequence of Fibonacci Numbers using recursion.
2+
# Recursive function is a function that calls itself, sort of like loop.
3+
# Recursion works like loop but sometimes it makes more sense to use recursion than loop.
4+
# You can convert any loop to recursion. ... Recursive function is called by some external code.
5+
# If the base condition is met then the program do something meaningful and exits.
6+
7+
8+
# Let us use recursion to find fibonacci numbers.
9+
# Fibonacci numbers are: 0, 1, 1, 2, 3, 5, 8, 13, 21....
10+
def fibonacci(n):
11+
if n == 0 or n == 1: # this is the base condition -- it is the index value of the above sequence.
12+
return n # so, if user wants fibonacci number at index 0, it'll return 0 and if at index 1, it'll return 1
13+
return fibonacci(n - 2) + fibonacci(n - 1) # but if user wants fibonacci number at index 4, it'll add
14+
# the fibonacci number at index (n-2) i.e. (4-2) and index (n-1) i.e. (4-1)
15+
# so, it'll return 2nd position element i.e. 1 and 3rd position element i.e. 2 and then it's sum i.e. 3
16+
17+
18+
n = int(input("Enter the number of Fibonacci numbers you want: "))
19+
20+
for i in range(n): # we print all the numbers in range that user inputs
21+
print(fibonacci(i))

0 commit comments

Comments
 (0)