For statement to while statement

I have to change the for statement into a while statement. But i’m getting a different output. Where is my mistake?

for (int k = 3; k > 0; k--) {
  if (k%2 == 0)
    continue;
  println(k);
}


int k = 3;
while (k > 0) {
    if (k%2 == 0)
      continue;
    k--;
    println(k);
  }

In the doc’s is written that continue; should work in a while loop, so I’m also curious. Following code is cheating isn’t it?

int k = 3;

while (k > 0) {
  if (k%2 != 0)
    println(k);
  k--;
}
1 Like

Bit of a puzzler there.

The thing here is that in the while loop, continue also skips the index variable counting / setting k--, since it’s not built into the while statement.

int k = 3;
while (k > 0) {
    if (k%2 == 0) {
      k--;
      continue;
    }
    println(k);
    k--;
  }
3 Likes