C program to check a number contain the alternative pattern of bits

Here, we are going to learn how to check a number contain the alternative pattern of bits in C programming language?
Submitted by Nidhi, on July 24, 2021

Problem statement

Read an integer number from the user, then check given number contains an alternate bit pattern or not using C program.

C program to check a number contain the alternative pattern of bits

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;
}

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.

C Bitwise Operators Programs »


Related Programs

Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.