PrepGo

Random Values - AP Computer Science Principles Study Guide

Written by AP Content Team, Verified for 2026 AP Exams, Last updated: May 2026

Learn with study guides reviewed by top AP teachers. This guide takes about 10 minutes to read.

Getting Started

Computers are designed to be predictable, following instructions precisely every time. But what about tasks that require surprise or unpredictability, like shuffling a playlist, creating a unique level in a video game, or simulating a weather pattern? To achieve this, programmers use random values to introduce variability and create dynamic, less predictable programs that can model the complexities of the real world.

What You Should Be Able to Do

  • Explain the purpose of using random values in a program.

  • Use the RANDOM(a, b) function to generate integers within a specific, inclusive range.

  • Describe how random numbers are applied in simulations and modeling.

  • Trace the execution of an algorithm that includes random number generation and predict the possible outcomes.

Key Concepts & Application

The Core Idea

At their core, computers are deterministic machines; given the same input, they will always produce the same output. To create an element of chance, we use algorithms to generate pseudo-random numbers. These are not truly random but are calculated in a way that is statistically random enough for most purposes. Think of it like a perfectly shuffled deck of cards—while the order is determined by the shuffle, the next card drawn is unpredictable to the player.

This capability is essential for creating simulations and models. A simulation is a simplified representation of a more complex object or phenomenon, often created to test theories or make predictions. For example, a traffic simulation can help city planners predict how a new road will affect commute times. This process is a form of abstraction, which is the process of reducing complexity by focusing on the main idea and hiding details that are not relevant to the current purpose. By using random numbers to simulate driver behavior or traffic incidents, the model becomes a powerful, abstract tool for understanding a complex system without having to build a real road first.

Logic & Application

The primary tool for generating random values in programming is a function that produces a number within a specified range. In the pseudocode used for this course, this function is RANDOM(a, b).

Key Principles of RANDOM(a, b)

  • Inclusive Range: The function returns an integer between a and b, including both a and b as possible outcomes.

  • Equal Probability: Every integer in the range has an equal chance of being selected. RANDOM(1, 6) will produce a 2 just as often as it produces a 6 over many repetitions.

  • Integer Output: The function typically returns a whole number.

Annotated Pseudocode Examples

  1. Simulating a Six-Sided Die

    This is the most direct application. The goal is to get a random integer from 1 to 6.

    
    // Generate a random integer between 1 and 6, inclusive.
    
    dieRoll <- RANDOM(1, 6)
    
    
    // Display the result to the user.
    
    DISPLAY("You rolled a: ")
    
    DISPLAY(dieRoll)
    
  2. Simulating a Coin Flip

    Here, we can map numbers to outcomes. For a coin, there are two possibilities: heads or tails. We can use RANDOM(1, 2) and assign 1 to "Heads" and 2 to "Tails".

    
    // Generate a random integer, either 1 or 2.
    
    flipResult <- RANDOM(1, 2)
    
    
    // Use selection to determine the outcome.
    
    IF (flipResult = 1)
    
    {
    
      DISPLAY("Heads")
    
    }
    
    ELSE
    
    {
    
      DISPLAY("Tails")
    
    }
    
  3. Randomly Selecting from a List

    Random numbers are often used to pick an item from a list by its index. If a list has 3 items at indices 1, 2, and 3, RANDOM(1, 3) can be used to select a random index.

    
    // A list of possible prizes.
    
    prizes <- ["Sticker", "Keychain", "Free T-Shirt"]
    
    
    // Generate a random index from 1 to the length of the list.
    
    // In this case, the length is 3.
    
    randomIndex <- RANDOM(1, 3)
    
    
    // Retrieve the prize at the randomly chosen index.
    
    chosenPrize <- prizes[randomIndex]
    
    
    // Display the result.
    
    DISPLAY("You won a: ")
    
    DISPLAY(chosenPrize)
    

Tracing & Analysis

  • Logic Trace

    Because algorithms with random values can produce different results on each run, we trace the possible paths of execution. Let's trace the coin flip example.

    Path 1:

    1. flipResult <- RANDOM(1, 2) is executed. The function returns 1.

    2. The variable flipResult now holds the value 1.

    3. The condition IF (flipResult = 1) is evaluated. Since 1 = 1 is true, the code inside the IF block runs.

    4. The program displays "Heads".

    Path 2:

    1. flipResult <- RANDOM(1, 2) is executed. The function returns 2.

    2. The variable flipResult now holds the value 2.

    3. The condition IF (flipResult = 1) is evaluated. Since 2 = 1 is false, the code inside the ELSE block runs.

    4. The program displays "Tails".

  • Broader Applications

    The use of randomness extends beyond simple games. In scientific modeling, random numbers help simulate particle physics or genetic mutations. In cybersecurity, they are fundamental for creating encryption keys that are impossible to guess. In data analysis, random sampling allows researchers to draw conclusions about a large population from a small, representative subset.

Key Terminology & Logic

A compact reference for the core logic introduced in this topic.

Keyword / SymbolNamePurpose
RANDOM(a, b)Random FunctionGenerates a random integer between a and b, inclusive.
<-Assignment OperatorStores a value (like a random number) in a variable.
DISPLAY(value)Display CommandOutputs a value to the screen, showing the result of the random event.

Core Concepts & Terminology

This section provides concise, textbook-style definitions for key terms and concepts related to random values.

  • Abstraction: The process of reducing complexity by hiding details to focus on the essential characteristics of a system. Using a RANDOM function is a form of abstraction, as we don't need to know how it generates the number, only that it does.

  • Simulation: A simplified representation of a real-world process or system, created to study its behavior. Simulations often use random values to model unpredictable events.

  • Modeling: The process of creating a simplified representation (a model) of a system to gain insight or make predictions. Randomness is a key component in many computational models.

  • Core Logic: Random Number Generation: The fundamental structure for using a random value involves generating it and storing it in a variable for later use in decisions, calculations, or selections.

    
    // Generate a random number in the range 1 to 100
    
    // and store it in the variable 'score'.
    
    score <- RANDOM(1, 100)
    

Core Skill Check

Apply your knowledge with these brief exercises.

  • Logic Tracing: What are all the possible values of x after this pseudocode runs: x <- RANDOM(10, 13)?

  • Debugging: A programmer wants to simulate picking a random day of the week, numbered 1 (Sunday) through 7 (Saturday). Identify the logic error in this code: day <- RANDOM(1, 8).

  • Application: Describe how a music streaming service could use a RANDOM function to implement a "shuffle playlist" feature.

Common Misconceptions & Clarifications

  • "Computers can generate truly random numbers."

    Clarification: Most computers generate pseudo-random numbers using complex mathematical algorithms. For everyday applications like games and simulations, they are effectively random, but they are not truly unpredictable like subatomic events.

  • "RANDOM(1, 10) means any number from 1 up to, but not including, 10."

    Clarification: In the pseudocode for this course, RANDOM(a, b) is inclusive, meaning both a and b are possible results. RANDOM(1, 10) can produce any integer from 1 to 10.

  • "Randomness is only useful for games."

    Clarification: While games are a common example, random values are critical in many fields, including scientific modeling (e.g., climate change), cryptography (e.g., secure communication), machine learning (e.g., initializing models), and statistical sampling.

Summary

Introducing random values is a powerful technique for breaking the deterministic nature of computer programs. By using a function like RANDOM(a, b), programmers can generate unpredictable integers within a specified, inclusive range. This capability is the foundation for building simulations and models, which are forms of abstraction that allow us to study complex, real-world systems in a controlled, virtual environment. From shuffling a digital deck of cards to modeling a global pandemic, the controlled use of randomness is a fundamental tool in computational thinking and problem-solving.