While loop confusion

 

If this code is correct, then I think Output should be: 1, 2. Not: 1, 2, 4, 5.

And the while loop would go on forever with count always == 3, because continue; would skip both lines 6 and 7.

If the book is right and I am wrong, then what do I not understand here? Thanks.

1. int count = 1;
2. 
3. while(count <= 5)
4. {
5.  if(count == 3) continue;
6.   Print(count);             // Output: 1, 2, 4, 5
7.   count++;
8. }
 
afiverestatcastle:

If this code is correct, then I think Output should be: 1, 2. Not: 1, 2, 4, 5.

And the while loop would go on forever with count always == 3, because continue; would skip both lines 6 and 7.

If the book is right and I am wrong, then what do I not understand here? Thanks.

Have you run this? It should result in infinite loop, since when it skips both Print(count) and count++ when count==3 - it'll stay as count==3 for ever and ever...

To print 1, 2, 4 and 5, should change to:

1. int count = 1;
2. 
3. while(count <= 5)
4. {
5.  if(count != 3)
6.   Print(count);             // Output: 1, 2, 4, 5
7.   count++;
8. }

To print 1, 2 only, should change to:

1. int count = 1;
2. 
3. while(count <= 5)
4. {
5.  if(count < 3)
6.   Print(count);             // Output: 1, 2, 4, 5
7.   count++;
8. }
 
Seng Joo Thio:

Have you run this? It should result in infinite loop, since when it skips both Print(count) and count++ when count==3 - it'll stay as count==3 for ever and ever...

To print 1, 2, 4 and 5, should change to:

To print 1, 2 only, should change to:

You didn't understand the question. He asked why in the book the output is 1 2 4 5. Is the book wrong or he is the one who does not understand???
 
Mafuta Landou:
You didn't understand the question. He asked why in the book the output is 1 2 4 5. Is the book wrong or he is the one who does not understand???
You are absolutely right, thanks for pointing it out. (It is 5+ in the morning and my eyes have not fully opened 😂)
PS. The book is wrong. 


 

Thank you both for your response.


I didn't think I would get a response on a Sunday.


Book is wrong.

Reason: