大象传媒

Types of subroutines - procedures and functions

There are two types of subroutine:

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 to zero, or to clear a screen.

A procedure is created using the following :

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 (values) that the procedure needs, for example:

clear_screen(5)

This would print five blank lines on the screen.

Functions

A 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 , 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.

Local variables

A local variable is a variable that is used in one specific section of code, such as within a subroutine. Outside of the subroutine, the variable cannot be accessed or changed.

This subroutine, which prints 鈥楬ello!鈥 5 times on the screen contains a local variable, lines:

SUBROUTINE print_hello() lines = 5 FOR count <- 1 TO lines
  OUTPUT "Hello!"
 ENDFOR
ENDSUBROUTINE

Outside of the subroutine, it鈥檚 as if the variable does not exist. Its use, or scope, is limited to the subroutine only.

Because a local variable is confined to the subroutine, a programmer can reuse the variable name again in other parts of the program. For example, the same variable name could be used in several subroutines, meaning the programmer does not have to worry about always using a different variable name.