Java Program to Print Fibonacci Series upto K Number.
In this post we will see how to Print Fibonacci series using Recursive 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 Recursive approach,
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 Recursive approach.
package javabypatel; public class FibonacciSeries { public static void main(String[] args) { int length = 10; System.out.println("\nFibonacciSeries Recursive..."); fibonacciSeriesRecurisve(-1, 1, length); } 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