Why does this loop create infinite loop? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 6

Why does this loop create infinite loop?

#include <stdio.h> int main() { int num = 5; while (num > 0) { if (num == 3) { continue; } num--; printf("%d\n", num); } }

27th Sep 2018, 11:56 AM
Binyam Equar
Binyam Equar - avatar
4 Answers
+ 12
The reason that the code creates an infinite loop is mainly because of your if statement within the loop. What's happening is that when num is equal to 3, the if statement runs and because of the continue statement, the loop starts again before decreasing the value of num, which leaves it to always equal 3 and always restarting the loop because of the continue statement. To fix this, you need to add a line right before continue; in the if statement that decreases the value of num so that it doesn't get stuck to that value.
27th Sep 2018, 12:11 PM
Faisal
Faisal - avatar
+ 4
#include <stdio.h> int main() { int num = 5; while (num > 0) { num--; if (num == 3) { continue; } printf("%d\n", num); } }
27th Sep 2018, 10:57 PM
ShortCode
- 4
the var 5 which is outside the range of the loop (The number is too big). so the number will always equal 5.
28th Sep 2018, 9:37 PM
Devo
Devo - avatar
- 5
Your decrement of num- - is outside of while range of while loop! The variable num will always be equal to 5!
28th Sep 2018, 12:04 PM
Lloyd L Conley
Lloyd L Conley - avatar