Fibonacci series using recursion in Java
In this post, you will learn how to write Fibonacci series program using recursion in the Java programming language.
The Fibonacci series is the sequence of numbers in which the next number is the sum of the two previous numbers. The Fibonacci series was well-known hundreds of years earlier. The "Fibonacci" name came from the nickname "Bonacci".
We can easily remember the Fibonacci sequence using the Fibonacci day, which is November 23rd. As 23rd November has the digits "1, 1, 2, 3" which is part of the sequence.
In the above image, the first two numbers are 0 and 1. So, according to the Fibonacci rule, the third number is 1 (sum of 0 and 1). The fourth number is 2, and so on.
0 + 1 = 1 // 0, 1, 1
1 + 1 = 2 // 0, 1, 1, 2
1 + 2 = 3 // 0, 1, 1, 2, 3
2 + 3 = 5 // 0, 1, 1, 2, 3, 5
0 ,1 , 1, 2, 3, 5, 8, 13, 21, 34....
Fibonacci series in Java using recursion
A recursion function is a function that is called by itself. In the given example, we call the recursion function to get the Fibonacci series. A recursion function continues until some condition is met to prevent it. That's why we use the if statement to break the infinite recursion.
In the given program, we use recursion to generate the fibonacci series. The function fibonacciSeries() is called recursively until we get the result. In the function, we first check if the number count is greater than 0. If yes, we recursively call fibonacciSeries() with the values count-1 and count-2.
public class FibonacciSeries{
static int n1=0,n2=1,n3=0;
static void fibonacciSeries(int count){
if(count>0){
n3 = n1 + n2;
n1 = n2;
n2 = n3;
System.out.print(" "+n3);
fibonacciSeries(count-1);
}
}
public static void main(String args[]){
int count = 15;
//printing 0 and 1
System.out.print(n1+" "+n2);
fibonacciSeries(count-2);
}
}
Output of the above code:
0 112 3 5 8 13 21 34 55 89 144 233 377
Related Articles
Remove space from string JavaJava random number between 1 and 10
Simple interest program in Java
Determinant of a matrix in Java
Find the greatest of three numbers in Java
Java program to check eligibility for voting
nth prime number in Java
Capitalize first letter of each word Java
Convert binary to decimal in Java
Convert decimal to binary in Java
Convert decimal to octal in Java
Convert decimal to hexadecimal in Java
Simple interest program in Java
Check whether the given number is even or odd in java
Print prime numbers from 1 to 100 in Java
Java prime number program
Java program to convert celsius to fahrenheit
Java program to check leap year
Java program to find factorial of a number