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.