A subroutine is a set of instructions inside an algorithm stored under one name.
Subroutines save us from repeating the same code over and over again. They give your program more structure and readability whilst reducing the amount of code you have to write.
There are two types of subroutines: functions and procedures.
A procedure is a subroutine which doesn't return a value.
Example 1 shows a procedure to output the string "Hello".
Example 1
SUBROUTINE greeting1()
OUTPUT "Hello"
ENDSUBROUTINE
Now, when we want to use this procedure, we can call it like this: greeting1()
Subroutines can also take parameters (inputs)
Example 2 shows a procedure to output the string "Hello " + the user's name.
Example 2
SUBROUTINE greeting2(name)
OUTPUT "Hello" + name
ENDSUBROUTINE
Now, if this procedure is called with the code
greeting2("Rujul"),
it will output "Hello Rujul".
A function is a subroutine which does return a value.
The return value of a function can be assigned to a variable.
We have already looked at and used several built-in functions in pseudo-code,
including LEN, POSITION, STRING_TO_INT,
and many more.
Example 3 shows a function to convert inches to centimetres.
Example 3
SUBROUTINE inches_to_cms(inches)
RETURN inches * 2.54
ENDSUBROUTINE
input ← USERINPUT
cms ← inches_to_cms(input)
OUTPUT cms, "cm"
Example 4 shows a function to return the maximum of two numbers.
Example 4
SUBROUTINE max(a, b)
IF a > b THEN
RETURN a
ELSE
RETURN b
ENDIF
ENDSUBROUTINE
Make one change to the body of the
max function in Example 4 to make it return the minimum instead of the maximum.
Tap/click to reveal
Change a > b to a < b.