+ 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); } }
4 Antworten
+ 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.
+ 4
#include <stdio.h>
int main() {
int num = 5;
while (num > 0) {
num--;
if (num == 3) {
continue;
}
printf("%d\n", num);
}
}
- 4
the var 5 which is outside the range of the loop (The number is too big). so the number will always equal 5.
- 5
Your decrement of num- - is outside of while range of while loop! The variable num will always be equal to 5!