# C Program to convert a decimal number to a hexadecimal number

The following is a C program to convert a decimal number to a binary number:

Expected Output:

1st run:

2nd run:

## How it works

To convert a decimal number to a hexadecimal number, we follow these steps:

Step 1: Divide the decimal number continuously by 16 and write the remainder on the right-hand side of the dividend. We repeat this process until we get the quotient 0.

Step 2: If the remainder is greater than 10, then replace it with a hexadecimal character given in the table below:

`10` `A`
`11` `B`
`12` `C`
`13` `D`
`14` `E`
`15` `F`

Step 3: Write the remainders from bottom to top.

Let’s take some examples:

Example 1: Convert decimal 210 to hexadecimal number.

Step 1:

Quotient Remainder
`210/16` `13` `2`
`13/16` `0` `13`

Step 2:

`210/16` `13` `2` `2`
`13/16` `0` `13` `D`

Step 3:

21010 = 0xD216

Example 2: Convert decimal 100 to a hexadecimal number.

Step 1:

Quotient Remainder
`100/16` `6` `4`
`6/16` `0` `6`

Step 2:

In this case, both the remainders are smaller than 10, so we don’t need to replace them with the hexadecimal characters.

Step 3:

10010 = 0x6416

The following table shows what happens at each iteration of the loop (assuming `num = 198`):

Iteration rem hex_arr num i
After 1st iteration `rem=198%16=6` `hex_arr[0]=48+6=54` `num=198/16=12` `i=1`
After 2nd iteration `rem=12%16=12` `hex_arr[1]=55+12=67` `num=12/16=0` `i=2`