Blue Sheep
Blue Sheep

Reputation: 438

For Loop Second Parameter Confusing

I am working on code from Code Golf, and was compacting a script that finds two prime numbers whose sum is an integer selected by the user.

a=prompt();function b(n){for(i=2;i<n;i++)if(n%i<1)return;return 1}for(c=2,r=1;c<a&&r;c++)if(b(c)&&b(a-c))alert(a+": "+c+" + "+(a-c)),r=0

I tried changing the first for loop to:

for(i=2;1;i++)

But this broke the code. It turns out that for(i=2;true;i++) also will not work. But i<n yields true. Why is it that I can have i<n but not true?

Upvotes: 0

Views: 246

Answers (2)

Chuck
Chuck

Reputation: 237060

i<n only yields true when i is less than n. Since your loop increments i every time through the loop, i will eventually not be less than n, and then the loop will stop.

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201447

You need not put any value at all! This will work,

for(i=2;;i++)

EDIT Your assertion is not true. The expression i<n yields false when the loop must terminate.

for (i=2;;i++) {
  if (i >= n) break; // <-- Added break, and inverted the test.
  // as before....
}

Upvotes: 4

Related Questions