java - Method calling itself.. recursive? -
public static int m(int i, int j) { if ( > j) return 0; else { i++; m(i++, j); } return i; } i had 2 questions. 1.) returned out.print(m(3,8)); , 2.) how many times method m called? answers should 5 , 7 respectively.
when worked out question 1, came out 5 way did incorrect because method not called 7 times, called twice. way did went straight else statement since (i > j) false @ start , method m called again time (4, 8) figured still false went line m called , variable changed 5 because of i++ in m(i++, j). after return 5 value of i.
that wrong added out.prints values of throughout program see how value changing , went 3 9 out.print(i); @ beginning of method m. out.print(i); right before return i; showed values started go backwards 10 5 , method called 7 times. how work?
edit: after logging it, able come logic clarify correct.
method m called 3,8 @ start. after, calls 4,8 5,8....until 9,8 if statement becomes true , method returns 0. called 6 times starts go backwards or decrement-ing 6 times since m(i++, j) post(the i) becomes 10 , 10 returned, 9, 8, 7, 6, , 5. when returned 10 1, 9 2, 8 3, 7 4, 6 5, , 5 6. since 6 when = 5, value returned. correct? , if is, more in depth explanation nice have.
to better understand what's happening, might refactor code 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 haven't modified of actual logic. i've done add statements print values, , variable keep track of number of times method called.
Comments
Post a Comment