Tuesday, 25 September 2012

Program to find 2's complement


void revert(char *str,char *comp,int l);

int main()
{
  int i,found=0,l,stlen;
  char *str,*comp;

  clrscr();

printf("\nEnter a binary string\n");
gets(str);
stlen=strlen(str);
l=stlen;
l--;
       // printf("\nlength=%d..%c..",l,str[l]);
while(l)
{
if(found)
{
revert(str,comp,l);
break;
}
else
{
if(str[l]=='1')
found=1;
comp[l]=str[l];
printf("%c",str[l]);
l--;
}
}
printf("\ncopmlement is");
puts(comp);

getch();
return(0);
}


void revert(char *str,char *comp,int l)
{
while(l>=0)
{
if(str[l]=='1')
{printf("0");comp[l--]='0' ;}
else
{printf("1");comp[l--]='1';}
}
}

No comments:

Post a Comment