← C++ from Scratch
Lesson 32 of 62 · 10 XP
Recursion
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
A recursive function calls itself for a simpler case:
int factorial(int n)
{
if (n <= 1) // the base case — where the recursion stops
return 1;
return n * factorial(n - 1); // the step: reduce the task to a smaller one
}
Each call puts its own local variables on the stack. Without a base case (or with very deep recursion) the stack overflows, and the program crashes.
Recursion is natural for trees, nested structures and "divide and conquer" (quicksort, binary search).
Task. Write a recursive function int digitSum(int n) — the sum of a number's digits — and a recursive
void binary(int n) that prints the number in binary (for 0 — 0). Read n, print the sum of its digits and its binary form.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.