Skip to content
🎯⭐ INTERACTIVE LESSON

Procedures & Lists

Learn step-by-step with interactive practice!

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

OperationPseudocodeEffect
Accesslist[i]Get element at index i
Assignlist[i] ← valueSet element at index i
InsertINSERT(list, i, value)Insert value at index i, shifting others right
AppendAPPEND(list, value)Add value to the end of the list
RemoveREMOVE(list, i)Remove element at index i, shifting others left
LengthLENGTH(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 ✍️

  1. APPEND(list, value) adds the value to the _______ of the list.

  2. REMOVE(list, i) removes the element at index i and shifts remaining elements _______.

  3. 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.

ConceptMeaning
ParameterVariable in the procedure's definition.
ArgumentValue passed in when calling.
Return valueWhat the procedure produces.
CallThe act of running the procedure.

Concept Check 🎯

Why Procedures Matter

BenefitExplanation
ReuseWrite logic once, call from many places.
AbstractionCaller doesn't need to know HOW it works.
TestabilityTest the procedure in isolation.
ReadabilityA 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:

OperationEffect
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 ✍️

  1. A named, reusable block of instructions is called a _______.

  2. The variable in a procedure's definition that receives a value is called a _______.

  3. 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.

TraversalCode shape
Complete, by valueFOR EACH item IN aList { … }
Complete, by indexi ← 1, then REPEAT UNTIL (i > LENGTH(aList)) { … i ← i + 1 }
PartialThe 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 ✍️

  1. minimum([7, 3, 9, 3]) returns _______.

  2. evensOnly([5, 8, 2, 7]) returns a list of length _______.

  3. 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.

CallExpected resultWhat it tests
countAbove([95, 80, 91], 90)2a typical case
countAbove([90, 90], 90)0values equal to the cutoff
countAbove([], 90)0an empty list

Applied Recall ✍️

  1. Giving a collection of data one name, without referring to how it is stored, is called data _______.

  2. Dividing a computer program into separate subprograms is called _______.

  3. 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"]:

OperationResulting listLENGTH
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 ✍️

  1. After list ← [1, 2, 3] and INSERT(list, 2, 9), what is list[3]? _______

  2. After list ← [5, 6, 7, 8] and REMOVE(list, 3), what is LENGTH(list)? _______

  3. 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 ✍️

  1. topK([90, 80, 70, 60], 3) returns a list of length _______.

  2. After the even-squares loop runs with nums ← [1, 2, 3, 4], total is _______.

  3. 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

TermDefinition
ProcedureNamed, reusable block of code.
ParameterVariable in the definition.
ArgumentValue at the call site.
ReturnValue the procedure produces.
ListOrdered indexed collection.
LENGTHNumber of elements.
APPENDAdd to end.
TraversalAccessing list elements with a loop (complete or partial).
Data abstractionOne name for a collection of data.
Procedural abstractionUsing a procedure knowing what it does, not how.
ModularityDividing 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 ✍️

  1. Dividing a program into separate subprograms is called _______.

  2. The number of elements in a list is given by the _______ operation.

  3. 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 🎯