C Program to Convert Decimal to Hexadecimal

C program to convert decimal to hexadecimal : This c program converts a decimal number number into its equivalent hexadecimal number.

Algorithm :

  1. Accept a decimal number as input.
  2. Divide the input number by 16. Store the remainder in the array.
  3. Do step 2 with the quotient obtained until quotient becomes zero.
  4. Print the array in the reversed fashion to get hexadecimal number.

C Program to Convert Decimal to Hexadecimal using while loop

/* Aim: C program to Convert Decimal number to Hexadecimal number */

#include<stdio.h>
#include<math.h>

int main()
{
  int i, decimal, decimal_orginal, remainder, hexadecimal = 0;

  printf("\n Enter decimal nunber:- ");
  scanf("%d", &decimal);

  decimal_original = decimal;

  while(decimal != 0)
  {
	remainder = decimal % 16;
	hexadecimal = hexadecimal + remainder * pow(10, i);
	decimal = decimal / 16;
	i++;
  }

  printf("\n Equivalent hexadecimal number of %d is %X", decimal_original, hexadecimal);

  return 0;
}
    
/* Example Output of Above Code:-

Enter decimal number:- 10
Equivalent hexadecimal number of 10 is A

*/

C Program to Convert Decimal to Hexadecimal using Function

#include<stdio.h>
#include<math.h>
 
int decimalToHex(int dec)
{
  int i, hexadecimal, remainder;

  for(i = 0; dec > 0; i++)
  {
	remainder = dec % 16;
	hexadecimal = hexadecimal + remainder * pow(10, i);
	dec /= 16;
  }

  return hexadecimal;
}
 
int main()
{
  int decimal, hex_value;
  
  printf("\n Enter decimal number:- ");
  scanf("%d", &decimal); 

  hex_value = decimalToHex(decimal);

  printf("\n Hex Equivalent of %d is %X", decimal , hex_value);

  return 0;
}
    
/* Example Output of Above Code:-

Enter decimal number:- 11
Hex Equivalent of B

*/