Procedures & Lists - Complete Interactive Lesson
Part 1: List Operations, Traversals, and Procedure Design
📝 Procedures & Lists
Part 1 of 7 — List Operations, Traversals, and Procedure Design
Lists in AP CSP
A list (also called an array) stores an ordered collection of values.
// AP CSP pseudocode uses 1-based indexing!
myList ← ["apple", "banana", "cherry"]
DISPLAY(myList[1]) // "apple" (index 1 is the first element)
DISPLAY(myList[3]) // "cherry"
⚠️ AP CSP lists are 1-indexed (first element at index 1). Most programming languages are 0-indexed.
List Operations
| Operation | Pseudocode | Effect |
|---|---|---|
| Access | list[i] | Get element at index i |
| Assign | list[i] ← value | Set element at index i |
| Insert | INSERT(list, i, value) | Insert value at index i, shifting others right |
| Append | APPEND(list, value) | Add value to the end of the list |
| Remove | REMOVE(list, i) | Remove element at index i, shifting others left |
| Length | LENGTH(list) | Number of elements in the list |
Example
scores ← [90, 85, 78]
APPEND(scores, 92) // [90, 85, 78, 92]
INSERT(scores, 2, 88) // [90, 88, 85, 78, 92]
REMOVE(scores, 1) // [88, 85, 78, 92]
DISPLAY(LENGTH(scores)) // 4
Concept Check 🎯
List Traversal
FOR EACH Loop
total ← 0
FOR EACH score IN scores
{
total ← total + score
}
average ← total / LENGTH(scores)
Index-Based Loop
i ← 1
REPEAT UNTIL (i > LENGTH(scores))
{
DISPLAY(scores[i])
i ← i + 1
}
Common List Algorithms
Find the Maximum
PROCEDURE findMax(list)
{
max ← list[1]
FOR EACH item IN list
{
IF (item > max)
{
max ← item
}
}
RETURN(max)
}
Filter a List
PROCEDURE getPositives(list)
{
result ← []
FOR EACH item IN list
{
IF (item > 0)
{
APPEND(result, item)
}
}
RETURN(result)
}
Swap Two Elements
temp ← list[i]
list[i] ← list[j]
list[j] ← temp
Applied Recall ✍️
-
APPEND(list, value) adds the value to the _______ of the list.
-
REMOVE(list, i) removes the element at index i and shifts remaining elements _______.
-
To swap two list elements without losing data, you need a _______ variable.
List Operations 🔍
AP Exam Strategy: Procedures & Lists
- Lists are 1-indexed on the AP exam — first element is list[1], NOT list[0]
- Know all list operations: access, assign, INSERT, APPEND, REMOVE, LENGTH
- INSERT shifts elements RIGHT (list grows). REMOVE shifts elements LEFT (list shrinks)
- The swap algorithm (using temp) appears frequently — memorize it
- Common patterns: sum/average, find max/min, filter, count matches
- FOR EACH is read-only for the loop variable — changes to the variable do NOT change the list
AP-Style Application 🎯
Part 2: Key Processes
📋 Procedures & Lists
Part 2 of 7 — Key Processes
Procedures Bundle Reusable Logic
A procedure (a.k.a. function or method) is a named, reusable block of instructions. Define once, call many times.
PROCEDURE greet(name)
{
DISPLAY("Hello,")
DISPLAY(name)
}
Calling greet("Alex") runs the body with name assigned "Alex", so it displays Hello, Alex.
| Concept | Meaning |
|---|---|
| Parameter | Variable in the procedure's definition. |
| Argument | Value passed in when calling. |
| Return value | What the procedure produces. |
| Call | The act of running the procedure. |
Concept Check 🎯
Why Procedures Matter
| Benefit | Explanation |
|---|---|
| Reuse | Write logic once, call from many places. |
| Abstraction | Caller doesn't need to know HOW it works. |
| Testability | Test the procedure in isolation. |
| Readability | A well-named procedure documents intent. |
Lists Hold Many Values
A list is an ordered collection of values, accessed by index.
grades ← [85, 92, 78, 90]
DISPLAY(grades[1]) // 85 (AP lists start at index 1)
DISPLAY(LENGTH(grades)) // 4
Common list operations:
| Operation | Effect |
|---|---|
| APPEND(list, x) | Add x at the end. |
| INSERT(list, i, x) | Insert x at index i. |
| REMOVE(list, i) | Remove element at index i. |
| list[i] | Read / write element i. |
| LENGTH(list) | Number of elements. |
Mini-walkthrough
PROCEDURE average(scores)
{
total ← 0
FOR EACH s IN scores
{
total ← total + s
}
RETURN(total / LENGTH(scores))
}
Now anywhere we need an average, we call average(myList).
Applied Recall ✍️
-
A named, reusable block of instructions is called a _______.
-
The variable in a procedure's definition that receives a value is called a _______.
-
In AP CSP pseudocode, the first element of a list is at index _______.
Targeted Practice 🔍
AP Exam Strategy: Procedures & Lists
- Know the parameter / argument distinction.
- Be careful with 1-based indexing in AP pseudocode.
- LENGTH, APPEND, INSERT, REMOVE are the core list ops.
AP-Style Application 🎯
Part 3: List Traversal Algorithms
📋 Procedures & Lists
Part 3 of 7 — List Traversal Algorithms
Complete and Partial Traversals
Traversing a list means using iteration to access its elements. A complete traversal accesses every element; a partial traversal accesses only some of them, for example by RETURNing at the first match.
| Traversal | Code shape |
|---|---|
| Complete, by value | FOR EACH item IN aList { … } |
| Complete, by index | i ← 1, then REPEAT UNTIL (i > LENGTH(aList)) { … i ← i + 1 } |
| Partial | The same loop, with an early RETURN or a smaller stopping index |
FOR EACH assigns item the value of each element in order, from the first element to the last.
Concept Check 🎯
Existing List Algorithms
Knowing these existing algorithms helps you build new ones.
Sum and Average
PROCEDURE average(nums)
{
total ← 0
FOR EACH n IN nums
{
total ← total + n
}
RETURN(total / LENGTH(nums))
}
Minimum
PROCEDURE minimum(nums)
{
smallest ← nums[1]
FOR EACH n IN nums
{
IF (n < smallest)
{
smallest ← n
}
}
RETURN(smallest)
}
Keeping Only Some Elements
PROCEDURE evensOnly(nums)
{
result ← []
FOR EACH n IN nums
{
IF (n MOD 2 = 0)
{
APPEND(result, n)
}
}
RETURN(result)
}
To build a new list from every element, APPEND without an IF: APPEND(doubled, n * 2).
Linear Search
PROCEDURE indexOf(aList, target)
{
i ← 1
REPEAT UNTIL (i > LENGTH(aList))
{
IF (aList[i] = target)
{
RETURN(i)
}
i ← i + 1
}
RETURN(-1)
}
Traversing two lists at the same time with one shared index is not on the exam; exam questions traverse one list at a time.
Applied Recall ✍️
-
minimum([7, 3, 9, 3]) returns _______.
-
evensOnly([5, 8, 2, 7]) returns a list of length _______.
-
indexOf(["a", "b", "c"], "c") returns _______.
Targeted Practice 🔍
AP Exam Strategy: List Traversals
- Name the algorithm from its shape: running total → sum/average; best-so-far → min/max; APPEND inside IF → keep some elements; early RETURN of an index → linear search.
- Start a min/max tracker from list[1], not from 0, so a list of all negative (or all large) values still works.
- FOR EACH gives values, not indexes; use an index loop when the position matters.
- Check the empty list: FOR EACH runs zero times, and LENGTH(list) is 0.
AP-Style Application 🎯
Part 4: Data Abstraction and Procedural Abstraction
📋 Procedures & Lists
Part 4 of 7 — Data Abstraction and Procedural Abstraction
Lists Are Data Abstractions
Data abstraction manages complexity by giving a collection of data one name, without referring to the details of how it is stored. Compare:
score1 ← 88
score2 ← 92
score3 ← 75
scores ← [88, 92, 75]
With the list, one loop processes every score, and adding a fourth score changes the data, not the code. Data abstractions make a program easier to develop and maintain. A list can also hold different types of elements.
Assigning One List to Another
The reference sheet says aList ← bList assigns a copy of bList to aList. After the copy, changing one list does not change the other.
Concept Check 🎯
Procedural Abstraction
Procedural abstraction names a process so it can be used knowing only what it does, not how.
- Modularity: a program is divided into separate subprograms, and the solution to a large problem is built from solutions to smaller subproblems.
- Parameters generalize a procedure, so it can be reused with a range of input values.
- Internals can change (to be faster or clearer) without telling callers, as long as what the procedure does stays the same.
PROCEDURE countAbove(nums, cutoff)
{
count ← 0
FOR EACH n IN nums
{
IF (n > cutoff)
{
count ← count + 1
}
}
RETURN(count)
}
countAbove(scores, 90) and countAbove(temperatures, 30) reuse one procedure instead of two nearly identical ones.
Testing a Procedure
Testing uses defined inputs with expected outputs. Good test inputs include values at or just beyond the extremes of the input data.
| Call | Expected result | What it tests |
|---|---|---|
| countAbove([95, 80, 91], 90) | 2 | a typical case |
| countAbove([90, 90], 90) | 0 | values equal to the cutoff |
| countAbove([], 90) | 0 | an empty list |
Applied Recall ✍️
-
Giving a collection of data one name, without referring to how it is stored, is called data _______.
-
Dividing a computer program into separate subprograms is called _______.
-
countAbove([12, 45, 30, 45], 30) returns _______.
Targeted Practice 🔍
AP Exam Strategy: Abstraction
- "Manages complexity" with a list → one name for many values, one loop instead of repeated code, no code change when the amount of data changes.
- "Manages complexity" with a procedure → reuse instead of duplication, parameters for generalization, readability, and one place to fix bugs.
- aList ← bList makes a copy.
- Pick test inputs that include typical values, boundary values, and an empty list.
AP-Style Application 🎯
Part 5: Inserting, Removing, and Updating Elements
📋 Procedures & Lists
Part 5 of 7 — Inserting, Removing, and Updating Elements
How List Operations Shift Elements
Starting each time from list ← ["a", "b", "c", "d"]:
| Operation | Resulting list | LENGTH |
|---|---|---|
| APPEND(list, "e") | ["a", "b", "c", "d", "e"] | 5 |
| INSERT(list, 2, "x") | ["a", "x", "b", "c", "d"] | 5 |
| REMOVE(list, 1) | ["b", "c", "d"] | 3 |
| list[3] ← "z" | ["a", "b", "z", "d"] | 4 |
- INSERT shifts the elements at indices ≥ i one place to the right.
- REMOVE shifts the elements after index i one place to the left.
- Assigning to list[i] replaces one element; the length does not change.
⚠️ For every list operation, an index less than 1 or greater than LENGTH(list) produces an error, and the program stops.
Concept Check 🎯
Removing While Traversing
REMOVE shifts later elements left. If the loop always moves on with i ← i + 1, the element that slid into position i is never checked.
i ← 1
REPEAT UNTIL (i > LENGTH(nums))
{
IF (nums[i] < 0)
{
REMOVE(nums, i)
}
i ← i + 1
}
With nums ← [3, -1, -2, 5]: at i = 2, -1 is removed and -2 slides into index 2, but i becomes 3, so -2 is skipped. The result is [3, -2, 5].
Fix: move to the next index only when nothing was removed.
IF (nums[i] < 0)
{
REMOVE(nums, i)
}
ELSE
{
i ← i + 1
}
Updating Every Element by Index
FOR EACH assigns item a copy of each value, so item ← item * 2 does not change the list. To change the elements themselves, use an index:
i ← 1
REPEAT LENGTH(prices) TIMES
{
prices[i] ← prices[i] * 2
i ← i + 1
}
Applied Recall ✍️
-
After list ← [1, 2, 3] and INSERT(list, 2, 9), what is list[3]? _______
-
After list ← [5, 6, 7, 8] and REMOVE(list, 3), what is LENGTH(list)? _______
-
The first (buggy) removal loop runs on nums ← [-4, -6, 2]. How many negative values are left in nums? _______
Targeted Practice 🔍
AP Exam Strategy: Changing Lists
- Redraw the list after every INSERT, APPEND, or REMOVE; indexes of later elements change.
- INSERT and APPEND add 1 to LENGTH; REMOVE subtracts 1; list[i] ← x leaves LENGTH unchanged.
- Any index below 1 or above LENGTH(list) is an error.
- When removing inside a loop, only advance the index when nothing was removed.
- Use an index loop, not FOR EACH, to change the elements of a list.
AP-Style Application 🎯
Part 6: Problem-Solving Workshop
📋 Procedures & Lists
Part 6 of 7 — Problem-Solving Workshop
Procedures & Lists Workshop
End-to-end problems that combine procedures, parameters, and list traversals, written in exam reference sheet pseudocode.
Concept Check 🎯
Worked: Top k From a Sorted List
The list is already sorted from highest to lowest. Return a new list holding its first k values.
PROCEDURE topK(sortedScores, k)
{
result ← []
i ← 1
REPEAT k TIMES
{
APPEND(result, sortedScores[i])
i ← i + 1
}
RETURN(result)
}
If k > LENGTH(sortedScores), sortedScores[i] goes out of range and the program stops with an error. A guard at the top fixes this: IF (k > LENGTH(sortedScores)) { k ← LENGTH(sortedScores) }.
Worked: Several Steps in One Traversal
Sum the squares of the even numbers in nums:
total ← 0
FOR EACH n IN nums
{
IF (n MOD 2 = 0)
{
total ← total + n * n
}
}
The IF picks the even values, and the accumulator adds each square.
Worked: Procedures Calling Procedures
PROCEDURE topAverage(sortedScores, k)
{
best ← topK(sortedScores, k)
RETURN(average(best))
}
Here average(nums) is the sum-and-divide procedure from Part 3. For topAverage([98, 91, 85, 70], 2), topK returns [98, 91], and average returns 94.5. Each procedure solves one subproblem, and the results are combined.
Applied Recall ✍️
-
topK([90, 80, 70, 60], 3) returns a list of length _______.
-
After the even-squares loop runs with nums ← [1, 2, 3, 4], total is _______.
-
topAverage([88, 84, 79, 60], 2) returns _______.
Targeted Practice 🔍
AP Exam Strategy: Workshop
- Trace the innermost or earliest call first, then pass its result outward.
- Count APPENDs to find the length of a returned list.
- Check every index a loop can reach; a value above LENGTH(list) is an error.
- Combining a filter and an accumulator in one FOR EACH loop is a common exam pattern.
AP-Style Application 🎯
Part 7: AP Review
📋 Procedures & Lists
Part 7 of 7 — AP Review
AP Exam Recap — Procedures & Lists
Concept Check 🎯
Final Vocab
| Term | Definition |
|---|---|
| Procedure | Named, reusable block of code. |
| Parameter | Variable in the definition. |
| Argument | Value at the call site. |
| Return | Value the procedure produces. |
| List | Ordered indexed collection. |
| LENGTH | Number of elements. |
| APPEND | Add to end. |
| Traversal | Accessing list elements with a loop (complete or partial). |
| Data abstraction | One name for a collection of data. |
| Procedural abstraction | Using a procedure knowing what it does, not how. |
| Modularity | Dividing a program into separate subprograms. |
Common Pitfalls
- Confusing parameter and argument.
- Off-by-one with 1-indexed lists.
- Forgetting to RETURN a value.
- Reading an index below 1 or above LENGTH(list), which is an error.
- Writing one big function instead of decomposing.
Applied Recall ✍️
-
Dividing a program into separate subprograms is called _______.
-
The number of elements in a list is given by the _______ operation.
-
A loop that RETURNs as soon as it finds a match performs a _______ traversal.
Targeted Practice 🔍
Final Exam Tips
- Parameter vs. argument: definition vs. call.
- LENGTH, APPEND, INSERT, REMOVE, list[i] are AP's core list ops.
- Name the traversal pattern when you see it: sum/average, min/max, keep some (APPEND inside IF), or linear search.
- Decomposing into named procedures is almost always the right move.
AP-Style Application 🎯