This is a C Program to check whether the given integer has an alternate pattern.
This C Program checks whether the given integer has an alternate pattern.
Take input from the user and checks alternate pattern as shown in the program below.
Here is source code of the C Program to check whether the given integer has an alternate pattern. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/* * C Program to Check whether the given Integer has an Alternate * Pattern */ #include <stdio.h> #include <stdlib.h> int main () { int num = 0, n = 0, i =0; int count = 0; printf("Enter the number: "); scanf ("%d", &num); n = num; // first lets count the number of bits while (n) { count ++; n = n >> 1; } printf ("\n COUNT : %d", count); // now check for alternative for (i = 0; i <= count - 2; i++) { if (((num >> i) & 1) == ((num >> (i+2)) & 1)) { continue; } else { printf ("\nFALSE : ALTERNATIVE PATTERN DOES NOT EXIST\n"); exit (0); } } printf ("\nTRUE : ALTERNATIVE PATTERN DOES EXIST\n"); return 0; }
1. In this C Program, we are reading the number using ‘num’ variable. Take the input from the user in the number form.
2. Count the number of bits in the given number using while loop.
3. (num >> n) & 1 is used to convert the n’th bit in the binary number. Where n is the nth position of the bit.
4. for loop statement is used to check that any alternative pattern exists or not. If there is an alternative pattern just continue. else break the statement.
Test case 1 – Here, the entered number is a valid number.
$ gcc alternative.c -o alternative $ ./alternative Enter the number: 10 COUNT : 4 TRUE : ALTERNATIVE PATTERN DOES EXIST
Test case 2 – Here, the entered number is a invalid number.
$ gcc alternative.c -o alternative $ ./alternative Enter the number: 15 COUNT : 4 FALSE : ALTERNATIVE PATTERN DOES NOT EXIST
Sanfoundry Global Education & Learning Series – 1000 C Programs.
Here’s the list of Best Books in C Programming, Data-Structures and Algorithms
- Practice Computer Science MCQs
- Check Computer Science Books
- Watch Advanced C Programming Videos
- Apply for Computer Science Internship
- Check C Books