Display Name
Display Name

Reputation: 55

For loop in C and how it works?

#include <stdio.h>

int main() {

    int i, j;

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

    return 0;
}

I am a Beginner at C and trying to understand how the for loop works. My question is at the 4th iteration, the condition in the nested loop will return TRUE

(j < (i/j))    // 2 <= 4/2

and the first if statement will also return TRUE because of NOT operator

(!(i%j));    // 4/2 = !(0)

so now the value of j = 3 because of incrementation, but why the second if statement did not print the output if it is TRUE?

(j > (i/j));    // 3 > 4/3

Upvotes: 0

Views: 102

Answers (2)

A break statement ends its nearest enclosing loop prematurely. Everything after it (and that includes the third statement of the for loop), will not occur.

So j is still 2 when the condition for printing is checked, like Mark answered.

Upvotes: 3

Mark
Mark

Reputation: 166

You're breaking out of the loop before j is incremented, so j is still 2, not 3

Upvotes: 4

Related Questions