C++ Program to Convert Decimal to Hexadecimal

«
»

This is a C++ Program to Convert a Decimal Number to its HexaDecimal Equivalent.

Problem Description

The program takes a decimal number and converts it into its hexadecimal equivalent.

Problem Solution

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.
4. Exit.

C++ Program/Source code

Here is the source code of C++ Program to Convert a Decimal Number to its HexaDecimal Equivalent. The program output is shown below.

  1. #include<iostream>
  2. using namespace std;
  3. int main ()
  4. {
  5.     int num, temp, i = 1, j, r;
  6.     char hex[50];
  7.     cout << " Enter a decimal number : ";
  8.     cin >> num;
  9.     temp = num;
  10.     while (temp != 0)
  11.     {
  12.         r = temp % 16;
  13.         if (r < 10)
  14.             hex[i++] = r + 48;
  15.         else
  16.             hex[i++] = r + 55;
  17.         temp = temp / 16;
  18.     }
  19.     cout << "\nHexadecimal equivalent of " << num << " is : ";
  20.     for (j = i; j > 0; j--)
  21.         cout << hex[j];
  22.     return 0;
  23. }
Program Explanation

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.

advertisement
advertisement
Runtime Test Cases
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.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.