Thursday, October 20, 2016

C Progarm to convert Decimal to Binary and Hexadecimal using Switch


Aim: Write a C Progarm to convert Decimal to Binary and Hexadecimal using Switch.

Theory:

Binary number system: It is base 2 number system which uses the digits from 0 and 1.Decimal number system:It is base 10 number system which uses the digits from 0 to 9Hexadecimal number system: It is base 16 number system which uses the digits from 0 to 9 and A, B, C, D, E, F.
Following steps describe how to convert decimal to any Base Number SystemStep 1: Divide the original decimal number by desired base(eg: 2 for binary)Step 2: Divide the quotient by baseStep 3: Repeat the step 2 until we get quotient equal to zero.Equivalent Desired base number would be remainders of each step in the reverse order

Program:

#include<stdio.h>
void binary(int);
void hex(int);
main()
{
   int decimalNumber,choice;
   printf("Enter any decimal number: ");
   scanf("%ld",&decimalNumber);
   printf("1-Binary Number\n 2-Hexadecimal Number\n");
   printf("Enter Choice:");
   scanf("%d",&choice);
   switch(choice)
   {
      case 1:binary(decimalNumber);
                 break;
      case  2:hex(decimalNumber);
    break;
      default:printf("Invalid option");
   }
}
void binary(int d)
{
   int remainder,quotient;
   int binaryNumber[100],i=1,j;
   quotient = d;
    while(quotient!=0)
    {
         binaryNumber[i++]= quotient % 2;
         quotient = quotient / 2;
    }
    printf("Equivalent binary value of decimal number %d: ",d);
    for(j = i -1 ;j> 0;j--)
         printf("%d",binaryNumber[j]);
}

void hex(int d)
{
   int remainder,quotient;
   int i=1,j,temp;
   char hexadecimalNumber[100];
    quotient = d;
    while(quotient!=0)
     {
         temp = quotient % 16;
         /*To convert integer into character
             ASCII value of zero is 48
             ASCII value of A is 65   */
         if( temp < 10)
             temp =temp + 48;
         else
             temp = temp + 55;
         hexadecimalNumber[i++]= temp;
             quotient = quotient / 16;
      }

    printf("Equivalent hexadecimal value of decimal number %d: ",d);
    for(j = i -1 ;j> 0;j--)
      printf("%c",hexadecimalNumber[j]);
}


Output:


Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home