#include <stdio.h>
// Function to convert decimal to hexadecimal
void decimalToHexadecimal(int decimalNumber) {
int remainder;
char hexadecimal[100]; // Array to store hexadecimal digits
int index = 0;
// Loop to process the decimal number
while (decimalNumber != 0) {
remainder = decimalNumber % 16; // Get the remainder of the division by 16
// Convert remainder to hexadecimal character
if (remainder < 10)
hexadecimal[index] = remainder + '0'; // For digits 0-9
else
hexadecimal[index] = remainder - 10 + 'A'; // For letters A-F
decimalNumber /= 16; // Divide the decimal number by 16 for the next digit
index++; // Move to the next position
}
// Print the hexadecimal number in reverse order
printf("Hexadecimal equivalent: ");
for (int i = index - 1; i >= 0; i--) {
printf("%c", hexadecimal[i]);
}
printf("\n");
}
int main() {
int decimalNumber;
// Input a decimal number from the user
printf("Enter a decimal number: ");
scanf("%d", &decimalNumber);
// Check if the input is zero
if (decimalNumber == 0) {
printf("Hexadecimal equivalent: 0\n");
} else {
// Convert decimal to hexadecimal and display the result
decimalToHexadecimal(decimalNumber);
}
return 0;
}
Explanation:
Input: The program asks the user to enter a decimal number
.Conversion: It repeatedly divides the decimal number by 16, storing the remainders (which represent hexadecimal digits). If the remainder is between 0-9, it stays the same; if it’s between 10-15, it is converted to letters A-F .
Result: The hexadecimal digits are stored in reverse order, so the program prints them in reverse to get the correct hexadecimal number.
Special Case: If the input is 0
, the program directly outputs 0
in hexadecimal.
Output:
- Enter a decimal number: 255
Hexadecimal equivalent: FF