Skip over navigation

Examples of Recursion

Recursion on Numbers

Problems

Recursion on Numbers, page 2

page 1 of 2

There exist many opportunities to use recursive techniques when doing numerical computation.

Printing an Integer

Suppose you wanted to print out an integer. How would you do it? Your first response would probably be that you would use printf. But what if printf didn't exist? What if you were actually responsible for writing the code for printf to print out an integer? Enter recursion.

One way to implement printf's integer printing facilities would be to use the modulo and division operators to look at each digit of the integer. For example, let's use the number 214. To get the first digit, we do 214%10 which results in the digit in the 10s place, 4 . We then divide 214 by 10 to get 21. Now we repeat. We mod 21 by 10 and get 1; divide 21 by 10 and get 2. Now we repeat. We mod 2 by 10 and get 2; divide 2 by 10 and get 0. Now that we've reached 0, we're done. A problem with this solution, however, is that we've received the digits in reverse order. One way to fix this would be to use an array to store each of the digits as we receive them, and then iterate through the array in the reverse order, printing out the digits as we go.


void print_int(int num)
{
	int len = 0;
	int digits[100]; /* 100 digit limit */
	for(len=0; len < 100 && num!=0; len++) {
		digits[len] = num % 10;
		num /= 10;
	}
	for(; len >= 0; len--) putchar('0' + digits[len]);
}

Note: The putchar('0' + digits[len]) might look slightly strange, but it works. The putchar() function writes a single character to stdout. By adding a digit to '0' we're converting a digit to its character equivalent. In other words, '0' + 2 == '2' and '0' + 9 == '9'.

The above method works, but it is much more complicated then need be. Believe it or not (and you will after seeing it below), we can write the same function using recursion in only two lines, and no extra variables. So let's think about this recursively.

What is our small problem? We know how to print out a single digit: putchar(num % 10 + '0'), right?

Follow Us