I have two similar methods with each returning different values as shown below
public static int recurse1(int x) {
//base condition
if(x <= 0) return 1;
int re = recurse1(x - 1);
System.out.print("re "+re+", ");
return re;
}
and this
public static int recurse2(int x) {
//base condition
if(x <= 0) return 1;
int re = recurse2(x - 1);
System.out.print("re "+re+", ");
return x;
}
when I called each of the methods in the main method passing an argument of 5,I expected the outputs to be something like re 1, re 1, re 1 ... for the respective methods since the base case for each should return 1.But the output for recursive2(5) printed re 1, re 1, re 2, re 3, re 4. I really want to know why the difference in the output. I am sorry if this question has already been asked as I couldn’t find a clear explanation.
>Solution :
You must know that the return at the end of the function is different?
Change you program to be like this, explicitly outputting the values as walk through the program and showing the call depth to your recursive program. Maybe this will help you understand what is going on:
public class T {
public static void main(String[] args) {
System.out.println("Version 1\n");
recurse1(5, 0);
System.out.println("\n=============\nVersion 2\n");
recurse2(5, 0);
}
public static int recurse1(int x, int callDepth) {
//base condition
if(x <= 0) return 1;
System.out.println(indent(callDepth) + "About to recurse passing value " + (x-1));
int re = recurse1(x - 1, callDepth+1);
System.out.println(indent(callDepth) + "Returned with " + re + ", returning this value");
//System.out.println("re "+re+", ");
return re;
}
public static int recurse2(int x, int callDepth) {
//base condition
if(x <= 0) return 1;
System.out.println(indent(callDepth) + "About to recurse passing value " + (x-1));
int re = recurse2(x - 1, callDepth+1);
System.out.println(indent(callDepth) + "Returned with " + re + ", but returning " + x);
//System.out.print("re "+re+", ");
return x;
}
public static String indent(int padding) {
String pad = "";
for(int i=0; i< padding; i++) {
pad += " ";
}
return pad;
}