Recursion visualized

Step through how a recursive C++ function calls itself: the factorial call stack and the Fibonacci call tree.

Everything is simulated in this browser; nothing is sent to any server.

factorial(4) is called

Calls: 1 · factorial(4) = 24

factorial(4) is called

Call stack

factorial(4)?
  • Running
  • Waiting
  • Resolved

Step 1 / 16

Code

#include <iostream>
using namespace std;
long factorial(int n) { // Computes n! recursively
if (n == 0) return 1; // Base case: 0! is 1 and there are no more calls
long r = n * factorial(n - 1); // Recursive case: call with n - 1 and multiply
return r; // Returns the result to the caller
}
int main() {
int n = 4; // This is the slider value
long resultado = factorial(n); // First call, from main
cout << resultado << endl; // Final result
return 0;
}

This tool explains recursion visually with two classic C++ examples. With factorial you see the call stack: each call to factorial(n) is pushed as a frame until the base case is reached, and then the frames resolve one by one, returning their value to the caller. With Fibonacci you see the call tree: each fib(n) branches into fib(n-1) and fib(n-2), and repeated calls are highlighted to show why this recursive version does so much duplicate work. You choose n with a slider, play the animation step by step and follow the line of code being executed at each moment. Everything is simulated in your browser.

How to use it

  1. Pick the Factorial or Fibonacci tab depending on the example you want to see.
  2. Adjust n with the slider; the animation goes back to the first step.
  3. Press Play or move with the previous and next step buttons, and change the speed if you need to.
  4. Watch the call stack or call tree, the call counter and the highlighted line of C++ code.

Frequently asked questions

What is recursion?
A technique where a function calls itself on a smaller problem until it reaches a case that can be solved directly, and then combines the results.
What is the base case?
The condition that stops the calls: in factorial, n equal to 0 returns 1; in Fibonacci, n less than 2 returns n. Without a base case the recursion never ends.
What is the call stack?
The structure where the program keeps every call in progress. Each call is pushed when it is made and popped when it returns its value, following LIFO order.
Why does the recursive Fibonacci repeat work?
Because fib(n) calls fib(n-1) and fib(n-2), and those calls compute the same values again several times. That is why the tree grows so fast and repeated calls are highlighted.

Related tools