An if statement is a conditional statement that changes the control flow according to a conditional outcome, true or false. As per Fig.55 and Fig.56, the illustration shows two IF statements to evaluate Symbol price against the moving average MA. Depending on the answer from the conditional statement, the program will execute action accordingly.
Anatomy of an IF statement
- An IF statement is composed of an if followed by a conditional statement that compares values or variables with logical operators. The conditional statement must be between parentheses.
- Curly brackets are required if more than one operation is performed.
Note:
|
In the Fig.58, instruction_one() and instruction_two() will be executed if Condition is met while instruction_three() will be executed by the programme regardless of the Condition.
Fig.59 demonstrates that without the use of the curly brackets, the programme will only execute the first instruction in the code sequence if the if-condition is true. In this example, instruction_one() will be called if Condition is met. The function instruction_two() and instruction_three() will be called irrespective of the Condition.
Fig.60 demonstrates a code sample that returns the same result as Fig.59, but with an if-statement written on one line of code. However, for best practice, it is recommended to provide space between block code to improve readability.
Fig.61 is an example of nested if-statements. A nested structure is basically a multi-level conditional test. Note the curly brackets that delimit the first if-statement to test the first Condition, which if true, instruction_one() and instruction_two() will be executed. For instruction_three() to be called, an additional condition must be met, Condition_two and Condition_three must be true.
Coding tips:
To simplify the code, an if-Statement can be nested into several nested structures which allow building complex algorithms such as demonstrated in Fig.61.
|