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.