One of the common programming problem to print Fibonoci Series.
Series like 0, 1, 1, 2, 3, 5, 8 .....n
Solution:
public class FiboSeries { public static void main(String args[]) { int n = 5; // By procedural method List<Integer> fiboList = getFibo(n); System.out.println(fiboList); // Using recursion technique for(int i = 0; i<n; i++) { System.out.print(getFiboRecursive(i)); } } static List<Integer> getFibo(int n) { List<Integer> fiboList = new ArrayList<Integer>(); if (n <= 0) {fiboList.add(0); return fiboList;} if (n == 1) {fiboList.add(1); return fiboList;} if (n == 2) {fiboList.add(0); fiboList.add(1); return fiboList;} int a = 0; int b = 1; fiboList.add(a); fiboList.add(b); for(int i =2; i<n; i++) { int nextItem = a + b; fiboList.add(nextItem); a = b; b = nextItem; } return fiboList; } static int getFiboRecursive(int n) { if( n==0) return 0; if (n==1) return 1; return getFiboRecursive(n-1) + getFiboRecursive(n-2); } }
There was an error while loading. Please reload this page.