# C program to Convert Decimal to Hexadecimal

This is a C program to Convert Decimal to Hexadecimal.

Problem Description

This program takes a decimal number as input and converts to hexadecimal.

Problem Solution

1. Take a decimal number as input.
2. Divide the input number by 16. Store the remainder in the array.
3. Do step 2 with the quotient obtained until quotient becomes zero.
4. Print the array in the reversed fashion to get hexadecimal number.

Program/Source Code

Here is source code of the C program to Convert Decimal to Hexadecimal. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

1. `/*`
2. ` * C program to Convert Decimal to Hexadecimal`
3. ` */`
4. `#include <stdio.h>`
5. ` `
6. `int main()`
7. `{`
8. `    long decimalnum, quotient, remainder;`
9. `    int i, j = 0;`
10. `    char hexadecimalnum[100];`
11. ` `
12. `    printf("Enter decimal number: ");`
13. `    scanf("%ld", &decimalnum);`
14. ` `
15. `    quotient = decimalnum;`
16. ` `
17. `    while (quotient != 0)`
18. `    {`
19. `        remainder = quotient % 16;`
20. `        if (remainder < 10)`
21. `            hexadecimalnum[j++] = 48 + remainder;`
22. `        else`
23. `            hexadecimalnum[j++] = 55 + remainder;`
24. `        quotient = quotient / 16;`
25. `    }`
26. ` `
27. `    // display integer into character`
28. `    for (i = j; i >= 0; i--)`
29. `            printf("%c", hexadecimalnum[i]);`
30. `    return 0;`
31. `}`
Program Explanation

1. Take a decimal number as input and store it in the variable decimalnum.
2. Initialize the variable j=0 and copy decimalnum to variable quotient.
3. Obtain the quotient and remainder of the variable quotient. Store the obtained remainder in the variable remainder and override the variable quotient with obtained quotient.
4. Check if the remainder is less than 10. If it is, then add 48 to the remainder and store the result in the array hexadecimalnum. Otherwise, add 55 to the remainder and store the result in the array hexadecimalnum.
5. Do steps 3-4 until variable quotient becomes zero.
6. When it becomes zero, print the array hexadecimalnum in the reversed fashion as output.

Runtime Test Cases
```Output:

Enter decimal number: 12
Equivalent hexadecimal value of 12 : C```

Sanfoundry Global Education & Learning Series – 1000 C Programs.

Here’s the list of Best Books in C Programming, Data-Structures and Algorithms

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
If you wish to look at other example programs on Simple C Programs, go to Simple C Programs. If you wish to look at programming examples on all topics, go to C Programming Examples.

If you find any mistake above, kindly email to [email protected]