Thursday, 16 February 2017

Fibonacci series Iterative and Recursive program in Java

Java Program to print Fibonacci series. OR
Java Program to Print Fibonacci Series upto K Number. OR
Iterative Program to print Fibonacci series. OR
Recursive Program to print Fibonacci series.


What is Fibonacci Series?
Fibonacci series is series of natural number where next number is equivalent to the sum of previous two number.
Example: 
Java program to print fibonacci series up to a given number k. 
Input   = 5 Output = 0, 1, 1, 2, 3

Input   = 2
Output = 0, 1

Input   = 7
Output = 0, 1, 1, 2, 3, 5, 8  

Algorithm


STEP 1 :
Take 2 variable a and b and initialise it to -1 and 1 respectively.

  •  a = -1
  •  b =  1
STEP 2 :
Add both numbers a & b and store it in temporary variable c.

  • c = a + b
STEP 3 :
Print "c"


STEP 4 :
As we are done working with "a" and "b" which result to new value "c".
In each iteration, we need only 2 values a and b, so we will discard old value from "a", "b" and "c".

Initialise "a" to value of "b" and "b" to value of "c". (older value of "a" is discarded)
  • a = b;
  • b = c;
If we repeat Step 2, Step 3 and Step 4 in loop, It will print Fibonacci sequence.

Java Program to Print Fibonacci series Iterative and Recursive approach.


package javabypatel;

public class FibonacciSeries {
 public static void main(String[] args) {
  
  int length = 10;
  
  System.out.println("FibonacciSeries Iterative...");
  fibonacciSeriesIterative(length);
  
  System.out.println("\nFibonacciSeries Recursive...");
  fibonacciSeriesRecurisve(-1, 1, length);
 }

 public static void fibonacciSeriesIterative(int length){
  int a = -1;
  int b =  1;
  
  int c = 0;
  for (int i = 0; i < length; i++) {
   c = a+b; 
   System.out.print(c + ", ");
   a = b;
   b = c;
  }
 }
 
 public static void fibonacciSeriesRecurisve(int a, int b, int length){
  if(length == 0){
   return;
  }
  
  int c = a+b;
  System.out.print(c + ", ");
  fibonacciSeriesRecurisve(b, c, length-1);
 }
}


You may also like to see


Convert integers to roman numerals equivalent in Java

Factorial of Big Number using Recursion in Java

Get Level/Height of node in binary tree

Implement Queue using One Stack in Java (Recursive Implementation)

Rotate matrix by 90 degree

Enjoy !!!! 

If you find any issue in post or face any error while implementing, Please comment.

No comments:

Post a Comment