AP CSP Practice: Procedures & Return Values
Share
Practice Question
PROCEDURE mystery(a, b)
{
IF (a > b)
{
RETURN a - b
}
ELSE
{
RETURN b - a
}
}
mystery(8, 15)?Step-by-Step Trace
Call: mystery(8, 15)
Parameters: a = 8, b = 15
| Step | Code | Evaluation |
|---|---|---|
| 1 | IF (a > b) | IF (8 > 15) → FALSE |
| 2 | Go to ELSE branch | — |
| 3 | RETURN b - a | RETURN 15 - 8 = 7 |
What Does This Procedure Do?
This procedure calculates the absolute difference between two numbers:
- If a > b, return a - b (positive result)
- If b ≥ a, return b - a (positive result)
The result is always positive because it always subtracts the smaller from the larger!
// Examples:
mystery(10, 3) → 10 - 3 = 7 // a > b, use IF branch
mystery(3, 10) → 10 - 3 = 7 // b > a, use ELSE branch
mystery(5, 5) → 5 - 5 = 0 // equal, use ELSE branch
Common Mistakes
If you got -7, you calculated a - b (8 - 15) instead of b - a. Since 8 is NOT greater than 15, we use the ELSE branch, which computes b - a = 15 - 8 = 7.
The procedure subtracts values, not adds them. 8 + 15 = 23, but the code says RETURN b - a.
In mystery(8, 15), the first value (8) becomes 'a' and the second value (15) becomes 'b'. Parameter order matters!
When tracing procedures: (1) Write down what each parameter equals, (2) Evaluate conditions with those values, (3) Follow ONLY the branch that executes. Don't try to hold everything in your head—write it out!
Want More AP CSP Practice?
Get personalized help from an experienced AP CS teacher
AP CSP Study Guide Schedule 1-on-1 Tutoring