
Recursion Example with Debugging?
Problem: Find factorial of a number using recursion. 5! = 5 × 4 × 3 × 2 × 1 = 120 Java Code (with debug prints): public class Main { static int fact ( int n ) { System . out . println ( "Calling fact(" + n + ")" ); if ( n == 1 ) { System . out . println ( "Base case reached: fact(1) = 1" ); return 1 ; } int result = n * fact ( n - 1 ); System . out . println ( "Returning from fact(" + n + ") = " + result ); return result ; } public static void main ( String [] args ) { int output = fact ( 5 ); System . out . println ( "Final Answer: " + output ); } } Step-by-Step Debug Output: Calling fact(5) Calling fact(4) Calling fact(3) Calling fact(2) Calling fact(1) Base case reached: fact(1) = 1 Returning from fact(2) = 2 Returning from fact(3) = 6 Returning from fact(4) = 24 Returning from fact(5) = 120 Final Answer: 120 Image Explanation:
Continue reading on Dev.to Webdev
Opens in a new tab



