- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Recursive fibonacci method in Java
The fibonacci series is a series in which each number is the sum of the previous two numbers. The number at a particular position in the fibonacci series can be obtained using a recursive method.
A program that demonstrates this is given as follows:
Example
public class Demo { public static long fib(long n) { if ((n == 0) || (n == 1)) return n; else return fib(n - 1) + fib(n - 2); } public static void main(String[] args) { System.out.println("The 0th fibonacci number is: " + fib(0)); System.out.println("The 7th fibonacci number is: " + fib(7)); System.out.println("The 12th fibonacci number is: " + fib(12)); } }
Output
The 0th fibonacci number is: 0 The 7th fibonacci number is: 13 The 12th fibonacci number is: 144
Now let us understand the above program.
The method fib() calculates the fibonacci number at position n. If n is equal to 0 or 1, it returns n. Otherwise it recursively calls itself and returns fib(n - 1) + fib(n - 2). A code snippet which demonstrates this is as follows:
public static long fib(long n) { if ((n == 0) || (n == 1)) return n; else return fib(n - 1) + fib(n - 2); }
In main(), the method fib() is called with different values. A code snippet which demonstrates this is as follows:
public static void main(String[] args) { System.out.println("The 0th fibonacci number is: " + fib(0)); System.out.println("The 7th fibonacci number is: " + fib(7)); System.out.println("The 12th fibonacci number is: " + fib(12)); }
- Related Articles
- Recursive factorial method in Java
- JavaScript code for recursive Fibonacci series
- Fibonacci of large number in java
- What is a recursive method call in C#?
- Fibonacci series program in Java using recursion.
- Java Program to Display Fibonacci Series
- Fibonacci series program in Java without using recursion.
- Java Program for Binary Search (Recursive)
- Java Program for Recursive Bubble Sort
- Java Program for Recursive Insertion Sort
- Java program to print a Fibonacci series
- Java Program for n-th Fibonacci number
- How to implement the Fibonacci series in JShell in Java 9?
- How to implement the Fibonacci series using lambda expression in Java?
- Java Program for nth multiple of a number in Fibonacci Series

Advertisements