An infinite loop runs forever because its condition never becomes false. Your program freezes, and you have to force-quit it. Here is a classic example:
int x = 1;
while (x > 0) {
x++;
}
Since x starts positive and only increases, x > 0 never becomes false. (Eventually x overflows, but that's a separate issue.)
Common causes of infinite loops:
- Forgetting the update step entirely (
i++is missing) - Updating the wrong variable (incrementing
jwhen the condition checksi) - Moving in the wrong direction (decrementing when you should increment)
To avoid them, ask yourself before each loop: "What changes each iteration, and does it move the condition toward false?"