Python Program for Fibonacci Numbers | Using for loop, while loop & recursion
The Fibonacci series is a sequence where the next term is obtained by the sum of previous two terms.
Fibonacci series- 0, 1, 1, 2, 3, 5, 8, 13, 21,....etc. The first two numbers of Fibonacci series are 0 and 1.
Python Program to display Fibonacci series:
Using for loop
num = int(input("Enter the number of elements: "))
first = 0
second = 1
print("Fibonacci Series: ")
print(first, second, end=" ")
for i in range(2, num):
    next = first + second
    print(next, end=" ")
    first = second
    second = next
Using while loop
nterms = int(input("Enter the number of elements: "))
# first two terms
n1, n2 = 0, 1
count = 0
if nterms <= 0:
   print("Please enter a positive integer")
elif nterms == 1:
   print("Fibonacci sequence upto",nterms,":")
   print(n1)
else:
   print("Fibonacci Series: ")
   while count < nterms:
    print(n1, end = ' ')# (end = ' ') to print value on same line 
    nth = n1 + n2
    n1 = n2
    n2 = nth
    count += 1
Using recursion
def recur_fibo(n):  
   if n <= 1:  
       return n  
   else:  
       return(recur_fibo(n-1) + recur_fibo(n-2))  
# take input from the user  
nterms = int(input("Enter the number of elements: "))  
if nterms <= 0:  
   print("Plese enter a positive integer")  
else:  
   print("Fibonacci Series:")  
   for i in range(nterms):  
       print(recur_fibo(i), end=" ") #(end = ' ') to print value on same line 
Output
Enter the number of elements: 5
Fibonacci Series: 0 1 1 2 3 
Enter the number of elements: 9
Fibonacci Series: 0 1 1 2 3 5 8 13 21 
Run Code- If you want run this code copy this code, paste here and run.


 
 
 
No comments: