Selection

<< Previous: Variables & constants Next: Iteration >>

Assignment is described at the end of the video after the data types section

About selection

Selection is a programming construct that allows a program to take a different path based on the result of a Boolean check, or perhaps take no action. The Boolean check is a condition that can either evaluate as true or false. The code that is to be run as a result of a selection check is indented. Even though the examples show just one line of code, any number of lines of code can be executed as the result of a check.

If statements

The simplest form of selection is a basic if statement. This allows a condition to be checked and if it is true some code is executed but if it is not then nothing is executed. An example is shown below. If the user enters the name Bob then some code will be executed, otherwise the program just carries on to the next line of code.

The next form of selection is an if-else statement. This allows a condition to be checked and if it is true some code is executed but if it is not then different code is executed. An example is shown below. In this instance some code will always be executed. If the user enters Bob it will output Hi, I'm Bob too and otherwise it will say Hello and use the name that was input by the user.

Another form of selection is an if-else if-else statement. This allows a condition to be checked and if it is true some code is executed but if it is not then another condition is checked and if that is true it is executed and not the else code. You can have as many else if checks as you like and either include an else condition or not. An important thing to remember is that the if stetement will be over as soon as any condition evaluates as true or if all conditions evaluate as false. The remainder of the if statement will not get checked once a condition evaluates as true.

Case select statements

The other form of selection is the case select statement. You may have noticed that as we add more else if conditions the algorithm becomes more complex to follow. The case select statement is used to make code look neater and easier to read. It accepts a variable or expression as input and checks to see if this matches one of the cases, then executes the code for that option. You can also define a default case which works like the else condition in an if statement.



Knowledge check


Questions:
Correct:

Question text


<< Previous: Variables & constants Next: Iteration >>

© All materials created by and copyright S.Goff