An ELSE statement is employed in conjunction with the IF statement. The ELSE statement will perform alternative computations and actions when the IF condition is not fulfilled. If the conditional statement is not true, the alternative block code after ELSE will be executed. As per Fig.62, the conditional statement is:
- IF checks whether the LastPrice is greater than the variable MA.
- In case it finds the value of variable MA greater than that of LastPrice, Buy is executed.
- Alternatively, ELSE executes Sell
|Anatomy of an ELSE statement|
An ELSE statement is combined with an IF statement and comprise:
- A Conditional statement that compares values and arguments with logical operators. Conditional statements must be enclosed inside the parentheses.
- If the condition by the 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, the program will execute the alternative block of code within the curly brackets of the ELSE.
Fig.65 shows a typical IF-ELSE block of code. If condition_one is met, instruction_one() and instruction_two() will be executed by the programme. On the other hand, if condition_one is not fulfilled, alternative code instructions that are inside the ELSE statement will be run by the program. ELSE statement offers an elegant way to manage alternative instructions.
Fig.66 shows the same instructions as fig.65 but with a call of function instruction_five() outside of the IF-ELSE statement block. Note that instruction_five() will be executed by the program in any case of condition_one.
The ELSE statement with a single line of instruction does not require curly brackets to delimit the operations block, as demonstrated in Fig.76.
Fig.68 demonstrates two different ways to achieve the same program execution. Note that it is preferable to use an ELSE statement to simplify the management of alternative instructions.
Fig.68 IF-ELSE statement is more concise than having multiple IF statements.
The ELSE statement is useful to simplify your code. Instead of having a code with too many IF, ELSE offers a reliable method to manage alternative conditions not met by the IF condition (Fig.68).