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 के बिना एक recursive method static int power(int base, int exp) लिखें। 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.