Selection
In programming, there are occasions when a decision needs to be made. selectionA decision within a computer program when the program decides to move on based on the results of an event. is the process of making a decision. The result of the decision determines which path the algorithmA sequence of logical instructions for carrying out a task. In computing, algorithms are needed to design computer programs. will take next.
For example, an algorithm could tell a user whether they are old enough to learn how to drive a car. If the user's age meets the required driving age, the program would follow one path and executionThe process of a program being run on a computer. one set of instructionA single action that can be performed by a computer processor.. Otherwise, it would follow a different path and execute a different set of instructions.
Selection works by testing a conditionIn computing, this is a statement that is either true or false. A computation depends on whether a condition equates to true or false.. The test gives a BooleanA data type in computing which only has two possible values, true or false. result 鈥 TRUE
or FALSE
, YES
or NO
, 1 or 0. In the next example, if the result is YES
, the program follows one path, otherwise it follows another.
In pseudocode Also written as pseudo-code. A method of writing up a set of instructions for a computer program using plain English. This is a good way of planning a program before coding., selection is implemented using if else end if
statementThe smallest element of a programming language which expresses an action to be carried out.:
age is integer
input 鈥淗ow old are you?鈥, age
if age >= 17
output 鈥淵ou are old enough to drive a car!鈥
else
output 鈥淐ome back when you are older!鈥
end if
In the above pseudocode program, the path the program takes depends on the condition. A variableA memory location within a computer program where values are stored., in this case age
, is used to test the condition.
If the value of age
is 17 or more, the result of the tested condition is YES
and the program follows the first path, which informs the user that they are old enough to drive.
If the value of age
is 16 or under, the result is NO
and the program follows the second path, which follows the statement else
. This path informs the user that they are not yet old enough to drive.
The statement end if
ends the selection.