Read an integer number from the user, then check given number contains an alternate bit pattern or not using C program.
Program:
The source code to check a number contain the alternative pattern of bits is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.
// C program to check a number contain
// alternative pattern of bits
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num = 0;
int tmp = 0;
int cnt = 0;
int i = 0;
printf("Enter number: ");
scanf("%d", &num);
tmp = num;
while (tmp) {
cnt++;
tmp = tmp >> 1;
}
printf("Binary Number: ");
for (i = cnt - 1; i >= 0; i--) {
if (num & (1 << i))
printf("1");
else
printf("0");
}
//Check number contains the alternate pattern of bits.
for (i = 0; i < cnt - 1; i++) {
if (((num >> i) & 1) == ((num >> (i + 2)) & 1)) {
continue;
}
else {
printf("\nAlternate BIT pattern does not exist\n");
return 0;
}
}
printf("\nAlternate BIT pattern exists\n");
return 0;
}// C program to check a number contain
// alternative pattern of bits
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num = 0;
int tmp = 0;
int cnt = 0;
int i = 0;
printf("Enter number: ");
scanf("%d", &num);
tmp = num;
while (tmp) {
cnt++;
tmp = tmp >> 1;
}
printf("Binary Number: ");
for (i = cnt - 1; i >= 0; i--) {
if (num & (1 << i))
printf("1");
else
printf("0");
}
//Check number contains the alternate pattern of bits.
for (i = 0; i < cnt - 1; i++) {
if (((num >> i) & 1) == ((num >> (i + 2)) & 1)) {
continue;
}
else {
printf("\nAlternate BIT pattern does not exist\n");
return 0;
}
}
printf("\nAlternate BIT pattern exists\n");
return 0;
}
Output:
RUN 1:
Enter number: 10
Binary Number: 1010
Alternate BIT pattern exists
RUN 2:
Enter number: 170
Binary Number: 10101010
Alternate BIT pattern exists
RUN 3:
Enter number: 123
Binary Number: 1111011
Alternate BIT pattern does not exist
Explanation:
In the main() function, we read an integer number from the user and then print its corresponding binary number and then check given number contains an alternate bit pattern and print the appropriate message on the console screen.
Read an integer number from the user, then check given number contains an alternate bit pattern or not using C program.
Program:
The source code to check a number contain the alternative pattern of bits is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.
Output:
Explanation:
In the main() function, we read an integer number from the user and then print its corresponding binary number and then check given number contains an alternate bit pattern and print the appropriate message on the console screen.
need an explanation for this answer? contact us directly to get an explanation for this answer