Computer Science Essentials, Unit 2, Lesson 4 of 6

Subroutines

GCSE Computer Science, Programming, 20 minutes

Sign in

Functions and procedures, parameters and return values, local and global variables, and why programs are built from subroutines.

What you will learn

  • Tell a function from a procedure
  • Follow parameters and return values
  • Pick out local and global variables
  • Explain the benefits of subroutines

Functions and procedures

A subroutine is a named block of code that runs when it is called.

  • A function returns a value to the code that called it.
  • A procedure does a job but returns nothing. (AQA style calls both SUBROUTINE; Python uses def for both.)
  • Parameters are the names in the brackets of the definition; the values passed in when it is called are arguments.
function area(w, h)
    return w * h
endfunction
procedure banner(msg)
    print("== " + msg + " ==")
endprocedure
banner("Room " + str(area(3, 4)))
SUBROUTINE area(w, h)
    RETURN w * h
ENDSUBROUTINE
SUBROUTINE banner(msg)
    OUTPUT "== " + msg + " =="
ENDSUBROUTINE
banner("Room " + INT_TO_STRING(area(3, 4)))
def area(w, h):
    return w * h
def banner(msg):
    print("== " + msg + " ==")
banner("Room " + str(area(3, 4)))
  1. The last line runs first, because the lines above it only define the subroutines.
  2. To build the message it needs area(3, 4). Inside area, w = 3 and h = 4, so it returns 12.
  3. str(12) is "12", so the argument passed to banner is "Room 12".
  4. banner prints == Room 12 ==. A procedure returns nothing, so nothing comes back.

A function can call another function. The inner call is worked out first and its returned value is used where the call was: if double(n) returns n * 2, then double(double(3)) + 1 is double(6) + 1 = 13.

The rest of this lesson and its 7 practice questions are locked.

In this lesson

  1. Functions and procedures
  2. Scope
  3. Try it: Follow a function call

7 practice questions, marked as you go; about 20 minutes in all.

Key terms

Subroutine, Function, Procedure, Parameters, Arguments, Global

In this unit: Programming

Data types, operators, selection, loops, arrays, strings, subroutines, robust programs, SQL and files, read and traced step by step.

All of Programming