Java Reference
In-Depth Information
The following recursive method implements this algorithm:
public static void decToBin( int num, int base)
{
if (num == 0)
System.out.print(0);
else if (num > 0)
{
decToBin(num / base, base);
System.out.print(num % base);
}
}
Figure 13-8 traces the execution of the following statement:
decToBin(13, 2);
where num is 13 and base is 2 .
decToBin(13,2)
num base
13
2
execute
System.out.print(13 % 2);
Call 1
because num > 0
decToBin(13/2,2);
decToBin(6,2)
num base
Output: 1
execute
System.out.print(6 % 2);
6
2
Call 2
because num > 0
decToBin(6/2,2);
Output: 0
decToBin(3,2)
num base
execute
System.out.print(3 % 2);
3
2
Call 3
because num > 0
decToBin(3/2,2);
decToBin(1,2)
num base
Output: 1
execute
System.out.print(1 % 2);
1
2
Call 4
because num > 0
decToBin(1/2,2);
decToBin(0,2)
num base
Output: 1
0
2
Call 5
because num is 0
exit this call
FIGURE 13-8 Execution of decToBin(13, 2)
Because the if statement in Call 5 succeeds, this call prints 0 . The second output is
produced by Call 4, which prints 1 ; the third output is produced by Call 3, which
Search WWH ::




Custom Search