CompTIA Tech+ (FC0-U71)Software Development ConceptsMedium
A developer is creating a program to simulate a simple traffic light. The program needs to continuously cycle through the states: Red, Yellow, Green, and then back to Red indefinitely. Which type of loop is most appropriate for a process that should run forever or until an external stop signal is received?
- AWhile loop with a true condition
- BDo-while loop
- CFor loop
- DRecursion
Show answer & explanationAnswer & explanation
Correct answer: A. While loop with a true condition
A `while(true)` loop (or similar construct like `while(1)` in C) creates an infinite loop that continues indefinitely until explicitly broken out of or the program terminates. This is ideal for processes that are meant to run continuously, like a system service or a simulation that never ends.
Why the other options are wrong
- B. A do-while loop guarantees at least one execution but still relies on a condition that eventually becomes false to stop.
- C. A for loop is typically used for a known number of iterations.
- D. Recursion solves problems by calling itself, not typically used for indefinite continuous execution without a clear base case for termination.
Infinite Loop
A sequence of instructions that continues endlessly because the loop's termination condition is never met or is designed to always be true. Often used for processes that should run continuously, like operating system kernels or server applications.
- Created when a loop's condition never evaluates to false.
- Can be intentional (e.g., embedded systems, event loops) or unintentional (bug).
- Unintentional infinite loops consume system resources and can crash programs.
- Often implemented with `while(true)` or `for(;;)` constructs.
Memory trick: Infinite loop: It just 'loops' and 'loops' and never stops.