How to Code a Fibonacci Sequence in Java

Fibonacci Sequence in Java

What is a Fibonacci Sequence?

The Fibonacci sequence is a series of numbers in which the next number is found by adding the two numbers before it. It was developed by a guy named Leonardo Pisano Bogollo, who lived between 1170 and 1250 in Italy.

“Fibonacci” was his nickname, which means “Son of Bonacci”.

Now back to the sequence …

Imagine this series of numbers:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 …

  • The 2 is found by adding the two numbers before it (1+1)
  • The 3 is found by adding the two numbers before it (1+2),
  • And the 5 is (2+3),
  • and round and around we go!

Can you figure out the next number in the sequence above?

That’s right 89! [55 + 34]

Now to the code …

We will be using a recursive function to make this Fibonacci logic work out. A recursive function is one which calls itself for execution.

Open up your favourite IDE. We’ll use netbeans in case you’re looking to switch. But whichever one works fine for you is great. Create a Java file called Fibonacci.java and add the following code.

public class Fibonacci {
    
    public static long fibonacci(int a){
        if(a == 0)return 0;
        if(a <= 2) return 1;
        
        long fistNum = fibonacci(a -1) + fibonacci(a-2);
        return fistNum;
    }
    
    public static void main(String args[]){
        int value =0;
        while(true){
            value ++;
            System.out.println(fibonacci(value));
        }
    }
}

Here’s the result:

Java Programming Training in Abuja

So, there you have it guys.

Want a one-on-one Java Programming training? Contact us

Leave a Reply

Your email address will not be published. Required fields are marked *