Recursive fibonacci method : Recursive Method « Class Definition « Java Tutorial

Home
Java Tutorial
 1 Language 2 Data Type 3 Operators 4 Statement Control 5 Class Definition 6 Development 7 Reflection 8 Regular Expressions 9 Collections 10 Thread 11 File 12 Generics 13 I18N 14 Swing 15 Swing Event 16 2D Graphics 17 SWT 18 SWT 2D Graphics 19 Network 20 Database 21 Hibernate 22 JPA 23 JSP 24 JSTL 25 Servlet 26 Web Services SOA 27 EJB3 28 Spring 29 PDF 30 Email 31 J2ME 32 J2EE Application 33 XML 34 Design Pattern 35 Log 36 Security 37 Apache Common 38 Ant 39 JUnit
 Java Tutorial » Class Definition » Recursive Method
5.10.5.Recursive fibonacci method
 ```public class MainClass {   // recursive declaration of method fibonacci   public static long fibonacci(long number) {     if ((number == 0) || (number == 1)) // base cases       return number;     else       // recursion step       return fibonacci(number - 1) + fibonacci(number - 2);   }   public static void main(String[] args) {     for (int counter = 0; counter <= 10; counter++)       System.out.printf("Fibonacci of %d is: %d\n", counter, fibonacci(counter));   } }```
```Fibonacci of 0 is: 0
Fibonacci of 1 is: 1
Fibonacci of 2 is: 1
Fibonacci of 3 is: 2
Fibonacci of 4 is: 3
Fibonacci of 5 is: 5
Fibonacci of 6 is: 8
Fibonacci of 7 is: 13
Fibonacci of 8 is: 21
Fibonacci of 9 is: 34
Fibonacci of 10 is: 55```
 5.10.Recursive Method 5.10.1. Recursion: a method (function) calls itself 5.10.2. The Towers of Hanoi 5.10.3. Recursion: another example 5.10.4. Recursive factorial method 5.10.5. Recursive fibonacci method 5.10.6. Recursive method to find all permutations of a String