Back

Recursion Examples

What is Recursion?

Recursion is a programming technique where a function calls itself to solve a problem. It consists of:

  1. Base case: The condition that stops the recursion
  2. Recursive case: The function calling itself with a simpler version of the problem

Recursion is particularly useful for problems that can be broken down into smaller, similar subproblems.

Factorial Example

The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. For example: 5! = 5 × 4 × 3 × 2 × 1 = 120

function factorial(n) {
  if (n === 0 || n === 1) return 1;
  return n * factorial(n - 1);
}
Result will appear here.
Call stack visualization will appear here.

Logs will appear here.

Fibonacci Sequence Example

The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, starting from 0 and 1. For example: 0, 1, 1, 2, 3, 5, 8, 13, 21, ...

function fibonacci(n) {
  if (n === 0) return 0;
  if (n === 1) return 1;
  return fibonacci(n - 1) + fibonacci(n - 2);
}
Result will appear here.
Call stack visualization will appear here.

Logs will appear here.

Recursive Countdown Example

A simple countdown function that demonstrates recursion by counting down from a given number to 1.

function countdown(n) {
  if (n <= 0) return;
  console.log(n);
  countdown(n - 1);
}
Countdown sequence will appear here.
Call stack visualization will appear here.

Logs will appear here.