2’s complement of a number is obtained by scanning it from right to left and complementing all the bits after the first appearance 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.

Algorithm:

Step 1: Start
Step 2: declare the subprogram “complement(char *a)”
Step 3: initialize the variable i
Step 4: read the binary number
Step 5: perform the loop operation. if it is true then follows. if not goto step 7
         i) for(i = 0; a[i]! = ’\0’; i  )
         ii) if(a[i] != ’0’ && a[i]! = ’1’) then displayed the number is not valid. enter the correct number.
         iii) Exit the loop
Step 6: call sub program ‘complemt(a)’
Step 7: Stop

Sub Program:

Step 1: initialize the variable I, c = 0, b[160]
Step 2: 1 = strlen(a)
Step 3: perform the loop operation. if it is true then follows. if not goto
            i)  for(i = l - 1; i >= 0; i--)
            ii) if(a[i] == ’0’) then b[i] = ’1’ else
            iii)b[i] = ’0’
Step 4: for(i = l - 1; i >= 0; i--) is true
            i)  if(i == l - 1) then
            ii) if(b[i] == ’0’) then b[i] = ’1’ else
            iii)b[i] = ’0’, c = 1 if not goto step 5
Step 5: if(c == 1 && b[i] == ’0’) is true then
            i)b[i] = ’1’, c=0 if not goto Step 6
Step 6: if(c == 1 && b[i] == ’1’) then b[i] = ’0’, c = 1
Step 7: displayed b[l] = ’\0’
Step 8: print b and return to main program

Program:

#include <stdio.h>
#include <string.h>
#include <conio.h>
void main()
{
   char a[20];
   int i, carry, l;
   clrscr();
   printf("Enter the binary number \n");
   scanf("%s", &a);
   l = strlen(a);
   for(i = 0; i < l; i++)
   {
       if(a[i] == '0')
       {
      a[i] = '1';
       }
       else
       {
      a[i] = '0';
       }
   }
   printf("The 1's compliment of the binary number is %s \n", a);
   i = strlen(a) - 1;
   while(i >= 0)
   {
      if(a[i] == '0')
      {
     a[i] = '1';
     carry = 0;
     break;
      }
      else
      {
     a[i] = '0';
     carry = 1;
     i = i - 1;
      }
  }
  printf("The 2's compliment of the binary number is ");
  if(carry == 1)
  {
    printf("1");
  }
  printf("%s", a);
  getch();
}

Input & Output:

Enter the binary number  
100101
The 1’s compliment of binary number is 
011010
The 2’s compliment of binary number is 
011011