Lesson 15 of 23

RecursionRecursion

10 min 30 XP

Recursive function தன்னைத்தானே சிறிய input-உடன் அழைக்கும். Base case இல்லையெனில் stack overflow ஆகி program crash ஆகும்.

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.

fib(40) recursive-ஆக மிக மெதுவாக இருக்கும் (O(2ⁿ)). Loop அல்லது memoization பயன்படுத்தினால் O(n). இந்த ஒப்பீடு interview-ல் கேட்கப்படும்.

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

Challenge

+30 XP

int sumDigits(int n) என்ற recursive function எழுதுங்கள் (loop கூடாது). main()-ல் n படித்து விடையை print செய்யுங்கள். Input: 9875 → Output: 29

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.