LAB week 7 (iv): 2's complement

/*code is typed by bhayyA by taking it from S.chand text book
 'Introduction to Programming' authored by KV SAmbasivarao & DAvuluri sunita. Output is observed to be satisfactory for 3 given inputs*/
 
#include<stdio.h>
void main()
{
 int b2comp[9],n,i,j;
 printf("\n enter no of bits:");
scanf("%d",&n);
printf("\n enter the binary no. without leading zeros:");
for(i=0;i<n;++i)
{
scanf("%1d",&b2comp[i]);
}
//find 2's complement
for(i=n-1;i>=0;--i)
{
if(b2comp[i]==1)
break;
}
if(i==-1)
{
printf("\n 2's complement:");
for(i=0;i<n;++i)
{
printf("%d",b2comp[i]);
}
}
else
{
  for(j=i-1;j>=0;--j)
  {
  b2comp[j]=1-b2comp[j];
  }
  printf("\n 2's complement:");
  for(i=0;i<n;++i)
{
printf("%d",b2comp[i]);
}
}
}

తెరమీద 
enter no of bits: 5
enter the binary no. without leading zeros: 10011
2's complement: 01101

మరోసారి
enter no of bits: 5
enter the binary no. without leading zeros: 10110
2's complement: 01010

ఇంకోసారి
enter no of bits: 7
enter the binary no. without leading zeros: 0011100 (intentionally leading and trailing zeros are given)
2's complement: 1100100

కామెంట్‌లు

ఈ బ్లాగ్ నుండి ప్రసిద్ధ పోస్ట్‌లు

100% C prog to write content into a file and then read it back onto the console

Spic macay

శ్రీరస్తు.. రామలింగ 18-1-24 (సూరసాని వారి ఆహ్వానము)