⬅ Previous Topic
Loop Control Statements - break, continue, passNext Topic ⮕
What Are Functions?⬅ Previous Topic
Loop Control Statements - break, continue, passNext Topic ⮕
What Are Functions?An infinite loop is a loop that never terminates unless an external condition forces it to stop. It continues executing endlessly because the loop's exit condition is never met or missing entirely.
while (true)
This loop will never end because the condition is always true and nothing changes inside the loop.
counter = 0
while counter < 5
print "Hello"
// Forgot to increase counter
Output:
Hello Hello Hello ... (infinite)
To prevent infinite execution, we must modify the loop variable so that the condition eventually becomes false.
counter = 0
while counter < 5
print "Hello"
counter = counter + 1
Output:
Hello Hello Hello Hello Hello
Why did the previous version of the loop run forever?
Because the variable counter
was never updated, so the condition counter < 5
always stayed true.
Sometimes infinite loops are used intentionally, such as in servers or menu-based programs. In these cases, an explicit break condition is added inside the loop.
loop forever
input = read_input()
if input == "exit"
break
print "You entered:", input
Output:
You entered: hello You entered: 123 You entered: goodbye ... (loop ends when input is "exit")
Is using loop forever
always a bad idea?
No, it’s valid in cases where you want the loop to continue until an explicit instruction is given (like user input or system signal). But always include a safe exit inside the loop.
break
or return
to exitTo avoid hanging systems, you can include a safety limit to break out of the loop after a certain number of steps.
attempts = 0
max_attempts = 10
loop forever
if condition_is_met()
break
attempts = attempts + 1
if attempts >= max_attempts
print "Breaking due to too many attempts"
break
Output:
Breaking due to too many attempts
Understanding infinite loops and how to control them is a foundational concept in programming. Whether you're preventing accidental endless loops or building intentional ones, knowing how and when to exit is critical for writing safe and efficient code.
⬅ Previous Topic
Loop Control Statements - break, continue, passNext Topic ⮕
What Are Functions?You can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.