So been studying for my past exam and come across this question which asks what will the return value be if num = 7? Plugging it into BlueJ tells me 16, what does the func1 do to make it 16? How can the method declared be used again within the method? I searched but hard to find this exact example as it all comes up with just using methods normally.
Thanks,
public int func1(int num)
{
if ( num <= 2 ) return 1;
return func1(num – 2) + num;
}
That is a recursive call to the same function you are using it in.
So,
func1(num – 2)will invoke the same function –public int func1(int num)withnum = num - 2, untilnum >= 2So, you recursion goes like this: –
UPDATE: – Generalized the above recursion, to let you figure out how it works.
You can go through: – Recursion – Wiki Page