Programs & Examples
Functions and Default Arguments · Study material
Tower of Hanoi with recursion
To move n disks, move n − 1 disks to the spare peg, move the largest disk, then move the n − 1 disks on top of it. The recursion makes 2n − 1 moves.
#include <iostream>
int moves = 0;
void hanoi(int n, char from, char to, char via) {
if (n == 0) return;
hanoi(n - 1, from, via, to); // move n-1 disks out of the way
std::cout << "disk " << n << ": " << from << " -> " << to << '\n';
++moves;
hanoi(n - 1, via, to, from); // put them back on top
}
int main() {
hanoi(3, 'A', 'C', 'B');
std::cout << moves << " moves\n"; // always 2^n - 1
return 0;
}
disk 1: A -> C disk 2: A -> B disk 1: C -> B disk 3: A -> C disk 1: B -> A disk 2: B -> C disk 1: A -> C 7 moves
Prime numbers with small helper functions
is_prime tests divisors only up to √n; next_prime reuses it. Small functions with clear names make the main program read like a description.
#include <iostream>
bool is_prime(int n) {
if (n < 2) return false;
for (int d = 2; d * d <= n; ++d)
if (n % d == 0) return false;
return true;
}
int next_prime(int n) {
while (!is_prime(++n)) {}
return n;
}
int main() {
std::cout << "primes below 40:";
for (int i = 2; i < 40; ++i)
if (is_prime(i)) std::cout << ' ' << i;
std::cout << "\nnext prime after 100: " << next_prime(100) << '\n';
return 0;
}
primes below 40: 2 3 5 7 11 13 17 19 23 29 31 37 next prime after 100: 101
Returning several results with a struct
The stats function from the introduction returns minimum, maximum and average together; the caller unpacks them with auto [lo, hi, avg] = stats(marks);.