Which control structure allows you to choose between multiple alternatives ?
ADo-while
BWhile
CFor
DSwitch-Case
Answer:
D. Switch-Case
Read Explanation:
The Switch Statement
- The switch statement is the primary control structure used in programming to select one of many code blocks to be executed based on the value of a single variable or expression.
- It serves as an efficient alternative to using long chains of if-else-if statements, especially when comparing a variable against multiple constant values.
- Syntax and Structure: It evaluates an expression once and compares the result with various 'case' labels. When a match is found, the corresponding block of code is executed.
- The Break Keyword: Crucial to the switch structure is the break statement. Without it, the program continues to execute the next case (known as 'fall-through') regardless of whether the case matches.
- Default Case: Most implementations include a default label, which serves as a catch-all block to execute code if no matches are found among the defined cases.
- Limitations: Unlike if-else blocks that can evaluate complex boolean conditions (e.g.,
x > 10 && x < 20), the switch statement typically requires discrete, constant values (like integers or characters) for its case labels in languages like C, C++, and Java.
