Fibonacci Series using Recursion

Java Programming Language Class, Object and Methods in java (Article) Class, Object and Methods in java (Program)

1256

Program:

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);
       }
   }
}

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

This Particular section is dedicated to Programs only. If you want learn more about Java Programming Language. Then you can visit below links to get more depth on this subject.