Lesson 15 of 23

Recursion

10 min 30 XP

A recursive function calls itself with a smaller input. Without a base case, the stack overflows and the program crashes.

Example: edit me and press Run

Output Loading C (first time takes a few seconds)
Press Run to see the result here.

Recursive fib(40) is very slow (O(2ⁿ)); a loop or memoization makes it O(n). Interviewers love this comparison.

Challenge

+30 XP

Write a recursive function int sumDigits(int n) without loops. In main(), read n and print the result. Input: 9875 → Output: 29

Output Loading C (first time takes a few seconds)
Press Run to see the result here.