In: Computer Science
Foundation of computer science
Discuss the selection constructs. Give an illustrative example for each one of them.
It is also known as conditional construct. It is used to indicate decision in a program. There are different kinds of selection constructs. They are
1. IF ....THEN CONSTRUCT :
This structure is also called as the ‘one-way branch ‘ decision structure.
IF test-condition then
Statement 2
Endif
In some situations, certain statements have to be executed only if a certain condition is met. In such cases, a test condition is specified. The test-condition is a Boolean expression which when tested results in TRUE or FALSE. When the condition is TRUE, statement enclosed between THEN and ENDIF are executed. If the condition is false, the statements are ignored and control is transferred to the statement following the if..then structure.
Example showing If Then:
2. If ..Then ….Else Construct
This structure is also called as the ‘two-way branch” decision structure
If test-condition then
Statement 1
Else
Statement 2
Endif
If test-condition results in TRUE value, statement 1 is executed. If it is FALSE, statement 2 is executed. Statement 1 , Statement 2 can either be a single statement or a set of simple statements.
Example showing If ..Then ….Else:
3. IF … THEN … ELSEIF…. Construct
A nested if is an if statement that is the target of another if statement.
if (condition1): # Executes when condition1 is true if (condition2): # Executes when condition2 is true # if Block is end here # if Block is end here
Example showing If ..Then ….Else:
4. MULTIPLE SELECTION
switch (n) { case 1: // code to be executed if n = 1; break; case 2: // code to be executed if n = 2; break; default: // code to be executed if n doesn't match any cases }
Example showing MULTIPLE SELECTION