Search⌘ K

Solution Review: Calculate nth Fibonacci Number Using Recursion

Explore how to implement a recursive function in C++ to calculate the nth Fibonacci number. Understand the role of base cases and recursive cases, and see binary recursion in action. This lesson strengthens your grasp of recursion through a practical example critical for many programming challenges.

We'll cover the following...

Solution #

Press the RUN button and see the output!

C++
#include <iostream>
using namespace std;
// Recursive fibonacci function
int Fibonacci(int n) {
// Base Case
if (n == 0) {
return 0;
}
else if (n == 1) {
return 1;
}
// Recursive Case
else {
return Fibonacci(n - 1) + Fibonacci(n - 2);
}
}
// main function
int main() {
// Initialize variable n
int n = 4;
// Declare variable result
int result;
// Call fibonacci function in main and store its output in result
result = Fibonacci(4);
// Print value of result
cout << n << "th Fibonacci number = " << result;
return 0;
}

Explanation

fibonacci function

The recursive fibonacci function ...