AP Computer Science Principles · Study guide

Developing Procedures

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

Developing Procedures

How to write your own procedures, and why breaking a program into named procedures with parameters makes it shorter, easier to read, easier to fix, and easier to improve.

1Know what, not how

Procedural abstraction gives a name to a process and lets anyone use the procedure knowing only what it does, not how it does it. You use LENGTH(aList) and DISPLAY all the time without knowing their insides. When you write your own procedures, the rest of your program gets the same benefit.

Abstraction is a way of managing complexity: it hides details you don't need at the moment, so you can think about the problem in bigger pieces.

2Big problems, small procedures

Procedural abstraction lets the solution to a large problem be built from the solutions to smaller subproblems, with one procedure for each. Dividing a program into separate subprograms like this is called modularity.

Figure 1. Modularity: the program is divided into separate procedures, each solving one smaller subproblem.
PROCEDURE countCorrect(answers, key)
{
  correct ← 0
  i ← 1
  REPEAT LENGTH(key) TIMES
  {
    IF (answers[i] = key[i])
    {
      correct ← correct + 1
    }
    i ← i + 1
  }
  RETURN(correct)
}
PROCEDURE percent(part, whole)
{
  RETURN(part * 100 / whole)
}
PROCEDURE letterGrade(pct)
{
  IF (pct ≥ 90)
  {
    RETURN("A")
  }
  IF (pct ≥ 80)
  {
    RETURN("B")
  }
  IF (pct ≥ 70)
  {
    RETURN("C")
  }
  RETURN("F")
}

With those three procedures written, the main program reads almost like a sentence:

right ← countCorrect(answers, key)
pct ← percent(right, LENGTH(key))
DISPLAY(letterGrade(pct))

For answers B, D, C, A, C against the key B, D, A, A, C, right is 4, pct is 80, and the program displays B. If grades come out wrong, you can test letterGrade alone with a few percentages instead of reading the whole program.

3One procedure instead of copies

A procedural abstraction can pull out the shared part of repeated code so it is written once and reused. These lines find three class averages by copying the same steps three times:

Three copies
total ← 0
FOR EACH s IN mathScores
{
  total ← total + s
}
DISPLAY(total / LENGTH(mathScores))
total ← 0
FOR EACH s IN sciScores
{
  total ← total + s
}
DISPLAY(total / LENGTH(sciScores))
total ← 0
FOR EACH s IN artScores
{
  total ← total + s
}
DISPLAY(total / LENGTH(artScores))
One procedure, three calls
PROCEDURE average(scores)
{
  total ← 0
  FOR EACH s IN scores
  {
    total ← total + s
  }
  RETURN(total / LENGTH(scores))
}
DISPLAY(average(mathScores))
DISPLAY(average(sciScores))
DISPLAY(average(artScores))

Both versions display 83 91 80. The second is shorter, easier to read (the name average says what is happening), and if the averaging needs to change, say to round the result, there is one place to fix instead of three. Reusing code instead of copying it is one of the main ways procedures manage complexity.

4Parameters make procedures general

Parameters let one procedure handle a whole range of inputs. Without them you end up with near-identical procedures that differ in one number:

Two procedures, one difference
PROCEDURE withStateTax(price)
{
  RETURN(price + price * 6 / 100)
}
PROCEDURE withCityTax(price)
{
  RETURN(price + price * 8 / 100)
}
One general procedure
PROCEDURE withTax(price, ratePercent)
{
  RETURN(price + price * ratePercent / 100)
}

The rate that was built into each copy has become a parameter. withTax(50, 6) gives 53, the same as withStateTax(50), and withTax(50, 10) gives 55 for a rate neither old procedure could handle. A program checked that the general version matches both old ones on several prices.

The key idea

Procedures manage complexity: they name a process so it can be used without knowing how it works, split big problems into smaller subproblems (modularity), replace copied code with one reusable definition, become general through parameters, and make programs easier to read.

5Changing the inside

Because callers rely only on what a procedure does, a programmer can change its insides, to make it faster, use less memory, or fix a bug, without telling anyone who uses it, as long as what it does stays the same.

Version 1
PROCEDURE sumTo(n)
{
  total ← 0
  k ← 1
  REPEAT n TIMES
  {
    total ← total + k
    k ← k + 1
  }
  RETURN(total)
}
Version 2
PROCEDURE sumTo(n)
{
  RETURN(n * (n + 1) / 2)
}
Caller (unchanged)
DISPLAY(sumTo(10))
DISPLAY(sumTo(100))
Figure 2. Callers depend only on what a procedure does. Its inside can be replaced, here with something far faster, as long as that stays the same.

Both versions display 55 and 5050; a program checked that they agree for every n from 0 to 300. Version 2 is far faster for large n, and nothing in the calling program had to change. If version 2 had returned a different result, every caller would have been affected; that is the promise a procedure must keep.

6Writing a procedure

Reference language: two shapes
PROCEDURE procName(parameter1, parameter2, ...)
{
  <block of statements>
}

PROCEDURE procName(parameter1, parameter2, ...)
{
  <block of statements>
  RETURN(expression)
}

A procedure can take zero or more parameters. RETURN is optional and can appear anywhere inside; when it runs, the procedure ends immediately and control goes back to the calling statement. Writing one means three decisions:

DecisionQuestion to askisEvenshowAll
NameWhat does it do, in a few words?isEven (a yes/no question)showAll (an action)
ParametersWhat does it need to be told?the numberthe list
RETURN or effectDoes it produce a value, or do something?returns true or falsedisplays; returns nothing
PROCEDURE isEven(n)
{
  RETURN(n MOD 2 = 0)
}
DISPLAY(isEven(14))
DISPLAY(isEven(9))
PROCEDURE showAll(names)
{
  FOR EACH name IN names
  {
    DISPLAY(name)
  }
}
showAll(["Ruth", "Omar", "Kai"])

These display true false and Ruth Omar Kai. If a procedure computes something other code may need, RETURN the value and let the caller decide whether to display it.

Where RETURN goes matters. To check whether a list contains a value, return true as soon as you find it, and return false only after the loop has checked everything:

Correct
PROCEDURE contains(aList, target)
{
  FOR EACH item IN aList
  {
    IF (item = target)
    {
      RETURN(true)
    }
  }
  RETURN(false)
}
Returns too early
PROCEDURE contains(aList, target)
{
  FOR EACH item IN aList
  {
    IF (item = target)
    {
      RETURN(true)
    }
    ELSE
    {
      RETURN(false)
    }
  }
}
CallCorrect versionEarly-return version
contains([4, 9, 2, 7], 7)truefalse
contains([4, 9, 2, 7], 4)truetrue
contains([4, 9, 2, 7], 5)falsefalse

The second version returns on the very first element either way, so it only ever looks at element 1. It gets 7 wrong. It happens to give the right answer for 4 and 5, which is why testing with only one or two inputs can miss this bug.

7Worked examples

Worked Example 1 Write a procedure

The larger of two

Write maxOf(a, b), which returns the larger of two numbers.

  1. 1
    Name given; two parameters; it produces a value, so it needs RETURN.
  2. 2
    If a > b, return a. Otherwise the code reaches the last line and returns b:
    PROCEDURE maxOf(a, b)
    {
      IF (a > b)
      {
        RETURN(a)
      }
      RETURN(b)
    }
  3. 3
    Test both orders and a tie: maxOf(3, 8) is 8, maxOf(8, 3) is 8, maxOf(5, 5) is 5.
Answer: A program checked these and a pair of negative numbers.
Worked Example 2 Return, don't just display

Comparing two classes

A program needs to know which of two classes has the higher average. Why can't it use this procedure?

PROCEDURE showAverage(scores)
{
  total ← 0
  FOR EACH s IN scores
  {
    total ← total + s
  }
  DISPLAY(total / LENGTH(scores))
}
  1. 1
    showAverage displays the average but returns nothing.
  2. 2
    So x ← showAverage([80, 90]) shows 85 on the screen but leaves x with no value, and there is nothing to compare.
  3. 3
    The average procedure from section 3 returns the value, so IF (average([80, 90]) > average([70, 95])) works.
Answer: A value that is only displayed cannot be used by the rest of the program. Return it.
Worked Example 3 Generalize

Count any value

A program has countYes(votes) and countNo(votes), identical except for the word they look for. Replace them with one procedure.

  1. 1
    The difference between the two is the target word, so make it a parameter.
  2. 2
    Write the shared steps once:
    PROCEDURE countOf(aList, target)
    {
      count ← 0
      FOR EACH item IN aList
      {
        IF (item = target)
        {
          count ← count + 1
        }
      }
      RETURN(count)
    }
    votes ← ["yes", "no", "yes", "yes", "no"]
    DISPLAY(countOf(votes, "yes"))
    DISPLAY(countOf(votes, "maybe"))
Answer: It displays 3 0, and the same procedure can now count any value in any list.
Worked Example 4 Explain the benefit

Why procedures?

A student replaces 40 lines of a game with calls to moveEnemy, checkCollision, and updateScore. Explain two ways this manages complexity.

  1. 1
    Modularity: each procedure solves one smaller subproblem and can be written and tested on its own; a scoring bug means opening updateScore only.
  2. 2
    Readability and abstraction: the main loop now says what happens each turn in three named steps, without the details of how.
  3. 3
    If checkCollision is later made faster, the main loop does not change, as long as it still reports collisions the same way.
Answer: Any two of: smaller subproblems (modularity), readability, reuse instead of copies, and changing internals without changing callers.

8Common mistakes

Common Mistake 1 · RETURN inside the loop when it belongs after it

A RETURN in both branches of an IF inside a loop ends the procedure on the first pass. The “not found” RETURN goes after the loop.

Common Mistake 2 · Displaying instead of returning

If other code needs the result, RETURN it. A displayed value cannot be stored or compared.

Common Mistake 3 · Copying code with one value changed

Near-identical procedures are a sign that the changing value should be a parameter.

Common Mistake 4 · Changing what a procedure does, not only how

The inside can change freely only if the results stay the same. Change the results and every caller is affected.

Explain how a procedure manages complexity like this

“The procedure average(scores) replaces three copies of the same loop. Because scores is a parameter, one definition works for any class's list, and a change to how averages are computed is made in one place instead of three. The calls also make the program easier to read.”

Name the procedure, say what repeated work or subproblem it handles, and connect it to reuse, parameters, readability, or modularity.