AP Computer Science Principles · Unit 3: Algorithms & Programming
3.15 Random Values
Why programs use random values
Programs often use random values to simulate unpredictable events, create variety, or model real-world uncertainty (e.g., dice games, simulations). Most languages provide a function like `RANDOM(a, b)` that returns a random integer between a and b, inclusive, with each value having an equal chance of being selected.
Random in expressions and simulations
Random values can be combined with arithmetic operators, conditionals, and variables to build more complex behavior — like simulating a coin flip (`RANDOM(1,2)`) or moving a sprite randomly. Simulations use repeated random values to model real-world processes that involve uncertainty, such as weather patterns or population growth.
Random values and testing
Because randomness introduces unpredictability, programs using random values can be harder to test and debug — the same run may produce different outputs each time. Developers must consider all possible ranges of random output when tracing code or checking for errors.
Key terms
- RANDOM(a, b)
- A function that returns a random integer between a and b, inclusive, with equal probability for each value.
- Why use random values?
- To simulate unpredictability, add variety, or model real-world uncertain events.
- Simulation
- A program that uses repeated random values to model real-world processes involving uncertainty.
- Testing challenge with randomness
- Random values can produce different outputs each run, making programs harder to test and debug.
- Example: coin flip simulation
- RANDOM(1,2) can represent heads (1) or tails (2), each with 50% probability.
Try an AP-style question
What values can RANDOM(1, 6) return?
- Any integer from 1 to 5
- Any integer from 1 to 6
- Any decimal from 1 to 6
- Any integer from 0 to 6
Show the answer
B. Inclusive on both ends.
Practice 8 AP-style questions with instant explanations, flashcards and spaced review.
Study 3.15 free in APrep