Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in Java by (13.1k points)

Can anyone help me understand this code for fibonacci:

public int fibonacci(int n)  {

    if(n == 0)

        return 0;

    else if(n == 1)

      return 1;

   else

      return fibonacci(n - 1) + fibonacci(n - 2);

}

What is the last line of the code can do? How it is calculate the value?

1 Answer

0 votes
by (26.7k points)

Basically, Fibonacci will help you to provide a sequence that will be the sum of the previous two elements. You can understand it from the below example:

fibonacci(5) = fibonacci(4) + fibonacci(3)

fibonacci(3) = fibonacci(2) + fibonacci(1)

I hope this will help.

Want to become a Java Expert? Join Java Certification now!!

Want to know more about Java? Watch this video on Java Tutorial for Beginners | Java Tutorial:

Browse Categories

...