r/learnjava • u/Apostle_1882 • Feb 08 '21
Help me understand recursion, please!
public static long method(long a, long b) {
if (b == 0) {
return b;
}
return a + method(a, b - 1);
}So this apparently resolves to essentially a * b. I really don't understand this. The base case only ever returns b when b is zero, so in my flawed logic it's always a * 0 = 0.
51
Upvotes
4
u/popey123 Feb 08 '21 edited Feb 08 '21
Recursion work a bit like Stack. It pile up every work it has done until you quit the loop. Then it unleach everything to give you what you want. What i didn t understand first was how can it give me something other than the last value when you finally break the loop.