Generating Fibonacci Sequence

Generating the Fibonacci sequence programmatically

What is a Fibonacci Sequence
The Fibonacci sequence starts with the number 0 followed by 1. Each subsequent number is the addition of the previous two numbers. Thus the Fibonacci sequence looks like below
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, and so on.


Algorithm for generating the Fibonacci sequence

1.   Fibonacci (N)
2.   If N <= 2
3.     for number from 0 upto N-1
4.     print number
5.   Else
6.     Initialize a = 0, b = 1
7.     print a, b
8.     While N is greater than 2 do
9.         next_number = a + b
10.         print next_number
11.         a = b
12.         b = next_number
13.         N = N-1


Java

Java Program for generating Fibonacci Sequence.


C++

C++ Program for generating Fibonacci Sequence.


Python Program for generating Fibonacci sequence.

#!/usr/bin/python3 

def Fibonacci (n) :
    a, b = 0, 1
    print(a, end = ' ')
    print(b, end = ' ')

    for _ in range(n-2) :
        print(int(a+b), end = ' ')
        temp = a + b 
        a = b 
        b = temp
    
def main() :
    n = int(input("Generating first N Fibonacci numbers. Enter N : "))
    if n <= 1 : 
       for i in range(n) :
           print(i, end = ' ')
    else :
       Fibonacci(n)

if __name__ == "__main__" :
    main()

Output of Fibonacci sequence implemented in Python3

Generating first N Fibonacci numbers. Enter N : 10
0 1 1 2 3 5 8 13 21 34 
Generating first N Fibonacci numbers. Enter N : 1
0

Copyright (c) 2019-2020, Algotree.org.
All rights reserved.