Lesson 21 of 34

Recursion: தன்னைத்தானே அழைக்கும் methodRecursion: Methods That Call Themselves

10 min 35 XP

Recursion-ல் method தன்னைத்தானே சிறிய input-உடன் அழைக்கும். இரண்டு பகுதிகள் அவசியம்: base case (நிறுத்தும் இடம்) மற்றும் recursive case (சிறிய பிரச்சனைக்கு அழைப்பு). Base case இல்லையெனில் StackOverflowError வரும்.

A recursive method calls itself with a smaller input. It needs a base case (where it stops) and a recursive case (a call on a smaller problem). Without a base case you get a 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. காகிதத்தில் இப்படி எழுதிப் பார்த்தால் recursion எளிதாகப் புரியும்.

sumTo(3) = 3 + sumTo(2) = 3 + 2 + sumTo(1) = 3 + 2 + 1 + sumTo(0) = 6. Tracing it on paper like this makes recursion click.

Challenge

+35 XP

static int power(int base, int exp) என்ற recursive method எழுதுங்கள் (Math.pow பயன்படுத்தக் கூடாது). main()-ல் base, exp படித்து விடையை print செய்யுங்கள். Input: 2 10 → Output: 1024

Write a recursive method static int power(int base, int exp) without Math.pow. In main(), read base and exp and print the result. Input: 2 10 → Output: 1024

Output Loading Java (first time takes a few seconds)
Press Run to see the result here.