CompTIA Tech+ (FC0-U71)Software Development ConceptsMedium
A developer needs to create a program that repeatedly asks a user for input until a specific keyword is entered. Which programming construct is best suited for this task?
- AFunction call
- BFor loop
- CWhile loop
- DIf-Else statement
Show answer & explanationAnswer & explanation
Correct answer: C. While loop
A While loop is ideal for situations where a block of code needs to be executed repeatedly as long as a certain condition remains true (or until it becomes false). In this case, the loop continues 'while' the keyword has not been entered.
Why the other options are wrong
- A. A Function call executes a block of code, but does not inherently provide repetition based on a condition.
- B. A For loop is typically used when the number of iterations is known beforehand or for iterating through a collection.
- D. An If-Else statement executes code conditionally only once, not repeatedly.
While Loop
A control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The loop continues as long as the condition evaluates to true.
- Repeats code block as long as a condition is true.
- Number of iterations can be unknown beforehand.
- Condition is checked before each iteration.
Memory trick: While you 'wait' for a condition, the loop 'runs'.