Programming concepts - AQAProcedures and functions of subroutines

Programs are designed using common building blocks, known as programming constructs. These programming constructs form the basis for all programs.

Part ofComputer ScienceComputational thinking and problem solving

Procedures and functions of subroutines

There are two types of subroutine:

  • procedures
  • functions

Procedures

A procedure is a subroutine that performs a specific task. When the task is complete, the subroutine ends and the main continues from where it left off. For example, a procedure may be written to reset all the values of an array to zero, or to clear a screen.

A procedure is created using the following syntax:

SUBROUTINE identifier (parameters) procedure code
ENDSUBROUTINE

This procedure would clear the screen by printing x blank lines:

SUBROUTINE clear_screen(lines) FOR count <- 1 TO lines OUTPUT " " ENDFOR
ENDSUBROUTINE

A procedure is run by calling it. To call it, a programmer uses the procedure name and includes any parameters (values) that the procedure needs, for example:

clear_screen(5)

This would print five blank lines on the screen.

Functions

A function works in the same way as a procedure, except that it manipulates and returns a result back to the main program.

For example, a function might be written to turn Fahrenheit into Celsius:

SUBROUTINE f_TO_c(temperature_in_f) temperature_in_c ← (temperature_in_f –32) * 5/9 RETURN temperature_in_c
ENDSUBROUTINE

A function is run by calling it. To call it, a programmer uses the function's identifier, the value to be passed into the function, and a variable for the function to return a value into, for example:

celsius ← f_to_c(32)

This would result in the value of Celsius being zero.

Note: AQA pseudo-code does not use a different keyword to show the difference between a procedure and a function. Instead, it adds a RETURN to show that a subroutine is a function.