public static int m(int i, int j)
{
if ( i > j)
return 0;
else
{
i++;
m(i++, j);
}
return i;
}
I had two questions. 1.) What is returned by out.print(m(3,8));
and 2.) How many times is the method m called? The answers should be 5 and 7 respectively.
When I worked out question 1, I came out with 5 but the way I did it was incorrect because the method was not called 7 times, it was only called twice. The way I did this was I went straight to the else statement since (i > j)
was false at the start and method m was called again this time with (4, 8)
I figured it was still false so I went back to the line where m is called and the variable i changed to 5 because of the i++
in m(i++, j)
. After that it would return 5 for the Value of i.
That was obviously wrong so I added some out.prints for the values of i throughout the program to see how the value was changing and it went from 3 to 9 with an out.print(i);
at the beginning of method m
. An out.print(i);
right before return i;
showed the values started to go backwards from 10 to 5 and the method was called 7 times. How does this work?
EDIT: After logging it, I was able to come up with some logic to it but I would like someone to clarify that it is correct.
method m is called with 3,8 at the start. After, it calls itself with 4,8 then 5,8....until 9,8 where the if statement becomes true and the method returns 0. It called itself 6 times so it starts go backwards or decrement-ing 6 times so since m(i++, j) is post(the i) then i becomes 10 and 10 is returned, then 9, then 8, then 7, 6, and finally 5. When it returned 10 that was 1, 9 was 2, 8 was 3, 7 was 4, 6 was 5, and 5 was 6. So since it was 6 when i = 5, that was the value that was returned. Is this correct? And if it is, a more in depth explanation would be nice to have.
To better understand what's happening, it might help to refactor the code as such:
public static int m(int i, int j) {
static int calls = 0;
System.out.println("entering. count: " + calls);
calls++;
System.out.println("i = " + i);
System.out.println("j = " + j);
if (i > j) {
System.out.println("returning 0");
return 0;
} else {
i++;
m(i++, j);
}
System.out.println("returning " + i);
return i;
}
Note that I haven't modified any of the actual logic. All I've done is add some statements to print values, and a variable to keep track of the number of times the method is called.