﻿ C Program: Convert a decimal number to hexadecimal - w3resource

# C Exercises: Convert a decimal number to hexadecimal

## C For Loop: Exercise-55 with Solution

Write a C program to convert a decimal number to hexadecimal.

This C program converts a decimal number into its hexadecimal equivalent. It prompts the user to input a decimal number, then iteratively divides it by 16, storing the remainders as hexadecimal digits in an array. Finally, it prints the hexadecimal number by traversing the array in reverse order and printing each digit.

Visual Presentation:

Sample Solution:

C Code:

``````#include <stdio.h>
int main() {
// Declare variables
long int decn, q, m;
int tmp;
// Print output header
printf("\n\nConvert Decimal to Hexadecimal:\n ");
printf("-------------------------\n");
// Get decimal input
printf("Input any Decimal number: ");
scanf("%ld", &decn);
// Convert decimal to hex
// Use an array to store hex digits
char hexDigits[20];  // Adjust the size as needed
int index = 0;  // Index to store hex digits in the array
while (decn > 0) {
// Get remainder
tmp = decn % 16;
// Convert to hex digit
if (tmp < 10) {
hexDigits[index] = tmp + '0';
} else {
hexDigits[index] = tmp + 'A' - 10;
}
index++;
decn = decn / 16;
}
// Print hex number in reverse order
printf("\nThe equivalent Hexadecimal Number : ");
for (int i = index - 1; i >= 0; i--) {
printf("%c", hexDigits[i]);
}
printf("\n\n");
return 0;
}
```
```

Output:

```Convert Decimal to Hexadecimal:
-------------------------
Input  any Decimal number: 79

The equivalent Hexadecimal Number : 4F
```

Explanation:

Here's a brief explanation.

• Header and Declaration:
• Includes the necessary header file (stdio.h).
• Declare variables 'decn' (decimal input), 'q' (temporary variable), 'm' (temporary variable), and 'tmp' (temporary variable for remainder).
• Declares an array 'hexDigits' to store the hexadecimal digits.
• User Input:
• Asks the user to input a decimal number.
• Reads the input and stores it in the variable 'decn'.
• Conversion Loop:
• Enters a while loop that continues until the decimal number ('decn') becomes zero.
• Inside the loop, calculate the remainder when dividing 'decn' by 16 ('tmp').
• Converts the remainder to a hexadecimal digit and stores it in the 'hexDigits' array.
• Update the 'decn' by dividing it by 16.
• Print Hexadecimal Result:
• Prints the header for hexadecimal output.
• Prints the equivalent hexadecimal number by iterating through the 'hexDigits' array in reverse order.
• Return Statement:
• Returns 0 to indicate successful execution.

Flowchart:

C Programming Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿