This is a C++ Program to Convert a Decimal Number to its HexaDecimal Equivalent.
The program takes a decimal number and converts it into its hexadecimal equivalent.
1. A decimal number is entered.
2. Using a while loop, the number is divided by 16 and the hexadecimal equivalent of the remainders are stored.
3. The result is printed in reverse order.
Here is the source code of C++ Program to Convert a Decimal Number to its HexaDecimal Equivalent. The program output is shown below.
using namespace std;
int main ()
int num, temp, i = 1, j, r;
cout << " Enter a decimal number : ";
cin >> num;
temp = num;
while (temp != 0)
r = temp % 16;
if (r < 10)
hex[i++] = r + 48;
hex[i++] = r + 55;
temp = temp / 16;
cout << "\nHexadecimal equivalent of " << num << " is : ";
for (j = i; j > 0; j--)
cout << hex[j];
1. The user is asked to enter a decimal number and its value is stored in num.
2. num is copied to a temporary variable ‘temp’ and is divided by 16.
3. If the remainder is less than 10, 48 is added to it according to ASCII value and stored in the character array hex.
4. Else 55 is added to the remainder and stored in hex.
5. The loop terminates when the quotient becomes 0.
6. The array hex is then printed in reverse order which is the hexadecimal equivalent of the number entered.
Case 1 : Enter a decimal number : 116 Hexadecimal equivalent of 116 is : 74 Case 2 : Enter a decimal number : 15 Hexadecimal equivalent of 15 is : F Case 3 : Enter a decimal number : 33 Hexadecimal equivalent of 33 is : 21
Sanfoundry Global Education & Learning Series – C++ Programs.
To practice all C++ programs, here is complete set of 1000+ C++ Programming examples.