Lesson 15 of 23

Recursion

10 min 30 XP

Recursive function खुद को छोटे input के साथ call करता है। Base case के बिना stack overflow होता है और प्रोग्राम crash हो जाता है।

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) बहुत धीमा है (O(2ⁿ)); loop या memoization इसे O(n) बना देता है। Interviewers को यह तुलना बहुत पसंद है।

Challenge

+30 XP

Loops के बिना recursive function int sumDigits(int n) लिखें। main() में n पढ़ें और परिणाम print करें। Input: 9875 → Output: 29

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