ADVERTISEMENT
ADVERTISEMENT

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 Solution:

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

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 »



ADVERTISEMENT


ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.