Print Fibonacci series using Iterative approach in Java

Java Program to Print Fibonacci Series upto K Number.


In this post we will see how to Print Fibonacci series using Iterative approach in Java.
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


Lets explore algorithm to print fibonacci series using Iterative approach, 

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 using Iterative approach.


package javabypatel;

public class FibonacciSeries {
 public static void main(String[] args) {
  
  int length = 10;
  
  System.out.println("FibonacciSeries Iterative...");
  fibonacciSeriesIterative(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;
  }
 }
}

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.

Post a Comment