Q24 Write a C program to convert from decimal to binary, octal, or hex number system.

#include<stdio.h>

void decimal_to_any_base(int number, int base)

{

        int i, x, digits[1000], flag;

        i = 0;

        while(number)

        {

                x = number%base;

                digits[i] = “0123456789abcdefghijklmnopqrstuvwxyz”[x];

                number = number/base;

                i++;

        }

        /* Removing leading zeros */

        for(i–; i >= 0; i–)

        {

                if(!flag && digits[i] != ‘0’)

                {

                        flag = 1;

                }

                if(flag)

                {

                        printf(“%c”,digits[i]);

                }

        }

}

int main()

{

        int number;

        int base;

        printf(“Give any number and base to covert in\n”);

        scanf(“%d”,&number);

        scanf(“%d”,&base);

        printf(“Converting %d to the number base %d\n”,number, base);

        decimal_to_any_base(number,base);

}

Output:

$ ./a.exe

Give any number and base to covert in

16

2

Converting 16 to the number base 2

10000

$ ./a.exe

Give any number and base to covert in

100

8

Converting 100 to the number base 8

144

$ ./a.exe

Give any number and base to covert in

100

16

Converting 100 to the number base 16

64

 $ ./a.exe

Give any number and base to covert in

15

16

Converting 15 to the number base 16

f

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.