The examples below use AP CSP Pseudocode. For Java, see Writing and calling methods.

It is possible to write very large programs without procedures. Most programmers prefer to break up their programs using procedures. Procedures offer advantages including:

Procedures are also known as functions or methods.

Program written entirely without procedures

DISPLAY("Daily schedule")

DISPLAY("Wake up")
DISPLAY("Make breakfast")

DISPLAY("Feed the baby")
DISPLAY("Burp the baby")
DISPLAY("Change the baby")

DISPLAY("Make lunch")

DISPLAY("Feed the baby")
DISPLAY("Burp the baby")
DISPLAY("Change the baby")

DISPLAY("Hope that the baby naps")

DISPLAY("Make dinner")

DISPLAY("Feed the baby")
DISPLAY("Burp the baby")
DISPLAY("Change the baby")

Note that the code to handle the baby is repeated.

Program written with careForBaby procedure

PROCEDURE careForBaby()
{
    DISPLAY("Feed the baby")
    DISPLAY("Burp the baby")
    DISPLAY("Change the baby")
}

DISPLAY("Daily schedule")
DISPLAY("Wake up")
DISPLAY("Make breakfast")

careForBaby();

DISPLAY("Make lunch")

careForBaby()

DISPLAY("Hope that the baby naps")
DISPLAY("Make dinner")

careForBaby()

The code to care for the baby has been moved to the careForBaby procedure. The careForBaby procedure can be written and tested independently from the rest of the program. Each time the careForBaby procedure is called, the code inside is run.

The procedure has a header:

PROCEDURE careForBaby()

The code inside the careForBaby procedure is run by calling the procedure: careForBaby(). Each time the careForBaby procedure is called, the code inside is executed before the code continues.

Adjusted output of both programs

Note: The DISPLAY procedure is defined as displaying its parameter followed by a space. The spaces have been replaced by line breaks below to make the repeated output clearer.

Daily schedule
Wake up
Make breakfast
Feed the baby
Burp the baby
Change the baby
Make lunch
Feed the baby
Burp the baby
Change the baby
Hope that the baby naps
Make dinner
Feed the baby
Burp the baby
Change the baby

Both programs produce the same output in the same order.

Procedures with parameters

AP CSP Pseudocode procedures can accept parameters that can be used to affect how the procedure behaves when called. See Procedures with parameters in AP CSP Pseudocode for details.

Help & comments

Get help from AP CS Tutor Brandon Horn

Comment on Writing and calling procedures in AP CSP Pseudocode