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.