In this tutorial you will learn about the Java Program to Generate Fibonacci Series using Recursion and its application with practical example.
Java Program to Generate Fibonacci Series using Recursion
In this tutorial, we will learn to create a Java program that will Print the Fibonacci Series Program using Java programming.
Prerequisites
Before starting with this tutorial, we assume that you are the best aware of the following Java programming topics:
- Operators in Java Programming.
- Basic Input and Output function in Java Programming.
- Basic Java programming.
- For loop in Java Programming.
- Functions in Java Programming.
What is Fibonacci Series?
The Fibonacci series is a series that is strongly related to Binet’s formula (golden ratio). In the Fibonacci series, the series starts from 0, 1 and then the third value is generated by adding those numbers.
Algorithm:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
STEP 1: START STEP 2: INITIALIZE n STEP 3: Sending the message to inter the value of n from user STEP 4: Grabbing the n number element from the user STEP 5: Using that number in for loop and calculations STEP 6: Generating the Fibonacci series STEP 7: Printing the series. STEP 8: Return 0. STEP 10: END. |
Programs to Generate Fibonacci Series:-
In this program, we take the number of elements for the series from the user. Then we will generate the Fibonacci series using the while loop. At last, we will print the series using the print function. The code for the program is given below.
Program:-
Program to Generate Fibonacci Series.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import java.util.*;//Importing the default packages. //Using For Loop public class FibonacciExample { public static void main(String[] args) { // Set it to the number of elements you want in the Fibonacci Series int maxNumber = 10; int previousNumber = 0; int nextNumber = 1; //Printing the Fibonacci series to the user. System.out.print("Fibonacci Series of "+maxNumber+" numbers:"); //Using the loop to generate the series. for (int i = 1; i <= maxNumber; ++i) { System.out.print(previousNumber+" "); /* On each iteration, we are assigning second number * to the first number and assigning the sum of last two * numbers to the second number */ //Calculating the next term of the series. int sum = previousNumber + nextNumber; previousNumber = nextNumber; nextNumber = sum; } } } |
Output:-
In the above program, we have first initialized the required variable
- i = it will hold the integer value for the loop.
Generating the Fibonacci series using the loops.
Program Code for Printing the series.