An algorithm is a finite, step-by-step method for a task, and every algorithm can be written with three building blocks: sequencing, selection and iteration. In AP® Computer Science Principles, it pays to know a few standard algorithms (sum, count, maximum, minimum, average) by heart, and you check any algorithm by tracing it on test inputs.
Quick check
How many times does the body of REPEAT 3 TIMES run?Show answerHide answer
Three times, then the program moves on to the line after the loop.
Two programs both display 1 + 2 + … + 10 using different steps. Are they the same algorithm?Show answerHide answer
No. They are two different algorithms that solve the same problem.
Know these already? Jump to the practice questions
What you'll be able to do
- Identify sequencing, selection and iteration in an algorithm.
- Predict what the sum, count, maximum, minimum and average algorithms produce.
- Decide whether two algorithms give the same result by tracing both.
- Test an algorithm you design by tracing it on chosen inputs.
Key terms
Algorithm
A precise, finite list of steps that carries out a task.
- In plain English
- A recipe a computer can follow, which always finishes.
- Don't write
- "An algorithm is the same thing as a program."
Sequencing
Running steps one after another, in the order they are written.
- In plain English
- Line 1, then line 2, then line 3.
- Don't write
- "The order of the lines doesn't matter."
Selection
Using a condition to decide which steps run, as IF and ELSE do.
- In plain English
- A fork in the road.
- Don't write
- "Selection means picking an item from a list."
Iteration
Repeating a block of steps: a fixed number of times, or until a condition becomes true.
- In plain English
- A loop.
- Don't write
- "Iteration means the program runs again from the start."
What are algorithms built from?
Any algorithm can be built from sequencing, selection and iteration alone. This segment uses all three to count the even numbers from 1 to 6.
count ← 0
n ← 1
REPEAT 6 TIMES
{
IF(n MOD 2 = 0)
{
count ← count + 1
}
n ← n + 1
}
DISPLAY(count)
The lines run in order (sequencing). REPEAT 6 TIMES gives iteration, so n takes the values 1 to 6. The IF gives selection: count goes up only for 2, 4 and 6, so the segment displays 3. Order matters: with DISPLAY(count) inside the loop, it would show a running count on every pass.
Check yourself
Show answerHide answer
IF(n MOD 2 = 0), because it decides whether count ← count + 1 runs on each pass.
What are the standard algorithms?
Each pattern sets up a variable before the loop, updates it inside, and uses it after. The patterns are Learn this; the REPEAT, IF and ← they use are on the exam reference sheet.
| Goal | Before the loop | Inside, for each value x | After |
|---|---|---|---|
| Sum | total ← 0 | total ← total + x | total |
| Count | count ← 0 | IF(condition), then count ← count + 1 | count |
| Maximum | set big to the first value | IF(x > big), then big ← x | big |
| Minimum | set small to the first value | IF(x < small), then small ← x | small |
| Average | total ← 0, count ← 0 | add x to total, 1 to count | total / count |
A maximum or minimum starts at the first value, not 0, because 0 might be larger or smaller than every value in the data.
Key idea
Set up before the loop, update inside, use after; a setup line inside the loop wipes out the work.
Check yourself
Show answerHide answer
It starts at 0 and goes up by 1 only on a pass where the value is greater than 50.
Can two algorithms solve the same problem?
Yes. To find 1 + 2 + … + n you can loop and add, or work out n × (n + 1) / 2. Both give 10 when n is 4, but the loop's body runs n times while the formula is one calculation.
Algorithms that look alike can still differ. Both segments start with total ← 0 and k ← 1 and repeat 4 times:
| Segment | Loop body | Values added | Result |
|---|---|---|---|
| A | total ← total + k, then k ← k + 1 | 1, 2, 3, 4 | 10 |
| B | k ← k + 1, then total ← total + k | 2, 3, 4, 5 | 14 |
Only the order of two lines differs, so sequencing changed the answer.
Check yourself
Show answerHide answer
Trace both on the same inputs, including a boundary case such as the smallest allowed input, and compare what each displays.
How do you test an algorithm?
A test case is an input together with the output it should give. Choose a typical input, a boundary value (exactly equal to a limit in a condition) and an edge case (a tie, the largest value first or last). Trace each with a table: one column per variable, one row per pass.
A count of scores of 50 or more written as IF(score > 50) is right for 70 and 30 but misses exactly 50. Only the boundary test shows the fault.
Check yourself
Show answerHide answer
18, because it equals the limit, so it shows whether the condition uses ≥ or >.
Worked example 1: Trace a minimum with a counter
Question: The user enters 8, 5, 9, 3 and 3, in that order. What is displayed?
low ← INPUT()
changes ← 0
REPEAT 4 TIMES
{
num ← INPUT()
IF(num < low)
{
low ← num
changes ← changes + 1
}
}
DISPLAY(low)
DISPLAY(changes)
What tells you the method
A loop updates two variables, so trace with a table.
Step 1: Set the starting values.
lowis 8 (the first input) andchangesis 0.WhyThe minimum starts at the first value, so the loop reads the other four.
Step 2: Trace each pass.
Pass numnum < low?lowchanges1 5 yes 5 1 2 9 no 5 1 3 3 yes 3 2 4 3 no 3 2 WhyBoth lines inside the
IFrun only when the condition is true. EachDISPLAYthen shows its value and a space, so 3 and 2 appear on one line.
Check it
Pass 4 is a tie: 3 < 3 is false, so changes stays 2. With ≤ it would be 3.
Answer
3 2
Worked example 2: Design an average that skips zeros
Question: A program reads 5 quiz scores; a 0 means a missed quiz and is ignored. Design an algorithm that displays the average of the other scores, then state what it displays for 8, 0, 10, 6, 0.
What tells you the method
A design task: state the input, output and steps, choose variables, then test by tracing.
Step 1: State the input, output and plan.
Input: 5 scores. Output: the average of the non-zero scores (assume there is at least one). Plan: sum and count only those, then divide.
WhyAn average needs a sum and a count.
Step 2: Write the steps.
total ← 0 count ← 0 REPEAT 5 TIMES { score ← INPUT() IF(score ≠ 0) { total ← total + score count ← count + 1 } } DISPLAY(total / count)WhyOne
IFguards both updates, so the sum and count agree.Step 3: Trace on 8, 0, 10, 6, 0.
totalbecomes 8, 18, 24 andcountbecomes 1, 2, 3; the zeros change nothing. 24 / 3 = 8.WhyTracing a design on a real input tests it before you trust it.
Check it
Trace 7, 7, 7, 7, 7: total is 35 and count is 5, so it displays 7, as expected.
Answer
8
Worked example 3: Compare two algorithms
Question: Both segments should display 1 + 2 + … + n for a positive whole number n. Which statement is true?
Segment I:
total ← 0
k ← 1
REPEAT n TIMES
{
total ← total + k
k ← k + 1
}
DISPLAY(total)
Segment II:
total ← 0
k ← 0
REPEAT UNTIL(k = n)
{
k ← k + 1
total ← total + k
}
DISPLAY(total)
- A) Both segments display the correct sum.
- B) Only segment I displays the correct sum.
- C) Only segment II displays the correct sum.
- D) Neither segment displays the correct sum.
What tells you the method
"Which give the same result": trace both on the same inputs, including n = 1.
Step 1: Trace segment I for n = 3.
It adds 1, 2 and 3, then displays 6.
Whykis added before it goes up, so the values added are 1 to n.Step 2: Trace segment II for n = 3.
kbecomes 1, 2, 3 and each newkis added: 6. The check that stops the loop happens whenkis 3, after 3 was added.WhyREPEAT UNTILchecks before each pass, so you must see whether n was added before the check.
Check it
For n = 1, both segments add 1 and display 1.
Answer
A
Your turn
Question: The user enters 4, 15, 9, 22 and 6, in that order. What is displayed?
count ← 0
total ← 0
REPEAT 5 TIMES
{
num ← INPUT()
IF(num ≥ 9)
{
count ← count + 1
total ← total + num
}
}
DISPLAY(count)
DISPLAY(total)
Step 1: Trace passes 1 and 2.
4 ≥ 9 is false, so nothing changes. 15 ≥ 9 is true, so
countis 1 andtotalis 15.Step 2: Your go: trace passes 3 to 5 and read the display.
Show the full solutionHide the solution
Step 2. Pass 3: 9 ≥ 9 is true (the boundary), so count is 2 and total is 24. Pass 4: 22 ≥ 9, so count is 3 and total is 46. Pass 5: 6 ≥ 9 is false. The displays show 3 and 46 on one line.
Answer: 3 46
Traps
Trap
A maximum can start at 0, just like a total.
It seems right because a sum starts at 0. But if every value is negative, nothing beats 0, so it reports 0, which isn't in the data. Start at the first value.
A maximum starts at 0 and reads -4, -9 and -2. What does it report, and what should it report?
It reports 0, but the largest value is -2.
Trap
An algorithm that passes one test is correct.
It seems right because the trace matched. But one input can miss a boundary or a tie. Test a typical value, a boundary value and an edge case.
Code to count scores of at least 60 uses IF(score > 60). Which test exposes it: 45, 60 or 75?
- It should be counted, but 60 > 60 is false.
Trap
total ← 0 can go inside the loop.
It seems right because the variable needs a starting value. But a line inside the loop runs every pass, so the running total is wiped each time. Setup belongs before the loop.
With total ← 0 inside the loop, a sum reads 3, 5 and 4. What does it display?
4: each pass resets total, so only the last value survives.
What's examined
On the AP® Computer Science Principles exam, this is Big Idea 3: Algorithms and Programming. Multiple-choice questions ask what a segment displays, which code completes it, and which algorithms give the same result. The written-response questions ask about your own Create program, whose procedure must use sequencing, selection and iteration. Counting steps is in the note on algorithmic efficiency.
Practice questions
- Recall Name the building block that
IFandELSEprovide in an algorithm.
Show answer
Answer: Selection.
Marking points:
IFuses a condition to decide which steps run, which is selection.
- Apply What is displayed when this code segment runs?
x ← 1
steps ← 0
REPEAT UNTIL(x > 40)
{
x ← x * 3
steps ← steps + 1
}
DISPLAY(x)
DISPLAY(steps)
Show answer
Answer: 81 4
Marking points:
xtakes the values 3, 9, 27 and 81, andstepscounts 4 passes.- 27 > 40 is false, so the loop runs again; 81 > 40 is true, so it stops.
- Apply What value does
counthold after this code segment runs?
count ← 0
n ← 20
REPEAT UNTIL(n < 1)
{
IF(n MOD 2 = 0)
{
count ← count + 1
}
n ← n - 3
}
Show answer
Answer: 4
Marking points:
ntakes the values 20, 17, 14, 11, 8, 5 and 2, then -1 stops the loop.- The even values are 20, 14, 8 and 2, so
countis 4.
- Exam-style The program should display the smallest of five numbers the user enters. Which line can replace
<MISSING CODE>?
small ← INPUT()
REPEAT 4 TIMES
{
num ← INPUT()
<MISSING CODE>
}
DISPLAY(small)
- A)
IF(num > small) { small ← num } - B)
IF(num < small) { num ← small } - C)
small ← num - D)
IF(num < small) { small ← num }
Show answer
Answer: D. It replaces small only when a smaller number arrives.
Why the others are wrong:
- A uses the wrong comparison, so it finds the largest number.
- B assigns the wrong way round, so
smallnever changes. - C has no selection, so it keeps the last number entered.
- Exam-style This segment should display 1 × 2 × 3 × 4 × 5, which is 120. Give the number of the line that stops it working.
1: product ← 0
2: k ← 1
3: REPEAT 5 TIMES
4: {
5: product ← product * k
6: k ← k + 1
7: }
8: DISPLAY(product)
Show answer
Answer: Line 1.
Marking points:
- Anything multiplied by 0 is 0, so the segment displays 0.
- Starting with
product ← 1makes it display 120.
- Exam-style Algorithm P counts the multiples of 5 from 1 to
nby testing every number withMOD. Algorithm Q does this:
count ← 0
k ← 5
REPEAT UNTIL(k ≥ n)
{
count ← count + 1
k ← k + 5
}
DISPLAY(count)
Which value of n shows that P and Q do not always display the same result?
- A) 4
- B) 7
- C) 10
- D) 12
Show answer
Answer: C. For n = 10, P counts 5 and 10, giving 2, but Q stops as soon as k reaches 10 and displays 1.
Why the others are wrong:
- A gives 0 for both: Q's loop never runs.
- B gives 1 for both, because 7 is not a boundary.
- D gives 2 for both, because 12 is not a multiple of 5.
- Recall Algorithm X sums 1 to 100 with a loop; algorithm Y displays 100 × 101 / 2. Which is true?
- A) Only X is an algorithm, because Y has no loop.
- B) Both display 5050, using different steps.
- C) They display different values, because Y uses multiplication.
- D) Both display 5050, so they are the same algorithm.
Show answer
Answer: B. 100 × 101 / 2 = 5050, the same sum the loop builds, so two different algorithms solve the same problem.
Why the others are wrong:
- A assumes an algorithm needs iteration; a fixed sequence of steps is also an algorithm.
- C ignores that the formula gives exactly the loop's sum.
- D treats the same result as the same algorithm; the steps differ.
Key points
Recall, then reveal
Say the main points from memory first, then check them.
Show key pointsHide key points
- Sequencing, selection and iteration are enough to build any algorithm, and the order of lines can change the result.
- Sums and counts start at 0; a maximum or minimum starts at the first value.
- Setup goes before the loop, updates inside, and the answer is used after.
- Different algorithms can solve one problem; compare them by tracing each on the same inputs.
- Test with a typical value, a boundary value and an edge case, not just one input.