The examples below use AP CSP Pseudocode. For Java, see Methods with parameters.
In Writing and calling procedures in AP CSP Pseudocode, the careForBaby
procedure did the same thing each time it was called (displayed the same 3 phrases). Programmers often want procedures to perform differently each time they are called. A procedure can accept one more more parameters. The values of parameters can be used to affect how the procedure behaves when it is called.
It is up to the programmer to determine how the values of parameters are used. The values can be used as part of output. The values can be used to control which lines of code are executed.
Program using procedure with parameters
PROCEDURE careFor(name, isBaby)
{
DISPLAY("Feed")
DISPLAY(name)
if(isBaby)
{
DISPLAY("Burp")
DISPLAY(name)
DISPLAY("Change")
DISPLAY(name)
}
}
careFor("Evan", false)
careFor("Aubrey", true)
A procedure header specifies the name of each parameter in the parentheses to the right of the procedure name.
PROCEDURE careFor(name, isBaby)
Procedure careFor
accepts 2 parameters, name
and isBaby
.
Each call to a procedure specifies values for each of the procedure’s parameters.
The call careFor("Evan", false)
passes "Evan"
as the value of name
and false
as the value of isBaby
.
The call careFor("Aubrey", true)
passes "Aubrey"
as the value of name
and true
as the value of isBaby
.
The values passed to a procedure when it is called are known as arguments.
The careFor
procedure uses the value of its parameter name
as part of the output.
The careFor
method uses the value of its parameter isBaby
to determine whether or not to print 2 additional lines. See Working with boolean variables in AP CSP Pseudocode for additional information.
When writing the code inside a procedure that accepts parameters, assume that each parameter already has a value. The values of parameters are set when the procedure is called, not within the procedure itself.
Adjusted output
Spaces between outputs have been replaced with line breaks.
Feed Evan
Feed Aubrey
Burp Aubrey
Change Aubrey
Procedures with return values
A procedure can return 0 or 1 value to the code that called the procedure. See Procedures with return values in AP CSP Pseudocode for details.
Help & comments
Get help from AP CS Tutor Brandon Horn