Coders Packet

Nth Fibonacci Numbers Using Recursion in C++

By AMAN KUMAR PANDEY

This code will find nth fibonacci numbers in C++ using recursion function("int nth_fibonacci(int n)") including 0 as the first term.

Fibonacci Numbers are - 0 1 1 2 3 5 8 13 21 34 55 89..............
Since the 9th term is 21 so my code will give output as 21.
Since in most of the recursion code, they start the series from 1 but in my code, it will start from 0 (which is the actual first term of the Fibonacci series).
In this code when an integer is passed to function "int nth_fibonacci(int n)" then it will go inside the function check for the base condition if any of this gets satisfied it will return. Base conditions are also used to terminate or stop the recursive call. then it will take two integers a and b. The value obtained by a recursive call of "n-1" is stored in "a" and "b" stores the value obtained by the recursive call of "n-2".Now (a+b) is returned, which is our actual nth Fibonacci number, and the result is printed.


CODE-

#include<bits/stdc++.h>
using namespace std;
int nth_fibonacci(int n)
{
    if(n==1)
    {
        return n-1;
    }
    if(n==2)
    {
        return n-1;
    }
    int a=nth_fibonacci(n-1);
    int b=nth_fibonacci(n-2);
    return (a+b);
}
int main()
{
    int n;
    cout<<"ENTER THE NTH TERM OF FIBONACCI-";
    cin>>n;
    cout<<endl;
    cout<<"Nth FIBONACCI NUMBER IS : "<<nth_fibonacci(n)<<endl;
    return 0;
}

 

 

 

INPUT- ENTER THE NTH TERM OF FIBONACCI-9

OUTPUT- Nth FIBONACCI NUMBER IS : 21

 


INPUT- ENTER THE NTH TERM OF FIBONACCI-11
OUTPUT-Nth FIBONACCI NUMBER IS : 55

Download project

Reviews Report

Submitted by AMAN KUMAR PANDEY (amanpandey)

Download packets of source code on Coders Packet