Skip to content
Justice Tech School

Recursion

A function may call itself with a base case.

Example
#include <iostream>

long fact(int n) { return n <= 1 ? 1 : n * fact(n - 1); }
int fib(int n) { return n < 2 ? n : fib(n - 1) + fib(n - 2); }

int main() {
  std::cout << fact(5) << " " << fib(10) << "\n";
  return 0;
}

Result

120 55

Exercise

Base case.

if (n <= 1) return ;

Quiz Test

What stops recursion?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.