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:
- allowing a programmer to focus on a small part of a program at a time.
- facilitating testing each part of a program independently.
- reusing the same code without writing it multiple times.
- simplifying changes and additions to the larger program.
- allowing team members to work on different parts of a program at the same time.
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()
careForBaby
is the name of the procedure.- The blank parentheses
()
indicate that the procedure does not take parameters. - The code inside the brackets
{
and}
is the body of the procedure.
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