Home >Backend Development >C++ >Count the number of binary strings without consecutive 1's in C
The given task is to count the number of all binary strings of length n that do not have consecutive 1's.
The binary number system is a type of number representation technology. It is most popular and used in digital systems. The binary system is used to represent binary quantities that can be represented by any device that has only two operating states or possible conditions. For example, a switch has only two states: on or off.
In a binary system, there are only two symbols or possible numerical values, 0 and 1. Represents an operating state or possible condition by any device with only 2. Binary strings are those strings that contain binary values i.e. 0 or 1
Now let us use an example to understand what we have to do -
Enter - n = 2
Output - The count of binary strings without consecutive 1's in 2 is: 3
Explanation - 00, 01, 10 so only 3 binary strings of length n without consecutive 1
input − n = 7
output
Input strong> - The count of binary strings without consecutive 1's in 7 is - 34
Take an input n represents the string length
In the count function, we will count the binary string without consecutive 1, define two arrays arr[] and arr_2 of size n, and an array with To the stored variable temp
Assign the 0th element of the two arrays to 1
Start the loop from i=1 until I Less than n.
In the loop, set arr[i] = arr[i-1] arr_2[i-1] and arr_2[i] = arr[i-1]
Set temp = arr[n-1] arr_2[n-1], and then print temp.
Live Demonstration
#include<stdio.h> //create function to calculate binary strings without consecutive 1’s void count(int num){ int arr[num]; int arr_2[num]; int i=0, temp=0; arr[0] = arr_2[0] = 1; //loop till number isn't equals to 0 for (i = 1; i < num; i++){ arr[i] = arr[i-1] + arr_2[i-1]; arr_2[i] = arr[i-1]; } temp = arr[num-1] + arr_2[num-1]; printf("Count of binary strings without consecutive 1’s of %d is : %d",num,temp); printf("</p><p>"); } int main(){ //call the count function count(10); count(7); count(1); return 0; }
If we run the above code, we will get the following output-
Count of binary strings without consecutive 1’s of 10 is : 144 Count of binary strings without consecutive 1’s of 7 is : 34 Count of binary strings without consecutive 1’s of 1 is : 2
The above is the detailed content of Count the number of binary strings without consecutive 1's in C. For more information, please follow other related articles on the PHP Chinese website!