Search⌘ K
AI Features

Solution Review: Recursive Base Converter

Explore the recursive approach to converting numbers between bases in C. Understand how remainders are handled differently for numeric and hexadecimal conversions, using a step-by-step example turning the decimal 18 into hexadecimal.

We'll cover the following...

Solution

See the code given below!

C
#include <stdio.h>
void converter ( int n, int base ) ;
int main( )
{
int num, base ;
num = 18 , base = 16;
converter ( num, base ) ;
return 0 ;
}
void converter ( int n, int base )
{
int r ;
r = n % base ;
n = n / base ;
if ( n != 0 )
converter ( n, base ) ;
if ( r <= 9 )
printf ( "%d", r ) ;
else
printf ( "%c", 'A' + r % 10 ) ;
}

Explanation

Follow the flow of control. Assuming the value of n is 18, and ...