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.