Home / Programs / Printing the Fibonacci Series using Iteration different approach
🚀 Programming Example

Printing the Fibonacci Series using Iteration different approach

👁 1,364 Views
💻 Practical Program
📘 Step Learning

We will see how recursion can be used to print the Fibonacci Series. We will write a program which takes an input n and prints the first (n+1) terms of the Fibonacci series. n = 0 and n = 1 will be

💻 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();
       fibonacci(n);
   }

   public static void fibonacci(int n) {
       if (n == 0) {
           System.out.println("0");
       } else if (n == 1) {
           System.out.println("0 1");
       } else {
           System.out.print("0 1 ");
           int a = 0;
           int b = 1;
           for (int i = 1; i < n; i++) {
               int nextNumber = a + b;
               System.out.print(nextNumber + " ");
               a = b;
               b = nextNumber;
           }
       }
   }
}
                        

🖥 Program Output

Enter the value of n: 6
0 1 1 2 3 5 8 
                            

📘 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.