CompTIA Tech+ (FC0-U71)Software Development ConceptsHard

A developer is creating a program that simulates a simple traffic light. The program needs to continuously cycle through the states of 'Red', 'Yellow', and 'Green' indefinitely. Which control structure is most appropriate for implementing this continuous, repeating behavior?

  1. AIf-Else Statement
  2. BFor Loop
  3. CSwitch Statement
  4. DWhile Loop
Show answer & explanation

Correct answer: D. While Loop

A While Loop is designed to repeatedly execute a block of code as long as a specified condition remains true. For an indefinite cycle like a traffic light, a 'while(true)' or similar always-true condition creates an infinite loop that continues cycling through states, which is exactly the behavior required.

Why the other options are wrong

  • A. An If-Else statement executes code conditionally once, not repeatedly.
  • B. A For Loop typically executes a fixed number of times or iterates over a collection, not indefinitely.
  • C. A Switch statement selects one of many code blocks to execute based on a variable's value, but does not provide repetition.

While Loop

A while loop repeatedly executes a block of code as long as a given Boolean condition evaluates to true. It is suitable for situations where the number of iterations is not known in advance.

  • Condition is checked before each iteration.
  • Continues as long as the condition is true.
  • Can lead to infinite loops if the condition never becomes false.

Memory trick: Loops are like a merry-go-round, going round and round.

More Software Development Concepts questions