Procedures, functions and maintainable programs

Computer Science · Programming. The idea in plain words, the rules to remember, the mistake to avoid and a worked example, written and checked by Mega Lecture.

Test this topic freeAll Computer Science topics

The idea

A subroutine is a named block of code that does one job. You write it once and call it whenever it is needed. A procedure carries out a task and does not return a value. A function carries out a task and always returns one value to the place where it was called.

A parameter is a value passed into a subroutine when it is called. A local variable is declared inside a subroutine and exists only there. A global variable is declared in the main program and can be used anywhere.

Library routines are ready-made functions. A maintainable program is one that another programmer can read, understand and change easily.

In simpler words

A subroutine is a named block of code that does one job. You write it once and use it many times. A procedure does a task and gives nothing back. A function does a task and always returns one value. Parameters pass values in. Local variables only live inside the subroutine. Global variables can be used anywhere.

An everyday comparison

A function is like a calculator: you type in two numbers and it hands back one answer for you to use. A procedure is like a printer: you send it a job and it does the task, but nothing comes back. The comparison stops working because a function's returned value must be used in the program, for example stored in a variable.

Rules to remember

Common mistake

A function is not called with CALL. Its returned value must be used, for example assigned to a variable or output. CALL is only for procedures.

In the exam

Write the full header, for example FUNCTION Area(L : INTEGER, W : INTEGER) RETURNS INTEGER, then the body and ENDFUNCTION. Include RETURN in every function. Call a procedure with CALL, and use a function inside an expression. Define local and global variables. For maintainable programs, list features: meaningful identifiers, comments, subroutines and indentation, each with its benefit.

Worked example

What is output by this program?
FUNCTION Area(L : INTEGER, W : INTEGER) RETURNS INTEGER
    RETURN L * W
ENDFUNCTION

OUTPUT Area(3, 4) − Area(2, 5)

  1. Area(3, 4): L = 3 and W = 4, so it returns 3 * 4 = 12.
  2. Area(2, 5): L = 2 and W = 5, so it returns 2 * 5 = 10.
  3. The two returned values are subtracted: 12 − 10 = 2.

Answer: 2

Ask about this

Type what you are stuck on. The helper finds the explanation, worked examples and the notes to read, free and instant.

Keep going

← Sequence, selection, iteration and string handlingArrays and file handling →Take a Computer Science test