In: Computer Science
Write a program in C that takes as input an 8-bit binary number and prints the next 10 binary
numbers. Define a binary number as
int binNum[8];
Use binNum[0] to store the most significant (i.e., leftmost) bit and binNum[7] to store the least
significant bit. Ask the user to input the first binary number with each bit separated by at
least one space.
#include<stdio.h>
int main()
{
int binNum[8],no[9];
int i,s=0,j;
//input the binary number
printf("Enter the binary number");
for(i=0;i<8;i++)
scanf("%d",&binNum[i]);
//display the input number
for(i=0;i<=7;i++)
printf("%d ",binNum[i]);
//condition when the 1ft 5 bit's are 1(from MSB)
if(binNum[0]==1 && binNum[1]==1 &&
binNum[2]==1 && binNum[3]==1 && binNum[4]==1)
{
no[0]=0;
for(j=1,i=0;i<8;i++,j++)
no[j]=binNum[i];
printf("\n Binary Numbers :\n");
//loop to print the 10 next binary numbers
for(j=1;j<=10;j++)
{
s=1; //assign s to 1 to generate
next number
for(i=8;i>=0;i--) //loop to scan each bit of
binary number from LSB to MSB
{
if(no[i]==0) //if bit is 0 then add
1 to that position
{
no[i]= no[i]+s;
s=0; //set s to 0
break; //terminate the
loop
}
else
if(no[i]==1 && s==1 ) //if
bit is 1 and s=1 theh set the bit to 0 and set s to 1
{
no[i]=0;
s=1; //carry forward
bit
}
}
printf("\n");
//display the next number
if(no[0]==0) //if the 9th bit is 0 (MSB)
{
for(i=1;i<=8;i++)
printf("%d ",no[i]);
}
else
for(i=0;i<=8;i++)
printf("%d ",no[i]);
}
}
else
{
printf("\n Binary
Numbers :\n");
//loop to print the 10 next binary numbers
for(j=1;j<=10;j++)
{
s=1; //assign s to 1 to generate
next number
for(i=7;i>=0;i--) //loop to scan each bit of
binary number from LSB to MSB
{
if(binNum[i]==0) //if bit is 0 then
add 1 to that position
{
binNum[i]= binNum[i]+s;
s=0; //set s to 0
break; //terminate the
loop
}
else
if(binNum[i]==1 && s==1 )
//if bit is 1 and s=1 theh set the bit to 0 and set s to 1
{
binNum[i]=0;
s=1; //carry forward
bit
}
}
printf("\n");
//display the next number
for(i=0;i<=7;i++)
printf("%d ",binNum[i]);
}
}
}
OUTPUT