In: Computer Science
ite a C program that prompts for and reads in a non-negative integer from the keyboard. Read it into an int variable x. Then display the 32 bits in x from the lsb to the msb (so the display will show the value in x in binary with the bits in reverse order). For example, if you input 6, then your program displays 00000000000000000000000000000110 Use the algorithm given in class (repeatedly divide by 2). Use the / and % operators. Because this algorithm determines the bits in right-to-left order and you have to display the bits in left-to-right order, you first have to determine and save all the bits, then display them. To save the bits, save them in an int array named bits: int bits[32]; The following statement assigns the remainder to the ith element of the array: bits[i] = quotient % 2;
Program:
#include<stdio.h>
int main()
{
int n, i=0,remainder=0, q=0, bits[32];
printf("Enter a non negative integer: ");
scanf("%d",&n);
q=n; // assigned the value of n to another integer so
that the original value does not change. You can avoid this
assignment also.
while(q>0)
{
bits[i++]=q%2; // calculating the remainder dividing by 2 for
finding binary and store in the bits array
q=q/2; // the quotient is stored
for next iteration
}
while(i<32) // the calculated binary value may be
less than 32 bits. So the remaining bits are set to 0
{
bits[i]=0;
i++;
}
for(i=31;i>=0;i-- ) //the bits array is pronted in
reverse order
{
printf("%d",bits[i]);
}
return 0;
}
Output
Without assigning the value of the integer n to q you can also use this code it will also run fine
Program:
#include<stdio.h>
int main()
{
int n, i=0,remainder=0, bits[32];
printf("Enter a non negative integer: ");
scanf("%d",&n);
while(n>0)
{
bits[i++]=n%2; // calculating the
remainder dividing by 2 for finding binary and store in the bits
array
n=n/2; // the quotient is stored
for next iteration
}
while(i<32) // the calculated binary value may be
less than 32 bits. So the remaining bits are set to 0
{
bits[i]=0;
i++;
}
for(i=31;i>=0;i-- ) //the bits array is pronted in
reverse order
{
printf("%d",bits[i]);
}
return 0;
}
Output:
N.B: If you face any difficulty please contact through comment. Otherwise please give your feedback.