C Online Compiler
Example: Decimal to Hexadecimal using Manual Algorithm in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Decimal to Hexadecimal using Manual Algorithm #include <stdio.h> // Required for printf and scanf int main() { // Step 1: Declare variables long int decimalNum; // Use long int for potentially larger numbers int remainder; char hexChars[17] = "0123456789ABCDEF"; // Maps remainder to hex char char hexResult[100]; // Buffer to store the hexadecimal string (reversed initially) int i = 0; // Index for hexResult array int j; // Step 2: Prompt user for input printf("Enter a decimal number: "); scanf("%ld", &decimalNum); // Step 3: Handle the special case of decimal 0 if (decimalNum == 0) { printf("Decimal 0 is Hexadecimal 0\n"); return 0; } // Step 4: Convert decimal to hexadecimal using division and modulo // Loop until the decimal number becomes 0 while (decimalNum > 0) { remainder = decimalNum % 16; // Get the remainder hexResult[i] = hexChars[remainder]; // Map remainder to hex character decimalNum = decimalNum / 16; // Divide the number by 16 i++; // Move to the next position in the hexResult array } hexResult[i] = '\0'; // Null-terminate the string // Step 5: Print the hexadecimal result (in reverse order) printf("Hexadecimal equivalent is: "); for (j = i - 1; j >= 0; j--) { printf("%c", hexResult[j]); } printf("\n"); return 0; }
Output
Clear
ADVERTISEMENTS