Below is a C program which converts the given decimal number to binary format and then prints the one's complement of the given number. First the number is converted to binary and then each bit is inverted to get the 1's complement.
/*Program to find the one's complement of given number*/
main()
{
int num,tnum,tbin[16],bin[16],i,j,k,quot,rem;
clrscr();
/*Reading the decimal number from user*/
printf("Enter a decimal number:");
scanf("%d", &num);
/*Converting decimal number to binary*/
tnum = num;
i = 0;
while(num > 0)
{
tbin[i] = num % 2;
num = num / 2;
i++;
}
for(k=0,j=i-1;j>=0;j--,k++)
bin[k] = tbin[j];
/*Printing the binary number*/
printf("Binary representation of %d is: ",tnum);
for(k=0;k<i;k++)
printf("%d",bin[k]);
/*One's complement of the number*/
for(k=0;k<i;k++)
{
if(bin[k]==0)
bin[k] = 1;
else
bin[k] = 0;
}
/*Printing one's complement*/
printf("\nOne's complement of %d is: ",tnum);
for(k=0;k<i;k++)
printf("%d",bin[k]);
getch();
}
Sample input and output:
Enter a decimal number:36
Binary representation of 36 is: 100100
One's complement of 36 is: 011011
No comments:
Post a Comment