Sub Programs

Sub Programs

Understanding Sub Programs

  • Sub programs are separate pieces of code performing specific tasks within a larger program.
  • They can be defined as functions, which return a value, or procedures, which execute instructions but don’t return a value.
  • Sub programs are also known as routines, methods or subroutines in different contexts or programming languages.

Benefits of using Sub Programs

  • They increase readability and manageability of code by breaking larger, complex tasks into smaller, more understandable components.
  • Allow for code reusability, which means the same piece of code can be used multiple times within a program without repeating it.
  • Can help to make debugging easier. By isolating specific tasks or procedures, any problems occurring within those tasks can be identified and fixed more easily.

Function

  • A function returns a value to the place where the function was called from. It can make a computation and the result can be stored in a variable or used immediately.
  • Functions are defined with a function name, parameters (input) and a return value (output).

Procedure

  • A procedure is a set of programming instructions that perform a specific task, for which no value is returned.
  • Similar to functions, they have a procedure name and can have parameters but they do not return a value.
  • Can be used for tasks such as print to screen or saving data to a file.

Local and Global Variables

  • Variables defined within sub programs are called local variables. Their scope is limited to the specific sub program, they cannot be accessed by other parts of the program.
  • Global variables are declared outside all sub programs. They can be accessed from any part of the program, including sub programs. However, global variables can lead to erroneous behaviour if not managed properly, and can also make debugging more difficult.

Parameter Passing

  • Parameter passing enables data to be passed into a sub program when it is called. This data is then used as part of the execution of the sub program.
  • Parameters are listed in the parentheses following the function or procedure name.
  • There are two main types of parameter passing: pass-by-value, where a copy of the data is passed to the sub program, and pass-by-reference, where a reference to the actual data is passed. The difference impacts whether or not the original data can be modified by the sub program.