Fibonacci using Recursion in C++
Recursive Fibonacci in C++ with a call tree for F(5): two base cases, why plain recursion is exponential, and how memoization or a loop makes it O(n).
1#include <iostream>2using namespace std;34// Recursive function to calculate Fibonacci number5int fibonacci(int n) {6 // Base cases7 if (n == 0) {8 return 0;9 }10 if (n == 1) {11 return 1;12 }1314 // Recursive case15 return fibonacci(n - 1) + fibonacci(n - 2);16}1718int main() {19 int terms;20 cout << "Enter number of terms: ";21 cin >> terms;2223 if (terms < 0) {24 cout << "Invalid input." << endl;25 return 1;26 }2728 cout << "Fibonacci series:" << endl;29 for (int i = 0; i < terms; i++) {30 cout << fibonacci(i) << " ";31 }32 cout << endl;3334 // Show individual Fibonacci numbers35 cout << "\nIndividual Fibonacci numbers:" << endl;36 for (int i = 0; i <= 10; i++) {37 cout << "F(" << i << ") = " << fibonacci(i) << endl;38 }3940 return 0;41}
Sample Output
0 1 1 2 3 5 8 13 21 34
F(0) to F(9) for 10 terms.
F(10) = 55
34 + 21.
In this one
- Why Fibonacci needs two base cases
- How the call tree branches
- Why naive recursive Fibonacci is exponential
- How memoization fixes it
How it works
- 1
Read terms and reject negatives.
- 2
Print fibonacci(i) for i = 0 to terms − 1.
- 3
fibonacci returns n for 0 and 1, else the sum of the two previous.
- 4
Print F(0) to F(10).
Dry run: Fibonacci using Recursion
F(5)
- 1.├─ F(4)
- 2.│ ├─ F(3) → F(2) + F(1)
- 3.│ └─ F(2) → F(1) + F(0)
- 4.└─ F(3)
- 5. ├─ F(2) → F(1) + F(0)
- 6. └─ F(1)
- 7.F(3) is computed twice and F(2) three times.
F(5) ├─ F(4) │ ├─ F(3) → F(2) + F(1) │ └─ F(2) → F(1) + F(0) └─ F(3) ├─ F(2) → F(1) + F(0) └─ F(1) F(3) is computed twice and F(2) three times.
Edge cases
Large n
Ask for 45 terms.
The run takes seconds because the call count explodes. A loop answers instantly.
Zero terms
Enter 0.
The series loop runs zero times, so the line after "Fibonacci series:" is empty, then F(0) to F(10) still print.
Overflow
Compute F(47) with int.
It exceeds 2,147,483,647 and overflows. Use long long, which lasts until F(92).
What's going on
The Fibonacci sequence starts 0, 1, and each next number is the sum of the two before it: 0 1 1 2 3 5 8 13 21 34 55. The recursive definition copies that rule directly: F(n) = F(n − 1) + F(n − 2), with F(0) = 0 and F(1) = 1.
The function has two base cases, because the recursive case reaches back two steps. Without n == 1, fibonacci(1) would call fibonacci(0) and fibonacci(−1), and the second one would never stop.
main reads how many terms to show and prints F(0) up to F(terms − 1). With 10, that is 0 to 34. A negative count prints "Invalid input." and exits with status 1. Then it prints F(0) to F(10) on separate lines.
The code is short and correct, but it is famously slow. Each call makes two more calls, and the same values are recomputed again and again. To get F(5), the function computes F(3) twice, F(2) three times, and F(1) five times. The total number of calls grows roughly like 1.6ⁿ, so F(40) takes over 300 million calls and F(50) is too slow to wait for.
The fix is to remember answers. Store each F(i) in an array the first time you compute it (memoization), or build up from F(0) with a loop that keeps only the last two values. Both are O(n).
Also note the type limit: int overflows after F(46) = 1,836,311,903.
The headers come first. <iostream> is there because it provides cout and cin for input/output operations. Leave one out and the compiler stops at the first name it does not recognize.
Understanding Fibonacci Sequence
Fibonacci Definition:
Sequence:
Multiple Base Cases
Base Cases:
if (n == 0) {
return 0;
}
if (n == 1) {
return 1;
}
What happens here:
Recursive Case
Function Calls Itself:
return fibonacci(n - 1) + fibonacci(n - 2);
What happens here:
Recursion Flow
Example: fibonacci(5):
Performance Consideration
Time Complexity:
Optimization:
When to Use Recursive Fibonacci
Good fits:
Not Recommended For:
Important Considerations
Base Cases:
Stack Overflow:
Repeated Calculations:
return 0;
return 0; closes main and tells the operating system the program finished without an error.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Why is fibonacci(40) slow here?
Pick an answer to check it.
Question 2
What is fibonacci(6)?
Pick an answer to check it.
Questions people ask
How do I memoize it?
Keep a vector<long long> memo(n + 1, -1) and return memo[n] if it is already set.
What is the loop version?
Keep a = 0, b = 1; repeat n times: next = a + b; a = b; b = next.
Is there a formula?
Binet's formula uses the golden ratio, but floating-point rounding makes it wrong for large n.