Last active
January 14, 2019 04:35
-
-
Save theArjun/6b0fb961c179bcdd66d0a17d5d70924b to your computer and use it in GitHub Desktop.
Fibonacci By Recursion in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include<iostream> | |
| using namespace std; | |
| int fibonacci(int); | |
| int main(){ | |
| int number; | |
| cout << "Enter how many elements you want to see in Fibonacci Series : "; | |
| cin >> number; | |
| // Recursively calls the fibonacci function. | |
| for(int i=0; i<number; i++){ | |
| cout << fibonacci(i) << " "; | |
| } | |
| } | |
| int fibonacci(int number){ | |
| if(number <= 1){ | |
| return 1; | |
| }else{ | |
| // Key algorithm | |
| return fibonacci(number - 1) + fibonacci (number - 2); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Fibonacci{ | |
| // Declaring variables for array and index used for storing the elements of fibonacci series. | |
| private int index; | |
| private final int[] list; | |
| // Parameterized constructor that stores index and initializes array of particular index. | |
| Fibonacci(int index){ | |
| this.index = index; | |
| list = new int[index]; | |
| } | |
| // Fibonacci Series that implements by recursion | |
| public int fibonacci(int number){ | |
| if(number <= 1){ | |
| // If provided input is 1 or less than 1, 1 is returned. | |
| return 1; | |
| }else{ | |
| // Key algorithm | |
| return fibonacci(number - 1) + fibonacci(number -2); | |
| } | |
| } | |
| public void display(){ | |
| // Loop runs from 0 to index-1 or before index. | |
| for(int i = 0; i < this.index ; i++){ | |
| // Stores each fibonacci element to array. | |
| list[i] = fibonacci(i); | |
| // Prints the array. | |
| System.out.print(" "+list[i]); | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class FibonacciDemo{ | |
| public static void main(String[] args){ | |
| // Pass parameter as how many elements you want to see : | |
| Fibonacci fibonacciObjectOne = new Fibonacci(10); | |
| fibonacciObjectOne.display(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment