Algorithm


  1. Input: Take the number of terms (n) for the Fibonacci sequence as input.

  2. Initialize Variables:

    • Set a to 0 (the first Fibonacci number).
    • Set b to 1 (the second Fibonacci number).
  3. Print Initial Terms:

    • Print a.
    • Print b.
  4. Generate Fibonacci Sequence:

    • Use a loop to iterate from 2 to n (exclusive).
    • In each iteration, calculate the next Fibonacci number c as the sum of the previous two numbers (a and b).
    • Update a to the value of b.
    • Update b to the value of c.
    • Print the current Fibonacci number c.

 

Code Examples

#1 Example- Using Simple Iteration

Code - Python Programming

# Write a program to print fibonacci series upto n terms in python
num = 10
n1, n2 = 0, 1
print("Fibonacci Series:", n1, n2, end=" ")
for i in range(2, num):
    n3 = n1 + n2
    n1 = n2
    n2 = n3
    print(n3, end=" ")

print()
Copy The Code & Try With Live Editor

Output

x
+
cmd
Fibonacci Series: 0 1 1 2 3 5 8 13 21 34

#2 Example- Using Recursive Function

Code - Python Programming

# Python program to print Fibonacci Series
def fibonacciSeries(i):
if i <= 1:
return i
else:
return (fibonacciSeries(i - 1) + fibonacciSeries(i - 2))

num=10
if num <=0:
print("Please enter a Positive Number")
else:
print("Fibonacci Series:", end=" ")
for i in range(num):
print(fibonacciSeries(i), end=" ")
Copy The Code & Try With Live Editor

Output

x
+
cmd
Fibonacci Series: 0 1 1 2 3 5 8 13 21 34

#3 Example- Direct formula to find nth term of Fibonacci Series as –

Code - Python Programming

# write a program to print fibonacci series in python
import math

def fibonacciSeries(phi, n):
    for i in range(0, n + 1):
        result = round(pow(phi, i) / math.sqrt(5))
        print(result, end=" ")


num = 10
phi = (1 + math.sqrt(5)) / 2
fibonacciSeries(phi, num)
Copy The Code & Try With Live Editor

Output

x
+
cmd
Fibonacci Series:0 1 1 2 3 5 8 13 21 34 55
Advertisements

Demonstration


Python Program Example to Print the Fibonacci sequence-DevsEnv