Selection structure is used when a decision has to be made, based on some condition, before selecting an instruction to execute. The condition tested in the selection structure must be a Boolean expression (evaluating to true or false). The Boolean expression can contain variables, constants, arithmetic operators, comparison operators, and logical operators.
Types of selection structure:
if-else chain is a nested if statement occurring in the else clause of the outer if-else. If any condition is true, the corresponding statement is executed and the chain terminates. Final else is only executed if no conditions were true. Serves as a catch-all case. if-else chain provides one selection from many possible alternatives
Syntax:The switch statement can be used to code a multiple-alternative selection structure. The statement begins with switch keyword followed by a selector expression in parentheses.
The Selector expression can contain any combination of variables, constants, functions, and operators. It must result in a data type that is bool, char, short, int, or long. There are one or more case clauses (as many as necessary) and each case clause represents a different alternative and contains a value followed by a colon.
Syntax:Value for each case clause can be a literal constant, a named constant, or an expression composed of literal and named constants. The data type of the value should be the same as the selector expression. Each case clause contains one or more statements processed when the selector expression matches that case’s value
Break Statement tells the computer to break out of switch at that point; must be the last statement of a case clause. Without a break statement, the computer continues to process instructions in later case clauses. After processing the break statement, the computer processes the next instruction after the switch statement’s closing brace
Can also include one default clause; processed if the selector expression does not match any values in case clauses. default clause can appear anywhere, but is usually entered as the last clause. If it is the last clause, a break statement is not needed at its end. Otherwise, a break statement is needed to prevent the computer from processing later case clauses.