
- C Programming Tutorial
- C - Home
- C - Overview
- C - Environment Setup
- C - Program Structure
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Constants
- C - Storage Classes
- C - Operators
- C - Decision Making
- C - Loops
- C - Functions
- C - Scope Rules
- C - Arrays
- C - Pointers
- C - Strings
- C - Structures
- C - Unions
- C - Bit Fields
- C - Typedef
- C - Input & Output
- C - File I/O
- C - Preprocessors
- C - Header Files
- C - Type Casting
- C - Error Handling
- C - Recursion
- C - Variable Arguments
- C - Memory Management
- C - Command Line Arguments
- C Programming useful Resources
- C - Questions & Answers
- C - Quick Guide
- C - Useful Resources
- C - Discussion
Program to Count number of binary strings without consecutive 1’s in C/C++?
Here we will see one interesting problem. Suppose one value of n is given. We have to find all strings of length n, such that there are no consecutive 1s. If n = 2, then the numbers are {00, 01, 10}, So output is 3.
We can solve it using dynamic programming. Suppose we have a tables ‘a’ and ‘b’. Where arr[i] is storing the number of binary strings of length i, where no consecutive 1s are present, and ending with 0. Similarly, b is holding the same but numbers ending with 1. We can append 0 or 1 where last one is 0, but add only 0 if the last one is 1.
Let us see the algorithm to get this idea.
Algorithm
noConsecutiveOnes(n) −
Begin define array a and b of size n a[0] := 1 b[0] := 1 for i in range 1 to n, do a[i] := a[i-1] + b[i - 1] b[i] := a[i - 1] done return a[n-1] + b[n-1] End
Example
#include <iostream> using namespace std; int noConsecutiveOnes(int n) { int a[n], b[n]; a[0] = 1; b[0] = 1; for (int i = 1; i < n; i++) { a[i] = a[i-1] + b[i-1]; b[i] = a[i-1]; } return a[n-1] + b[n-1]; } int main() { cout << noConsecutiveOnes(4) << endl; }
Output
8
- Related Articles
- C/C++ Program to Count number of binary strings without consecutive 1’s?
- Count number of binary strings without consecutive 1's in C
- Python Program to Count number of binary strings without consecutive 1’
- Count Binary String without Consecutive 1's
- Count number of binary strings of length N having only 0’s and 1’s in C++
- C# program to check if there are K consecutive 1’s in a binary number
- Python program to check if there are K consecutive 1’s in a binary number?
- Program to find longest consecutive run of 1 in binary form of a number in C++
- Count the number of 1’s and 0’s in a binary array using STL in C++
- Finding maximum number of consecutive 1's in a binary array in JavaScript
- C# program to find the length of the Longest Consecutive 1’s in Binary Representation of a given integer
- Binary representation of next greater number with same number of 1’s and 0’s in C Program?
- Javascript Program to Count 1’s in a sorted binary array
- C# Program to Count the Number of 1's in the Entered Numbers
- Count 1’s in a sorted binary array in C++

Advertisements