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.