Given a non-negative integer n, Find the nth fibonacci number using recursion.
Fibonacci numbers is form a special sequence in which each term is obtained by adding the two terms just before it. The sequence begins with 0 and 1.
Mathematically,
- F(0) = 0
- F(1) = 1
- F(n) = F(n − 1) + F(n − 2), for n > 1
Examples:
Input: n = 3
Output: 2
Explanation: The sequence is 0, 1, 1, 2 . . . . i.e. F(3) = 2Input: n = 5
Output: 5
Explanation: The sequence is 0, 1, 1, 2, 3, 5 . . . . i.e. F(5) = 5
Approach:
Since each Fibonacci number is formed by adding the two preceding numbers. We can recursively calculate these smaller numbers as a subproblems and combine their results, continuing this process until we reach the base cases (0 or 1). Once the base cases are reached, the results are successively added back together to give the final Fibonacci number.

#include <iostream>
using namespace std;
int nthFibo(int n){
// Base case
if (n <= 1){
return n;
}
// Recursive case
return nthFibo(n - 1) + nthFibo(n - 2);
}
int main(){
int n = 5;
int result = nthFibo(n);
cout << result << endl;
return 0;
}
#include <stdio.h>
int nthFibo(int n){
// Base case
if (n <= 1){
return n;
}
// Recursive case
return nthFibo(n - 1) + nthFibo(n - 2);
}
int main(){
int n = 5;
int result = nthFibo(n);
printf("%d\n", result);
return 0;
}
class GfG {
static int nthFibo(int n){
// Base case
if (n <= 1) {
return n;
}
// Recursive case
return nthFibo(n - 1) + nthFibo(n - 2);
}
public static void main(String[] args){
int n = 5;
int result = nthFibo(n);
System.out.println(result);
}
}
def nthFibo(n):
# Base case
if n <= 1:
return n
# Recursive case
return nthFibo(n - 1) + nthFibo(n - 2)
if __name__ == "__main__":
n = 5
result = nthFibo(n)
print(result)
using System;
class GfG {
static int nthFibo(int n){
// Base case
if (n <= 1) {
return n;
}
// Recursive case
return nthFibo(n - 1) + nthFibo(n - 2);
}
static void Main(){
int n = 5;
int result = nthFibo(n);
Console.WriteLine(result);
}
}
function nthFibo(n){
// Base case
if (n <= 1) {
return n;
}
// Recursive case
return nthFibo(n - 1) + nthFibo(n - 2);
}
//Driven Code
let n = 5;
let result = nthFibo(n);
console.log(result);
Output
5
Time Complexity: O(2n) At each level of recursion, the number of recursive call gets double(2, 4, 8, …, 2^n) so the total number of calls ≈ 2^n.
Auxiliary Space: O(n), Recursive Stack Space