Loops 3 Question (incrementor up top?)

Hello,

In attempting to set up a while loop for the Loops 3 assessment, I’m not understanding the final expression/incrementor placement that makes the loop generate the desired output.

In the cats loop example using the while loop, the final expression/incrementor is placed at the bottom…

initializer
while (exit-condition) {
  // code to run

  final-expression
}

In Loops 3, it would only work with the final expression at the top…

initializer
while (exit-condition) {
final-expression
 // code to run - false
} else {
 // code to run - true
 }

 // why doesn't the final-expression get placed here?
}

Why is that? Thanks for the help!

@timandes this is an interesting one. The reason we don’t put the iterator at the bottom of the block is that, earlier on in the block, we continue the loop if the number is not a prime number. If we don’t decrement the value of i first, this would result in us continually running the isPrime() function on a non-prime number, then continuing, then doing it again, forever. An infinite loop, in effect.

So therefore this fixes that:

while(i > 2) {
  i--;

  if(!isPrime(i)) {
    continue;
  }

  para.textContent += `${i} `;

}

I’ve changed the exit condition to > 2. Because the lowest prime number is 2 — 1 and 0 don’t count as prime numbers! I’ve updated this in the question already.

Now, strictly speaking, the above answer is still a bit shonky, as we are reducing the value of i immediately before we actually do anything to it, so therefore 500 gets skipped completely. This doesn’t matter for the purposes of this code, because we know 500 is not a prime number, but it’s not a very good practice.

In addition, you end up outputting 1 if you do i >= 2, which is the range we are told to work between, so therefore you have to end up putting i > 2. to make it work. But this is not very intuitive.

So therefore a better answer would be this:

while(i >= 2) {


  if(!isPrime(i)) {
    i--;
    continue;
  }

  para.textContent += `${i} `;
  i--;

}

It is difficult to write it more elegantly, because in the if block, the i-- has to come before the continue, otherwise we break out of the loop iteration and i-- never runs.

1 Like

Oh man, that makes total sense. Interesting balance between functionality and elegance. Functionality wins on this one!

Adding “shonky” to my vocabulary, haha.

Thanks for the time and answer.

You’re welcome. And I’m glad you are enjoying my strange English vocab :wink: