Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the same method declared in the method?

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;
}
like image 825
user1782493 Avatar asked Aug 26 '26 02:08

user1782493


1 Answers

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) with num = num - 2, until num >= 2

So, you recursion goes like this: -

func(n)
   calls func(n-2)
      calls func(n-4)
         .. so on
         calls func(1)
            returns 1
         returns 1 + 3 + ... + (n - 4)
      returns 1 + 3 + ... + (n - 4) + (n - 2) 
   returns 1 + 3 + ... + (n - 4) + (n - 2) + n

UPDATE: - Generalized the above recursion, to let you figure out how it works.

You can go through: - Recursion - Wiki Page

like image 52
Rohit Jain Avatar answered Aug 28 '26 15:08

Rohit Jain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!