Java Reference
In-Depth Information
9.
Control goes to the printf statement, which prints 1 % 2, that is, 1.
10.
The call decToBin(1) can now return, and the argument on top of the stack, 3, is reinstated
as the value of n.
11.
Control goes to the printf statement, which prints 3 % 2, that is, 1.
12.
The call decToBin(3) can now return, and the argument on top of the stack, 6, is reinstated
as the value of n.
13.
Control goes to the printf statement, which prints 6 % 2, that is, 0.
14.
The call decToBin(6) can now return, and the argument on top of the stack, 13, is
reinstated as the value of n.
15.
Control goes to the printf statement, which prints 13 % 2, that is, 1.
16.
The call decToBin(13) can now return, and 1101 has been printed.
We can summarize the above description as follows:
decToBin(13) decToBin(6)
print(13 % 2)
decToBin(3)
print(6 % 2)
print(13 % 2)
decToBin(1)
print(3 % 2)
print(6 % 2)
print(13 % 2)
decToBin(0) = do nothing
print(1 % 2) = 1
print(3 % 2) = 1
print(6 % 2) = 0
print(13 % 2) = 1
One of the most important properties of recursive functions is that when a function calls itself, the current
arguments (and local variables, if any) are pushed onto a stack. Execution of the function takes place with the new
arguments and new local variables. When execution is completed, arguments (and local variables, if any) are popped
from the stack, and execution resumes (with these popped values) with the statement following the recursive call.
Consider the following function fragment and the call test(4, 9) :
public static void test(int m, int n) {
char ch;
.
test(m + 1, n - 1);
System.out.printf("%d %d", m, n);
.
}
Search WWH ::




Custom Search