AP Computer Science A · Study guide

Represent Patterns and Algorithms

AP® Computer Science A · Using Objects and Methods

Representing Patterns and Algorithms

What an algorithm is, how to write one precisely in words or draw it as a flowchart, why the order of steps matters, and how everyday patterns turn into the statements Java runs.

Big Picture

Before writing any code, a programmer needs a plan. An algorithm is a step-by-step process for completing a task or solving a problem. Algorithms are everywhere: recipes, directions to a friend's house, the steps for checking out at a store. They can be written in ordinary language or drawn as diagrams such as flowcharts. Every algorithm depends on sequencing, the order in which its steps happen, and steps are carried out one at a time. Learning to describe a process precisely is the first and most important skill in programming, because a computer does exactly what it is told and nothing more.

1What an Algorithm Is

An algorithm defines a step-by-step process to follow when completing a task or solving a problem. The word sounds technical, but people follow algorithms all day. Brushing your teeth, tying a shoe, calculating a tip, and looking up a word in a dictionary all follow a sequence of steps that reliably produces a result.

What separates an algorithm from a loose set of suggestions is precision. A good algorithm has these properties:

  • Clear steps. Each step describes exactly one action, so two people following it would do the same thing.
  • A definite order. It is always clear which step comes next.
  • A finish. The process eventually stops, either after a fixed number of steps or when a stated condition is met.
  • A purpose. It takes some starting information (input) and produces a result (output), such as a total, an answer, or a completed task.

Humans are good at filling in missing details. If a recipe says "add salt to taste," an experienced cook knows what to do. Computers cannot fill gaps. A computer follows instructions literally, so an algorithm meant for a computer must spell out every decision. That is why programmers often plan an algorithm in words or diagrams first, test it by hand, and only then write code.

There is usually more than one correct algorithm for a task. Two students can find the largest number in a list in slightly different ways and both be right. Algorithms can still be compared: one may take fewer steps, be easier to understand, or handle unusual cases (such as an empty list) more gracefully.

RepresentationWhat it looks likeStrengthsWatch out for
Written languageNumbered steps in plain sentencesEasy to write and read; good for planningVague words such as "some" or "until done"
Flowchart (diagram)Shapes connected by arrowsShows decisions and repetition visuallyDecisions without both exits labelled
Program codeStatements in a programming languageCan be run by a computerMust follow the language's exact rules

2Writing Algorithms in Words

The simplest way to represent an algorithm is written language: a numbered list of steps in plain sentences. Written algorithms are quick to produce and easy to share, which makes them a good first draft for any program.

Precision is the challenge. Compare two versions of directions to a classroom:

  • Vague: "Go down the hall a bit and turn near the stairs."
  • Precise: "Walk straight from the main entrance for 40 steps. At the stairs, turn left. Enter the third door on the right, Room 214."

The precise version replaces judgment calls ("a bit," "near") with measurable actions. When writing algorithms, look for words that hide decisions: some, a few, until done, if needed, etc. Each one should become either a specific quantity or a yes/no test that anyone could check.

A useful habit is to test a written algorithm by hand on a small, concrete example before trusting it. Following the steps exactly, without adding your own common sense, quickly reveals missing steps or ambiguous instructions.

Worked Example 1 Written language

Writing a Precise Algorithm for Finding the Tallest Person

A coach wants written instructions a helper can follow to find the tallest player in a line of players. Write an algorithm precise enough that two different helpers would always produce the same answer.

  1. 1Name what you need to remember. The helper must keep track of one thing: the tallest player seen so far.
  2. 2Start with a real value. "Point to the first player. Remember that player as the tallest so far." Starting with an actual player avoids guessing a height.
  3. 3Repeat a single comparison. "Move to the next player. If this player is taller than the tallest so far, remember this player instead." The same two-sentence step is repeated.
  4. 4Say exactly when to stop. "Repeat the previous step until there are no more players. Then announce the remembered player." Without a stopping rule, the algorithm never finishes.
  5. 5Test it on a small case. For heights 170, 182, 176, the remembered value goes 170, 182, 182, and the answer is 182 centimeters.
Result: A precise written algorithm has a clear starting point, a repeated step that does one thing, and an exact stopping rule. This "remember the best so far" pattern appears constantly in later code.
Worked Example 2 Written language

Repairing an Ambiguous Recipe

A recipe says: "Boil some water. Add pasta. Cook until done. Add salt if needed." Identify what is ambiguous and rewrite the steps so a person who has never cooked could follow them exactly.

  1. 1"Some water" is not a quantity. Replace it with "Fill a pot with 2 liters of water."
  2. 2"Boil" hides two steps. "Put the pot on the stove on high heat. Wait until large bubbles rise continuously."
  3. 3"Until done" has no test. "Cook for 10 minutes. Taste one piece. If it is still hard in the center, cook 1 more minute and taste again."
  4. 4"If needed" has no condition. "Add 1 teaspoon of salt to the water before adding the pasta." Moving the step earlier also fixes the sequencing: salt goes into the water, not onto drained pasta.
Result: Every vague word ("some," "done," "if needed") becomes a measurable action or a yes/no test. Computers need this level of precision because they cannot guess what the writer meant.
Common Mistake 1 · Writing Steps a Computer Cannot Follow

Instructions such as "sort the cards sensibly" or "cook until it looks right" depend on human judgment. A computer needs every decision made explicit: compare which values, stop when exactly. If you cannot describe how a person would check whether a step is finished, the step is not yet precise enough.

3Representing Algorithms With Diagrams

Algorithms can also be represented using diagrams. The most common is the flowchart, which uses standard shapes for different kinds of steps and arrows to show the order. Flowcharts make the structure of an algorithm visible: you can see at a glance where decisions happen and which steps repeat.

Figure 1. The four basic flowchart shapes. A flowchart is a diagram of an algorithm: each shape is one step, and arrows show which step comes next.
Flowchart shapeMeaningEveryday example
OvalStart or end of the algorithm"Start," "End"
RectangleA process step: an action"Pour 100 mL of water"
ParallelogramInput or output"Read the order total," "Show the shipping cost"
DiamondA decision with yes and no exits"Is the soil dry?"
ArrowThe order in which steps happenFrom one step to the next, or back to repeat

Two rules keep flowcharts clear. First, every decision diamond has exactly two exits, labelled with the two possible answers (yes/no or true/false). Second, a loop needs a way out: an arrow that returns to an earlier step must pass through a decision that can eventually send the flow elsewhere. A loop with no exit describes a process that never ends.

Figure 2 shows a small everyday algorithm. It starts, performs a step, asks a question, and depending on the answer either finishes or performs more steps and asks again. That shape, a question followed by repeated work, is one of the most common patterns in all of programming.

Figure 2. An everyday algorithm as a flowchart. It combines all three building blocks: steps in sequence, a decision with two exits, and an arrow that loops back to repeat the check until the soil is no longer dry.
Worked Example 3 Diagrams

Tracing a Flowchart for Shipping Cost

A store's flowchart: Start → read the order total → decision "Is the total at least 50?" → if yes, shipping is 0; if no, shipping is 7 → display shipping → End. Find the shipping charge for orders of 49, 50, and 120.

  1. 1Order total 49. Is 49 at least 50? No. Follow the "no" arrow: shipping is 7.
  2. 2Order total 50. Is 50 at least 50? Yes, because "at least" includes 50 itself. Shipping is 0.
  3. 3Order total 120. Yes. Shipping is 0.
  4. 4Check the boundary. The value exactly at the cutoff (50) is where people most often misread a decision. "At least 50" means 50 or more; "more than 50" would have sent 50 down the "no" path.
Result: Shipping is 7, 0, and 0. Tracing a flowchart means following exactly one arrow out of each decision, and testing the boundary value separately.
Common Mistake 2 · Unlabelled or One-Sided Decisions

A decision diamond with only one arrow, or with arrows that are not labelled, leaves the reader guessing what happens for the other answer. Label both exits, and check the boundary value: "at least 50" includes 50, while "more than 50" does not. Most errors in reading or drawing flowcharts happen exactly at the boundary.

4Sequencing: Order Matters

Sequencing defines the order in which the steps in a process are completed. Steps are completed one at a time: each step finishes before the next one begins. Putting on socks and then shoes works; putting on shoes and then socks does not, even though the steps are identical.

In programs, sequencing is just as strict. Java executes statements one after another, from the top of a block to the bottom. A statement can only use information that earlier statements have already produced. A program that tries to display an average before computing it, or computes a total before reading the scores, fails, either by not compiling or by producing the wrong result.

The classic example is swapping two values. Exchanging the contents of two boxes requires a third, empty box: move the first box's contents into the spare box, move the second box's contents into the first, then move the spare's contents into the second. Each move depends on the ones before it, as Figure 3 shows.

Figure 3. Sequencing in action. Swapping two values takes three steps in exactly this order. Skipping the temporary variable, or changing the order, loses one of the values.
Statementabtemp
int a = 5;5--
int b = 9;59-
int temp = a;595
a = b;995
b = temp;955
Worked Example 4 Sequencing

Predicting Output From Statement Order

Predict the output, then predict how it changes if the last two lines are swapped.

Code
System.out.println("Preheat oven");
System.out.println("Mix batter");
System.out.println("Bake 25 minutes");
System.out.println("Cool on rack");
Output
Preheat oven
Mix batter
Bake 25 minutes
Cool on rack
  1. 1Statements run one at a time, top to bottom. Each println finishes before the next begins, so the lines appear in the order written.
  2. 2Swap the last two lines. The program would print "Cool on rack" before "Bake 25 minutes." Java does not know that this order makes no sense in a kitchen; it simply follows the sequence it is given.
  3. 3Sequencing is the programmer's responsibility. The computer cannot reorder steps to make them sensible.
Result: The output lists the four steps in written order. Changing the order of statements changes the order of results, even when the new order is illogical.
Worked Example 5 Sequencing

Why a Swap Needs a Temporary Variable

A programmer wants to exchange the values of a and b. Their first attempt is below. Trace it, explain the bug, then fix it.

First attempt
int a = 5;
int b = 9;
a = b;
b = a;
System.out.println(a + " " + b);
Output
9 9
  1. 1Trace line by line. After a = b, both variables hold 9. The original 5 is gone.
  2. 2The second assignment copies the new value. b = a copies 9 into b, so the output is 9 9.
  3. 3Fix by saving one value first. Copy a into a temporary variable before overwriting it, as in Figure 3.
    Fixed swap
    int a = 5;
    int b = 9;
    int temp = a;
    a = b;
    b = temp;
    System.out.println(a + " " + b);
    Output
    9 5
  4. 4Check the order. The three assignments must happen in exactly this sequence; any other order loses a value.
Result: The first attempt prints 9 9 because the value 5 is overwritten before it is saved. The three-step swap with temp prints 9 5.
Common Mistake 3 · Assuming the Computer Will Fix the Order

A computer never rearranges steps to make them sensible. If the statements say "cool the cake" before "bake the cake," that is what happens. When code gives an unexpected result, trace the statements in the exact order they appear, one at a time, writing down what changes after each one. Many bugs are simply steps in the wrong order.

5Patterns in Everyday Algorithms

Look closely at everyday algorithms and three building blocks appear again and again. Sequencing puts steps in order. Selection makes a decision: "If it is raining, take an umbrella; otherwise, wear sunglasses." Repetition repeats steps: "Stir until the batter is smooth," "Knock on each door on the street." Any algorithm, no matter how complex, can be built from these three patterns, and Java has statements that express each one.

Recognizing patterns also makes algorithms reusable. Finding the tallest player, the cheapest price, and the highest test score all follow the same pattern: remember the best value so far, compare each new item against it, and update when you find something better. Counting how many items meet a condition (how many days were above 30 degrees) and adding up values (total minutes practiced this week) are two more patterns that appear in countless programs. When you meet a new problem, asking "which pattern does this look like?" is often the fastest way to an algorithm.

Building blockWhat it meansEveryday exampleWhere it appears later in Java
SequencingSteps happen one at a time, in a set orderWash, rinse, dryEvery program: statements run top to bottom
SelectionA decision chooses between pathsIf it is raining, take an umbrellaif and if-else statements
RepetitionA step or group of steps repeats until a condition changesStir until smoothwhile and for loops

6From Steps to Code

A precise written algorithm or flowchart translates almost directly into code. Each process step becomes one or more statements, each decision becomes a selection statement, and each loop becomes a repetition statement. Figure 4 shows a three-step algorithm turned into three Java statements.

Figure 4. A precise written algorithm translates almost line for line into code. Java runs the statements one at a time, from top to bottom, in the order written.
Worked Example 6 From algorithm to code

Translating Written Steps Into Java

Turn this written algorithm into Java and test it with the scores 88, 92, and 79: (1) add the three scores; (2) divide the total by 3.0; (3) display the average.

  1. 1One step, one statement. Each written step maps to one line of code, as in Figure 4.
    Code
    int s1 = 88;
    int s2 = 92;
    int s3 = 79;
    int total = s1 + s2 + s3;
    double avg = total / 3.0;
    System.out.println(avg);
    Output
    86.33333333333333
  2. 2Check the arithmetic by hand. 88 + 92 + 79 = 259, and 259 ÷ 3 ≈ 86.33, so the program's result is reasonable.
  3. 3Keep the order. The average cannot be computed before the total exists, and it cannot be displayed before it is computed.
Result: The program prints 86.33333333333333. A precise written algorithm made the code almost automatic to write, and a hand calculation confirmed the result.
Common Mistake 4 · Starting to Code Without a Plan

Jumping straight into code tends to mix two hard problems: deciding what the steps are and remembering how to write them in Java. Writing the algorithm first, in words or as a flowchart, and testing it by hand on a small example, separates those problems. If the plan is right, translating it into code becomes much easier, and when the code fails, you can check whether the plan or the translation is at fault.

Four Habits for Designing Algorithms

1. One Action per Step

Each step should do exactly one thing that anyone could carry out the same way.

2. Make Every Decision Testable

Replace "if needed" with a yes/no question someone can actually check.

3. Respect the Order

Ask what each step needs from earlier steps; swaps need a temporary value.

4. Trace Before You Trust

Follow the steps by hand on a small example, especially at boundary values.

Core Synthesis

An algorithm is a step-by-step process for completing a task or solving a problem. Algorithms can be represented in written language or with diagrams such as flowcharts, which use standard shapes for steps, decisions, input and output, and arrows for order. Sequencing defines the order in which steps are completed, and steps are completed one at a time, so changing the order can change the result, as the swap example shows. Everyday algorithms are built from sequencing, selection, and repetition, and a precise plan translates naturally into Java statements that run from top to bottom.