Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 4 years ago.
Please explain ths recursion step by step;
public class TestClass {
private static void printit(int i) {
if (i == 1) {
return;
}
System.out.println(i);
printit(i / 2);
printit(i / 2);
}
public static void main(String args[]) {
int i = 8;
printit(i);
}
}
If you're using IDE you can just use the debugger and see with you own eyes what's happening step by step.
Anyway, let's try and what happens when we call the recursive method:
You call the method with 8 (printit(8);
):
System.out.println(8);
-> 8
printit(8 /2 );
-> Call to method again with 8/2=4
System.out.println(4);
-> 4
printit(4 /2 );
> Call to method again with 4/2=2
System.out.println(2);
-> 2
printit(2 /2 );
> Call to method again with 2/2=1
return;
-> Continues with previous call, the (printit(4 /2);
)
printit(2 /2 );
> Call to method again with 2/2=1
return;
-> Continues with previous call, the (printit(4 /2);
)
- method finishes, continues with the previous call (
printit(8 /2);
)
printit(4 /2 );
> Call to method again with 4/2=2
System.out.println(2);
-> 2
- calls
printit(2/2);
which we already know result in nothing.
- Now we are in the first call again, the
printit(8);
, calling for printit(8/2);
System.out.println(4);
-> 4
- 16 etc...