Unsuccessful if condition

98 views Asked by At

My function is supposed to have a successful start sequence when ever it encounters 0 0 0 0 1 1 0 but when i input these numbers the number of successful start sequence does not change However that doesn't stop it from compiling and I can't spot where the mistake Ive made is.

main()

{
    int i,num;
    int array[300];
    i=0;
    num=0;
    while(i<100)
    {
        scanf("%d",&array[i]); //input


        i++;
        //checks for start sequences while making sure there is atleast 8 numbers input
        if((i>=8)&&((array[i-1])==0)&&((array[i-2])==1)&&((array[i-3])==1)&&((array[i-4])==0)&&     ((array[i-5])==0)&&((array[i-6])==0)&&((array[i-7])==0))
        {
            num++;//counts the number of successful startsequences

        }
    printf("Number of valid start sequences is %d\n",num);
    }
}
2

There are 2 answers

1
Natasha Dutta On

You're facing off-by-one error.

Remember, the element number n in array is marked by n-1 the index.

for example,

if((i>=8)&&((array[i-1])==0)&&((array[i-2])==1)&&((array[i-3])==1)&&((array[i-4])==0)&&     ((array[i-5])==0)&&((array[i-6])==0)&&((array[i-7])==0))

never checksarray[0] element, does it?

Maybe, you want to start with changing if((i>=8) to if((i>=7)

0
user3629249 On
this line that checks for the sequence,
which is probably where the problem is located
is very difficult to read.
suggest writing it like so:

if(   (i>=8)
   && (0 == array[i-1])
   && (1 == array[i-2])
   && (1 == array[i-3])
   && (0 == array[i-4])
   && (0 == array[i-5])
   && (0 == array[i-6])
   && (0 == array[i-7]))


now that the line is readable, it looks like the array offsets are not correct.
and when i = 8, then 8 items have been read, 
and the code is only checking the last 7 inputs
so to not miss the first possible matching sequence: 

I suspect the line should be:

if(   (i>=7)
   && (0 == array[i-0])
   && (1 == array[i-1])
   && (1 == array[i-2])
   && (0 == array[i-3])
   && (0 == array[i-4])
   && (0 == array[i-5])
   && (0 == array[i-6]))