AP® Computer Science Principles · Big Idea 3 · Topic 3.13
Writing Procedures with Parameters
A parameter is a placeholder in a procedure's definition that gets replaced by whatever value is passed in when the procedure is called, turning one fixed-case procedure into one that works for a whole range of inputs.
A procedure without parameters can only ever do the one thing it was written to do. If drawSquare always draws a square of size 50, that 50 is baked into the code, and the only way to draw a different size is to write a whole new procedure. A parameter fixes this by replacing that literal value with a name, like size, that stands in for whatever value the caller sends when they call the procedure. The body of the procedure is written in terms of size, not 50, so the same code runs correctly no matter what size turns out to be.
Mechanically, when you call a procedure with an argument, that argument's value gets copied into the parameter's name for the duration of that call. Call drawSquare(50) and size becomes 50; call drawSquare(12) and size becomes 12, same code, different outcome. This is why a procedure like square(side) that computes side times side can take the argument 9 and return 81 just by substituting 9 everywhere side appears. Nothing about the procedure's logic changes between calls, only the value plugged into the parameter.
This generalization is what makes procedures worth writing in the first place. A repeated block of code copied five times with slightly different numbers becomes one procedure called five times with five different arguments, which shrinks the program and means a bug only needs fixing in one place. Parameters are also what connect procedures to the rest of the course's toolkit: a loop can call the same procedure with a different argument on each pass, which is how parameters and iteration combine to do large amounts of varied work from a small amount of code.
Key terms
- Parameter
- A named placeholder in a procedure's definition that receives a value when the procedure is called.
- Argument
- The actual value passed into a procedure call, which fills in for the parameter during that call.
- Procedure
- A named, reusable block of code that performs a task and can be called whenever that task is needed.
- Generalization
- Rewriting specific code so it works correctly across a whole range of inputs instead of just one.
Watch it explained
- How it worksHow do parameters generalize a procedure so it works across a whole range of inputs?
- Worked exampleShow me turning a procedure that always draws a square of size 50 into one that takes a size.
- Worked exampleFind what a procedure returns when it computes side times side for the argument 9.
- Going furtherWhat changes about a program when a repeated block becomes a procedure with parameters?
Check yourself
End of topic.