Sub Programs (OCR GCSE Computer Science): Revision Notes
📚 Revision Notes
Sub Programmes
Sub programmes are smaller, reusable blocks of code that are used to structure larger programmes. They allow you to break down complex problems into smaller, manageable tasks. The two main types of sub programmes are functions and procedures.
Functions and Procedures
- Functions and procedures both help to create structured code by organising logic into independent blocks.
- Functions return a value after performing a task, whereas procedures do not return a value.
| Type | Definition | Example |
|---|---|---|
| Function | A sub programme that returns a value. |
function triple(number)
return number * 3
endfunction
Calling:y = triple(7)| | Procedure | A sub programme that performs a task but does not return a value. |procedure greeting(name)
print("Hello " + name)
endprocedure
Calling:greeting("Hamish")|
Using Sub Programmes Effectively
- Functions and procedures can be used to improve code structure by avoiding repetition, making the programme easier to read and maintain.
- They allow modular programming, where each part of the programme does one thing and can be reused in different contexts.
Where to Use Sub Programs
- When performing repetitive tasks to avoid code duplication.
- To break down a complex problem into simpler, smaller tasks.
- When returning a specific result (use a function) or just executing a task without needing a return value (use a procedure).
Local and Global Variables
Sub programmes can use two types of variables:
- Local variables/constants: Declared inside a sub programme and only accessible within it. These are useful for keeping data isolated to avoid conflicts with other parts of the programme.
- Global variables/constants: Declared outside any sub programme and accessible throughout the entire programme. Be cautious when using global variables as they can cause unintended side effects if modified unexpectedly.
Arrays in Sub Programmes
Arrays can be passed to and returned from sub programmes, allowing the manipulation of multiple values at once:
Passing an Array
Arrays can be passed into sub programmes as arguments, allowing you to perform operations on large sets of data.
Example:
procedure printNames(names)
for name in names:
print(name)
endprocedure
Calling: printNames(["Bob", "Alice", "Eve"])
Returning an Array
Functions can also return arrays, which allows them to process and return multiple values at once.
Example:
function getMultiples(numbers)
for i in range(0, len(numbers)):
numbers[i] = numbers[i] * 2
return numbers
endfunction
infoNote
Key Points to Remember
- Functions return a value, while procedures do not.
- Sub programmes use local and global variables, but local variables help avoid conflicts within the programme.
- Arrays can be passed to and returned from sub programmes, making them useful for processing lists of data efficiently.