C Program to Convert Decimal to Hexadecimal
printf("%X", decimalNumber); or by manual conversion with a loop.Examples
How to Think About It
Algorithm
Code
#include <stdio.h> int main() { int decimal, temp; char hex[20]; int i = 0; printf("Enter a decimal number: "); scanf("%d", &decimal); if (decimal == 0) { printf("Hexadecimal: 0\n"); return 0; } temp = decimal; while (temp > 0) { int rem = temp % 16; if (rem < 10) hex[i++] = rem + '0'; else hex[i++] = rem - 10 + 'A'; temp /= 16; } printf("Hexadecimal: "); for (int j = i - 1; j >= 0; j--) putchar(hex[j]); printf("\n"); return 0; }
Dry Run
Let's trace the decimal number 26 through the code.
Input
decimal = 26
First division
temp = 26; remainder = 26 % 16 = 10; hex[0] = 'A'; temp = 26 / 16 = 1; i = 1
Second division
temp = 1; remainder = 1 % 16 = 1; hex[1] = '1'; temp = 1 / 16 = 0; i = 2
Stop loop
temp = 0; exit loop
Print hex
Print hex in reverse: hex[1] = '1', hex[0] = 'A' => 1A
| Iteration | temp | remainder | hex array | i |
|---|---|---|---|---|
| 1 | 26 | 10 (A) | ['A'] | 1 |
| 2 | 1 | 1 | ['A','1'] | 2 |
Why This Works
Step 1: Divide by 16
Dividing the decimal number by 16 gives the remainder which is the hex digit starting from the right.
Step 2: Store remainders
Each remainder is converted to a hex character (0-9 or A-F) and stored in an array.
Step 3: Reverse output
Since the first remainder is the least significant digit, printing the array in reverse order gives the correct hex number.
Alternative Approaches
#include <stdio.h> int main() { int decimal; printf("Enter a decimal number: "); scanf("%d", &decimal); printf("Hexadecimal: %X\n", decimal); return 0; }
#include <stdio.h> void decToHex(int n) { if (n == 0) return; decToHex(n / 16); int rem = n % 16; if (rem < 10) putchar(rem + '0'); else putchar(rem - 10 + 'A'); } int main() { int decimal; printf("Enter a decimal number: "); scanf("%d", &decimal); if (decimal == 0) printf("0"); else decToHex(decimal); printf("\n"); return 0; }
Complexity: O(log n) time, O(log n) space
Time Complexity
The loop runs proportional to the number of hex digits, which is about log base 16 of the decimal number.
Space Complexity
Extra space is used to store hex digits, proportional to the number of digits (log base 16 of the number).
Which Approach is Fastest?
Using printf with %X is fastest and simplest; manual conversion is educational but slower and uses more memory.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Manual loop conversion | O(log n) | O(log n) | Learning and understanding conversion |
| printf with %X | O(1) | O(1) | Quick and practical conversion |
| Recursive conversion | O(log n) | O(log n) | Elegant code without extra array |
printf("%X", number); for quick decimal to hexadecimal conversion in C.