If you want to practice data structure and algorithm programs, you can go through 100+ java coding interview questions.
For example :
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 etc.
There are two ways to print Fibonacci series.
- Using iteration
- Using recursion
Using iteration:
Algorithm:
- Initialise first two terms with 0 and 1
- Find sum of first two terms.
- Iterate upto numberOfElements
- Print the sum
- Assign prev to next and next to sum to go for next two terms.
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
package org.arpit.java2blog.algo; public class FibonnacciIterativeMain { public static void main(String[] args) { System.out.println("Printing Fibonacci series:"); // first two number of series int prev=0,next=1; //printing first two elements System.out.print(prev+" "+next); //number of elements to be printed int numberOfElements=10; int sum=0; for(int i=2;i<numberOfElements;i++) { sum=prev+next; System.out.print(" "+sum); prev=next; next=sum; } } } |
1 2 3 4 |
Printing Fibonacci series: 0 1 1 2 3 5 8 13 21 34 |
Using recursion:
Algorithm:
- Initialise first two terms with 0 and 1
- Base case will be when numberOfElements becomes 0.
- Find sum of first two terms.
- Print the sum
- Assign prev to next and next to sum to go for next two terms.
- Call same function again and decrease numberOfElements.
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
package org.arpit.java2blog.algo; public class FibonnacciRecursionMain { //First two number of series static int prev=0,next=1; static int sum=0; public static void main(String[] args) { System.out.println("Printing Fibonacci series:"); //printing first two elements System.out.print(prev+" "+next); //number of elements to be printed int numberOfElements=10; // -2 because we have already printed 2 elements printFibonacciSeriers(numberOfElements-2); } public static void printFibonacciSeriers(int numberOfElements) { if(numberOfElements==0) return; else { sum=prev+next; System.out.print(" "+sum); //prepare for next 2 terms prev=next; next=sum; printFibonacciSeriers(numberOfElements-1); } } } |
1 2 3 4 |
Printing Fibonacci series: 0 1 1 2 3 5 8 13 21 34 |