# C program to convert decimal to hexadecimal

Source:www.opentechguides.com | Date Published: 2016-01-06 14:31:07

A decimal number as we all know uses 10 symbols from 0 to 9 to represent any number. Hexadecimal number system, also called hex, uses the 10 symbols 0 to 9 from the decimal number system and an additional 6 English alphabets from A to F. A hexadecimal A is equivalent to a decimal 10, Hex B equals Decimal 11, Hex F equal Decimal 15 and Hex 10 equal Decimal 16. This is a **C program to convert a decimal number to its hexadecimal equivalent.**

The method used for this conversion is to repeatedly divide the decimal number by 16 and store the remainder in an array. Finally when the array is printed out, the program checks if the array element is less than 10 in which case then it is printed as decimal number using `%d`

format modifier. If array element is greater than or equal to 10 then its corresponding English alphabet is obtained by adding 55 and the value printed out as character using `%c`

format modifier.

## Program Source Code

/* **********************************************
* C program to convert Decimal to Hexadecimal *
************************************************/
#include<stdio.h>
int main()
{
int num, hex_num[20], dec_num, i, j;
// Read a Decimal number
printf("Enter a decimal number : ");
scanf("%d",&num);
dec_num = num;
// Convert Decimal to Hexadecimal
i=0;
while (dec_num) {
hex_num[i] = dec_num % 16;
dec_num = dec_num / 16;
i++;
}
// Print the hexadecimal value
printf("Hexadecimal Value of %d is ",num);
for (j=i-1; j>=0; j-- ) {
if (hex_num[j] < 10)
// print 0-9
printf("%d",hex_num[j]);
else
// print A-F
printf("%c",hex_num[j] + 55);
}
//Wait for key press
printf("\n\nPress any key to continue...");
getchar();
getchar();
return 0;
}

## Sample Output

`
Enter a decimal number : 50
Hexadecimal Value of 50 is 32
Press any key to continue...
`

Open Tech Guides | www.opentechguides.com