It took me a while to figure out recursion, and for one reason or another, I never found the debuggers useful. I will try to explain to you how I do it, and this is not related to the debugger ( disclaimer : this is a personal method, and it may be wrong or not common).
In recursive code, you always have at least a completion block and a recursive block. Mentally isolate these 2 sections.
return n; β completion block
return fibonacci(n - 1) + fibonacci(n - 2); β recursion block
The recursion block expresses the abstract recursion rule (s). Instead of these values ββin the variables Fn1 and Fn2 you get these values ββusing the same function. Think of a brick wall: your recursive function creates a wall that adds brick to an existing wall. Inside the recursion block, at a certain stage, you donβt mind who and how the created wall was created, you just add a new brick to it. This happens when the wall was created by the same function, one brick at a time.
In the completion block, the code is called with some values. What should happen at the end of the process before this value? Speaking of Fibonacci, at the end of the process ( n = 1 or n = 0 ) I have to add this number to the total again. This is done using a recursive block. In other words, the completion block provides concrete values ββ(and not the process of obtaining them) to the recursion block.
When I need to troubleshoot, I print the values ββat every step, and this is the best solution I have found for me. Then I check that they are what they should be. For your Fibonacci, I would like to see a conclusion similar to
the code:
public static int fibonacci( int n ) { System.out.println( "\nInput value: " + n ); if( n == 0 || n == 1 ) { System.out.println( "Terminating block value: " + n ); return n; } else { System.out.println( "Recursion block value: fibonacci(" + (n - 1) + ") + fibonacci(" + (n - 2) + ")" ); int result = fibonacci( n - 1 ) + fibonacci( n - 2 ); System.out.println( "Recursion block return value: " + result ); return result; } }
Conclusion:
Input value: 4 Recursion block value: fibonacci(3) + fibonacci(2) Input value: 3 Recursion block value: fibonacci(2) + fibonacci(1) Input value: 2 Recursion block value: fibonacci(1) + fibonacci(0) Input value: 1 Terminating block value: 1 Input value: 0 Terminating block value: 0 Recursion block return value: 1 Input value: 1 Terminating block value: 1 Recursion block return value: 2 Input value: 2 Recursion block value: fibonacci(1) + fibonacci(0) Input value: 1 Terminating block value: 1 Input value: 0 Terminating block value: 0 Recursion block return value: 1 Recursion block return value: 3
You can also find useful Induction information that is strictly related to recursion.
source share