Unbounded loops and Bounded loops
Unbounded loops and Bounded loops
Let’s learn about Unbounded loops and Bounded loops in this tutorial. Unbounded loops refer to those whose number of iterations depends on the runtime and until the termination condition is satisfied. Bounded loops refer to those whose number of iterations is known beforehand.
Unbounded Loops
Definition:
An unbounded loop is a loop that runs an unknown number of times. It continues to run until a certain condition is met, which may not be known in advance.
Examples:
-
A
while
loop that continues until a user types “exit”. -
Waiting for a sensor to report a certain value.
Bounded Loops
Definition:
A bounded loop is a loop that runs a known or fixed number of times. You know in advance how many times it will execute.
Examples:
-
A
for
loop that runs from 1 to 10. -
Looping through all elements in a list of known size.
Bounded Loop vs Unbounded Loop
Bounded Loop | Unbounded Loop | |
---|---|---|
Number of iterations | Known in advance | Unknown; depends on a condition |
Common type | For Loop is a Bounded Loop | While loop and Do-While Loops are Unbounded Loops. |
Risk of infinite loop | Low | High, if the condition is not handled well |