Write a C program to find the 2’s complement of a binary number.

Program Code:
#include<stdio.h>
void twoscomplement(int a[10],int);
void main()
{
int n,i,a[10];
printf("\n enter number of bits in the binary number: ");
scanf("%d",&n);
printf("\n enter the binary number into the array: ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
twoscomplement(a,n);
getch();
}
void twoscomplement(int a[10],int n)
{
int i,c=1;
for(i=0;i<n;i++)
{
if(a[i]==0)
a[i]=1;
else
a[i]=0;
}
printf("\n one's complement of the binary number is: ");
for(i=0;i<n;i++)
printf("%5d",a[i]);
for(i=n-1;i>=0;i--)
{
a[i]=a[i]+c;
if(a[i]==1)
{
c=0;
break;
}
else{
a[i]=a[i]-2;
c=1;
}
}
printf("\n 2's complement of the binary number is: ");
if(c==1)
printf("%5d",c);
for(i=0;i<n;i++)
printf("%5d",a[i]);
}
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: