3

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;
}

6 Answers6

6

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

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • Thanks, time to go study some recursion it seems. Makes sense though. Thank you all/ – user1782493 Oct 29 '12 at 09:53
  • @user1782493. You should try to understand what happens behind the scene of this recursive process. Then it would be easier for you to work out recursive codes. – Rohit Jain Oct 29 '12 at 09:55
3

This is called recursion. The best way to understand it is to watch it in the debugger, and consider how the sequence of calls will terminate (i.e. why doesn't it call itself indefinitely).

(sorry - not giving you a full answer since this is homework/exam related)

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
1

Well, this is what recursion is all about.The method is getting called recursively till a certain exit condition is satisfied. In your case, the exit condition is when the method parameter value hits a value that is <= 2

Sujay
  • 6,753
  • 2
  • 30
  • 49
1

In order to understand recursion, you must first understand recursion.

Here you can find a good explanation about that.

Community
  • 1
  • 1
Ricardo Rodriguez
  • 1,010
  • 11
  • 22
0

What you want to look at (especcially for your exam) is called Recursion

The function calls itself with different parameter values, until an internal criteria is met.

LuigiEdlCarno
  • 2,410
  • 2
  • 21
  • 37
0

How can the method declared be used again within the method?

Answer :Calling same method within the method called Recursion (computer science)

You can do without using recursion using loop

public int func1(int num) {
        int res=1;
        while(num >= 2 ) {
            res += num;
            num = num-2;
        }
        return res;
    }

But recursion is one of the most important feature to code reuse when you work with Tree, Hierarchy etc.,

vels4j
  • 11,208
  • 5
  • 38
  • 63