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

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more