Printing the Fibonacci Series using Iteration different approach

Java Programming Language / Decision Making and Looping in java

1294

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

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

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.