Recursion Programs
C++ recursion programs with dry runs: factorial, Fibonacci, Tower of Hanoi, GCD with Euclid's algorithm, and fast power, with base cases and call stack depth.
5 programs · open one, then the next
Start with Factorial using Recursion- 01Factorial using RecursionBeginnerRecursive factorial in C++ with a dry run of factorial(5): the base case, the call stack unwinding, why negatives never stop, and where int overflows.Open example →cpp#include <iostream> using namespace std; // Recursive function to calculate factorial
- 02Fibonacci using RecursionBeginnerRecursive Fibonacci in C++ with a call tree for F(5): two base cases, why plain recursion is exponential, and how memoization or a loop makes it O(n).Open example →cpp#include <iostream> using namespace std; // Recursive function to calculate Fibonacci number
- 03Tower of HanoiIntermediateSolve Tower of Hanoi in C++ with recursion: the three-step idea, how the peg parameters swap, a full move list for 3 disks, and why it takes 2^n − 1 moves.Open example →cpp#include <iostream> using namespace std; void towerOfHanoi(int n, char from, char to, char aux) {
- 04GCD using RecursionIntermediateRecursive GCD in C++ using Euclid's algorithm: why gcd(b, a % b) works, a dry run for 48 and 18, negatives, LCM from GCD, and the zero-input case.Open example →cpp#include <iostream> using namespace std; // Recursive function to calculate GCD using Euclidean algorithm
- 05Power using RecursionIntermediateFast recursive power in C++ using exponentiation by squaring: even and odd exponents, negative powers, O(log n) calls, and a dry run for 2^10.Open example →cpp#include <iostream> using namespace std; // Recursive function to calculate power