# C++ Code Example: convert decimal to hexadecimal number

This program converts a decimal number to a hexadecimal number.

## Code Example

``````#include <iostream>
using namespace std;

int main() {
int num, remainder, decimal, product = 1;
char c;
string hex = "";

cout << "Please enter a number: ";
cin >> num;

decimal = num;

while (decimal != 0) {
remainder = decimal % 16;
if (remainder >= 10) {
c = remainder + 55;
} else {
c = remainder + 48;
}

hex += c;
decimal = decimal / 16;
product *= 10;
}

reverse(hex.begin(), hex.end());

cout << "Hexadecimal value of number: " << num << " is: " << hex << endl;
}``````

### Output

``````Please enter a number: 1234
Hexadecimal value of number: 1234 is: 4D2``````

### Code Explanation

1. A variable `num` is declared and initialized to store the decimal number entered by the user.
2. A variable `remainder` is declared to store the remainder obtained from dividing the decimal number by 16.
3. A variable `decimal` is declared and initialized to the value of `num`.
4. A `while` loop is used to continue converting the decimal number to hexadecimal until the decimal number is equal to 0.
5. Within the `while` loop, the `remainder` is obtained by dividing the `decimal` by 16.
6. An `if` statement checks if the `remainder` is greater than or equal to 10. If it is, then it converts the remainder to its corresponding hexadecimal character. This is done by adding 55 to the remainder as the ASCII value of A (the first letter in hexadecimal) is 65.
7. If the `remainder` is less than 10, then it is converted to its corresponding hexadecimal character by adding 48 to the remainder. The ASCII value of 0 is 48.
8. The resulting hexadecimal character is appended to the `hex` string.
9. The `decimal` number is updated by dividing it by 16.
10. The loop continues until the `decimal` is equal to 0.
11. Once the loop is finished, the `hex` string is reversed using the `reverse()` function from the `algorithm` library.
12. The final hexadecimal number is output to the console using `cout`.
13. The `main()` function returns 0 to indicate that the program has run successfully.