Modelling



Selection

At its simplest, Selection in programming involves a binary answer to question.

The question involves two operands and a comparison operator:

  • = equals
  • < less than
  • > greather than
  • >= less than or equal
  • >= greather than or equal
  • ! not equal to

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.



The Algorithm

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:

  1. the actions are in a particular order
  2. the question is in a diamond box
  3. there are two different paths for the algorithm to take

image of fucntion


The Algorithm in Words - Pseudocode

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:

image of fucntion


The Program as JS Code

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

Generating a Random Number

This uses built-in functions:

  1. Math.random() generates a number between 0 and 1
  2. Math.random() + 100 makes the number between 0 and 100
  3. Math.floor() rounds the number down

The IF statement

This uses brackets:

  1. the condition is in round brackets
  2. each path is in a set of curly brackets
  3. else seperates the paths

the logic is: IF (condition is TRUE) follow the first path ELSE follow the second path

image of fucntion


Running the Function

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.