Appropriate libraries or APIs (College Board AP® Computer Science Principles): Study Guide
Using libraries and APIs
What is a library?
A library is a collection of pre-written procedures that can be imported and used in a program
Libraries provide tested, reusable code so programmers do not need to write common functionality from scratch
Code can come from existing libraries, other programmers, or online sources
What is an API?
An API (Application Programming Interface) is a set of rules and specifications that defines how procedures in a library can be used
APIs tell the programmer what procedures are available, what parameters they accept, and what values they return
Using a library simplifies development because the programmer only needs to understand the API, not the internal implementation
API documentation and specifications
API documentation describes how to use each procedure in a library: its name, parameters, return values, and behavior
Programmers read the documentation to understand what a procedure does without needing to read its source code
Well-written documentation includes examples showing how to call the procedure correctly
API documentation element | What it tells you |
|---|---|
Procedure name | What to call to access the functionality |
Parameters | What inputs the procedure accepts |
Return value | What the procedure sends back (if anything) |
Random value generation
How does random value generation work?
The
RANDOMfunction generates a random integer between two specified values (inclusive)In AP CSP pseudocode:
RANDOM(a, b)returns a value where a ≤ result ≤ bEach time
RANDOMis called, it may produce a different result, even with the same arguments
roll ← RANDOM(1, 6)
DISPLAY(roll)
This simulates a dice roll by generating a random integer from 1 to 6
Using random values in programs
Common uses include: simulating events, generating test data, and creating games
Repeated runs of the same program may produce different outputs when
RANDOMis used
REPEAT 3 TIMES
{
DISPLAY(RANDOM(1, 10))
}
Each execution displays three random numbers between 1 and 10, potentially different every time
Examiner Tips and Tricks
In code trace questions involving
RANDOM, the question will either give you the generated value or ask what range of outputs is possible; you never need to predict the exact random result.For the CPT, if your program uses a library or API (including
RANDOM), explain in your written response why you chose it and how it simplifies your solution.
Worked Example
What is the possible range of values displayed by the following code segment?
num ← RANDOM(5, 15)
result ← num + 10
DISPLAY(result)
(A) 5 to 15
(B) 10 to 20
(C) 15 to 25
(D) 5 to 25
[1]
Answer:
(C) 15 to 25 [1 mark]
RANDOM(5, 15)produces values from 5 to 15 inclusive; adding 10 to each possible value shifts the entire range to 15 through 25
Unlock more, it's free!
Was this revision note helpful?