At its simplest, Selection in programming involves a binary answer to question.
The question involves two operands and a comparison operator:
For example, say that firstNumber and secondNumber are operands to be compared.
We can ask a quesition using a comparison operator.
A question could be: is firstNumber > secondNumber?
The answer is binary - Yes or No
In programming, this would mean that we could divert the route through the program depending upon the answer - one route for YES and another route for NO.
Diagrams are good at showing Selection - this is a Flow Chart. It shows the order of processing for the algorithm with the added advantage of showing the route too
In this example, we a number and then ask a question and carry out the selection.
You should see that:
When writing code, we will often have an interim stage where we write the program using mainly English.
This mehtod is called PSEUDOCODE and is independent of any actual programming language.
This is the pseudocode that goes with the flowchart:
Here is how the code for the program is written in JS.
The concept is still that there is a controlling MAIN routine which calls a SUBROUTINE
This uses built-in functions:
This uses brackets:
the logic is: IF (condition is TRUE) follow the first path ELSE follow the second path
Here is how the code for MAIN routine and SUBROUTINE are written in JS.
The concept is that there is a controlling MAIN routine which calls a SUBROUTINE
This video shows the order in which the program is executed.