大象传媒

Programming constructs - EduqasSubroutines

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

Subroutines

are small blocks of code in a modular program designed to perform a particular task. Since a subroutine is in itself a small program, it can contain any of the , and constructs.

In the following example, the asks the user to enter two numbers. It then adds them together and, if the total is over 10, it runs the 鈥楥ountDown鈥 subroutine. If the total is not over 10, it will run the 鈥楥ountUp鈥 subroutine.

Flowchart for an algorithm designed to get a total of ten by adding two numbers together

Here is the same algorithm written using :

declare CountDown
                    聽聽聽聽while total <> 0
                    聽聽聽聽聽聽聽聽output total
                    聽聽聽聽聽聽聽聽total = total 鈥 1
                    聽聽聽聽repeat
                    end Subroutine
                    declare CountUp
                    i is integer
                    聽聽聽聽set i = 0
                    聽聽聽聽while i <> total
                    聽聽聽聽聽聽聽聽output i
                    聽聽聽聽聽聽聽聽i = i + 1
                    聽聽聽聽repeat
                    end Subroutine

                    num1 is integer
                    num2 is integer
                    total is integer
                    input 鈥淓nter first number鈥, num1
                    input 鈥淓nter second number鈥, num2
                    total = num1 + num2
                    if total > 10
                    聽聽聽聽call CountDown
                    else
                    聽聽聽聽call CountUp
                    end if