---
title: "Developing Algorithms | FiveStudy"
description: "How to compare algorithms by result and side effect, turn conditionals into Boolean expressions, and build new algorithms from known ones, including a robot's maze path."
url: https://fivestudy.com/guides/ap-csp-3-9-developing-algorithms
---

[AP Computer Science Principles](https://fivestudy.com/ap-computer-science-principles) · Study guide

# Developing Algorithms

[Figure: FiveStudy]

FiveStudy

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

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

# Developing Algorithms

How to tell whether two algorithms do the same thing, how a conditional and a Boolean expression can say the same thing, and how new algorithms are built from ones you already trust, including a robot's path through a maze.

1. What an algorithm is 2. Same job, different code 3. Result versus side effect 4. Conditionals and Boolean expressions 5. Building from known algorithms 6. A robot in a maze 7. Worked examples 8. Common mistakes

## 1 What an algorithm is

An **algorithm** is a finite set of instructions that accomplishes a specific task. A recipe, directions to a friend's house, and a program that adds up a list are all algorithms. They can be written in everyday language, drawn as diagrams such as flowcharts, or written in pseudocode; a program carries one out in a programming language.

Every algorithm can be built from three ways of arranging steps: **sequencing** (steps in order), **selection** (choosing steps with IF), and **iteration** (repeating steps with a loop). Developing an algorithm means choosing and arranging those pieces, and then checking that the result really does the job.

## 2 Same job, different code

Algorithms can be written in different ways and still do the same task, and different algorithms can be developed to solve the same problem. Here are two ways to add up a list called `nums`:

A: visit each item

```
total ← 0
FOR EACH n IN nums
{
  total ← total + n
}
DISPLAY(total)
```

B: count down the positions

```
total ← 0
i ← LENGTH(nums)
REPEAT UNTIL (i = 0)
{
  total ← total + nums[i]
  i ← i - 1
}
DISPLAY(total)
```

They look nothing alike, but for `nums` = [4, 7, 1, 8] both display `20`. (They also agree on a one-item list, a list with a zero in it, and an empty list.) The reverse is just as true: **algorithms that look similar can give different results**. This one differs from B in only a starting value and a stopping value:

C: count up the positions

```
total ← 0
i ← 1
REPEAT UNTIL (i = LENGTH(nums))
{
  total ← total + nums[i]
  i ← i + 1
}
DISPLAY(total)
```

It displays `12`. The loop stops as soon as `i` equals `LENGTH(nums)`, before it adds the last item, 8. Looking at code is not enough to decide whether two algorithms match: trace them on the same input, and pick inputs that test the edges.

## 3 Result versus side effect

The **result** of an algorithm is the value it produces: what it returns or displays at the end. A **side effect** is any other change it leaves behind, such as a list that was rearranged or shortened, or a variable that was overwritten. Two algorithms can have the same result and different side effects.

Largest value, version A

```
PROCEDURE largest(nums)
{
  best ← nums[1]
  FOR EACH n IN nums
  {
    IF (n > best)
    {
      best ← n
    }
  }
  RETURN(best)
}
```

Largest value, version B

```
PROCEDURE largest(nums)
{
  REPEAT UNTIL (LENGTH(nums) = 1)
  {
    IF (nums[1] < nums[2])
    {
      REMOVE(nums, 1)
    }
    ELSE
    {
      REMOVE(nums, 2)
    }
  }
  RETURN(nums[1])
}
```

Both are called the same way:

```
scores ← [62, 91, 78, 85]
DISPLAY(largest(scores))
DISPLAY(scores)
```

| Version | Displayed result | scores afterward |
| --- | --- | --- |
| A | `91` | `[62, 91, 78, 85]` (unchanged) |
| B | `91` | `[91]` (three scores removed) |

Same result, 91. But version B removed items from the very list it was given, so the caller's `scores` list is now just [91]. If the program later needs the other scores, version B has broken it. When you compare algorithms, compare both what they produce and what they change.

## 4 Conditionals and Boolean expressions

Some conditional statements can be written as an equivalent Boolean expression, and some Boolean expressions can be written as an equivalent conditional. The clearest case is an IF whose two branches only set a variable to true or false:

```
IF (temp < 0)
{
  frozen ← true
}
ELSE
{
  frozen ← false
}
```

does the same as the single line `frozen ← temp < 0`, because `temp < 0` already is true or false. Two more pairs that always agree:

```
IF (age ≥ 16)
{
  IF (hasPermit)
  {
    DISPLAY("may drive")
  }
}
```

```
IF (age ≥ 16 AND hasPermit)
{
  DISPLAY("may drive")
}
```

```
IF (NOT raining)
{
  DISPLAY("walk")
}
ELSE
{
  DISPLAY("bus")
}
```

```
IF (raining)
{
  DISPLAY("bus")
}
ELSE
{
  DISPLAY("walk")
}
```

| This conditional | is equivalent to |
| --- | --- |
|  |  |
|  |  |

A nested IF with no ELSE means both conditions must be true, which is what AND means. And `NOT` in front of a condition can be removed by swapping the two blocks. A program checked each pair for every combination of inputs; none disagreed.

## 5 Building from known algorithms

Algorithms can be created from an idea, by **combining** existing algorithms, or by **modifying** an existing one. Knowing some standard algorithms makes new ones much easier to build. Four come up again and again:

| Known algorithm | Core idea | On [12, 5, 30, 7] |
| --- | --- | --- |
| Maximum or minimum of two or more numbers | Keep the best so far; replace it when something beats it | max 30, min 5 |
| Sum or average of two or more numbers | Running total; divide by how many | sum 54, average 13.5 |
| Is one integer evenly divisible by another? | `n MOD d = 0` (the remainder is 0) | 21 MOD 7 = 0: divisible |
| A robot's path through a maze | Move, turn, check the square ahead | see Figure 2 |

Maximum

```
best ← nums[1]
FOR EACH n IN nums
{
  IF (n > best)
  {
    best ← n
  }
}
```

**Modifying** it into a minimum takes one change: flip `>` to `<` (and rename the variable so the code stays readable). **Combining** pieces gives something new: “average of the even numbers in a list” is the divisibility test, the running total and count, and the average step.

**Figure 1.** Each piece was already known to work, so new errors are most likely where the pieces join.

```
total ← 0
count ← 0
FOR EACH n IN nums
{
  IF (n MOD 2 = 0)
  {
    total ← total + n
    count ← count + 1
  }
}
average ← total / count
DISPLAY(average)
```

For [3, 8, 5, 12, 10] it displays `10`. For [3, 5, 9], with no even numbers, `count` stays 0 and the division `total / count` stops the program with an error. Each piece worked on its own; the problem is at the seam. Checking `count = 0` before dividing fixes it.

Building from existing correct algorithms **reduces development time** (nothing is written twice), **reduces testing** (only the new joins need new tests), and **makes errors easier to find** (the trusted pieces are already ruled out).

The key idea

Different code can do the same job, and similar code can do different jobs: trace on the same inputs, and compare both results and side effects. New algorithms are usually old ones combined or modified, and their errors tend to sit at the joins.

## 6 A robot in a maze

Finding a robot's path through a maze is one of the standard algorithms. The robot sits in one square of a grid and faces one direction. It understands four commands:

| Command | What it does |
| --- | --- |
| `MOVE_FORWARD()` | Moves one square in the direction the robot is facing |
| `ROTATE_LEFT()` | Turns 90 degrees left (counterclockwise) without moving |
| `ROTATE_RIGHT()` | Turns 90 degrees right (clockwise) without moving |
| `CAN_MOVE(direction)` | true if the square in that direction (forward, backward, left, or right, measured from where the robot faces) is open and on the grid |

If `MOVE_FORWARD()` would take the robot into a blocked square or off the grid, the robot stays where it is and the program ends. Here the robot starts in the bottom-left square facing up:

Gets to the goal

```
REPEAT 4 TIMES
{
  MOVE_FORWARD()
}
ROTATE_RIGHT()
REPEAT 4 TIMES
{
  MOVE_FORWARD()
}
```

Same moves, different order

```
ROTATE_RIGHT()
REPEAT 4 TIMES
{
  MOVE_FORWARD()
}
ROTATE_LEFT()
REPEAT 4 TIMES
{
  MOVE_FORWARD()
}
```

**Figure 2.** The orange triangle is the robot, pointing the way it faces. Trace position and direction after every command: one wrong turn order and the program stops at a wall.

The second program uses the same commands in a different order and never reaches the goal: after two squares to the right, the square ahead is blocked, so its third `MOVE_FORWARD()` ends the program. Track the robot's square and the way it faces after every command, and the mistake shows up immediately.

`CAN_MOVE` lets one algorithm work without counting squares. This version moves until blocked, turns right, and moves until blocked again:

```
REPEAT UNTIL (NOT CAN_MOVE(forward))
{
  MOVE_FORWARD()
}
ROTATE_RIGHT()
REPEAT UNTIL (NOT CAN_MOVE(forward))
{
  MOVE_FORWARD()
}
```

On this maze it follows the same path to the goal. Because it does not depend on the number 4, it also works on a taller or wider grid with the same shape.

## 7 Worked examples

Worked Example 1 Compare algorithms

### Same last value, different output

Do these segments produce the same output? Do they end with the same value of `x`?

```
x ← 0
REPEAT 3 TIMES
{
  x ← x + 2
  DISPLAY(x)
}
```

```
x ← 0
REPEAT 3 TIMES
{
  DISPLAY(x)
  x ← x + 2
}
```

1. 1

   First segment: add, then display, three times: `2 4 6`.

2. 2

   Second segment: display, then add: `0 2 4`.

3. 3

   Both add 2 three times, so both end with `x` = 6.

**Answer:** Different output, same final value. Swapping two statements inside a loop changes the result.

Worked Example 2 Rewrite as one expression

### Pass or fail

Which single assignment is equivalent to this conditional for every score: `passed ← score ≥ 60`, `passed ← score > 60`, or `passed ← NOT (score ≥ 60)`?

```
IF (score ≥ 60)
{
  passed ← true
}
ELSE
{
  passed ← false
}
```

1. 1

   The IF sets `passed` to true whenever `score ≥ 60` is true, and false otherwise.

2. 2

   `score > 60` gives false for a score of 60, but the IF gives true.

3. 3

   `NOT (score ≥ 60)` gives the opposite answer for every score.

**Answer:** `passed ← score ≥ 60`. A program checked all three against the IF for every score from 0 to 100.

Worked Example 3 Combine known algorithms

### Count multiples of 3

Write an algorithm that displays how many numbers in `nums` are divisible by 3, and trace it on [9, 14, 21, 4, 30].

1. 1

   Pieces: a traversal of the list, the divisibility test `n MOD 3 = 0`, and a counter.

2. 2

   Put the test inside the traversal and add 1 when it passes:

   ```
   count ← 0
   FOR EACH n IN nums
   {
     IF (n MOD 3 = 0)
     {
       count ← count + 1
     }
   }
   DISPLAY(count)
   ```

3. 3

   9 MOD 3 = 0 (count 1), 14 MOD 3 = 2, 21 MOD 3 = 0 (count 2), 4 MOD 3 = 1, 30 MOD 3 = 0 (count 3).

**Answer:** It displays `3`.

Worked Example 4 Modify an algorithm

### Second-largest value

A student modified the maximum algorithm to find the second-largest value. It works on [5, 9, 14] but not on [14, 9, 5]. Find and fix the problem. (Assume the values are positive and not all equal.)

```
first ← nums[1]
second ← nums[1]
FOR EACH n IN nums
{
  IF (n > first)
  {
    second ← first
    first ← n
  }
}
DISPLAY(second)
```

1. 1

   On [5, 9, 14], each value beats `first`, so the old maximum slides into `second`: it displays `9`.

2. 2

   On [14, 9, 5], 9 and 5 never beat 14, so `second` is never updated and stays 14: it displays `14`.

3. 3

   The missing case: a value smaller than `first` but bigger than `second`. Start `second` below every value and add that case:

   ```
   first ← nums[1]
   second ← -1
   FOR EACH n IN nums
   {
     IF (n > first)
     {
       second ← first
       first ← n
     }
     ELSE
     {
       IF (n > second AND n < first)
       {
         second ← n
       }
     }
   }
   DISPLAY(second)
   ```

**Answer:** The fixed version displays 9 for both lists (and 11 for [3, 20, 11, 7]). The error was in the one new part, not in the maximum algorithm it was built from.

## 8 Common mistakes

Common Mistake 1 · Judging by appearance

Similar code can give different results, and very different code can give the same result. Trace both on the same inputs, including edge cases.

Common Mistake 2 · Treating one matching example as proof

Two algorithms that agree on one input may disagree on another. One disagreement proves they differ; agreeing on every input is what makes them equivalent.

Common Mistake 3 · Ignoring side effects

Two procedures can return the same value while one also changes the list it was given. Compare what changes, not only what comes out.

Common Mistake 4 · Losing track of the robot's direction

ROTATE commands turn the robot without moving it, and left and right are measured from the way it faces. Write down the square and the direction after every command.

Compare two algorithms like this

“Both procedures return 91 for [62, 91, 78, 85], so they have the same result. Version B also removes items from the list it is given, leaving [91], so it has a side effect that version A does not.”

Name the input you used, the result of each, and any change each leaves behind.

FiveStudy AP® Computer Science Principles · Developing Algorithms
