6.2.2 Print Binary

In this first example, you will explore a basic procedural recursion example. Even though the recursive function is not returning a value, it is solving a problem by printing out the results as the function executes.

This recursive function will translate a decimal number into a binary number using the method where you repeatedly divide by 2 and take the remainder, then switch the order of the remainders.

Example: Convert 10 to binary:

1. 10 / 2 = 5, remainder 0
2. 5 / 2 = 2, remainder 1
3. 2 / 2 = 1, remainder 0
4. 1 / 0 = 0 remainder 1

Remainders reversed: 1010

Since you need to print left to right, the first remainder to print is the final remainder. With this in mind, the recursive call will actually come before the base case. Once the base case (number < 1) is reached, it goes back through the recursive calls and prints the remainders.

Last updated