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 ഇല്ലാതെ int sumDigits(int n) എന്ന recursive function എഴുതൂ. main()-ൽ n വായിച്ച് ഫലം print ചെയ്യൂ. Input: 9875 → Output: 29

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