Ads block

Banner 728x90px

Base Conversion

We have seen the program to displaying the series of number and its sum. Now we will write a recursive function which will convert a decimal number to binary, octal and hexadecimal base.

To do this conversion we have to divide the decimal number repeatedly by the base till it is reduced to 0 and print the remainders in reverse order.

If the base is hexadecimal then we have to print alphabets for remainder values greater than or equal to 10. We want to print the remainders in reverse order, so we can do this work in the unwinding phase.

#include<stdio.h>
void convert(int, int);
main()
{
    int num;
    printf("Enter a positive decimal no.: ");
    scanf("%d", num);
    convert(num, 2);     printf("\n");
    convert(num, 0);     printf("\n");
    convert(num, 16);     printf("\n");
}
void convert(int num, int base)
{
    int rem = num%base;
    if(num == 0)
        return;
    convert(num/base, base);

    if(rem < 10)
        printf("%d", rem);
    else
        printf("%c", rem-10+'A');
}