Wednesday, 7 March 2018

Fibonacci Sereies using Java

Fibonacci series is series of numbers and each number is sum of previous two numbers. like it will start with 0 and 1 and series will be 0 , 1, 1, 2, 3, 5, 8 ....etc.

We can print this series using below java program.

package com.sample.java.testing;

import java.util.Scanner;

/**
 * We can print the series with different approaches and given is one of it
 *
 */
public class FibonacciSeriesTest {

    public static void main(String[] args) {

        int lengthOfSeries = 10;//lehgth of series
        //we can make this also dynamic by taking input from user
       
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please enter length of fib series");
        int fibSeriesLength = scanner.nextInt();
        scanner.close();
       
        //Creating empty array with size equal to length given above
        int[] fSeries = new int[fibSeriesLength];
       
        //First two numbers are 0 and 1 in Fibonacci series. Hence initialized with these values
        fSeries[0] = 0;
        fSeries[1] = 1;
       
        //So iterating loop with index 2
        for (int i = 2; i < fibSeriesLength; i++) {

            fSeries[i] = fSeries[i - 1] + fSeries[i - 2];
            System.out.print(fSeries[i-2] + " ");//printing out put

        }
    }

}

Output :

Please enter length of fib series
15
0 1 1 2 3 5 8 13 21 34 55 89 144

========================

 //Print fibonacci series of length 10
package com.sample.java.testing;

public class FibonacciSeriesTest1 {

    public static void main(String a[]){
       
        int length = 10;
       
        int first = 0;
        int second = 1;
        int next;
        System.out.print(first + " " + second);
       
        for (int i = 2; i < length; i++) {
           
            next = first + second;
           
            System.out.print(next + " ");
           
            first = second;
            second = next;
           
        }
       
    }
}

output:

0 11 2 3 5 8 13 21 34 

No comments:

Post a Comment