13.2 M o r e Examples with Simple Variables | 643
public static voidconvert(int number)
// Converts number to binary and prints it
// Assumption: number >= 0
{
if (number > 0)
{
convert(number / 2); // Recursive call
outFile.print(number % 2);
}
// Empty else clause is the base case
}
Let’s do a code walk-through of convert( 10 ). We pick up our original example at step 3,
where the dividend is 10.
Call 1:convertis called with an argument of 10. Because numberis not equal to 0, the then
clause is executed. Execution pauses until the recursive call to convertwith an argument of
(number / 2 ) has completed.
Call 2:numberis 5. Because numberis not equal to 0, execution of this call pauses until the
recursive call with an argument of (number / 2 ) has completed.
Call 3:numberis 2. Because numberis not equal to 0, execution of this call pauses until the
recursive call with an argument of (number / 2 ) has completed.
Call 4:numberis 1. Because numberis not equal to 0, execution of this call pauses until the
recursive call with an argument of (number / 2 ) has completed.
Call 5:numberis 0. Execution of this call to convertis complete. Control returns to the pre-
ceding call.
Call 4:Execution of this call resumes with the
statement following the recursive call to convert.
The value of number % 2 (which is 1) is printed.
Execution of this call is complete.
Call 3:Execution of this call resumes with the
statement following the recursive call to convert.
The value of number % 2 (which is 0) is printed.
Execution of this call is complete.
Call 2:Execution of this call resumes with the
statement following the recursive call to convert.
The value of number % 2 (which is 1) is printed.
Execution of this call is complete.
Call 1:Execution of this call resumes with the
statement following the recursive call to convert.
The value of number % 2 (which is 0) is printed.
Execution of this call is complete. Because this is
the nonrecursive call, execution resumes with the
statement immediately following the original call.
Figure 13.3 shows the execution of theconvert
method with the values of the parameters.
convert( 10 )
Call 1:
Call 2:
Call 3:
Call 4:
Call 5:
Prints 0.
Prints 1.
Prints 0.
Prints 1.
number
10
number
5
number
2
number
1
number
0
Figure 13.3 Execution of convert( 10 )