±«Óătv

Using subprograms to produce structured code

Subprograms are small that are written within a larger, main program. The purpose of a subprogram is to perform a specific task. This task may need to be done more than once at various points in the main program.

There are two types of subprogram:

  • procedures
  • functions

Benefits of using subprograms

  • Subprograms are usually small in size, meaning they are much easier to write, test and . They are also easy for someone else to understand.
  • Subprograms can be saved separately as modules and used again in other programs. This saves time because the programmer can use code that has already been written, tested and debugged.
  • A subprogram may be used repeatedly at various points in the main program. However, the code only has to be written once, resulting in shorter programs.

Procedures

A procedure is a subprogram that performs a specific task. When the task is complete, the subprogram ends and the main program 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:

procedure identifier (value to be passed)
     procedure code
endprocedure

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

procedure clear_screen(x)
    for i = 1 to x: 
    print(" ")
endprocedure

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 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:

function f_to_c(temperature_in_f)
     temperature_in_c= (temperature_in_f –32) * 5/9
     return temperature_in_c
endfunction

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.

Built-in functions

Many languages include built-in, ready-made functions:

  • int - converts strings or floats into
  • str - converts a number into a string
  • asc - finds the ASCII number of a character

Additionally, some languages allow functions to be added in from external files called libraries. Libraries contain pre-written, tested functions that extend the functionality of a language.