As you move through your lessons on programming you will find that you use more subroutines (procedures & functions) to save yourself time. As programmers it means we write fewer lines of code, which is brilliant but it also saves the computer time and effort too.
The great thing about a subroutine is that the computer doesn’t have to assign any memory to it until the program uses the code, and when the subroutine is over any memory that was used is recycled freeing up the space for something else.
At GCSE we study procedural programming and so the only two subroutine types that we need to be concerned about are procedures and functions. All subroutines are a block of code that has a name and sits outside of the main program – functions use this technique to process something and send a value back.
Functions are particularly good for calculations that you need to repeat and validation of your user’s input. In the following example, we will assume that we have already written the menu procedure in the previous section. Our function pseudocode would look something like:
allowedMenu = [‘Deutsch’, “English”, “Espanol”]
choice = INPUT
WHILE choice is NOT IN allowedMenu DO
OUTPUT “Not a Valid Choice”
choice = INPUT
In this case, I’ve added a WHILE loop that insists that my user makes a valid choice before I send their choice back to my program. A function is particularly good in this case because I can write my validation code once and call it many times throughout my program and because it will send a value back I can rest assured that my variables won’t hold any dodgy values!