# Count number of binary strings without consecutive 1's in C

CServer Side ProgrammingProgramming

Given the task is to count the number of all the binary strings of length n without any consecutive 1’s.

Binary Number System is one the type of Number Representation techniques. It is most popular and used in digital systems. The binary system is used for representing binary quantities which can be represented by any device that has only two operating states or possible conditions. For example, a switch has only two states: open or close.

In the Binary System, there are only two symbols or possible digit values, i.e., 0 and 1.Represented by any device that only has 2 operating states or possible conditions. Binary strings are those strings that contain binary values i.e. either 0’s or 1’s

Let’s now understand what we have to do using an example −

Input − n = 2

Output − Count of binary strings without consecutive 1’s of 2 is : 3

Explanation − 00, 01, 10 so there are only 3 binary strings with length n a no consecutive 1’s

Input − n = 7

Output − Count of binary strings without consecutive 1’s of 7 is − 34

## Approach used in the below program as follows

• Take an input n for string length

• In count function we will count the binary strings without consecutive 1’s, define two arrays arr[] and arr_2 of size n, and a variable temp to store the result.

• Assign the 0th element of both arrays as 1

• Loop from i=1 till I less than n.

• While in 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 the temp.

## Example

Live Demo

#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 = arr_2 = 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("\n");
}
int main(){
//call the count function
count(10);
count(7);
count(1);
return 0;
}

## Output

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