show the fibonacci series upto 20 numbers in python
Answers
Answer:
Algorithm for printing Fibonacci series using a while loop
Step 1:Input the 'n' value until which the Fibonacci series has to be generated
Step 2:Initialize sum = 0, a = 0, b = 1 and count = 1
Step 3:while (count <= n)
Step 4:print sum
Step 5:Increment the count variable
Step 6:swap a and b
Step 7:sum = a + b
Step 8:while (count > n)
Step 9:End the algorithm
Step 10:Else
Step 11:Repeat from steps 4 to 7
Python program to print Fibonacci series until 'n' value using while loop
Python program to generate Fibonacci series until 'n' value
n = int(input("Enter the value of 'n': "))
a = 0
b = 1
sum = 0
count = 1
print("Fibonacci Series: ", end = " ")
while(count <= n):
print(sum, end = " ")
count += 1
a = b
b = sum
sum = a + b
Input:
Input:Enter the value of 'n': 5
Input:Enter the value of 'n': 5Output:
Input:Enter the value of 'n': 5Output:Fibonacci Series: 0 1 1 2 3
Method 2: Using recursion
Method 2: Using recursionRecursive function algorithm for printing Fibonacci series
Step 1:If 'n' value is 0, return 0
Step 2:Else, if'n'value is 1, return 1
Step 3:Else, recursively call the recursive function for the value (n - 2) + (n - 1)
Python program to print Fibonacci series until 'n' value using recursion
Python program to generate Fibonacci series Program using Recursion
def Fibonacci_series(Number):if(Number == 0):
return 0elif(Number == 1):
return 1else:
return (Fibonacci_series(Number - 2) + Fibonacci_series(Number - 1))
n = int(input("Enter the value of 'n': "))
print("Fibonacci Series:", end = ' ')
for n in range(0, n):
print(Fibonacci_series(n), end = ' ')
Input:
Input:Enter the value of 'n': 5
Input:Enter the value of 'n': 5Output:
Input:Enter the value of 'n': 5Output:Fibonacci Series: 0 1 1 2 3
Answer:
A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8....
The first two terms are 0 and 1. All other terms are obtained by adding the preceding two terms. This means to say the nth term is the sum of (n-1)th and (n-2)th term.
Source Code
# Program to display the Fibonacci sequence up to n-th term
nterms = int(input("How many terms? "))
# first two terms
n1, n2 = 0, 1
count = 0
# check if the number of terms is valid
if nterms <= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
Explanation:
Output
How many terms? 7
Fibonacci sequence:
0
1
1
2
3
5
8