AP CSP Day 70: Procedure Parameters and Variable Scope | Cycle 3
Share
In AP CSP pseudocode, procedure parameters are local. Changing a parameter inside a procedure does not affect the variable that was passed in. The RETURN value is the only way a procedure communicates a result back. If a procedure modifies its parameter and returns nothing, the original variable is unchanged.
Study the Concept First (Optional) Click to expand ▼
Parameters vs. Global Variables
Pass by Value
When you call myProc(x), the procedure receives a COPY of x’s value. Modifying the parameter does not change x in the calling code. The only way to send back a result is with RETURN.
Return Value Assignment
To capture a procedure’s result, the calling code must assign it: result ← myProc(x). If the call is just myProc(x) without assignment, the return value is discarded.
Practice Question
Consider the following code segment.
PROCEDURE transform(val)
{
val ← val + 10
val ← val * 2
RETURN(val)
}
x ← 5
y ← transform(x)
DISPLAY(x)
DISPLAY(" ")
DISPLAY(y)What is displayed as a result of executing the code segment?
x is set to 5. When transform(x) is called, a copy of 5 goes to val. Inside: val becomes 5 + 10 = 15, then 15 * 2 = 30. The procedure returns 30. y receives 30. The original x is still 5 because the procedure only modified its local copy. Output: 5 30.
A) Assumes x was modified by the procedure. The parameter val is a local copy; x remains 5. B) Assumes val ← val + 10 affected x (making it 15). Parameters are always local. D) Assumes the multiplication was not applied, returning val after only the addition.
Students believe that because x was passed to the procedure, changes to val are reflected in x. In AP pseudocode, parameters are passed by value. The original variable is never modified.
When tracing a procedure call, create a separate “scope box” for the procedure. Copy the argument values into the parameter names. Trace inside the box. Only the RETURN value crosses back to the caller.
Keep Practicing!
Consistent daily practice is the key to AP CSP success.
AP CSP Resources Get 1-on-1 Help