If…Then…ElseIf…Else
In some problems there are not just two different outcomes but more than two. If this is the case, then a simple If…Then…Else structure will not work. In these situations an If…Then…ElseIf…Else might be used. In this type of structure there can be more than just one Boolean condition and each is checked in sequence. Once a Boolean expression is met (the value is true), then the specified section of code for that Boolean expression is executed. Once executed, all other conditions are skipped over and the flow of logic goes right down to the bottom of the structure. It is important to remember that one and only one section of code can be executed. Even if several of the Boolean conditions happen to be met, the first and only the first one will be evaluated and run.
The structure can contain many ElseIfs, as many as the programmer needs. Another optional piece of the structure is the, “Else”. If none of the above Boolean conditions are met, the programmer might want a section of code to be executed that is a catch all. If this is the case, then the code is placed in the else section. Any code in the else section is run if and only if none of the Boolean expressions were met. It should also be noted that there is no Boolean condition associated with the else. That is because it is run only if all the above Boolean conditions are not met. The If…Then…ElseIf…Else statement (in most computer programming languages) takes the generic form of:
When you approach a street light, there are not just 2 choices there are actually 3 (or maybe more). The following example will tell the driver (or the self-driving car), what to do as they approach a stop light. The driver will need to know what to do if the light is red, yellow or green. If the light is red, the driver needs to stop. If the light is yellow, the driver needs to slow down. If the light is green, the driver needs to go. If the light is not red, yellow or green, the driver needs to do something else. The following code shows how this might be done: