PLAY WITH CODING

Home Basic Program If & Else Loops Conversion Pattern logo

Program Based on Conversion

Program to convert a decimal number into hexadecimal number

Input - Output

Input
Enter a decimal number : 25

Output
Hexadecimal equivalent of given number : 19

Input
Enter a decimal number : 28

Output
Hexadecimal equivalent of given number : 1C

Algorithm

Step 1: START

Step 2: Enter a number 'num' as an input.

Step 3: Create a char array as 'hexa[20]'.

Step 4: Apply for loop :

Step 5: Calculate remainderi.e (num%16)

     if rem< 10 i.e hexa[i]=rem+48

     else i.e hexa[i]=rem+55

Step 6: Divide the num by 16 i.e (num/16)

Step 7: Repeat the step 5 and 6 until the num is greater than zero

Step 8: END

CODE


/* Decimal to Hexadecimal Conversion */

#include <stdio.h>
int main()
{
      int num,i,j,rem;
      char hexa[10];
      printf(" Enter the decimal number : ");
      scanf("%d",&num);
      for(i=0;num>0;i++)
    {
        rem=num%16;
        if(rem<10)
          hexa[i]=rem+48;
        else
          hexa[i]=rem+55;
        num/=16;
    }
      printf(" Hexadecimal of given number is = ");
      for(j=i-1;j>=0;j--)
        printf("%c",hexa[j]);
    return 0;
}


/* Decimal to Hexadecimal Conversion */

#include <iostream>
using namespace std;
int main()
{
      int num,i,j,rem;
      char hexa[10];
      cout<<" Enter the decimal number : ";
      cin>>num;
      for(i=0;num>0;i++)
    {
        rem=num%16;
        if(rem<10)
          hexa[i]=rem+48;
        else
          hexa[i]=rem+55;
        num/=16;
    }
      cout<<" Hexadecimal of given number is = ";
      for(j=i-1;j>=0;j--)
        cout<<hexa[j];
    return 0;
}

OutPut

Enter a decimal number : 25

Hexadecimal equivalent of given number : 19