Home / Programs / Fibonacci Series using Recursion
🚀 Programming Example

Fibonacci Series using Recursion

👁 1,357 Views
💻 Practical Program
📘 Step Learning
Fibonacci Series using Recursion: The recursive definition of Fibonacci Series has already been stated at the start of this article. The Java program is given below.

💻 Program Code

import java.util.Scanner;

public class FibonacciSeries {

   public static void main(String[] args) {
       Scanner s = new Scanner(System.in);
       System.out.print("Enter the value of n: ");
       int n = s.nextInt();
       for (int i = 0; i <= n; i++) {
           System.out.print(fibonacci(i) + " ");
       }
   }

   public static int fibonacci(int n) {
       if (n == 0) {
           return 0;
       } else if (n == 1) {
           return 1;
       } else {
           return fibonacci(n - 1) + fibonacci(n - 2);
       }
   }
}
                        

🖥 Program Output

Enter the value of n: 10
0 1 1 2 3 5 8 13 21 34 55 
                            

📘 Explanation

The following sequence of numbers is known as Fibonacci numbers or sequence or series. 

0, 1, 1, 2, 3, 5, 8, 13, 21 ....

To obtain the sequence, we start with 0 and 1 after which every number is the sum of the previous two numbers. 

For example, the first two numbers will be 0 and 1 

0, 1

To obtain the next number, we add the previous two numbers - 0 and 1 which gives one. 

0, 1, 1

The next number would be 1 + 1 = 2 

0, 1, 1, 2 

Now, the next number would be 1 + 2 = 3 

0, 1, 1, 2, 3

Continuing in this way gives the Fibonacci series. A particular term in the series is represented as Fn where n is the position of that number from the beginning. For example, F0 = 0, F1 = 1, F2 = 1, F3=2, F4 = 3, F5 = 5 and so on... 

The Fibonacci series can be expressed as a recurrence relation as shown below: 

F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2 ; n>=2
📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.