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).

BeginnerRecursion ProgramsExample 2 of 5
fibonacci-using-recursion.cpp
1#include <iostream>
2using namespace std;
3
4// Recursive function to calculate Fibonacci number
5int fibonacci(int n) {
6 // Base cases
7 if (n == 0) {
8 return 0;
9 }
10 if (n == 1) {
11 return 1;
12 }
13
14 // Recursive case
15 return fibonacci(n - 1) + fibonacci(n - 2);
16}
17
18int main() {
19 int terms;
20 cout << "Enter number of terms: ";
21 cin >> terms;
22
23 if (terms < 0) {
24 cout << "Invalid input." << endl;
25 return 1;
26 }
27
28 cout << "Fibonacci series:" << endl;
29 for (int i = 0; i < terms; i++) {
30 cout << fibonacci(i) << " ";
31 }
32 cout << endl;
33
34 // Show individual Fibonacci numbers
35 cout << "\nIndividual Fibonacci numbers:" << endl;
36 for (int i = 0; i <= 10; i++) {
37 cout << "F(" << i << ") = " << fibonacci(i) << endl;
38 }
39
40 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. 1

    Read terms and reject negatives.

  2. 2

    Print fibonacci(i) for i = 0 to terms − 1.

  3. 3

    fibonacci returns n for 0 and 1, else the sum of the two previous.

  4. 4

    Print F(0) to F(10).

Dry run: Fibonacci using Recursion

F(5)

  1. 1.├─ F(4)
  2. 2.│ ├─ F(3) → F(2) + F(1)
  3. 3.│ └─ F(2) → F(1) + F(0)
  4. 4.└─ F(3)
  5. 5. ├─ F(2) → F(1) + F(0)
  6. 6. └─ F(1)
  7. 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:

F(0) = 0
F(1) = 1
F(n) = F(n-1) + F(n-2) for n > 1

Sequence:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
Each number = sum of previous two
Appears in nature, mathematics, art

Multiple Base Cases

Base Cases:

if (n == 0) {

return 0;

}

if (n == 1) {

return 1;

}

What happens here:

Two base cases needed
F(0) = 0, F(1) = 1
Stops recursion
Returns known values

Recursive Case

Function Calls Itself:

return fibonacci(n - 1) + fibonacci(n - 2);

What happens here:

Calls fibonacci(n-1) and fibonacci(n-2)
Adds results together
Reduces problem to smaller subproblems
Builds solution from base cases

Recursion Flow

Example: fibonacci(5):

1.fibonacci(5) = fibonacci(4) + fibonacci(3)
2.fibonacci(4) = fibonacci(3) + fibonacci(2)
3.fibonacci(3) = fibonacci(2) + fibonacci(1)
4.fibonacci(2) = fibonacci(1) + fibonacci(0)
5.Base cases return: F(1)=1, F(0)=0
6.Results propagate back: F(2)=1, F(3)=2, F(4)=3, F(5)=5

Performance Consideration

Time Complexity:

O(2^n) - exponential
Repeated calculations
Same values calculated multiple times
Inefficient for large n

Optimization:

Memoization: cache results
Iterative: O(n) time
Dynamic programming: store computed values
Better for large n

When to Use Recursive Fibonacci

Good fits:

Learning recursion
Small values of n
Understanding recursive structure
Educational purposes

Not Recommended For:

Large values of n
Performance-critical code
Production applications
Real-time systems

Important Considerations

Base Cases:

Must have both F(0) and F(1)
Stops recursion properly
Prevents infinite recursion
Essential for correctness

Stack Overflow:

Deep recursion uses stack
May overflow for large n
Consider iterative approach
Limited by stack size

Repeated Calculations:

Same values calculated multiple times
Inefficient recursive tree
Memoization improves performance
Trade-off: simplicity vs efficiency

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.