Labs ICT
๐ŸŽ“ SIWES/IT Login

Recursion

1 min read | C++ Tutorial
๐ŸŽ“

Doing SIWES / IT attachment?

Get a structured training programme, a supervised digital logbook, and a completion certificate with LabsICT SIWES / IT.

Explore SIWES / IT Training

Recursion

A recursive function calls itself. It's a natural fit for problems that can be broken into smaller, identical subproblems.

Every recursive function needs a base case โ€” a condition that stops the recursion. Without it, you get infinite recursion and a stack overflow.

int factorial(int n) {
  if (n <= 1) {
    return 1;
  }
  return n * factorial(n - 1);
}

Each call adds a frame to the call stack. When the base case is reached, the stack unwinds and each frame returns its result to the caller.

int fibonacci(int n) {
  if (n <= 1) {
    return n;
  }
  return fibonacci(n - 1) + fibonacci(n - 2);
}

Recursion can be elegant, but it uses memory. Iterative solutions are often more efficient. Use recursion when it makes the code simpler to understand.

๐Ÿงช Quick Quiz

What must every recursive function have?