An ELSE-IF statement is like the IF and ELSE statement; however, a choice is forced to be made at the end of the IF and ELSE statement. In the regular IF and ELSE statement that we looked at in the previous section, if the condition is met or true, the instruction on the if the statement is executed.
The ELSE part can be omitted by the program in the case of a series of nested operators. The ELSE-IF statement forces a default selection in case all the IF conditions in the block of nested operators are not met.
- IF the Time is less than 10, the greeting = “Good morning.”
- ELSE-IF Time is less than 20, the greeting = “Good day.”
- ELSE greeting = “Good evening.”
An ELSE-IF statement can be used multiple times to branch algorithms into numerous variations in the program. Moreover, each condition can be of different variables, which differs from the SWITCH statement (Fig.71).Fig.70 Code example of Fig.69.
An ELSE-IF statement is a combination of an IF statement and an ELSE statement. Like the functionality of an ELSE, an ELSE-IF extends an IF statement to perform a different instruction in case the original IF condition is false. However, it differs from the ELSE statement as the ELSE IF condition is required to be evaluated as true to execute its instruction.
- The first part of an ELSE-IF statement is the first conditional statement that compares values and arguments with logical operators. Conditional statements must be enclosed inside the parenthesis.
- If the condition by the original IF statement is true, the program will execute the code within the curly brackets of the IF statement.
- If the condition by the IF statement is not met, then the program will evaluate the ELSE-IF conditional statement that is enclosed inside the parenthesis. If the ELSE-IF statement is true, then the program will execute instructions related to the ELSE-IF block.
- If the condition by the ELSE-IF is false, the program will execute code within the ELSE block.
Note:
|
Fig.73 shows a typical ELSE-IF block of code. Note that the ELSE-IF statement allows simplification of multiple IF conditions and provides an elegant method to implement multiple expressions (left). A nested IF and ELSE block of code (right) is a more complicated way to achieve the same result, particularly when you have more than three branches in your algorithm.
Fig.73 ELSE-IF Block of code simplified a similar result with nested IF and ELSE statements
Coding tips:
The ELSE-IF statement is useful to simplify your code. Instead of having a code with too many IF, ELSE-IF offers a reliable method to manage alternative conditions from multiple variables or expressions (Fig.73). |