In Below code we have used recursion to return Fibonacci number and Fibonacci series.
To run the code click here.
Example 1:
Input :-
10
Output :-
55
Code in C++ :-
#include <iostream>
using namespace std;
int f(int n){
if(n ==0) return 0;
else if(n ==1 || n == 2) return 1;
else return f(n-2)+ f(n-1);
}
int main() {
int n;
cin>>n;
cout<<n<<"th fibonacci number is "<<f(n)<<"\n";
/*cout<<"Fibonacci Series till " << n <<"\n";
for(int i =0 ; i < n ; i++){
cout<<" "<<f(i);
}*/
}
Code in Java :-
import java.util.*;
public class MyClass {
public static int f(int n) {
if(n == 0) return 0;
else if(n == 1 || n ==2) return 1;
else return f(n-2) + f(n-1);
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.println(n+"th Febonacci number is :- " + f(n));
/* for(int i=0; i< n ; i++){ //uncomment to print series
System.out.println(" "+f(i));
} */
System.out.println("\n Time complexity O(2^n)");
sc.close();
}
}
Example 2:
Input :-
15
Output :-
610
Top comments (0)