Using the same method declared in the method?
java, methods, return-value
Solution
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
Problem
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; } ```