Fibonacci Series Example Java Program


Definition

The first two numbers in the Fibonacci sequence are either 1 and 1, or 0 and 1, depending on the chosen starting point of the sequence, and each subsequent number is the sum of the previous two.

Formula

F_n = F_{n-1} + F_{n-2}

Fibonacci Series Example Program

import java.util.Scanner;

public class FibonacciSeries{
    public static void main(String args[]) {
        System.out.print("Enter the number : ");
		Scanner in=new Scanner(System.in);
        int num=in.nextInt();
        System.out.println("\n\nFibonacci series upto " + num+" numbers : ");
        for(int i=1; i<=num; i++){
            System.out.print(fibonacciMethod(i) +" ");
        }
    } 
    public static int fibonacciMethod(int num){
        if(num== 1 || num== 2){
            return 1;
        }
        return fibonacciMethod(num-1) + fibonacciMethod(num-2);
    }
    public static int fibonacciLoop(int num){
        if(num == 1 || num == 2){
            return 1;
        }
        int num1=1, num2=1, fibonacci=1;
        for(int i= 3; i<= num; i++){
            fibonacci = num1 + num2;
            num1 = num2;
            num2 = fibonacci;
 
        }
        return fibonacci; 
    }     
}

Sample Output

Output is:
Enter the number : 7


Fibonacci series upto 7 numbers :
1 1 2 3 5 8 13