Search This Blog

Friday, May 28, 2021

Making a Fibonacci series source code(java) (two approaches)

 Making a Fibonacci series using 'for loop'


***********************************************

import java.util.Scanner;

public class fibonacci_series {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int times=0;
        while (times<10){
        int a=0;
        int b=1;
        int d;

            int upto= sc.nextInt();
            System.out.print(a+" "+b);

            for (int c=1;c<=upto-2;c++){
                d=a+b;
                System.out.print(" " +d+" ");
                a=b;
                b=d;

            }
            times++;
        }

    }
}


*****************************************


Making a Fibonacci series using Recursion


************************************

public class fibonacci_series_recursion {
    static int a=0,b=1,c=0;
    static void fib(int upto){
        if (upto>0){
            c=a+b;
            System.out.print(" "+c);
            a=b;
            b=c;
            fib(upto-1);
        }

    }

    public static void main(String[] args) {
        System.out.print(a+" "+b);
        int a=10;
        fib(a);
    }
}


**************************************