Question

I have a problem as stated below: i have an array(say) a[]={10,24,56,33,22,11,21} i have something like this

for(i=0;i<100;i++){
    if(a[i]==10)
        // do something
}

next when i=1

if(a[i]==10 && a[i+1]==24)

so on so at each iteration the arguments / conditions within if should be varying now this will be a very big sequence i cant explicitly write
if(a[i]==10 && a[i+1]==24 && a[i+2]==56 ...... a[i+100]=2322)

how can i achieve this varying conditions?

Was it helpful?

Solution

You have to have a cumulative "boolean" variable that checks a[i] at the i-th iteration and update that variable:

int a[] = {...};   /* array with some values to verify */
int v[] = {...};   /* these are the actual desired values in a[] */

/* the verifying loop */
int i;
int cond = 1;
for (i = 0; i < 100; i++)
{
    cond = cond && (a[i] == v[i]);
    if (cond)
    {
       /* do something */
    }
}

OTHER TIPS

I think that you should introduce a boolean value.

bool valid = true;

for(i=0;i<100;i++){
    if(a[i]==10 && valid)
        // do something
    else
    {
        valid = false;
        break;
    }
}

For every iteration, you need to change the value to which you are comparing a[i]

Have a loop within a loop:

for (i = 0; i != 100; ++i)
{
    int condition = 1;
    for (j = 0; i + j != 100 && condition; ++j)
    {
        condition = condition && (a[i + j] == /* your number */ );
    }
    if (condition) { /* ... */ }
}

In this case, you can use function pointers or blocks. You can find a good example here here

Seeing your examples, I think that the variations you are talking about is only in the length of array 'a' whose presence you want to check in some array x. If indeed it is so, memcmp can be of use to you.

Let me modify your example a bit to clarify what I am saying.

int a[7]={10,24,56,33,22,11,21} is the required values you want to check in some array 'x', with different lengths of 'a' each time, with 'x' declared as

int x[1000];

In that case, you could use memcmp as follow :-

for ( len = 1 ; len <= 7 ; ++len )
{ for ( i = 0 ; i <= 1000-len ; ++i )
  { if ( ! memcmp( a, x+i, len * sizeof(int) ) )
    { // do something
    }
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top