codegurukool.com · Free coding tutorials & online compiler

Home › C++ Tutorial › C++ recursion

C++ recursion

A function calling itself.

Needs a base case. Each call uses stack space.

Example code

#include <iostream>
using namespace std;
int fact(int n) { return n <= 1 ? 1 : n * fact(n - 1); }
int main() {
  cout << fact(5) << endl;
  return 0;
}

Run this code in the online editor

← C++ scopeC++ lambda →