Lesson 21 of 34

Recursion: സ്വയം call ചെയ്യുന്ന Methods

10 min 35 XP

Recursive method ചെറിയ input-ഓടെ സ്വയം call ചെയ്യുന്നു. അതിന് ഒരു base case (നിൽക്കുന്നിടം), ഒരു recursive case (ചെറിയ പ്രശ്നത്തിൽ call) എന്നിവ വേണം. Base case ഇല്ലെങ്കിൽ StackOverflowError വരും.

Example: edit me and press Run

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

sumTo(3) = 3 + sumTo(2) = 3 + 2 + sumTo(1) = 3 + 2 + 1 + sumTo(0) = 6. ഇങ്ങനെ കടലാസിൽ trace ചെയ്താൽ recursion എളുപ്പം മനസ്സിലാകും.

Challenge

+35 XP

Math.pow ഇല്ലാതെ static int power(int base, int exp) എന്ന recursive method എഴുതൂ. main()-ൽ base, exp വായിച്ച് ഫലം print ചെയ്യൂ. Input: 2 10 → Output: 1024

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