Sunday, May 5, 2013

2's complement of a number is obtained by scanning it form right to left and complementing all the bits after the first appearence of a 1, thus 2's complement of 11100 is 00100. Write a c program to find the 2's Complement of a binary number


/*2's complement of a number is obtained by scanning it form right to left and complementing all the bits after the first appearence of a 1, thus 2's complement of 11100 is 00100. Write a c program to find the 2's Complement of a binary number*/

#include<stdio.h>
#include<conio.h>
main()
{
   int a[10],i,n;
   clrscr();
   printf("Enter no of bits \n");
   scanf("%d",&n);
   printf("Enter binary numbers \n");
   for(i=0;i<n;i++)
       scanf("%d",&a[i]);
   for(i=0;i<n;i++)
   {
       if(a[i]==0)
       a[i]=1;
       else
       a[i]=0;
   }
   for(i=n-1;i>=0;i--)
   {
       if(a[i]==0)
       {
     a[i]=1;
     break;
       }
       else
       {
     a[i]=0;
     if(a[i-1]==0)
     {
       a[i-1]=1;
       break;
     }
       }
   }
   printf("The complement form is \n");
   for(i=0;i<n;i++)
   printf("%d",a[i]);
   getch();
}
output:

Enter no of bits
5
Enter binary numbers
1
1
1
0
0
The complement form is
00100

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More