Md Soman Khan Md Soman Khan - 1 month ago 6
C Question

keep track of successive repeatnace of a digit in C

I have an array with some 0's and 1's.Now I want to find how much time 1 comes successively(the largest value). Like I have an array of 0 1 1 1 0 0 1 1 1 1 0 1.Then my result will be 4. I can count the total occurrence of 1 but can't keep the successive occurrence. How can I keep the result of successive occurance.I am beginner

Answer

Each time you encounter a 0 you need to reset the counter. Before resetting however you need to check if the value is greater than the previous value you had for your counter.

I don't quite remember C syntax 100%, but something like this:

int size = sizeof(yourArray) / sizeof(int);
int largest = 0;
int counter = 0;

for(int i = 0; i < size; i++) {
    if(yourArray[i] == 1) {
        counter++;

    } else {
        if(counter > largest) {
            largest = counter;
        }
        counter = 0;
    }
}
if(counter > largest) {
    largest = counter;
}