Unit 4: Algorithms · Building algorithms

Article

One algorithm, many ways to write it

8 min read

How do you find the larger of two numbers? You could explain it in words, draw it, or write code. Each is a different form, and all of them can describe the same algorithm. Here you will write algorithms in several forms, say exactly what you mean, and build new algorithms from old ones.

One algorithm, four forms

Here is "display the larger of two numbers" written four ways. First, in everyday words (natural language):

  1. Look at the two numbers, a and b.
  2. If a is bigger than b, the answer is a.
  3. Otherwise, the answer is b.
  4. Display the answer.

Second, as a flowchart:

The larger of two numbers

truefalseStarta ← 8b ← 5a > b?DISPLAY(a)DISPLAY(b)Stop

Third, in AP pseudocode, and fourth, in Python, which you can run:

AP pseudocode
a ← 8
b ← 5
IF(a > b)
{
    DISPLAY(a)
}
ELSE
{
    DISPLAY(b)
}
Runs in your browser

Each form displays 8. The form does not change the algorithm. It only changes how easy it is to read, share or run:

FormGood forWeak point
Natural languageAnyone can read itCan be vague
FlowchartShows choices and loops at a glanceGets large for long algorithms
PseudocodeExact, and not tied to one languageA computer cannot run it
Programming languageA computer can run itStrict rules

Say exactly what you mean

A person can guess what a vague sentence means. A computer cannot. A sentence is ambiguous when it can be read in more than one way. Each step of an algorithm must have exactly one meaning.

AmbiguousWhyClear
"Display the numbers up to 10."Is 10 included?"Display every whole number from 1 to 10, including 10."
"Add 5 and double it."Double the number, or the sum? With 10 you get 25 or 30"Add 5 to the number, then double the result."
"Repeat until the number is big."How big is big?"Repeat until the number is greater than 100."

Check your understanding

Which step is clear enough to be part of an algorithm?

Reuse what you know

Programmers rarely build an algorithm from nothing. They reuse standard ones. You have met all of these:

TaskThe ideaKey line
Is n divisible by d?The remainder is 0n MOD d = 0
Is n even?Divisible by 2n MOD 2 = 0
Sum of a listStart a total at 0, add each elementtotal ← total + n
AverageThe sum divided by the number of elementstotal / LENGTH(nums)
Count the matchesAdd 1 each time a test is truecount ← count + 1 inside an IF
Largest in a listStart with the first element, replace it when a bigger one appearsIF(n > largest)
Smallest in a listThe same, with <IF(n < smallest)

A new algorithm can be made from scratch, or by modifying one of these, or by combining two or more. Known algorithms save time and are known to work.

Modify and combine

To modify an algorithm, change only the part that must change. This one counts the even numbers:

AP pseudocode
nums ← [10, 4, 15, 7, 20, 25]
count ← 0
FOR EACH n IN nums
{
    IF(n MOD 2 = 0)
    {
        count ← count + 1
    }
}
DISPLAY(count)

The even numbers are 10, 4 and 20, so it displays 3. To count the multiples of 5 instead, change only the test to n MOD 5 = 0. It then counts 10, 15, 20 and 25 and displays 4.

To combine algorithms, join their parts. "The average of the even numbers" needs a sum, a count and an even test:

AP pseudocode
nums ← [4, 9, 2, 7, 6]
total ← 0
count ← 0
FOR EACH n IN nums
{
    IF(n MOD 2 = 0)
    {
        total ← total + n
        count ← count + 1
    }
}
DISPLAY(total / count)
Runs in your browser

The even numbers are 4, 2 and 6, so total is 12 and count is 3. The AP program displays 4. (Python prints 4.0, the same number.) The divisor is count, not LENGTH(nums), because only some elements were added. With nums set to [1, 3], count stays 0 and dividing by 0 is an error, so a careful algorithm tests count > 0 first.

Different algorithms can also solve the same problem. To add 1 to 10 you can loop, or use a fact: 1 + 10, 2 + 9, 3 + 8, 4 + 7 and 5 + 6 each make 11, and there are 5 pairs.

AP pseudocode
total ← 0
n ← 1
REPEAT UNTIL(n > 10)
{
    total ← total + n
    n ← n + 1
}
DISPLAY(total)
AP pseudocode
DISPLAY(10 * 11 / 2)

Both display 55. A new way to solve a problem often teaches you something new about it.

Check your understanding

This code counts the even numbers in a list.

AP pseudocode
nums ← [9, 4, 12, 7, 5, 18]
count ← 0
FOR EACH n IN nums
{
    IF(n MOD 2 = 0)
    {
        count ← count + 1
    }
}
DISPLAY(count)

Which change makes it count the multiples of 3 instead?

Worked example: build it

Task: display how many numbers in [12, 5, 30, 9, 33, 21, 8] are multiples of 3 and greater than 10.

  1. Name the standard algorithm: "count the matches".
  2. Write the test in words: "a multiple of 3, and greater than 10".
  3. Turn it into a condition: n MOD 3 = 0 AND n > 10.
  4. Put it into the count algorithm:
AP pseudocode
nums ← [12, 5, 30, 9, 33, 21, 8]
count ← 0
FOR EACH n IN nums
{
    IF(n MOD 3 = 0 AND n > 10)
    {
        count ← count + 1
    }
}
DISPLAY(count)
Runs in your browser

Check the edges. 9 is a multiple of 3 but not greater than 10, so it is not counted. 5 and 8 fail both tests. The counted numbers are 12, 30, 33 and 21, so the program displays 4.

Common mistakes

  • Vague words. "Big", "small" and "up to" need a number, and a decision about the end values.
  • Starting the largest at 0. If every element is negative, 0 is wrongly the largest. Start with the first element.
  • Setting total ← 0 inside the loop. It resets on every pass.
  • Dividing by LENGTH when only some elements were added. Divide by the count of the ones you added.
  • Believing a problem has only one correct algorithm. Different algorithms can give the same result.

On the exam

Questions describe an algorithm in words, or show a flowchart, and ask which code implements it. Others show code with a line missing, or ask how to change the code for a new task. Say what each variable must hold, check the starting values, and try a tiny list on each option.

Key words

Natural language: everyday words, such as English.

Ambiguous: able to be understood in more than one way.

Standard algorithm: a well-known algorithm that programmers reuse, such as sum, count or largest.

Modify: change part of an existing algorithm to solve a new task.

Combine: join parts of two or more algorithms to solve a bigger task.

AP® is a trademark registered by the College Board, which is not affiliated with, and does not endorse, this site. All lessons and questions here are written by JrCodex.