Write a program to find the Fibonacci Series of the given number


This program is a simple implementation of the Fibonacci sequence. It starts by taking an input from the user, which is the number 'n' and assigns it to the variable 'n'. Then it initializes two variables 'n1' and 'n2' with the values 0 and 1 respectively. It also initializes a variable 'sum' with the value 0.

It then uses an if-else statement to check if the value of 'n' is less than or equal to 0, if it is then it prints a message asking the user to enter a positive integer. If the value of 'n' is equal to 1, then it prints the Fibonacci sequence upto the value of 'n' which is 0.

If 'n' is greater than 1, it enters the else block where it prints the message "Fibonacci sequence:". Then it uses a while loop to iterate until the value of 'sum' is less than 'n'. Inside the while loop, it first prints the value of 'n1', then it calculates the next value in the Fibonacci sequence by adding 'n1' and 'n2' and assigns it to the variable 'nth'. Then it updates the values of 'n1' and 'n2' with the values of 'n2' and 'nth' respectively. Finally, it increments the value of 'sum' by 1.

It continues to execute this loop until the value of 'sum' becomes equal to 'n' and it will print the fibonacci series upto n.

Source Code

n = int(input("Enter the Number :"))
n1, n2 = 0, 1
sum = 0
if n <= 0:
   print("Please enter a positive integer")
elif n == 1:
   print("Fibonacci sequence upto",n,":",n1)
else:
   print("Fibonacci sequence:")
   while sum < n:
       print(n1)
       nth = n1 + n2
       n1 = n2
       n2 = nth
       sum += 1

Output

Enter the Number :10
Fibonacci sequence:
0
1
1
2
3
5
8
13
21
34


Example Programs