Fibonacci Sequence Code and Animation Explained

The Fibonacci Sequence is one of the classic recursive algorithms that you learn in computer science.

Mathematically, the fibonacci sequence looks like this

f(x) = f(x-1) + f(x-2)  and base values of either f0 =0 and f1=1

The Java Code

Download the Java Code

public class Recursion{
 
     public static int FibonacciNumber(int number){
        if(number == 1 || number == 2){
            return 1;
        }
 
        return FibonacciNumber(number-1) + FibonacciNumber(number -2); //tail recursion
    }
 
}

The Python Code

Download the Python Code

def fibonacci( n ) :
    if n is 1 or n is 2 :
        return 1
        
    return fibonacci(n-1) + fibonacci( n-2)

Fibonnacci Recursion Animation


 

Want to Practice your skills with the Fibonacci Sequence?

Try these problems at the following coding practice sites