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
Add both numbers a & b and store it in temporary variable c.
- c = a + b
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;
Java Program to Print Fibonacci series Iterative and Recursive approach.
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.
Post a Comment