teach-ict.com logo

THE education site for computer science and ICT

Subroutines and functions

3. Building up a sub-procedure

The previous page has this block of code;

 
                 FirstName = "Joe"
                 SecondName = "Smith"
                 FullName = FirstName + SecondName
                 Print FullName

 
                 FirstName = "Lousie"
                 SecondName = "Brown"
                 FullName = FirstName + SecondName
                 Print FullName                
                 
                 FirstName = "Mandy"
                 SecondName = "Jones"
                 FullName = FirstName + SecondName
                 Print FullName
                 

The code in red is just doing the same thing, over and over. In order to create a sub-procedure, take this block of code and enclose is in a procedure statement, like this

                procedure
                 FullName = FirstName + SecondName
                 Print FullName
                end procedure

This block of code needs to be given a sensible name in order to use it - let's call it print_name as shown below

                procedure print_name
                 FullName = FirstName + SecondName
                 Print FullName
                end procedure

We are still not quite there yet, because the code is using two variables FirstName and SecondName but these need to be defined before they can be used. So let's supply that information to the procedure. Like this

                procedure print_name (FirstName, SecondName)
                 FullName = FirstName + SecondName
                 Print FullName
                end procedure

We can describe a subroutine as:

A subroutine is a block of code intended to be used a number of times within a program. The code is packaged as a single, named, unit.

 

The next page will show how this new procedure is used.

Challenge see if you can find out one extra fact on this topic that we haven't already told you

Click on this link: What is a subroutine?