Skip to content

Instantly share code, notes, and snippets.

@theArjun
Last active January 14, 2019 04:35
Show Gist options
  • Select an option

  • Save theArjun/6b0fb961c179bcdd66d0a17d5d70924b to your computer and use it in GitHub Desktop.

Select an option

Save theArjun/6b0fb961c179bcdd66d0a17d5d70924b to your computer and use it in GitHub Desktop.
Fibonacci By Recursion in Java
#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);
}
}
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]);
}
}
}
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