for loop guard..

Is someone able to explain the difference between these two segements of code?

I'm really confused and struggling to get my head around it..
My understanding is that the for loop keeps going through the cycle. A number is prime if it can be divided by itself.

If we were to input number (n) == 7, shouldn't the guard only work when it is c<n because c will be equal to 7, and no longer fit the guard and consequently will stop there. How come the code for the c<n and c<=n give me the same answer?? #confusedtothemax

1
 ``1234567`` ``````for ( c = 2 ; c < n ; c++ ) { if ( n % c == 0 ) break; } if ( c != n ) printf("Not prime.\n");``````

2.
 ``1234567`` ``````for ( c = 2 ; c <= n ; c++ ) { if ( n % c == 0 ) break; } if ( c != n ) printf("Not prime.\n");``````

Last edited on
1)Let n=10 then first loop will progress to c=9 only but second loop will progress to c=10

2)let n=3 then in first loop at end of loop c=3=n
In second loop however at c=3 loop continues and c=n=3 goes to if condition which is true so its break there.remember here c=3=n so Prime.

Same goes with n=7.

Second loop will take more time then first one but gives same results.
Topic archived. No new replies allowed.