Ifedee
Ifedee

Reputation: 25

Nested Loops in C programming

I was wondering how the line "if(!(i%j)) break;" in the code below would be interpreted. Since the "!" symbol is an inverter, does it mean that the bold line in the code below would interpret to saying that "if i mod j is equal to zero, invert and then break out of the loop"

Many thanks

int main ()
{
  /* local variable definition */
  int i, j;

  for (i = 2; i < 100; i++) {
    for (j = 2; j <= (i / j); j++)
      if (!(i % j))
        break;
    if (j > (i / j)) printf("%d is prime\n", i);
  }

  return 0;
}

Upvotes: 0

Views: 122

Answers (2)

Kenney
Kenney

Reputation: 9093

"if i mod j is equal to zero, invert and then break out of the loop"

Close: if i mod j equals zero then break.

if ( ! (i % j) ) break;

In C, 0 is false and anything else is true. So, when i % j is 0, ! (i % j) is 1, and thus true.

Upvotes: 1

Pavlin
Pavlin

Reputation: 5528

In C, an if (number) always evaluates to true, unless the number is 0. Therefore, that would evaluate to: if i mod j is equal to 0, basically, if i is a multiple of j.

Upvotes: 0

Related Questions