programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

Need Help to debug Recursive

M Hasan
Ranch Hand
Posts: 35
I have done some recursive problem like Fibonacci and factorial. I am trying to understand the following code which I created to understand recursive more. When I do debug them, I get lost. I need little explanation. If some can put some effort, I will be grateful

Here is my understanding:
#1 (arr, 0, 3)

#2 (arr, 1, 3)
#3 (arr, 2, 3)
#4 (arr, 3, 3): test = 1 and #4 erased

#3 will call the method again and create stack #4 (arr, 3, 3) in the for loop. which will make test = 2 . #4 erased and # will increase test = 3
#2 will call the method again and create stack #4 (arr, 2, 3) and #5 (arr, 3,3) in the for loop. #5 makes test = 3 and # 4 make test = 4. Stack #3,4 erased. #2 makes test = 5
#1 will increase test = 7

This understanding can be wrong. I am looking for some help please

Tony Docherty
Bartender
Posts: 3271
82
Debugging recursive methods can be confusing, try adding some debug so you can get a print out of what is happening. For example:

Note: I renamed your variable 'l' to 'j' as it can be hard to distinguish an 'l' from a '1'

Knute Snortum
Sheriff
Posts: 4279
127
If the object is to write a recursive method that returns the total of the array, your method can be a lot simpler.

* Are you using int total at all?
* Since you pass the array, do you need to pass the array length?
* You don't need a class variable like static int test.

M Hasan
Ranch Hand
Posts: 35
There is no reason to use array here for sure. All I ask to help me  to understand the stack and method call in the for loop here.

Carey Brown
Saloon Keeper
Posts: 3323
46
• 1
Similar to Tony's example but I like to add a "level" parameter.

Output

M Hasan
Ranch Hand
Posts: 35
Thanks