Friday , 28 July 2017
Latest Posts
Home » C Programs » C Program on Decimal to Hexadecimal Number Conversion

# C Program on Decimal to Hexadecimal Number Conversion

#### Question:

Write a Program in C to input a number in Decimal number system and convert it into its equivalent number in the Hexadecimal number system.

Note: Hexadecimal Number system is a number system which can represent a number in any other number system in terms of digits ranging from 0 to 9 and then A – F only. This number system consists of only sixteen basic digits i.e. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E and F. Here 10 is represented as A, 11 as B and so on till 15 which is represented as F.

For Example: 47 in the Decimal number system can be represented as 2F in the Hexadecimal number system.

#### Solution:

```/*
* C Program to convert a Decimal number into a Hexadecimal number
* @author : www.guideforschool.com
* @Program Type : C Program
*/

#include <stdio.h>
#include <string.h>
int main(void)
{
int deci,i=0,rem;
char hex[100]; // array for storing the result
char dig[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; // array storing digits of hexadecimal system

printf("\nEnter a decimal number : ");
scanf("%d",&deci);

while(deci > 0)
{
rem = deci % 16;
hex[i++] = dig[rem]; // adding the correct hexadecimal digit to the result based on remainder
deci = deci / 16;
}

hex[i] = '\0'; // converting the resultant character array to a string
strrev(hex); // reversing the string
return 0;
}

/*
* Note: If you do not want to use strrev() function,
* then you can use the following for loop:

for(j=i-1 ;j>=0;j--)
{
printf("%c",hex[j]);
}
*/
```

#### Output:

```Enter a decimal number : 47