|
|
|
|
|
|
|
IF number > 0
Convert(number / 2)
Print number MOD 2 |
|
|
|
|
|
|
|
|
|
If number is 0, we have called Convert as many times as we need to and can begin printing the answer. The base case is simply when we stop making recursive calls. The recursive solution to this problem is encoded in the Convert function. |
|
|
|
|
|
|
|
|
void Convert( /* in */ int number ) // Number being converted
// to binary
// Precondition:
// number >= 0
// Postcondition:
// IF number > 0
// number has been printed in binary (base 2) form
// ELSE
// No action has taken place
{
if (number > 0)
{
Convert(number / 2); // Recursive call
cout << 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: Convert is called with an actual parameter of 10. Because number is not equal to 0, the then-clause is executed. Execution pauses until the recursive call to Convert with an actual parameter of (number / 2) has completed. |
|
|
|
|
|
|
|
|
Call 2: number is 5. Because number is not equal to 0, execution of this call pauses until the recursive call with an actual parameter of (number / 2) has completed. |
|
|
|
|
|
|
|
|
Call 3: number is 2. Because number is not equal to 0, execution of this call pauses until the recursive call with an actual parameter of (number / 2) has completed. |
|
|
|
|
|