How does the 'break' statement work in a while loop?

The break statement in a while loop is used to exit the loop prematurely when a certain condition is met. When the break statement is executed, the control flow immediately jumps to the next statement following the loop.

Here’s a simple example in Python:

count = 0

while True:  # This creates an infinite loop
    count += 1
    print(count)
    
    if count == 5:  # Condition to break the loop
        print("Breaking the loop")
        break  # Exits the loop when count is 5

In this example, the loop will continue to increment count and print its value until count reaches 5, at which point the break statement is executed, and the loop is exited.

0 Comments

no data
Be the first to share your comment!