why my ‘while’ code doesn’t work, but the for one does?

I’m learning javascript.. my ‘while’ loop outputs senseless stuff but the ‘for’ one does the work (which is gives a prime number with 10 as a limit), i checked for syntax and ‘;’, what’s left?

Here is the working one ‘for’:

            let n = 10;
            nextPrime:
            for (let i = 2; i <= n; i++) { // for each i...
              for (let j = 2; j < i; j++) { // look for a divisor..
                if (i % j == 0 ) continue nextPrime; // not a prime, go next i
              }
              alert( i ); // a prime
            }

this one works just great.. gives 2,3,5,7 which are prime numbers..

here is the ‘while’ one:

            let n = 10; /*limit for the loop*/
            let i = 2; /*base*/
            let j = 2; /*factor*/
            nextPrime:
            while (i <= n) {
              while (j < i) {
                if (i % j == 0) {
                  continue nextPrime;
                }
                j++;
              }
              i++;
              alert(i);
            }

this one gives me senseless numbers (3,4,5,6,7,8,9,10,11).. but why? and what’s the solution?

  • 2

    You forgot to reset j in the while version

    – 

  • The for loop increments i after the alert, in your while loop you do so before.

    – 

  • before? even so it should output 3,5,7 innit?

    – 

  • btw i modified the code so it “resets” the j value by putting “let j” inside the while loop (i’m not pretty sure if this is right, i’m learning javascript on my own..) and the output is 2,3 and crash..

    – 




JavaScript While Loop Issue

I understand why the while-loop implementation of your prime number generator isn’t producing the desired results. The primary problem lies in where you’ve placed the i++, j++, and the alert(i) statement. Additionally, it seems you haven’t reset the value of j to 2 after identifying a prime number.

Revised while-loop Code:

let n = 10; /*limit for loop*/
let i = 2; /*base*/

nextPrime:
while (i <= n) {
  let j = 2; /*factor*/
  while (j < i) {
    if (i % j == 0) {
      i++;
      continue nextPrime;
    }
    j++;
  }
  alert(i);
  i++;
}

Leave a Comment