AP Computer Science Principles · Study guide

Calling Procedures

AP® Computer Science Principles · Big Idea 3 · Algorithms and Programming

Calling Procedures

What happens when a program calls a procedure: how arguments fill parameters, how control jumps to the procedure and back, the difference between RETURN and DISPLAY, and how to use procedures someone else wrote.

1What a procedure is

A procedure is a named group of programming instructions that may take inputs and may send back a value. Different programming languages call it a method or a function; it is the same idea. Once a procedure exists, any part of a program can use it by calling it by name, without knowing or rewriting the steps inside.

Reference language: define, call, call and keep the returned value
PROCEDURE procName(parameter1, parameter2, ...)
{
  <block of statements>
}

procName(arg1, arg2, ...)
result ← procName(arg1, arg2, ...)

2Arguments and parameters

Parameters are the input variables named in the procedure's definition. Arguments are the actual values supplied when it is called. The first argument is assigned to the first parameter, the second to the second, and so on. A procedure can also take no arguments at all, like INPUT().

PROCEDURE rectArea(width, height)
{
  RETURN(width * height)
}
a ← rectArea(4, 6)
DISPLAY(a)
DISPLAY(rectArea(10, 3) + 1)
Figure 1. The first argument goes to the first parameter, the second to the second, and so on. Names don't matter; order does.

This displays 24, then 31. In the second call, width is 10 and height is 3, so the call is worth 30, and 1 is added to it. A call that returns a value can sit anywhere a value can: on the right of ←, inside an expression, or as an argument to another call.

3The call is a detour

A procedure call interrupts the normal top-to-bottom order. The program jumps to the procedure, runs its statements, and once the last statement (or a RETURN) has run, control goes back to the point immediately after the call.

PROCEDURE greet(name)
{
  DISPLAY("hello")
  DISPLAY(name)
}
DISPLAY("start")
greet("Lee")
DISPLAY("end")
Figure 2. The numbers give the order the statements run. Displayed: start hello Lee end.

The procedure's definition comes first in the code, but nothing in it runs until it is called. The program displays start hello Lee end.

4RETURN and DISPLAY

StatementWhat it does
RETURN(expression)Sends the value of expression back to where the procedure was called, and ends the procedure right away
result ← procName(...)Stores the returned value in result
DISPLAY(expression)Shows the value on the screen, followed by a space; nothing is sent back

RETURN ends the procedure. Any statements after it in that call are skipped:

PROCEDURE sign(n)
{
  IF (n < 0)
  {
    RETURN("negative")
  }
  DISPLAY("checking")
  RETURN("not negative")
}
DISPLAY(sign(-4))
DISPLAY(sign(9))

This displays negative checking not negative. For −4 the first RETURN runs, so "checking" is never displayed for that call. For 9, the IF is skipped, "checking" is displayed, and the second RETURN runs.

DISPLAY is not RETURN. A procedure that only displays sends nothing back:

PROCEDURE showDouble(n)
{
  DISPLAY(n * 2)
}
PROCEDURE double(n)
{
  RETURN(n * 2)
}
x ← double(5)
y ← showDouble(5)

The screen shows 10 once (from showDouble). x holds 10, because double returned it. y holds no value at all: showDouble showed a number but returned nothing, so there was nothing to store. If a later line needs the number, the procedure must RETURN it.

The key idea

Calling a procedure copies the arguments into the parameters by position, runs the procedure, and continues at the line right after the call. RETURN ends the procedure and hands a value back to the caller; DISPLAY only shows a value.

5Getting input

INPUT() is a procedure with no arguments that accepts a value from the user and returns it, so it can be used on the right of ←.

age ← INPUT()
IF (age ≥ 13)
{
  DISPLAY("account created")
}
ELSE
{
  DISPLAY("ask a parent")
}

If the user types 15, this displays account created; if the user types 11, it displays ask a parent. The same code gives different output for different input, which is why testing a program means trying several inputs.

One more rule about parameters: a parameter holds a copy of the argument's value. Changing the parameter inside the procedure does not change the caller's variable.

PROCEDURE addTen(n)
{
  n ← n + 10
  RETURN(n)
}
score ← 50
newScore ← addTen(score)
DISPLAY(score)
DISPLAY(newScore)

This displays 50, then 60. Inside addTen, n became 60, but score was never touched. The only way the new value got out was through RETURN.

6Using procedures you are given

Often you use procedures you did not write, knowing only what each one does. Suppose a program has these:

ProcedureWhat it does
combine(a, b)Returns a new list with the elements of a followed by the elements of b
sort(lst)Returns a copy of lst in increasing (alphabetical) order
removeDups(lst)Returns a copy of lst with each run of repeated neighbors cut to one element; it only removes all duplicates if lst is sorted

Task: count the students who are on both the track team and in the band. Track: Ito, Ruiz, Gale, Moss. Band: Lane, Moss, Ito, Webb, Cole.

bothList ← combine(track, band)
sorted ← sort(bothList)
unique ← removeDups(sorted)
DISPLAY(LENGTH(bothList) - LENGTH(unique))

A student on both lists appears twice in bothList. Sorting puts the two copies next to each other, and removeDups drops one of them. So the drop in length is the number of students on both lists: the program displays 2 (Ito and Moss).

Skip the sort and it displays 0: the duplicate names are not next to each other, so removeDups removes nothing. With given procedures, read each description carefully, especially requirements like “only works if sorted.”

7Worked examples

Worked Example 1 Trace a call

Adding tax

What is displayed?

PROCEDURE tax(amount)
{
  RETURN(amount * 0.1)
}
bill ← 80
total ← bill + tax(bill)
DISPLAY(total)
  1. 1
    tax(bill) passes 80 to the parameter amount.
  2. 2
    It returns 80 * 0.1 = 8, which replaces the call in the expression: total ← 80 + 8.
Answer: 88
Worked Example 2 Write a call

The largest of three

A procedure larger(a, b) returns the larger of its two arguments. Write one statement that sets biggest to the largest of x, y, and z, and check it with x = 12, y = 30, z = 21.

PROCEDURE larger(a, b)
{
  IF (a > b)
  {
    RETURN(a)
  }
  RETURN(b)
}
  1. 1
    The inner call larger(x, y) gives the larger of x and y.
  2. 2
    Pass that result as the first argument of a second call:
    biggest ← larger(larger(x, y), z)
    DISPLAY(biggest)
  3. 3
    With 12, 30, 21: larger(12, 30) is 30, then larger(30, 21) is 30.
Answer: biggest ← larger(larger(x, y), z) displays 30. A program checked it on orders where the largest comes first, second, or third, with ties, and with negative numbers.
Worked Example 3 Trace a call

Display inside, return outside

What is displayed?

PROCEDURE mystery(a, b)
{
  DISPLAY(a)
  a ← a + b
  RETURN(a * 2)
}
x ← 3
DISPLAY(mystery(x, 4))
DISPLAY(x)
  1. 1
    The call copies 3 into a and 4 into b. The first statement displays 3.
  2. 2
    a becomes 7 (only the parameter changes; x is still 3). RETURN sends back 14, which the outer DISPLAY shows.
  3. 3
    Then DISPLAY(x) shows 3.
Answer: 3 14 3
Worked Example 4 Reuse a procedure

Hot days

What is displayed?

PROCEDURE countAbove(nums, limit)
{
  count ← 0
  FOR EACH n IN nums
  {
    IF (n > limit)
    {
      count ← count + 1
    }
  }
  RETURN(count)
}
temps ← [71, 84, 90, 66, 88]
DISPLAY(countAbove(temps, 85))
DISPLAY(countAbove(temps, 60))
  1. 1
    First call: limit is 85. Above 85: 90 and 88.
  2. 2
    Second call: limit is 60. All five temperatures are above 60.
  3. 3
    Each call starts fresh with count at 0.
Answer: 2 5. One procedure, two answers, because the argument changed.

8Common mistakes

Common Mistake 1 · Matching arguments by name

Arguments go to parameters by position. rectArea(6, 4) makes width 6, whatever the variables in the call are named.

Common Mistake 2 · Continuing after RETURN

RETURN ends the procedure at once. Statements after it in that call do not run.

Common Mistake 3 · Storing a value that was only displayed

A procedure without RETURN gives nothing to store. Showing a value on the screen is not the same as sending it back.

Common Mistake 4 · Expecting the caller's variable to change

A parameter is a copy. Changing it inside the procedure leaves the argument's variable as it was; return the new value instead.

Describe a procedure call like this

“The call tax(bill) assigns 80 to the parameter amount. The procedure returns 8, flow of control goes back to the statement that made the call, and 80 + 8 is stored in total, so 88 is displayed.”

Say which argument goes to which parameter, what the procedure returns or displays, and where the program continues.