大象传媒

Programming constructs - EduqasSelection

Programs are created using common building blocks, known as programming constructs. These programming constructs form the basis for all programs and are also used in algorithms.

Part of Computer ScienceSystems analysis

Selection

In programming, there are occasions when a decision needs to be made. is the process of making a decision. The result of the decision determines which path the 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 one set of . Otherwise, it would follow a different path and execute a different set of instructions.

An explanation of selection, as used in algorithms and programming

Selection works by testing a . The test gives a 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.

Flowchart for an algorithm designed to work out whether a person is old enough to drive a car

In , selection is implemented using if else end if :

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 , 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.