Recursion
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
A function can call itself. It needs a base case (an answer without recursion) and a step (reducing the task to a smaller one):
int factorial(int n)
{
if (n <= 1)
return 1; // base case
return n * factorial(n - 1); // step
}
Each call gets its own copy of the local variables on the call stack. Recursion that's too deep overflows the stack (stack overflow), and the program crashes.
Recursion is especially natural for tasks that are "recursive" by nature: trees, walking through folders, "divide and conquer". Fibonacci numbers are the classic example, but naive recursion is very slow for them: fib(40) recalculates the same things millions of times. A loop gives the same answer instantly.
Task. Write a recursive function int sum_digits(int n) that returns the sum of the digits of a non-negative number. No loops!
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.