DEV Community

Cover image for Fibonacci Number Using Recursion
Gourav Kadu
Gourav Kadu

Posted on

1 1

Fibonacci Number Using Recursion

In Below code we have used recursion to return Fibonacci number and Fibonacci series.
To run the code click here.

Example 1:

Input :-

10
Enter fullscreen mode Exit fullscreen mode

Output :-

55
Enter fullscreen mode Exit fullscreen mode

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);
  }*/
}
Enter fullscreen mode Exit fullscreen mode

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();
    }
}
Enter fullscreen mode Exit fullscreen mode

Example 2:

Input :-

15
Enter fullscreen mode Exit fullscreen mode

Output :-

610
Enter fullscreen mode Exit fullscreen mode

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more