Sub Programs
A sub program is a named section of code that performs a single job. You write it once, then call it whenever that job needs doing, so its instructions exist in one place only.
When a program reaches a call, it does not carry on down the page. Control jumps to the sub program, runs its lines in order, then returns to the line immediately after the call. The body of a sub program is stepped over where it is defined and only runs when it is called, so the order the lines run in is not the order they appear in the file.
Imagine a program that prints a joining letter for each of three after-school clubs: chess, art and coding. The letter-writing steps sit inside one sub program. The main program calls it three times, once for each club. Each time, control jumps in, prints that club's letter, and comes back ready for the next call. Reading the code from top to bottom shows you where the sub program lives, not the order things happen when it runs.
Procedures and functions are the two kinds of sub program, and the general name for a named block of code you call is a subroutine. A procedure carries out a task, while a function sends a value back to the code that called it. Either way, the block is written once and only runs when it is called.
OCR GCSE Computer Science · Sub Programs