This program converts a decimal number to a hexadecimal number.
#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;
}
Please enter a number: 1234
Hexadecimal value of number: 1234 is: 4D2
num
is declared and initialized to store the decimal number entered by the user.remainder
is declared to store the remainder obtained from dividing the decimal number by 16.decimal
is declared and initialized to the value of num
.while
loop is used to continue converting the decimal number to hexadecimal until the decimal number is equal to 0.while
loop, the remainder
is obtained by dividing the decimal
by 16.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.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.hex
string.decimal
number is updated by dividing it by 16.decimal
is equal to 0.hex
string is reversed using the reverse()
function from the algorithm
library.cout
.main()
function returns 0 to indicate that the program has run successfully.