Sometimes, we want the computer to make a decision based on some criteria. This means that not every line of code will be run, only that which is necessary at run time.
We use IF STATEMENTS to allow the computer to make decisions, which is also known as SELECTION.
Simple IF Statement:
All IF statements have a condition which is either TRUE or FALSE. Simply, if the condition is TRUE, then the code inside the IF is executed; if the condition is FALSE, then the code is not executed.
Example 1
IF statements using 'Else':
IF statements can be used to output a message if the condition is not TRUE (i.e. FALSE):
In another variation, If statements can have more than one condition (username and password has to be correct for the main menu to be shown):
Example 2
Nested If statements:
Sometimes, we need to check that the data has been entered correctly BEFORE we execute any more code i.e. there is no point running the code to check username and password, if the password length is less than 9 characters. We can use NESTED If statements (one IF statement inside another).
Firstly we check the length of the password. If the password is less than 9 characters, the computer does not try to execute the second IF statement i.e. we only then check the username and password is correct IF the password is at least 9 characters.
Here is the pseudocode:
This pseudocode translates in VB code below. Note how the IF statements are NESTED inside one another, with each IF statement having a matching IF, Else and End If.
Example 3