AP CSP topic 3.13
Developing Procedures
Writing your own procedures is procedural abstraction: you give a task a name and use it without thinking about the details each time. Parameters make a procedure general, so one procedure like area(width, height) works for any rectangle. Breaking a big problem into smaller procedures makes code easier to read, test, and fix, and a change inside a procedure updates everywhere it is used.
Developing Procedures vocabulary
- Procedural abstraction: Naming a process so it can be used by knowing what it does, not how.
- Parameter: A variable in a procedure definition that receives an argument.
- Modularity: Dividing a program into separate parts that each do one job.
- RETURN: Ends a procedure and sends a value back to the caller.
AP-style practice questions
Try each one, then open the answer. To save your progress, take this quiz in the interactive course.
PROCEDURE area(width, height)
{
RETURN (width * height)
}
1. Which of the following is the main benefit of using parameters in this procedure?
- (A) The procedure runs faster
- (B) The same procedure can find the area of any rectangle
- (C) The procedure no longer needs to return a value
- (D) It prevents all logic errors
Show answer
(B) The same procedure can find the area of any rectangle Parameters generalize a procedure so it works for many inputs.
2. A program draws 20 houses by repeating the same 15 lines of code for each one. Which change would best improve the program?
- (A) Write a procedure drawHouse(x, y) and call it 20 times
- (B) Copy the 15 lines 20 more times
- (C) Add more comments
- (D) Remove the houses
Show answer
(A) Write a procedure drawHouse(x, y) and call it 20 times Procedural abstraction removes repeated code and makes changes easier.
3. A programmer fixes a bug inside a procedure that is called in 12 places. Which of the following is true?
- (A) The bug must be fixed 12 separate times
- (B) The fix applies everywhere the procedure is called
- (C) The procedure must be renamed
- (D) The program must be rewritten without procedures
Show answer
(B) The fix applies everywhere the procedure is called Changing the procedure updates every call, a key benefit of modularity.
4. Which of the following procedures correctly returns true when n is a positive number and false otherwise?
- (A) PROCEDURE isPositive(n) { RETURN (n > 0) }
- (B) PROCEDURE isPositive(n) { RETURN (n < 0) }
- (C) PROCEDURE isPositive(n) { DISPLAY(n) }
- (D) PROCEDURE isPositive(n) { RETURN (n) }
Show answer
(A) PROCEDURE isPositive(n) { RETURN (n > 0) } n > 0 is a Boolean expression that is true exactly for positive numbers.