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.