how to print fibonacci series using while loop in python?
pls tell quickly
Answers
Answer:
fibonacci deries in Python
INPUT FORMAT:
Input consists of an integer
OUTPUT FORMAT:
A single line of output containing the Fibonacci series until 7 values.
SAMPLE INPUT:
7
SAMPLE OUTPUT:
0 1 1 2 3 5 8
PREREQUISITE KNOWLEDGE:while loop in Python and Recursion in Python
Method 1:Using a while loop
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:
Enter the value of 'n': 5
Output:
Fibonacci Series: 0 1 1 2 3
Method 2: Using recursion
Recursive 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:
Enter the value of 'n': 5
Output:
Fibonacci Series: 0 1 1 2 3