Q-03: | Write a JAVA program to display Fibanocci Series:
(i) Using Recursion (ii) Using Iteration |
---|
Using Recursion
// Contributed by - Anuj Das ( GC College, Silchar - @ Department of Computer Science ) import java.util.Scanner; class RecursiveFibonacci { public static int fibo(int x) { if(x == 0 || x == 1) return 0; if(x == 2 || x == 3) return 1; return fibo(x-1) + fibo(x-2); } public static void main(String[ ] args) { System.out.print("Enter the number of terms: "); int terms = new Scanner(System.in).nextInt(); System.out.println("FIBONACCI SERIES: "); for (int i = 1; i <= terms; i++) { System.out.print(fibo(i) + " "); } } }
OUTPUT
cmd-> javac RecursiveFibonacci.java cmd-> java RecursiveFibonacci Enter the number of terms: 6 FIBONACCI SERIES: 0 1 1 2 3 5
Using Iteration
// Contributed by - Anuj Das ( GC College, Silchar - @ Department of Computer Science ) import java.util.Scanner; class IterativeFibonacci { public static void main(String[ ] args) { System.out.print("Enter the number of terms: "); int terms = new Scanner(System.in).nextInt(); int num1 = 0, num2 = 1, num3; System.out.println("FIBONACCI SERIES: "); if(terms == 0 || terms == 1) System.out.print(num1+ " "); else { System.out.print(num1 + " " + num2 + " "); for(int i=2; i < terms; i++) { num3 = num1 + num2; System.out.print(num3 + " "); num1 = num2; num2 = num3; } } } }
OUTPUT
cmd-> javac IterativeFibonacci.java cmd-> java IterativeFibonacci Enter the number of terms: 9 FIBONACCI SERIES: 0 1 1 2 3 5 8 13 21