Loading

Program for finding the first n Fibonacci series by iterative method:                                      

package quipoin.javaeasyprograms;
import java.util.Scanner;

public class Fibonacci {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("enter the value of n:");
		int n = sc.nextInt();
		int i, a = -1, b = 1, c;
		for (i = 0; i < n; i++) {
			c = a + b;
			a = b;
			b = c;
			System.out.println(c);
		}
	}
}

Output:

enter the value of n: 5
0
1
1
2
3
5

Program to find the nth Fibonacci element through the recursive method:

package quipoin.javaeasyprograms;
public class Fibonacci {

	static int fib(int n) {
		if (n == 1 || n == 2)
			return n - 1;
		else
			return fib(n - 1) + fib(n - 2);
	}

	public static void main(String[] args) {
      System.out.println(fib(5));
	}
}

Output:

3