# C# program to check if there are K consecutive 1’s in a binary number

To check for consecutive 1’s in a binary number, you need to check for 0 and 1.

Firstly, set a bool array for 0s and 1s i.e. false and true −

bool []myArr = {false, true, false, false, false, true, true, true};

For 0, set the count to 0 −

if (myArr[i] == false)
count = 0;

For 1, increment the count and set the result. The Max() method returns the larger of two number −

count++;
res = Math.Max(res, count);

## Example

The following is the example to check if there are K consecutive 1’s in a binary number −

Live Demo

using System;
class MyApplication {
static int count(bool []myArr, int num) {
int myCount = 0, res = 0;
for (int i = 0; i < num; i++) {
if (myArr[i] == false)
myCount = 0;
else {
myCount++;
res = Math.Max(res, myCount);
}
}
return res;
}
public static void Main() {
bool []myArr = {false, true, false, false, false, true, true, true};
int num = myArr.Length;
Console.Write("Consecutive 1's = "+count(myArr, num));
}
}

## Output

Consecutive 1's = 3