Nested If Statements

Ok, first of all, sorry if this is vague and/or poorly worded; I am not much of a programmer really! If anything needs clarifying or I've made a mistake please let me know, and thank you in advance :)

In my program I have a function, which I shall call constrict() here, just for the sake of ease. This is what I would like it to do:
1
2
3
4
5
6
7
8
9
10
void constrict(int i, int j) {
   if( (i - 1)%x != 0 ) {
      if( (i - 2)%x != 0 ) {
         etc etc. until...
            if( (i - j)%x != 0 ) {
               foo();
            }
      }
   }
}

I know that x hasn't been defined and all that, but that's not the part I'm asking about, it's simply the repetition of the if statements of (i - a) where (a = 1; a <= j; a++)
I tried
1
2
3
4
5
6
7
void constrict(int i, int j) {
   for (int a = 1; a <= j; a++) {
      if( (i - a)%x != 0 ) {
         foo();
      }
   }
}

but that clearly isn't right, because that evaluates the if statement for a = 1, and if it is true, then does foo(), then evaluates it again for a = 2, then does foo() again. this is not what I want!
I want it to check for a = 1, and if that is true then check for a = 2, etc. and only do foo() after all values of a from 1 to j have been checked. basically, what I posted in the first code box.
How do I achieve this? Help!
closed account (o1vk4iN6)
1
2
3
4
5
6
7
8
9
void constrict(int i, int j) {
   for (int a = 1; a <= j; a++) {
       if( (i - a)%x == 0 ) 
           return;
   }

   foo();

}


Move the foo out of the loop and change the condition to the opposite.
Last edited on
void constrict(int i, int j) {
for ( int a=1; a<=j; ++a ) {
if ( (i-a)%x == 0 ) {
return;
}
}
foo();
}
Try the following code:

1
2
3
4
5
void constrict( int i, int j ) 
{
   for ( int a = 0; a < j && ( i - a - 1 ) % x; a++ );
   if ( a == j  )  foo();
}
ahh, I get how that works, moving the foo() out and making the condition the opposite, but my condition is a little different to what I wrote, as it is actually
 
if( (i - a)%x != 0 || (i == a) )

I get that:
1
2
3
4
//original
(i - a)%x != 0
//inverse
(i - a)%x == 0

but the || i == a part make things trickier (for me, at least...)

am I right in saying that the opposite of 'if A or B' is 'if notA and notB'? i.e.
1
2
3
4
//original
if( (i - a)%x != 0 || i == a )
//inverse
if( (i - a)%x == 0 && i != a )
Last edited on
Yes, you are right about the inverse.
thank you very much everyone!
Topic archived. No new replies allowed.