These are the examples from Lists as abstractions except in the AP CSP pseudocode language.

For different ways to traverse a list in the AP CSP language, see Traversals in AP CSP language.

Example 1: Finding an average

With a list

PROCEDURE findAverage(scores)
{
    sum ← 0

    FOR EACH scr IN scores
    {
        sum ← sum + scr
    }

    RETURN (sum / LENGTH (scores))
}

Without a list

PROCEDURE findAverage(s1, s2, s3)
{
    sum ← 0

    sum ← sum + s1
    sum ← sum + s2
    sum ← sum + s3

    RETURN (sum / 3)
}

Example 2: Finding the largest

With a list

PROCEDURE findMax(arr)
{
    max ← arr[1]
    index ← 2

    REPEAT UNTIL (index > LENGTH (arr))
    {
        IF(arr[index] > max)
        {
            max ← arr[index]
        }

        index ← index + 1
    }

    RETURN (max)
}

Without a list

PROCEDURE findMax(a, b, c)
{
    max ← a

    IF(b > max)
    {
        max ← b
    }

    IF(c > max)
    {
        max ← c
    }

    RETURN (max)
}

Example 3: Collecting values

With a list

scores ← []

DISPLAY("Score (-1 when done):")
score ← INPUT()

REPEAT UNTIL (score = -1)
{
    APPEND(scores, score)

    DISPLAY("Score (-1 when done):")
    score ← INPUT()
}

DISPLAY(scores)

Without a list

s1 ← 0
s2 ← 0
s3 ← 0
count ← 0

DISPLAY("Score (-1 when done):")
input ← INPUT()

REPEAT UNTIL (input = -1)
{
    count ← count + 1

    IF(count = 1)
    {
        s1 ← input
    }
    ELSE
    {
        IF(count = 2)
        {
            s2 ← input
        }
        ELSE
        {
            s3 ← input
        }
    }

    IF(count < 3)
    {
        DISPLAY("Score (-1 when done):")
        input ← INPUT()
    }
    ELSE
    {
        input = -1
    }
}

DISPLAY(count)
DISPLAY(s1)
DISPLAY(s2)
DISPLAY(s3)

Help & comments

Get help from AP CS Tutor Brandon Horn

Comment on Lists as abstractions