GCSE Revision

Sub programs and random numbers

Procedures and functions

A subprogram is a named section of code that can be used again. A procedure performs a task but does not return a value. A function returns a value. A parameter receives data; the value supplied when calling the subprogram is an argument.

procedure showTotal(scores)
    total = scores[0] + scores[1] + scores[2]
    OUTPUT total
endprocedure
scores = [4, 7, 2]
showTotal(scores)

Both print 13. Python has no separate procedure keyword: a function with no return is used for a task.

Key terms

Scope and arrays in subprograms

A local variable is created inside a subprogram and is only available there. A global variable is created outside subprograms and can be accessed by them. Passing an array as a parameter lets a subprogram use its elements; returning an array sends a new array back to the caller. In this example, passMark is global, while passed and result are local:

passMark = 50
function isPass(score)
    passed = score >= passMark
    return passed
endfunction
function doubleValues(values)
    result = [0, 0, 0]
    FOR i = 0 TO 2
        result[i] = values[i] * 2
    NEXT i
    return result
endfunction
scores = [4, 7, 2]
doubled = doubleValues(scores)
OUTPUT isPass(60)

doubled is [8, 14, 4]; isPass(60) returns true.

Key terms

Generating random numbers

Random numbers are useful when a program needs an unpredictable choice, such as a dice roll. ERL's random(1, 6) and Python's random.randint(1, 6) both include 1 and 6 as possible results:

roll = random(1, 6)
OUTPUT roll

Each call can produce a different integer from 1 to 6.

Key terms

Why use subprograms

Splitting a program into subprograms, rather than writing one long block of code, has several benefits:

  • Decomposition: each subprogram solves one part of the problem, so the whole is easier to design.
  • Reuse: a subprogram is written once and called as often as it's needed, so there is less code.
  • Testing: each subprogram can be tested on its own before the parts are put together.
  • Maintenance: a change is made in one place, rather than everywhere the code is repeated.
  • Teamwork: different programmers can write different subprograms at the same time.

Exam tip

Link the benefit to the program in the question: 'the isPass function is called for every student, so the pass check is only written once'.

Take the quiz