AP Computer Science Principles · Algorithms and programming
Procedures
1Procedures and parameters
A procedure is a named group of instructions that can be called (used) many times. It may take parameters (inputs) and may return a value.
PROCEDURE area(width, height)
{
RETURN (width * height)
}a ← area(4, 5)
- Parameters (
width,height) are the names in the definition. - Arguments (4, 5) are the values supplied in a call.
RETURNsends a value back to where the procedure was called and ends the procedure.
Check yourself
In a ← area(4, 5), what are 4 and 5?
Show the answer
Arguments
Values passed in.
2Procedural abstraction
Procedural abstraction lets programmers use a procedure knowing what it does without knowing how it does it. Benefits:
- Reuse: write the code once, call it many times.
- Readability: a well-named call like
calculateTax(price)explains itself. - Easier changes: fixing or improving the procedure updates every call.
- Teamwork: different people write different procedures.
Parameters make procedures general: area(w, h) works for any rectangle, rather than one specific size.
Procedural abstraction: arguments go in, a value comes back
Check yourself
A procedure's internal code can be changed without affecting the programs that call it, as long as:
Show the answer
It still does the same task with the same inputs and outputs
Abstraction boundary.
3Libraries and APIs
A software library is a collection of procedures written by others that programs can use (e.g. for maths, graphics or maps).
An API (Application Program Interface) is the documentation that explains how to use a library's procedures: their names, parameters and what they return.
Libraries save time and use tested code, so programs are developed faster and more reliably.
RANDOM(a, b) in AP pseudocode is a built-in procedure returning a random whole number from a to b inclusive.
Check yourself
What does an API describe?
Show the answer
How to use the procedures in a library
Interface documentation.
4Calling and tracing procedures
When a procedure is called, the arguments are matched to the parameters in order, the procedure body runs, and the result replaces the call.
Worked example:
PROCEDURE bigger(a, b)
{
IF (a > b)
{
RETURN (a)
}
RETURN (b)
}
DISPLAY (bigger(3, 8) + bigger(10, 2))
bigger(3, 8)returns 8.bigger(10, 2)returns 10.- Displays 18.
A procedure that displays a value is different from one that returns it: a displayed value cannot be used in a later calculation.
Check yourself
What is displayed by DISPLAY (bigger(5, 5))?
Show the answer
5
a > b is false, so b is returned.
5Going deeper: parameters, return values and procedural abstraction
A procedure is a named group of instructions. It may take parameters and may return a value. Other languages call it a function or method.
PROCEDURE average(numList)
{
total ← 0
FOR EACH n IN numList
{
total ← total + n
}
RETURN(total / LENGTH(numList))
}
Parameters and arguments
- Parameters are the variables named in the procedure's definition (
numList). - Arguments are the actual values supplied in a call: in
average(scores), the argument isscores. - Arguments are matched to parameters in order.
Calling a procedure interrupts the normal sequence: control jumps to the procedure, its statements run, and control returns to the point just after the call.
RETURN
- Sends a value back to the caller and ends the procedure at once. Statements after a RETURN that has executed are not run.
- A returned value must be used: stored, displayed or tested.
result ← average(scores). - A procedure with no RETURN simply performs actions (such as displaying).
Worked example (trace):
PROCEDURE mystery(a, b)
{
IF (a > b)
{
RETURN(a - b)
}
RETURN(b - a)
}
first ← mystery(3, 8)
second ← mystery(first, 2)
DISPLAY(second)
mystery(3, 8): 3 > 8 is false; returns 8 − 3 = 5. first = 5.mystery(5, 2): 5 > 2 is true; returns 3. The second RETURN is never reached.- Displays 3.
Displaying is not returning. A procedure that DISPLAYs a result gives the caller nothing to compute with. If the value is needed later, RETURN it.
Procedural abstraction: giving a name to a process so that it can be used knowing only what it does, not how.
- To use
average, you need its name, its parameters and what it returns. You need not read its code. - This lets a programmer manage complexity: think about one small problem at a time.
Benefits
- Reuse: write once, call many times, with different arguments. No duplicated code.
- Readability:
IF (isPrime(n))says more than the ten lines inside it. - Easier testing and debugging: each procedure can be tested alone; an error is fixed in one place.
- Maintainability: the inside of a procedure can be rewritten (to be faster or more accurate) without changing any code that calls it, as long as its name, parameters and result stay the same.
- Collaboration: different people can write different procedures.
Parameters make a procedure general. Compare drawSquareOfSize5() with drawSquare(size): the second handles every size. Replacing several near-identical procedures with one parameterized procedure is a classic improvement.
Worked example (generalizing): a program has three blocks that each add up a list (one for quiz scores, one for homework, one for tests) and display the total.
- The three blocks differ only in which list they use.
- Write one procedure
total(aList)that returns the sum. - Call it three times.
- The program is shorter; a mistake in the adding logic is fixed once.
Modularity: dividing a program into separate procedures, each responsible for one sub-task.
Libraries and APIs
- A library is a collection of procedures written by others that can be used in new programs.
- An API (application program interface) specifies how the procedures in a library behave and how to call them: names, parameters, return values.
- Documentation for an API is essential: you use the procedures without seeing their code.
- Libraries save time and are usually well tested.
RANDOM(a, b), which returns a random integer from a to b inclusive, is a built-in example.
Worked example (using RANDOM): RANDOM(1, 6) simulates a die; each of 1 to 6 is equally likely. RANDOM(1, 100) ≤ 30 is true about 30% of the time.
Simulations rely on procedures and random numbers to model real situations more cheaply and safely than experiments; they are simplifications and may leave out factors.
In the Create performance task, you must write your own procedure that
- has a name and a return type or action;
- has at least one parameter that affects what it does;
- contains an algorithm with sequencing, selection and iteration;
and you must show where it is called.
Common mistakes
- Confusing parameter (in the definition) with argument (in the call).
- Displaying a result when it should be returned.
- Calling a returning procedure and ignoring the value.
- Expecting code after an executed RETURN to run.
- Supplying arguments in the wrong order.
- Describing abstraction as "making code shorter" without mentioning hiding detail.
Check yourself
What is the main benefit of procedural abstraction?
Show the answer
A procedure can be used knowing what it does without knowing how it does it
Hiding the detail lets programmers manage complexity and change the inside without affecting callers.
6For top marks
- Explain procedural abstraction with both ideas: hiding details and allowing reuse/generalisation through parameters.
- In the Create task, your procedure needs at least one parameter that affects its behaviour, plus selection and iteration.
- Distinguish RETURN from DISPLAY.
- Name procedures for what they do.
"The procedure checkAnswer(guess, answer) is called for every question; without it, the comparison code would be repeated ten times, and a change to the scoring rule would need ten edits."
Check yourself
Why does adding a parameter make a procedure more useful?
Show the answer
It lets the same procedure work for different inputs
Generalisation.
Now test yourself
This lesson has a 8-question quiz and 5 exam-style questions with mark schemes in Impera. Free, with your progress saved.
Practise in Impera