Procedures and functions#

Note

A function can returns a value while procedure does not.

Sometimes we copy and paste our code#

FirstName ← "Larry"
OUTPUT "task completed"
OUTPUT ""

FOR Index ← 0 TO 9
  OUTPUT Index
NEXT Index
OUTPUT "task completed"
OUTPUT ""

Use functions instead of repeating code#

PROCEDURE PrintIt
  OUTPUT "task completed"
  OUTPUT ""
ENDPROCEDURE

FirstName ← "Larry"
CALL PrintIt

FOR Index ← 0 TO 9
  OUTPUT Index
NEXT Index
CALL PrintIt

What if I want a different message displayed?#

FirstName ← "Larry"
OUTPUT "first name assigned"
OUTPUT ""

FOR Index ← 0 TO 9
  OUTPUT Index
NEXT Index
OUTPUT "loop completed"
OUTPUT ""

Pass the task name as a parameter#

PROCEDURE PrintIt(TaskName : STRING)
  OUTPUT TaskName
  OUTPUT ""
ENDPROCEDURE

FirstName ← "Larry"
CALL PrintIt("first name assigned")

FOR Index ← 0 TO 9
  OUTPUT Index
NEXT Index
CALL PrintIt("loop completed")

Here’s another example where the code looks different but we are doing the same logic over and over#

OUTPUT "Enter your first name: "
INPUT FirstName
FirstNameInitial ← FirstName[0]
OUTPUT "Enter your last name: "
INPUT LastName
LastNameInitial ← LastName[0]

OUTPUT "Your initials are: ", FirstNameInitial, LastNameInitial

I can still use a function, but this time my function returns a value#

FUNCTION GetInitial(Name : STRING) RETURNS STRING
  DECLARE Initial : STRING
  Initial ← Name[0]
  RETURN Initial
ENDFUNCTION

OUTPUT "Enter your first name: "
INPUT FirstName
FirstNameInitial ← GetInitial(FirstName)
OUTPUT "Enter your last name: "
INPUT LastName
LastNameInitial ← GetInitial(LastName)

OUTPUT "Your initials are: ", FirstNameInitial, LastNameInitial

If you need to change something you only have to change it in one place!#

FUNCTION GetInitial(Name : STRING) RETURNS STRING
  DECLARE Initial : STRING
  Initial ← UCASE(Name[0])
  RETURN Initial
ENDFUNCTION

OUTPUT "Enter your first name: "
INPUT FirstName
FirstNameInitial ← GetInitial(FirstName)
OUTPUT "Enter your last name: "
INPUT LastName
LastNameInitial ← GetInitial(LastName)

OUTPUT "Your initials are: ", FirstNameInitial, LastNameInitial

Functions that return values allow clever code, but you might trade readability for less code#

FUNCTION GetInitial(Name : STRING) RETURNS STRING
  DECLARE Initial : STRING
  Initial ← Name[0]
  RETURN Initial
ENDFUNCTION

OUTPUT "Enter your first name: "
INPUT FirstName
OUTPUT "Enter your last name: "
INPUT LastName

OUTPUT "Your initials are: ", GetInitial(FirstName), GetInitial(LastName)

Tips#

Tip

  • Functions make your code more readable and easier to maintain

  • Always add comments to explain the purpose of your functions

  • Functions must be declared before the line of code where the function is called