fibonacci sequence formula in java code example

Example 1: java fibonacci series code

public class Fibonacci {

    public static void main(String[] args) {

        int n = 10, t1 = 0, t2 = 1;
        System.out.print("First " + n + " terms: ");

        for (int i = 1; i <= n; ++i)
        {
            System.out.print(t1 + " + ");

            int sum = t1 + t2;
            t1 = t2;
            t2 = sum;
        }
    }
}

Example 2: fibonacci sequence algorithm in java

public class Fibonacci_sequence {
	
	static int fib(int n) {
		if( n <= 0 ) {
			return 0;
		}else if( n == 1 ) {
			return 1;
		}else {
			return ( fib( n - 1 )+ fib( n - 2 ));
		}
		
	}
	
	public static void main(String[] args) {
		
		int n = 9;
		System.out.println(fib(n));
		
		// TODO Auto-generated method stub

	}

}

Example 3: program to get the Fibonacci series

public class Fibonacci {

    public static void main(String[] args) {

        int i = 1, n = 10, t1 = 0, t2 = 1;
        System.out.print("First " + n + " terms: ");

        while (i <= n)
        {
            System.out.print(t1 + " + ");

            int sum = t1 + t2;
            t1 = t2;
            t2 = sum;

            i++;
        }
    }
}

Tags:

Java Example