πŸ’» Computer Science · High School · CSP

AP Computer Science Principles

A complete, beginner-friendly introduction to how computers and programs actually work, built around the five Big Ideas of the AP Computer Science Principles framework: Creative Development, Data, Algorithms and Programming, Computing Systems and Networks, and the Impact of Computing. You will learn how software is designed and tested, how computers store numbers, text, images, and sound in…

Start the interactive course (quizzes, progress, videos) →

Free forever. No sign-up, no ads. 15 lessons. The full lesson text is below so you can read it right here.

Module 1: Creative Development

What computing is, and how software actually gets made. You will see that programs are built by people working together, step by step, and that finding and fixing mistakes is a normal, central part of the craft rather than a sign of failure.

Welcome to Computer Science Principles

  • Describe what a computer and a program are in plain language.
  • Name the five Big Ideas that organize this course.
  • Explain why computing is a creative, human activity.

The big picture

A computer is a machine that follows instructions to work with information, and a program is just a list of those instructions written for the computer to follow. This whole course is about how that works: how instructions are written, how information is stored, and how computing changes the world. You do not need any prior experience; every idea is explained from the ground up.

Key idea: a computer follows instructions to process information, and a program is the list of instructions.

What is a computer, really?

When people hear "computer" they picture a laptop, but the word is much broader. A computer is any device that can store information and follow step-by-step instructions to change it. That includes phones, game consoles, the chip in a microwave, and the system in a car. The instructions can be swapped out, which is what makes a computer so powerful: the same physical machine can run a game one minute and do your homework the next, simply by loading different instructions.

Think of a computer like a player piano. The piano is the same machine every time, but feed it a different paper roll of holes and it plays a different song. A computer is the piano, and a program is the roll of instructions that tells it what to do.

Key idea: the hardware stays the same while the program changes, so one machine can do countless different jobs.

What is a program?

A program is a sequence of instructions that tells a computer what to do, written in a special language the computer can carry out. When you open an app, you are running a program that someone wrote. Programming, also called coding, is the act of writing those instructions. A programmer is a bit like a recipe author: they write clear, ordered steps so that anyone (or any machine) that follows them exactly gets the intended result.

Here is the important part for this course: writing a program is a creative act. There is almost never a single "correct" program. Just as two authors can write very different stories about the same idea, two programmers can solve the same problem in very different ways, each making choices about how to structure and express the solution.

Key idea: a program is an ordered set of instructions, and writing one is a creative act with many valid solutions.

The five Big Ideas

AP Computer Science Principles is organized around five Big Ideas. They are the five lenses this course keeps returning to, and every module lines up with one of them.

Big IdeaWhat it is about
Creative DevelopmentHow programs are designed, built, tested, and improved, often by teams
DataHow computers store and process numbers, text, images, and sound, and what data reveals
Algorithms and ProgrammingThe building blocks of code and the step-by-step methods that solve problems
Computing Systems and NetworksHow the Internet and connected devices move information around the world
Impact of ComputingHow computing helps and harms people and society

These are not separate subjects to memorize; they overlap constantly. A weather app touches every one of them: it stores data, runs algorithms, sends information over a network, was built by a team, and affects the people who rely on it.

Key idea: the five Big Ideas are five connected lenses on computing, not five isolated topics.

Computing is for everyone

A common worry is that you have to be a "math genius" to study computing. You do not. The most valuable skills here are the ones you already practice: breaking a big problem into smaller pieces, following and giving clear instructions, and staying patient when something does not work the first time. Computing is a human, collaborative field, and its most interesting problems are solved by people with many different strengths, not by lone geniuses.

Key idea: the core skills of computing are problem breaking, clear instructions, and patience, which anyone can build.

How this course lines up with the AP framework

This course follows the official College Board framework for AP Computer Science Principles. The framework gives each Big Idea a short code. Creative Development is CRD. Data is DAT. Algorithms and Programming is AAP. Computer Systems and Networks is CSN. Impact of Computing is IOC. When a later lesson says "this is Big Idea 2, Data," it is pointing at that framework. The codes also tell you how the exam is built, because every multiple-choice question is tied to one Big Idea.

Big IdeaCodeShare of exam questions
Creative DevelopmentCRD10-13 percent
DataDAT17-22 percent
Algorithms and ProgrammingAAP30-35 percent
Computer Systems and NetworksCSN11-15 percent
Impact of ComputingIOC21-26 percent

Notice where the weight sits. Algorithms and Programming is the largest slice, and Impact of Computing is second. That is why this course spends so much time on code and on consequences. The AP assessment also includes the Create Performance Task, a program you build yourself and explain in writing. The final lesson walks through it in detail, but keep it in mind from the start, because the skills in every module feed it.

Key idea: the five Big Ideas have official codes (CRD, DAT, AAP, CSN, IOC), and Algorithms and Programming carries the most exam weight.

Your first look at AP pseudocode

The AP exam writes code in a special pseudocode described on the official reference sheet. It is not a language you install. It is a paper language designed to be read. You will meet it in every module of this course, so here is a first taste. The arrow symbol stores a value in a variable, the way an equals sign does in many languages. DISPLAY shows a value to the user.

a ← 3
b ← 4
total ← a + b
DISPLAY(total)

Read it line by line, exactly as the computer would. The table below is called a trace, and it records what each variable holds after each line runs.

LineabtotalWhat happened
a ← 33--a stores 3
b ← 434-b stores 4
total ← a + b3473 plus 4 is 7, stored in total
DISPLAY(total)347the program shows 7

That is the whole skill: run the lines in order, in your head, and track the values. Every later lesson builds on this habit, and the exam rewards it heavily.

One warning as you read exam code: the arrow always points at the variable receiving the value, so read it aloud as "gets" to keep the direction straight. If a line says b ← a, then b gets a copy of the value stored in a, and a itself is unchanged. Small careful readings like that prevent most of the careless mistakes students make under time pressure.

Key idea: AP pseudocode stores values with an arrow, and tracing a program line by line tells you exactly what it displays.

Computational thinking: the skill underneath everything

Computer scientists lean on four thinking moves so often that the set has a shared name: computational thinking. The first is decomposition, which means breaking a big problem into smaller pieces you can solve one at a time. The second is pattern recognition, spotting where the same work repeats. The third is abstraction, setting aside details you do not need right now. The fourth is writing algorithms, clear step-by-step plans anyone could follow. Planning a school event uses all four. You split the work into food, music, and tickets. You notice every ticket sale follows the same steps. You ignore details that do not matter yet. Then you write the checklist.

None of these moves require a computer. That is the point. This course, and Big Idea 1, Creative Development, treat programming as organized human thinking first and typing second. If you can plan a trip or organize a fundraiser, you have already practiced the core skills.

Key idea: decomposition, pattern recognition, abstraction, and algorithms are the four moves of computational thinking, and none of them require a computer.

Common misconceptions

  • "A computer is smart and understands what I mean." A computer follows instructions exactly and literally; it has no understanding. If your instructions are slightly wrong, it does the wrong thing without noticing, which is why precision matters so much.
  • "You must be a math genius to code." Programming leans far more on logical thinking and persistence than on advanced math. Plenty of strong programmers found math ordinary in school.
  • "There is one right program for each problem." Almost every problem has many valid solutions that differ in style, speed, and clarity. Programming is a design activity with real choices.
  • "Computers can only be laptops and phones." Any device that stores information and follows instructions is a computer, including the chips inside appliances, cars, and toys.
  • "AP CSP is only for students who already code." The course assumes no experience at all. It is designed as a first computing course, and the exam's pseudocode is read on paper rather than typed into a machine.
  • "Computer science is just coding." Programming is one Big Idea out of five. Data, networks, security, and the effects of computing on people are core parts of the field and of this course.

Recap

  • A computer is any device that stores information and follows step-by-step instructions.
  • A program is an ordered list of instructions; writing one is a creative act.
  • The same hardware can do many jobs because the program can be changed.
  • The course is organized around five connected Big Ideas.
  • Computing rewards clear thinking and persistence, and it is open to everyone.

Sources

  1. College Board. (2023). AP Computer Science Principles course and exam description. College Board. apcentral.collegeboard.org β†—
  2. College Board. (n.d.). AP Computer Science Principles course. AP Central. apcentral.collegeboard.org β†—
  3. College Board. (n.d.). AP Computer Science Principles. AP Students. apstudents.collegeboard.org β†—
  4. Code.org β†—. (n.d.). Computer Science Principles curriculum. Code.org β†—. code.org β†—
  5. Khan Academy. (n.d.). Computers and the Internet. Khan Academy. khanacademy.org β†—
  6. Malan, D. J. (2026). CS50x: Introduction to computer science. Harvard University. cs50.harvard.edu β†—
  7. K-12 Computer Science Framework Steering Committee. (2016). K-12 Computer Science Framework. K12CS.org β†—. k12cs.org β†—
Key terms
Computer
Any device that stores information and follows step-by-step instructions to process it.
Program
An ordered sequence of instructions that tells a computer what to do.
Programming
The act of writing the instructions that make up a program; also called coding.
Big Ideas
The five organizing themes of AP CSP: Creative Development, Data, Algorithms and Programming, Computing Systems and Networks, and Impact of Computing.
Hardware
The physical parts of a computer, which stay the same while the program running on them can change.
Instruction
A single step a computer can carry out; programs are built from many instructions in order.

How Programs Are Made: Design and Collaboration

  • Describe the iterative process of developing a program.
  • Explain why collaboration improves software.
  • Use design tools to plan a program before coding.

The big picture

Real software is almost never written perfectly in one straight shot. It is built in small loops of planning, coding, testing, and improving, usually by a team rather than one person. Understanding this process makes programming far less intimidating, because you no longer expect to get everything right on the first try.

Key idea: programs are developed in repeating cycles of design, build, test, and improve.

The development process is a loop

Developers follow an iterative process, which simply means they repeat a cycle many times, improving the work a little each round. A rough version of the cycle looks like this:

  1. Investigate and plan: understand the problem and decide what the program should do.
  2. Design: sketch how it will work before writing any code.
  3. Build: write the actual instructions.
  4. Test: run it, look for mistakes, and check it against the goal.
  5. Reflect and revise: fix problems and improve the design, then loop back.

Think of it like writing an essay. You do not produce a polished final draft in one pass; you outline, write a rough draft, reread it, and revise, often several times. Software grows the same way, one improved draft at a time.

Key idea: good programs, like good essays, come from drafting and revising, not from a single perfect attempt.

Why collaboration matters

Most real programs are too big for one person, so they are built by teams. Collaboration means people working together, and it makes software better for concrete reasons. Different people notice different bugs, bring different ideas, and catch each other's blind spots. A feature that seems obvious to the person who wrote it may confuse everyone else, and a teammate is the one who says so before users do.

Working well with others is a genuine skill. It includes explaining your thinking clearly, listening to feedback without taking it personally, giving credit, and dividing a large job into pieces different people can build at the same time. The AP course treats collaboration as a core practice, not an afterthought.

Key idea: teams build better software because different people catch different problems and contribute different ideas.

Managing shared work

When several people edit the same project, they need a way to combine their changes without overwriting each other. Programmers use version control systems that track every change, remember who made it, and let people merge their work together. If a new change breaks something, the team can look back through the history and even return to an earlier version. You can picture version control as a detailed undo history for an entire project shared by the whole team.

Key idea: version control lets a team combine everyone's changes safely and roll back mistakes.

Design tools: plan before you code

Experienced programmers plan before they type, because fixing a flaw in a sketch is far cheaper than fixing it in finished code. Two common planning tools are worth knowing:

  • Flowcharts are diagrams that show the steps of a program as boxes connected by arrows, with diamond shapes for decisions. They make the flow of a program visible at a glance.
  • Pseudocode is a plain-language sketch of the steps, written loosely like code but readable by any human. It lets you think through the logic without worrying about exact syntax.

For example, before coding a program that greets a user, you might write pseudocode: "ask for the user's name; if a name was given, print Hello plus the name; otherwise print Hello, stranger." That is not real code, but it captures the plan clearly enough to build from.

Key idea: flowcharts and pseudocode let you get the logic right before committing to real code.

Program purpose and requirements

Every program should start with a clear purpose: the problem it solves or the need it meets. From the purpose come requirements, the specific things the program must do. Writing these down first keeps a project focused and gives you a way to judge, at test time, whether the program actually works. A program with no stated purpose tends to drift and sprawl.

Key idea: a clear purpose and written requirements keep development focused and make success measurable.

Where this fits in the AP framework

Everything in this lesson sits inside Big Idea 1, Creative Development, code CRD. The College Board framework splits it into ideas you can now name. Program purpose and function asks what a program is for and what it actually does. Those are different questions. A to-do app's purpose is to help people remember tasks. Its function is what it does when it runs: it stores a list, displays it, and lets users check items off. Program design and development covers the iterative loop you just learned, described in the framework as investigating, designing, prototyping, and testing. Identifying and correcting errors is the next lesson. The framework also treats collaboration itself as a tested skill, because the exam asks about pair work, feedback, and team roles directly. Creative Development supplies about 10 to 13 percent of the exam questions, so this material earns real points.

A quick exam-style check: a team is building a weather app. Which choice shows iterative development? Option (a) is writing the whole app in one weekend and shipping it untested. Option (b) is building just the temperature display, testing it with classmates, fixing what confused them, and only then adding the forecast screen. The answer is (b), and the reason is the shape of the work: build a small piece, test it, improve it, repeat. Exam questions on this Big Idea reward recognizing that shape.

Key idea: this lesson is Big Idea 1 (CRD), where purpose, function, iterative design, and collaboration are all named, tested parts of the framework.

From plan to AP pseudocode

Here is the greeting plan from above, written in the pseudocode style used on the AP exam. The arrow stores a value. INPUT() reads what the user types. In AP pseudocode a single equals sign compares two values; it does not assign. IF runs a block when its condition is true, and ELSE gives the fallback.

name ← INPUT()
IF (name = "")
{
  DISPLAY("Hello, stranger")
}
ELSE
{
  DISPLAY("Hello")
  DISPLAY(name)
}

Trace it twice, because a plan is only tested when you try more than one input.

  1. Run 1: the user types Ada. Line 1 stores "Ada" in name. The IF condition asks whether "Ada" equals the empty text. It does not, so the ELSE block runs. The program shows Hello, then Ada.
  2. Run 2: the user types nothing. Line 1 stores "" in name. The condition is now true, so the program shows Hello, stranger, and the ELSE block never runs.

Notice what the second run did. It tested the empty input, the case most first drafts forget. Planning in pseudocode makes that case visible before any real code exists.

Key idea: in AP pseudocode the arrow assigns and = compares, and tracing a plan with more than one input exposes forgotten cases early.

How real teams work the loop

Professional teams wrap extra habits around the design-build-test cycle, and the AP framework names several. In pair programming, two people share one screen. The driver types while the navigator watches the logic, and they swap roles often. In a code review, a teammate reads your change before it joins the shared project and points out problems while they are still cheap to fix. Teams also show early versions, called prototypes, to real users, because users bump into confusions the builders stopped seeing weeks ago. Feedback from users then reshapes the requirements, and the loop begins again.

Documentation holds all of this together. Comments inside the code explain tricky parts to future readers, and written descriptions of each procedure let teammates use your work without rereading every line. Programs live for years. The person most helped by your comments is usually you, six months later, staring at your own code with no memory of writing it.

Key idea: pair programming, code reviews, user feedback on prototypes, and documentation are the habits that make team iteration work.

Common misconceptions

  • "Good programmers write finished code on the first try." Even experts loop through drafts, tests, and revisions. Expecting a perfect first attempt sets you up to feel like a failure at a normal part of the job.
  • "Planning is a waste of time; just start coding." A few minutes of pseudocode or a flowchart usually saves hours, because logic mistakes are far cheaper to fix in a sketch than in built code.
  • "Collaboration just slows things down." Coordination has a cost, but teams catch more bugs and produce better designs than a lone coder on any sizable project.
  • "Version control is only for huge companies." Even a solo beginner benefits from a saved history that lets them undo mistakes and see how a project changed.
  • "Version control just means keeping backup copies." A backup is one frozen snapshot. Version control records every change, who made it, and why, and it can merge two people's edits to the same file.
  • "A program's purpose and its function are the same thing." Purpose is the need it serves for people; function is what it does when it runs. The exam asks about both, and confusing them costs easy points.

Recap

  • Development is an iterative loop: investigate, design, build, test, reflect, repeat.
  • Collaboration improves software because different people catch different problems.
  • Version control combines a team's changes and lets them undo mistakes.
  • Flowcharts and pseudocode plan the logic before real code is written.
  • A clear purpose and written requirements keep a project focused and testable.

Sources

  1. College Board. (2023). AP Computer Science Principles course and exam description. College Board. apcentral.collegeboard.org β†—
  2. College Board. (n.d.). AP Computer Science Principles course. AP Central. apcentral.collegeboard.org β†—
  3. Code.org β†—. (n.d.). Computer Science Principles curriculum. Code.org β†—. code.org β†—
  4. Chacon, S., & Straub, B. (2014). About version control. In Pro Git (2nd ed.). Apress. git-scm.com β†—
  5. Khan Academy. (n.d.). Programming (AP/College Computer Science Principles). Khan Academy. khanacademy.org β†—
  6. Malan, D. J. (n.d.). CS50 AP. Harvard University. cs50.harvard.edu β†—
  7. K-12 Computer Science Framework Steering Committee. (2016). K-12 Computer Science Framework. K12CS.org β†—. k12cs.org β†—
Key terms
Iterative process
Developing something by repeating a cycle of design, build, test, and improve many times.
Collaboration
People working together on a project, sharing ideas and catching each other's mistakes.
Version control
A system that records every change to a project so a team can merge work and undo mistakes.
Flowchart
A diagram that shows a program's steps as connected boxes, with diamonds for decisions.
Pseudocode
A plain-language sketch of a program's steps, written loosely like code but readable by humans.
Requirements
The specific things a program must do, derived from its purpose.
Purpose
The problem a program is meant to solve or the need it is meant to meet.

Program Errors and Testing

  • Distinguish syntax errors, runtime errors, and logic errors.
  • Explain how testing finds problems in a program.
  • Use simple debugging strategies to locate a bug.

The big picture

Every programmer writes code that does not work at first. Mistakes in programs are called bugs, and finding and fixing them is called debugging. Learning the kinds of bugs and how to hunt them down turns a frustrating mystery into a calm, step-by-step search.

Key idea: bugs are normal, and debugging is a skill you can learn, not a sign that you are bad at coding.

Why "bug"?

The word bug for a defect is old, but a famous story cemented it in computing: in 1947 engineers found an actual moth stuck in a room-sized computer and taped it into the logbook as the "first actual case of bug being found." Today a bug means any mistake in a program that makes it behave wrongly. There are three main kinds, and telling them apart is the first step to fixing them.

Key idea: a bug is any defect that makes a program behave incorrectly, and there are three common kinds.

Syntax errors

A syntax error breaks the grammar rules of the programming language, so the computer cannot even understand the instruction. It is like a sentence with the punctuation so mangled that no one can read it. Forgetting a closing quotation mark or bracket is a classic example. The good news is that syntax errors are usually the easiest to fix, because the computer refuses to run and often points to the line where it got confused.

For instance, writing print("Hello) with a missing closing quote is a syntax error; the language cannot tell where the text is supposed to end.

Key idea: a syntax error breaks the language's grammar, so the program will not run until it is fixed.

Runtime errors

A runtime error happens while the program is running. The grammar was fine, so it started, but then it hit something impossible and crashed. A well-known example is dividing a number by zero, which has no answer, so the program stops. Runtime errors are like a recipe that reads correctly until step five tells you to add an ingredient you do not have; you cannot continue.

Key idea: a runtime error appears while the program runs, when it tries to do something impossible and crashes.

Logic errors: the sneaky kind

A logic error is the trickiest, because the program runs happily and produces an answer, but the answer is wrong. There is no crash and no complaint; the instructions were simply not what you meant. Imagine a recipe that says to add salt when you meant sugar. Nothing "breaks," but the result is not what you wanted. Logic errors are the hardest to find precisely because the computer gives you no error message; it did exactly what you told it, just not what you intended.

A quick way to remember the three: a syntax error means the computer cannot read it, a runtime error means it crashes partway, and a logic error means it runs but gives the wrong result.

Key idea: a logic error produces a wrong answer with no crash, making it the hardest kind to catch.

Testing: checking that it works

Testing means running a program with chosen inputs to see whether it behaves correctly. Good testing does not just try the easy, expected cases; it also tries edge cases, the unusual inputs at the boundaries, such as an empty entry, a zero, a negative number, or a very large value. Many bugs hide in these corners. A program that adds two numbers might work fine for 2 and 3 but fail when one input is left blank, and only a deliberate test uncovers that.

Key idea: testing tries both normal inputs and tricky edge cases to expose hidden bugs.

How to debug

When something is wrong, a few reliable strategies help you locate the bug without panic:

  • Read the error message. It often names the line and the kind of problem. Beginners skip it; experts read it first.
  • Print intermediate values. Adding instructions that show what the program is holding at each step lets you see exactly where reality diverges from your expectation.
  • Trace by hand. Walk through the instructions on paper as if you were the computer, tracking each value. This catches logic errors the machine cannot flag.
  • Change one thing at a time. Make a single small change, test, and repeat, so you always know which change caused what.

One more strategy earns its odd name: rubber duck debugging. Explain your code, line by line, out loud, to something that cannot answer back, such as a rubber duck on your desk. Saying each step forces you to slow down and compare what the code really does with what you meant to write. Programmers are routinely surprised by how often the bug announces itself halfway through the explanation. Teaching a bug is the fastest way to find it.

Key idea: read the message, print values, trace by hand, and change one thing at a time.

Worked example: catching a logic error by tracing

Here is a short program in AP exam pseudocode. The arrow stores a value, and REPEAT UNTIL keeps looping until its condition becomes true. The programmer intends to add the numbers 1, 2, and 3, so the display should show 6.

total ← 0
count ← 0
REPEAT UNTIL (count = 3)
{
  total ← total + count
  count ← count + 1
}
DISPLAY(total)

It runs without any error message. Now trace it, one pass at a time, writing down both variables after each pass.

Passtotal after the passcount after the pass
10 + 0 = 01
20 + 1 = 12
31 + 2 = 33, so the loop stops

The program displays 3, not 6. That is a textbook logic error: the machine is happy, the answer is wrong. The trace shows why. Each pass adds count before increasing it, so the program adds 0 + 1 + 2 instead of 1 + 2 + 3. The fix is to swap the two lines inside the loop, increasing count first:

REPEAT UNTIL (count = 3)
{
  count ← count + 1
  total ← total + count
}

Trace the fixed version the same way. Pass 1: count becomes 1, total becomes 1. Pass 2: count becomes 2, total becomes 3. Pass 3: count becomes 3, total becomes 6, and the loop stops. The display now shows 6. Nothing found this bug except a patient trace, which is exactly why the AP exam asks you to trace code again and again.

Key idea: a trace table exposes logic errors that produce no error message, like adding 0 + 1 + 2 when you meant 1 + 2 + 3.

Planning tests like a scientist

Good testers write their checks down before running anything. A test case is a chosen input plus the output you expect. If the program is supposed to average the list [4, 7, 5], the expected output is 16 divided by 3, about 5.33. Running the test and seeing something else tells you a bug exists; seeing the expected value builds confidence. A useful test plan for an averaging program might look like this: a normal list such as [4, 7, 5]; a list with one item, where the average should equal that item; and an empty list. The empty list is the interesting one. The program would divide the total by zero items, and dividing by zero is impossible, so an unprotected program crashes with a runtime error. A single planned test just connected two ideas from this lesson: edge cases and runtime errors.

This lesson belongs to Big Idea 1, Creative Development (CRD), where the framework names identifying and correcting errors as a required skill. The exam shows you short programs and asks which kind of error they contain, or which input would expose the bug. Trace first, then answer.

Key idea: a test case pairs an input with an expected output, and a good plan deliberately includes edge cases that could crash or mislead the program.

Common misconceptions

  • "Errors mean I am bad at programming." Every professional produces bugs constantly. Debugging is a core part of the work, not a personal failing.
  • "If the program runs, it must be correct." A logic error runs without any complaint yet gives the wrong answer. Running is not the same as being right.
  • "Testing the normal case is enough." Many bugs live in edge cases like empty, zero, or negative inputs, so those must be tested on purpose.
  • "The computer misunderstood me." The computer did exactly what the instructions said. A logic error is a gap between what you wrote and what you meant, not a misunderstanding by the machine.
  • "If all my tests pass, the program is proven correct." Tests can only show the presence of bugs, never their total absence. Passing tests raises confidence for the cases you tried; untested inputs can still fail.
  • "Syntax errors are the worst kind." They are actually the cheapest, because the computer refuses to run and points near the problem. The expensive ones are logic errors that hide silently in correct-looking output.

Recap

  • A bug is a defect that makes a program behave incorrectly; fixing bugs is debugging.
  • Syntax errors break grammar and stop the program from running.
  • Runtime errors crash the program while it runs, like dividing by zero.
  • Logic errors run without crashing but give a wrong result, and are hardest to find.
  • Testing tries normal and edge-case inputs; debugging uses reading messages, printing values, and hand tracing.

Sources

  1. College Board. (2023). AP Computer Science Principles course and exam description. College Board. apcentral.collegeboard.org β†—
  2. Computer History Museum. (n.d.). September 9: First instance of actual computer bug being found. This Day in History. computerhistory.org β†—
  3. MDN Web Docs. (n.d.). What went wrong? Troubleshooting JavaScript. Mozilla. developer.mozilla.org β†—
  4. Code.org β†—. (n.d.). Computer Science Principles curriculum. Code.org β†—. code.org β†—
  5. Khan Academy. (n.d.). Programming (AP/College Computer Science Principles). Khan Academy. khanacademy.org β†—
  6. Khan Academy. (n.d.). Computer programming: JavaScript and the web. Khan Academy. khanacademy.org β†—
  7. Malan, D. J. (2026). CS50x: Introduction to computer science. Harvard University. cs50.harvard.edu β†—
Key terms
Bug
Any mistake in a program that makes it behave incorrectly.
Debugging
The process of finding and fixing bugs in a program.
Syntax error
A mistake that breaks the language's grammar, so the program will not run.
Runtime error
An error that occurs while a program runs and causes it to crash, such as dividing by zero.
Logic error
A mistake where the program runs without crashing but produces the wrong result.
Testing
Running a program with chosen inputs to check that it behaves correctly.
Edge case
An unusual input at a boundary, such as empty, zero, or negative, where bugs often hide.

Module 2: Data - How Computers Store Everything

Underneath every photo, song, and message is nothing but numbers, and underneath those numbers is nothing but on and off. This module shows how binary represents numbers, text, images, and sound, how compression shrinks files, and what data reveals about us.

Binary: How Computers Count

  • Explain why computers use the binary number system.
  • Convert a small number between binary and decimal by hand.
  • Define bit and byte and relate them to storage.

The big picture

Underneath every number, word, picture, and song, a computer stores only two things: on and off. That two-state code is called binary, and learning to read it is the key that unlocks how computers store everything else. In this lesson you will convert small numbers to binary and back by hand and check your answer.

Key idea: computers represent all information with just two states, usually written as 1 and 0.

Why only two states?

Computers are built from billions of tiny electronic switches. A switch is either on or off, like a light switch on your wall: there is no reliable "half on." Because each switch has exactly two states, it is natural and dependable to build the whole machine around a two-symbol code. We write those two states as 1 (on) and 0 (off). Trying to use ten different voltage levels for the digits 0 through 9 would be error-prone, but telling apart just "on" and "off" is easy and reliable, which is why binary won.

Key idea: binary matches the hardware, because each switch is simply on or off, like a light switch.

Bits and bytes

A single binary digit, one 1 or 0, is called a bit. One bit alone can only say on or off, which is not much. So bits are grouped. Eight bits together make a byte, and a byte can represent 256 different combinations, which is enough for a single letter of text. Storage is measured in bytes: a kilobyte is about a thousand bytes, a megabyte about a million, and a gigabyte about a billion. When a photo is "3 megabytes," that is roughly three million bytes of binary.

Key idea: a bit is one binary digit, and eight bits form a byte, the basic unit of stored data.

How decimal really works

To understand binary, first notice how our everyday decimal system works. Decimal uses ten digits, 0 through 9, and each position is worth ten times the one to its right: ones, tens, hundreds, thousands. The number 253 means 2 hundreds, 5 tens, and 3 ones. The position of a digit tells you its value; that is why we call it place value.

Key idea: in decimal each place is worth ten times the place to its right, and position sets a digit's value.

How binary works

Binary uses the very same idea, but with only two digits, so each position is worth two times the one to its right instead of ten. Reading from the right, the place values are 1, 2, 4, 8, 16, 32, 64, 128, each double the last. To find a binary number's value, add up the place values wherever there is a 1.

Place value1286432168421
Bits00001101

The bits 00001101 have 1s in the 8, 4, and 1 places, so the value is 8 + 4 + 1 = 13. That is the whole trick: binary is just place value with doubling instead of times-ten.

Key idea: a binary number's value is the sum of the place values (1, 2, 4, 8, ...) wherever a 1 appears.

Worked example: decimal to binary

Let us convert the decimal number 19 into binary. One reliable method is to find the largest place value that fits, subtract it, and repeat.

  1. The largest place value that fits in 19 is 16. Put a 1 in the 16 place. Now 19 minus 16 leaves 3.
  2. The next place values 8 and 4 are both bigger than 3, so put 0 in each.
  3. 2 fits in 3. Put a 1 in the 2 place. Now 3 minus 2 leaves 1.
  4. 1 fits in 1. Put a 1 in the 1 place. Now 1 minus 1 leaves 0, so we are done.

Reading the places 16, 8, 4, 2, 1 gives 1, 0, 0, 1, 1, so 19 in binary is 10011. Let us verify by converting back: the 1s are in the 16, 2, and 1 places, and 16 + 2 + 1 = 19. It checks out. Always verify a conversion by adding the place values back up; it catches almost every mistake.

Key idea: to convert to binary, subtract the largest fitting place value repeatedly, then verify by adding the places back to the original.

Counting in binary

Counting works just like decimal, except you carry after 1 instead of after 9. Zero is 0, one is 1, and then, out of digits, two becomes 10, three is 11, four is 100, and so on. Each time every digit is used up, a new place is added. This is exactly what happens in decimal when 9 rolls over to 10; binary just rolls over sooner because it has fewer digits.

Key idea: binary counts by carrying to a new place after 1, the same way decimal carries after 9.

Worked example: both directions, all work shown

This lesson opens Big Idea 2, Data (DAT), and conversion in both directions is its first tested skill. Convert decimal 45 to binary. The place values are 32, 16, 8, 4, 2, 1. Does 32 fit in 45? Yes, so write a 1 and keep 45 - 32 = 13. Does 16 fit in 13? No, write 0. Does 8 fit? Yes, keep 13 - 8 = 5. Does 4 fit in 5? Yes, keep 1. Does 2 fit in 1? No, write 0. Does 1 fit? Yes, leaving 0. Reading the digits in order gives 101101. Verify by adding the places that hold a 1: 32 + 8 + 4 + 1 = 45. It checks.

Now the other direction. Convert binary 10110110 to decimal. Write the place values over the bits, from 128 down to 1, and add the places where a 1 appears.

Place1286432168421
Bit10110110

The 1s sit in the 128, 32, 16, 4, and 2 places, and 128 + 32 + 16 + 4 + 2 = 182. So 10110110 is decimal 182.

Key idea: subtraction of place values converts decimal to binary, and adding the places under each 1 converts binary back.

A second method: divide by two, keep the remainders

There is a mechanical method many programmers prefer. Divide the number by 2 over and over, keeping the whole-number part and writing down each remainder. The remainder is exactly what the MOD operation computes in AP pseudocode: 19 MOD 2 is 1, because 19 divided by 2 leaves 1 over.

19 / 2 = 9   remainder 1
 9 / 2 = 4   remainder 1
 4 / 2 = 2   remainder 0
 2 / 2 = 1   remainder 0
 1 / 2 = 0   remainder 1

read the remainders bottom to top: 10011

Reading the remainders from bottom to top gives 10011, the same answer the subtraction method gave for 19 earlier in this lesson. Two different algorithms, one matching result, is strong evidence both are right.

Key idea: repeated division by 2 produces the binary digits as remainders, read from the last remainder back to the first.

When a number does not fit: overflow

Real hardware stores each number in a fixed number of bits, and that creates a hard ceiling. Eight bits can hold the patterns 00000000 through 11111111, which is 0 through 255. Ask an 8-bit counter to go one past 255 and there is no ninth bit to carry into. The true answer, 256, needs nine bits, 100000000. This failure is called an overflow error, and the AP framework names it directly. With 4 bits the ceiling is 15, so 1111 plus 1 overflows the same way. Early video games really did break like this: a score kept in a single byte behaved strangely once play pushed it past 255. More bits raise the ceiling, but some ceiling always exists.

Key idea: a fixed bit width has a maximum value, such as 255 for 8 bits, and pushing past it causes an overflow error.

A cousin you will meet: hexadecimal

Programmers often write long binary patterns in hexadecimal, base 16, which uses digits 0 through 9 and then A through F for ten through fifteen. One hex digit stands for exactly four bits. The byte 10110110 splits into 1011 and 0110, which are 11 and 6, written B6. The byte 11111111 is 255, written FF, which is why a web color code like FF0000 means full red, no green, no blue. Hex is not a different kind of number, just a compact costume for binary.

Key idea: hexadecimal packs each group of four bits into one digit, so B6 is just a shorter way to write 10110110.

Common misconceptions

  • "Binary is a different, mysterious kind of math." It is ordinary place-value counting with two digits instead of ten. The rules are identical; only the base changes.
  • "Computers use binary because it is faster." They use it because hardware switches have two reliable states. Telling on from off is dependable, while many voltage levels would be error-prone.
  • "A bit and a byte are the same thing." A bit is a single 1 or 0; a byte is eight bits grouped together. The difference matters for measuring storage.
  • "The rightmost binary digit is the biggest." As in decimal, the rightmost digit is the smallest place, worth 1. Place values grow toward the left.
  • "Binary is only for numbers." Bits also encode text, images, sound, and the instructions of programs themselves. Anything that can be numbered can be stored in binary, which is the whole subject of the next lesson.
  • "With enough bits, overflow stops being possible." More bits only raise the ceiling. Every fixed width has a largest value, and a running total can always grow past it.

Recap

  • Computers store everything as binary: two states written 1 and 0.
  • Binary matches hardware because each switch is simply on or off.
  • A bit is one binary digit; eight bits make a byte.
  • Binary is place value with doubling: 1, 2, 4, 8, 16, and so on.
  • Convert to binary by subtracting the largest fitting place value, and always verify by adding the places back.

Sources

  1. College Board. (2023). AP Computer Science Principles course and exam description. College Board. apcentral.collegeboard.org β†—
  2. CS Unplugged. (n.d.). Binary numbers. University of Canterbury. csunplugged.org β†—
  3. Khan Academy. (n.d.). Digital information (Computers and the Internet). Khan Academy. khanacademy.org β†—
  4. Khan Academy. (n.d.). Digital information (AP/College Computer Science Principles). Khan Academy. khanacademy.org β†—
  5. Code.org β†—. (n.d.). Computer Science Principles curriculum. Code.org β†—. code.org β†—
  6. Malan, D. J. (2026). CS50x: Introduction to computer science. Harvard University. cs50.harvard.edu β†—
  7. MDN Web Docs. (n.d.). Glossary of web terms. Mozilla. developer.mozilla.org β†—
Key terms
Binary
A number system using only two digits, 1 and 0, matching a switch's on and off states.
Bit
A single binary digit, either 1 or 0; the smallest unit of data.
Byte
A group of eight bits, able to represent 256 combinations, enough for one letter.
Decimal
The everyday base-ten number system using digits 0 through 9.
Place value
The value a digit has because of its position; in binary each place doubles the one to its right.
Gigabyte
A unit of storage equal to about one billion bytes.

Storing Text, Images, and Sound

  • Explain how text is stored using a character code like ASCII or Unicode.
  • Describe how an image is stored as pixels with color values.
  • Explain how sound is stored by sampling a wave.

The big picture

If a computer only stores numbers in binary, how does it hold your name, a photo, or a song? The answer is a simple, powerful trick used everywhere in computing: agree on a code that turns each kind of information into numbers. Once text, images, and sound are numbers, binary can store them all.

Key idea: everything becomes numbers first, and then binary stores the numbers.

Text: every character is a number

To store text, we agree on a character code, a lookup table that pairs each character with a number. The classic one is ASCII, which assigns the letters, digits, and common symbols numbers from 0 to 127. In ASCII, capital A is 65, B is 66, and so on; lowercase a is 97. Storing the word "Hi" means storing the numbers for H and i, which the computer then keeps in binary. It is like a secret code where each letter is swapped for an agreed number.

ASCII only covers English, so the modern standard is Unicode, a much larger table that gives a number to characters from every writing system on Earth, plus emoji. This is why a message with Japanese text or an emoji can travel between phones and still display correctly: everyone agrees on the same Unicode numbers.

Key idea: text is stored by mapping each character to a number using a shared code such as ASCII or Unicode.

Worked example: decoding text

Suppose you receive the ASCII numbers 67, 97, 116. Using the rule that capital A is 65, the number 67 is two letters past A, which is C. The number 97 is lowercase a, and 98 would be b, so 97 is a and the next, well, 116 counts up from a (97) by 19, landing on t. Put together, 67, 97, 116 spells "Cat." The point is not to memorize the table but to see that text is genuinely just numbers under an agreed code.

Key idea: because each character maps to a fixed number, a string of numbers can be decoded straight back into text.

Images: a grid of colored dots

A digital image is a grid of tiny squares called pixels (short for picture elements). Each pixel is one solid color, and up close you can sometimes see them. To store a color, computers usually use the RGB system: every color is mixed from three numbers giving the amounts of red, green, and blue light, each from 0 to 255. Red is 255, 0, 0; pure white is 255, 255, 255; black is 0, 0, 0. So an image is stored as a long list of pixel colors, three numbers per pixel.

This explains resolution. More pixels packed into the image means finer detail but a bigger file, because every pixel needs its own color numbers. A photo that is 1000 pixels wide and 1000 tall holds a million pixels, and at three numbers each that is three million numbers to store. That is why high-resolution photos take up so much space.

Color depth follows the same bit logic as everything else in this module. Each of the three channels runs 0 to 255, which is exactly the range of one byte, 8 bits. Three channels means 24 bits per pixel, and 2 raised to the 24th power is 16,777,216, so a standard photo can choose among about 16.8 million colors for every pixel. That number is not marketing. It falls straight out of counting bit patterns, the skill from the previous lesson.

Key idea: an image is a grid of pixels, and each pixel's color is stored as red, green, and blue numbers.

Sound: measuring a wave many times a second

Sound in the air is a continuous wave, but a computer can only store numbers, so it measures the wave's height at rapid, even intervals and stores each measurement as a number. Each measurement is a sample, and taking them is called sampling. It is like drawing a smooth curve by plotting many closely spaced dots: from far enough away the dots look like the original curve. Music on a CD is sampled about 44,100 times every second, which is fast enough that human ears hear it as smooth, continuous sound.

Two settings control sound quality. The sample rate is how many samples are taken per second, and the bit depth is how many bits each sample uses, which sets how precisely each height is recorded. Higher values mean better quality and larger files, the same trade-off images face with resolution.

Key idea: sound is stored by sampling a wave's height many times per second and saving each height as a number.

The one unifying idea

Text, images, and sound feel completely different, yet they are stored the same way: pick a scheme to turn the information into numbers, then store those numbers in binary. This single principle, called data representation, is one of the most important ideas in all of computing. Master it once and the storage of every media type stops being mysterious. The principle even covers programs themselves: the instructions a computer runs are stored as numbers too, side by side with the data they process.

Key idea: all media are stored by the same recipe, turn it into numbers, then store the numbers in binary.

Analog versus digital

The AP framework, in Big Idea 2, Data (DAT), draws one more distinction worth naming. The real world is analog: sound waves, light, and temperature vary smoothly, with no steps. Computers are digital: they store separate, exact numbers. Sampling is the bridge between the two worlds, and it always involves an approximation, because a smooth wave measured at intervals loses whatever wiggled between the measurements. So why did digital win? Copies. An analog copy of a copy degrades, the way a photocopy of a photocopy grows blurry. A digital copy is just the same numbers written again, so the thousandth copy is exactly as perfect as the first. Digital data also travels well: a slightly noisy signal still reads clearly as 1s and 0s, while analog noise piles up.

Key idea: analog signals vary smoothly while digital data is discrete numbers, and digital wins because copies and transmissions stay exact.

Worked example: how big is that photo?

You can now predict file sizes with nothing but multiplication. Each pixel stores three color numbers, and each number fits in one byte, so figure three bytes per pixel. Here is the calculation in AP-style pseudocode for a 1000 by 1000 image:

width ← 1000
height ← 1000
bytesPerPixel ← 3
size ← width * height * bytesPerPixel
DISPLAY(size)

Trace it: width holds 1000, height holds 1000, bytesPerPixel holds 3. The fourth line computes 1000 times 1000, which is 1,000,000 pixels, times 3, and stores 3,000,000. The program displays 3,000,000 bytes, which is about 3 megabytes for one modest photo. Now scale up to a 12-megapixel phone camera, 4000 by 3000 pixels. That is 12,000,000 pixels times 3 bytes, or 36,000,000 bytes, roughly 36 megabytes for a single uncompressed photo. Your phone stores photos far smaller than that, and the next lesson explains the trick it uses.

Key idea: image size is width times height times bytes per pixel, so a raw 12-megapixel photo needs about 36 million bytes.

Worked example: how big is that song?

Sound sizes multiply the same way. CD-quality audio takes 44,100 samples every second, each sample uses 16 bits (2 bytes), and stereo records 2 channels at once. One second therefore costs 44,100 times 2 times 2, which is 176,400 bytes. A 3-minute song lasts 180 seconds, so the total is 176,400 times 180, which is 31,752,000 bytes, close to 32 megabytes of raw audio. Yet the same song streams or downloads at a few megabytes. Those two honest calculations, 36 megabytes for a photo and 32 for a song, explain why the next lesson on compression exists at all: raw media is simply too large to store and ship as-is.

Key idea: raw CD-quality stereo costs 176,400 bytes per second, so a 3-minute song is about 32 megabytes before compression.

Common misconceptions

  • "Computers store letters as actual letters." They store numbers from a character code; the letters you see are drawn from those numbers when displayed.
  • "A bigger screen automatically means a sharper image." Sharpness depends on the number of pixels (resolution), not the physical size. A big screen with few pixels looks blocky.
  • "Sound is stored as one continuous recording." It is stored as thousands of separate height measurements per second; playback reconstructs the wave from those samples.
  • "Emoji are pictures sent inside a message." Most emoji are Unicode characters, each a number; your device draws the little picture from that number.
  • "Digital copies wear out like photocopies." A digital copy rewrites the same numbers exactly, so the thousandth copy matches the first. Degrading copies are an analog problem.
  • "A higher sample rate always sounds better." Rates around 44,100 per second already cover the range human ears detect. Beyond that, higher rates mostly grow the file, not the audible quality.

Recap

  • All media are stored by first turning them into numbers, then storing the numbers in binary.
  • Text uses a character code: ASCII for English, Unicode for all writing systems and emoji.
  • Images are grids of pixels, each pixel a color given as red, green, and blue numbers.
  • Sound is sampled: the wave's height is measured many times per second and stored as numbers.
  • Higher resolution, sample rate, and bit depth mean better quality but larger files.

Sources

  1. College Board. (2023). AP Computer Science Principles course and exam description. College Board. apcentral.collegeboard.org β†—
  2. Unicode Consortium. (n.d.). FAQ: Basic questions. Unicode.org β†—. unicode.org β†—
  3. Unicode Consortium. (n.d.). Unicode: The world standard for text and emoji. Unicode.org β†—. home.unicode.org β†—
  4. MDN Web Docs. (n.d.). ASCII. MDN Glossary. developer.mozilla.org β†—
  5. MDN Web Docs. (n.d.). Character encoding. MDN Glossary. developer.mozilla.org β†—
  6. Khan Academy. (n.d.). Digital information (Computers and the Internet). Khan Academy. khanacademy.org β†—
  7. Encyclopaedia Britannica. (n.d.). Compact disc. In Britannica Technology. (Access via britannica.com β†—.)
Key terms
Character code
A table that pairs each character with a number so text can be stored as numbers.
ASCII
An early character code assigning numbers 0 to 127 to English letters, digits, and symbols.
Unicode
A large character code that gives a number to characters from every writing system, plus emoji.
Pixel
A single colored dot in a grid that makes up a digital image.
RGB
A color scheme mixing red, green, and blue values, each 0 to 255, to make any color.
Sampling
Measuring a sound wave's height at rapid, even intervals and storing each as a number.
Sample rate
How many sound samples are taken per second; higher means better quality and larger files.

Data Compression

  • Explain why data is compressed.
  • Distinguish lossless from lossy compression.
  • Choose the right kind of compression for a situation.

The big picture

Raw data can be huge: photos, songs, and videos would fill your storage and crawl across the Internet if sent as-is. Compression is the art of making data smaller so it takes less space and travels faster. There are two families of compression, and knowing when to use each is a genuinely useful skill.

Key idea: compression shrinks data so it takes less storage and moves faster over networks.

Why compress at all?

Every byte you store costs space, and every byte you send takes time. A single uncompressed photo could be tens of megabytes; a movie could be enormous. Compression lets a phone hold thousands of songs and lets a video stream without endless buffering. The goal is always the same: represent the same information, or something close enough, using fewer bits.

Compression also saves money and energy at scale. A service that stores a billion photos pays for every byte several times: once to store it, once to back it up, and once each time it crosses the network to a viewer. Shaving 30 percent off file sizes shaves real percentages off server bills and power use, which is why companies employ whole teams to squeeze formats harder.

Key idea: the aim of compression is to carry the same message with fewer bits.

Lossless compression: nothing is thrown away

Lossless compression shrinks data so that the original can be rebuilt exactly, bit for bit, with nothing lost. It works by spotting patterns and describing them more briefly. Imagine a message that reads "aaaaaaaa." Instead of storing eight a's, you could store "8a," meaning eight a's, which is far shorter and can be expanded back perfectly. Real lossless methods are cleverer, but the spirit is the same: find repetition and record it compactly.

Because it loses nothing, lossless compression is essential when every detail must survive: text documents, computer programs, and spreadsheets. You would never accept a "close enough" version of your bank statement or a program's code. Common lossless formats include ZIP files and PNG images.

Key idea: lossless compression rebuilds the original exactly, so it is used where no detail can be lost.

Worked example: run-length encoding, byte by byte

The simplest real lossless method is run-length encoding, or RLE: replace each run of repeated symbols with a count and one copy of the symbol. Take this 20-character message, where each character costs 1 byte in ASCII, 20 bytes total:

AAAAAAABBBBCCCCCCCCC

Scan it left to right and track the runs as an encoder would:

Run seenLengthOutput so far
AAAAAAA77A
BBBB47A4B
CCCCCCCCC97A4B9C

The encoded form is 7A4B9C: 6 characters, so 6 bytes instead of 20. That saves 14 of 20 bytes, a 70 percent reduction, and decoding is perfectly reversible: write 7 As, then 4 Bs, then 9 Cs, and the original 20 bytes return exactly. Check the count: 7 + 4 + 9 = 20. This is why RLE suits images with large single-color areas, like icons and screenshots, where thousands of identical pixels sit in a row.

Now watch it fail. Encode ABCABC, 6 bytes, the same way: every run has length 1, so the output is 1A1B1C1A1B1C, which is 12 bytes, twice the original. A lossless method can only shrink data that has patterns to describe; data with no repetition can even grow. That is not a flaw in RLE. It is a law about information itself.

Key idea: RLE stores each run as a count plus a symbol, turning 20 bytes into 6 when runs are long, but it can double patternless data.

Lossy compression: throw away what you will not miss

Lossy compression makes files much smaller by permanently discarding information the human senses are unlikely to notice. Once thrown away, that data cannot be recovered, which is exactly why the files get so small. Photographs, music, and video use lossy compression heavily. A JPEG photo drops fine color details your eye barely registers; an MP3 song removes sounds too quiet to hear behind louder ones. The result looks or sounds almost the same while taking a fraction of the space.

There is a dial here: compress lightly and the file stays large but nearly perfect; compress hard and the file shrinks but visible or audible flaws (called artifacts) creep in. Choosing the setting is a trade-off between size and quality.

Key idea: lossy compression permanently discards hard-to-notice detail to make media files far smaller.

The same song, three sizes

The previous lesson computed that a raw, CD-quality 3-minute song costs about 31,752,000 bytes, close to 32 megabytes. Here is what compression does to it. A lossless format like FLAC typically finds enough patterns to cut audio roughly in half, to somewhere near 16 megabytes, and playback rebuilds every sample exactly. A lossy MP3 at a common quality setting stores about 128,000 bits per second; over 180 seconds that is 128,000 times 180 divided by 8, which is 2,880,000 bytes, about 2.9 megabytes. That is roughly one eleventh of the raw size, achieved by permanently discarding sounds your ear was unlikely to notice. Photos tell the same story: the raw 36-megabyte phone photo from last lesson typically leaves the camera as a JPEG of a few megabytes, close to a tenth of the raw size. The pattern to remember: lossless buys real but modest savings, while lossy buys dramatic savings at the price of unrecoverable detail.

Key idea: the same 32-megabyte raw song becomes about 16 megabytes lossless or about 2.9 megabytes lossy, which shows the scale of the trade.

Choosing between them

The decision comes down to one question: can any information be lost? Use this quick guide:

SituationBest choiceWhy
A program's source codeLosslessA single changed character could break it
A text document or spreadsheetLosslessEvery word and number must survive exactly
A photo for a websiteLossySmall quality loss is invisible and saves lots of space
Streaming music or videoLossyHuge size savings with barely noticeable change

Professionals often use both, in sequence. A photographer keeps a lossless master file of every shoot, because edits should start from perfect data, and then exports small lossy copies for the web. A studio records and mixes music losslessly, then releases streaming versions in lossy formats. The master-and-copies pattern gets the best of both worlds: one perfect original, many cheap copies.

Key idea: if losing any detail is unacceptable, choose lossless; if minor quality loss is fine, lossy saves far more space.

There is no free lunch

Compression is powerful but not magic. Lossless methods cannot shrink truly random data with no patterns, because there is nothing repetitive to describe more briefly. And lossy methods buy their small sizes by permanently giving up detail. Understanding these limits keeps expectations realistic: you cannot compress everything infinitely, and every gain in size has a cost in either effort or quality.

Key idea: compression has limits, since random data resists lossless shrinking and lossy savings cost permanent detail.

How this appears on the AP exam

Compression lives in Big Idea 2, Data (DAT), and the exam tests it as a decision skill rather than a math drill. A typical question describes a situation, a scientist archiving measurements, a website trying to load photos faster, a musician sending a demo, and asks which kind of compression fits and why. The framework's own summary is worth memorizing: choose lossy when smaller size matters more than perfect reconstruction, and choose lossless when perfect reconstruction matters more than size. Watch for the word "exact" or "original" in the question; either one points straight at lossless. Real formats follow the same logic. ZIP archives and PNG images are lossless, because documents, code, diagrams, and text must survive exactly. JPEG photos and streaming audio and video are lossy, because eyes and ears forgive tiny losses and the bandwidth savings are enormous.

One more idea helps: modern lossless tools like ZIP go beyond counting runs. They spot repeated phrases and store them once, replacing later appearances with a short reference back to the first, the way a book's index points to a page instead of reprinting it. Repetition, whether of letters, phrases, or pixels, is the raw fuel every lossless method burns.

Key idea: on the exam, "must be exact" points to lossless and "must be small" points to lossy, and all lossless methods live off repetition.

Common misconceptions

  • "Compression always loses quality." Lossless compression loses nothing; it rebuilds the original exactly. Only lossy compression trades quality for size.
  • "You can keep compressing a file to make it tiny." Once data is compressed, there is little or no pattern left to exploit, so compressing again barely helps and can even add size.
  • "Lossy compression ruins files." Used at sensible settings, the loss is nearly imperceptible while the space savings are large, which is why photos and music rely on it.
  • "A ZIP file is a lossy format." ZIP is lossless; unzipping restores the exact original bytes, which is why it is safe for documents and programs.
  • "Compression physically squeezes the bits closer together." Bits do not shrink. Compression stores a cleverer, shorter description of the same content, like writing 9C instead of nine Cs.
  • "Lossless compression always makes a file smaller." On data with no repetition it saves nothing, and as the ABCABC example shows, it can even make the file bigger.

Recap

  • Compression shrinks data to save storage and speed up transfer.
  • Lossless compression rebuilds the original exactly by describing patterns compactly.
  • Lossy compression permanently discards hard-to-notice detail for much smaller files.
  • Use lossless when no detail can be lost; use lossy when minor quality loss is acceptable.
  • Compression has limits: random data resists lossless, and lossy savings cost permanent detail.

Sources

  1. College Board. (2023). AP Computer Science Principles course and exam description. College Board. apcentral.collegeboard.org β†—
  2. MDN Web Docs. (n.d.). Lossless compression. MDN Glossary. developer.mozilla.org β†—
  3. MDN Web Docs. (n.d.). Lossy compression. MDN Glossary. developer.mozilla.org β†—
  4. Khan Academy. (n.d.). Digital information (AP/College Computer Science Principles). Khan Academy. khanacademy.org β†—
  5. Code.org β†—. (n.d.). Computer Science Principles curriculum. Code.org β†—. code.org β†—
  6. Joint Photographic Experts Group. (n.d.). JPEG 1 standard overview. JPEG.org β†—. jpeg.org β†—
  7. World Wide Web Consortium. (n.d.). Portable Network Graphics (PNG) specification, third edition. W3C. (Access via w3.org β†—.)
Key terms
Compression
Making data smaller so it takes less storage and travels faster.
Lossless compression
Shrinking data so the exact original can be rebuilt with nothing lost.
Lossy compression
Shrinking data by permanently discarding hard-to-notice detail.
Artifact
A visible or audible flaw introduced by compressing a file too heavily.
JPEG
A common lossy image format that drops fine detail to make photos much smaller.
PNG
A common lossless image format that preserves every pixel exactly.

Data, Information, and Privacy

  • Distinguish raw data from information.
  • Explain how combining data can reveal private facts.
  • Describe basic ways to protect personal data.

The big picture

Data by itself is just raw numbers and facts. It becomes powerful when we process it into information, patterns and meaning that help us decide and predict. That power has a shadow side: data about people can reveal private things they never chose to share. This lesson looks at both the promise and the risk.

Key idea: processing turns raw data into useful information, and the same power raises real privacy concerns.

Data versus information

Data is raw, unorganized facts: a list of temperatures, a column of sales numbers, a stream of clicks. On its own it may mean little. Information is what you get after data is organized, analyzed, or summarized so it answers a question. The numbers 71, 68, 74, 90, 88 are data; noticing that "temperatures rose sharply over the last two days" is information. A helpful way to remember it: data is the ingredients, and information is the meal you cook from them.

Try one more example. A fitness tracker logs 8,412 steps on Monday, 9,105 on Tuesday, and 3,214 on Wednesday. Those three numbers are data. "Activity dropped sharply midweek" is information, and "the drop matches the rainy day" is the beginning of insight. Notice that the numbers never changed; questions and processing turned them into meaning.

Key idea: data is raw facts, and information is the meaning we extract by processing that data.

Finding patterns in data

Computers are extraordinary at sifting huge piles of data for patterns a human could never spot by hand. Analyzing millions of records can reveal trends, correlations, and predictions: which products sell together, when traffic peaks, how a disease spreads. This is the engine behind recommendations, search results, and much of modern science. Turning oceans of raw data into insight is one of computing's greatest strengths.

A caution comes with it: a correlation, meaning two things that tend to happen together, does not prove that one causes the other. Ice cream sales and sunburns rise together, but ice cream does not cause sunburn; hot sunny weather drives both. Good analysis separates real causes from coincidences.

Key idea: computers excel at finding patterns, but a correlation is not proof that one thing causes another.

Worked example: extracting information with a program

This is Big Idea 2, Data (DAT), and the framework calls this skill extracting information from data. Here is the extraction idea in AP exam pseudocode, run on the temperature data from above. The goal: count the hot days, meaning days above 85 degrees.

temps ← [71, 68, 74, 90, 88]
hotDays ← 0
FOR EACH t IN temps
{
  IF (t > 85)
  {
    hotDays ← hotDays + 1
  }
}
DISPLAY(hotDays)

The FOR EACH loop visits every item in the list in order, placing each one in t. Trace it:

tIs t > 85?hotDays after this pass
71no0
68no0
74no0
90yes1
88yes2

The program displays 2. Five raw numbers went in; one piece of information came out: two days were hot. Every dashboard, recommendation, and scientific result you have ever seen is this same move, repeated at enormous scale with fancier questions.

Scale is the reason programs, not people, do this work. A person checking one record every 5 seconds would need 5,000,000 seconds for a million records, which is about 58 days without sleep. A computer does it in well under a second, and a million records is a small dataset by modern standards.

Key idea: a loop plus a condition turns raw data into information, and computers matter because they make that move at a scale no human can.

The privacy problem

Every app you use, page you visit, and purchase you make can generate data about you. Individually, one fact seems harmless. The danger is aggregation: combining many small, harmless-looking pieces of data can reveal something private that no single piece exposed. Your location at 8 a.m. each weekday, plus your purchases, plus your searches, can together paint a detailed portrait, where you live, work, worship, and what your health might be, even if you never stated any of it.

This is why privacy matters even if you feel you "have nothing to hide." The concern is not one embarrassing fact; it is that the combination of ordinary facts can expose things you would reasonably want to keep private, and that this profile can be used in ways you did not agree to.

Key idea: combining many harmless-looking pieces of data can reveal private facts none of them showed alone.

Metadata: the data about the data

There is a second layer to every file and message that most people never see. Metadata is data about data: not the photo, but when and where it was taken and on what device; not the words of a message, but who sent it, to whom, and at what time. The AP framework names metadata directly, and privacy researchers pay it special attention, because metadata is generated automatically and rarely reviewed by the person it describes. A single photo's location tag seems harmless. The location tags on a year of photos map your home, your school, and your habits. Even with every message body deleted, the pattern of who contacts whom, and when, sketches a social map. When you post publicly, remember that you are usually publishing this quiet second layer along with the content you meant to share.

Key idea: metadata like timestamps, locations, and sender-receiver pairs is generated automatically and can reveal as much as the content itself.

Personally identifiable information

Some data is especially sensitive because it can single you out. Personally identifiable information, or PII, is any data that can identify a specific person, such as a full name, home address, phone number, government ID number, or exact location. PII deserves extra care because in the wrong hands it enables fraud, stalking, and identity theft. A useful habit is to pause before sharing PII online and ask whether the site truly needs it and can be trusted with it.

Key idea: personally identifiable information can single you out, so it needs extra protection.

Where your data goes after you share it

Sharing data with an app is rarely the end of the story. The company you gave it to is the first party, and it may pass copies to third parties: advertisers, analytics firms, and business partners. A whole industry of data brokers buys, combines, and resells profiles built from many such feeds, which is aggregation happening at industrial scale. Copies also linger. Data is cheap to keep and awkward to fully delete, so a photo or comment can outlive the account that posted it, and a company that shuts down may sell its data as an asset. Stored data can also leak in a breach and end up somewhere nobody agreed to. Even school accounts and game platforms fit the pattern, because most modern services log first and ask questions later. None of this means sharing is always wrong. It means each share is a small, hard-to-undo publication, which is why the habits below start with sharing less in the first place.

Key idea: shared data spreads to third parties and brokers, lingers in storage, and can leak, so every share is hard to take back.

Protecting your data

You cannot control everything, but sensible steps meaningfully reduce risk:

  • Share less. The data that is never collected cannot leak. Give apps only what they truly need.
  • Check permissions. Review what apps can access, such as location, camera, and contacts, and turn off what is not needed.
  • Read the trade. "Free" services are often paid for with your data. Notice what you are giving in exchange.
  • Use strong, unique passwords. This limits the damage if one account is breached, a habit you will study more in the cybersecurity lesson.

Key idea: sharing less, checking permissions, and using strong passwords are practical ways to protect your data.

Common misconceptions

  • "Data and information are the same thing." Data is raw facts; information is the meaning you get after processing it. Piles of data are useless until turned into information.
  • "If two things rise together, one must cause the other." Correlation is not causation. A hidden third factor often drives both, as with ice cream and sunburns.
  • "Privacy only matters if you have something to hide." Ordinary facts combined can expose private things, and profiles can be used in ways you never agreed to, so privacy protects everyone.
  • "A free app costs nothing." Many free services are funded by collecting and using your data, which is a real, if invisible, price.
  • "Metadata is harmless because it is not the actual content." Timestamps, locations, and contact patterns accumulate into a detailed portrait, which is why researchers treat metadata as sensitive in its own right.
  • "Data with my name removed cannot identify me." A few ordinary attributes combined, like a birth date plus a hometown, can narrow a crowd to one person, so removing names alone is weak protection.

Recap

  • Data is raw facts; information is the meaning extracted by processing it.
  • Computers find patterns in huge data sets, but correlation does not prove causation.
  • Aggregation can combine harmless data into a revealing private profile.
  • Personally identifiable information can single you out and needs extra care.
  • Share less, check permissions, notice the data-for-service trade, and use strong passwords.

Sources

  1. College Board. (2023). AP Computer Science Principles course and exam description. College Board. apcentral.collegeboard.org β†—
  2. Federal Trade Commission. (n.d.). How websites and apps collect and use your information. FTC Consumer Advice. consumer.ftc.gov β†—
  3. Khan Academy. (n.d.). Online data security (Computers and the Internet). Khan Academy. khanacademy.org β†—
  4. Khan Academy. (n.d.). Data analysis (AP/College Computer Science Principles). Khan Academy. khanacademy.org β†—
  5. Code.org β†—. (n.d.). Computer Science Principles curriculum. Code.org β†—. code.org β†—
  6. Cybersecurity and Infrastructure Security Agency. (n.d.). Use strong passwords. CISA Secure Our World. cisa.gov β†—
  7. National Institute of Standards and Technology. (n.d.). Cybersecurity and privacy. NIST. nist.gov β†—
Key terms
Data
Raw, unorganized facts such as numbers, clicks, or measurements.
Information
The meaning and patterns extracted by organizing and analyzing data.
Correlation
A tendency for two things to occur together, which does not prove one causes the other.
Aggregation
Combining many small pieces of data, which can reveal private facts none showed alone.
Personally identifiable information
Data such as a name, address, or ID number that can identify a specific person; abbreviated PII.
Permissions
Settings that control what data and features an app is allowed to access.

Module 3: Algorithms and Programming Foundations

The building blocks every program is made of. You will meet variables, lists, conditionals, and loops through plain analogies and short traced examples, so that reading and writing simple code stops feeling like magic.

Variables and Data Types

  • Explain what a variable is and how assignment works.
  • Name common data types and why type matters.
  • Trace how a variable's value changes as a program runs.

The big picture

Programs need to remember things: a score, a name, a running total. A variable is how a program stores a value and gives it a name so it can be used and changed later. Variables are the most basic building block of programming, and once they click, code becomes far easier to read.

Key idea: a variable is a named place that stores a value the program can use and change.

What a variable is

Picture a variable as a labeled box. The label is the variable's name, and inside the box is its value. You can look inside to read the value, and you can put a new value in, replacing the old one. When a program says the score is 10, it has a box labeled "score" holding the number 10. Naming the box lets the rest of the program refer to "score" without caring where in memory it actually lives.

Key idea: a variable is like a labeled box: the name is the label and the value is what is inside.

Assignment: putting a value in the box

Storing a value in a variable is called assignment, and most languages write it with an equals sign. Reading it as "gets" instead of "equals" avoids a classic confusion. The line score = 10 means "the box named score gets the value 10." Crucially, this is not a math equation claiming two things are already equal; it is a command to store. That is why a line like score = score + 1 makes sense in code even though it looks impossible in math: it means "take the current value in score, add 1, and put the result back in score."

Key idea: assignment stores a value into a variable, so read the equals sign as "gets," not "is equal to."

Worked example: tracing a variable

Let us trace these four lines as if we were the computer, writing down the value in the box after each step:

score = 5
score = score + 3
score = score * 2
score = score - 1
  1. score = 5: the box gets 5. Value is now 5.
  2. score = score + 3: current 5 plus 3 is 8, stored back. Value is now 8.
  3. score = score * 2: current 8 times 2 is 16, stored back. Value is now 16.
  4. score = score - 1: current 16 minus 1 is 15, stored back. Value is now 15.

The final value is 15. Tracing line by line, and writing the value after each step, is a skill you will use constantly, and it is exactly how you catch logic errors.

Key idea: to understand code, trace it one line at a time and record each variable's value as it changes.

Data types

Values come in different kinds, called data types. The type tells the computer what a value is and what you can do with it. The common types are:

TypeHoldsExample
IntegerA whole number42
Floating pointA number with a decimal3.14
StringText, in quotes"hello"
BooleanTrue or false onlytrue

A string is any sequence of characters treated as text, and it is written in quotes so the computer knows it is text rather than code. A Boolean, named after logician George Boole, can only be true or false, and it becomes essential when programs make decisions.

Key idea: a data type says what kind of value something is: whole number, decimal, text, or true/false.

Why type matters

Type matters because the same symbol can mean different things depending on type. Consider the plus sign. With numbers, 2 + 3 gives 5. But with strings, "2" + "3" often gives "23", because joining text end to end is called concatenation. The characters look identical, yet the result differs entirely because the types differ. Mixing up a number and a string that looks like a number is one of the most common beginner bugs, so knowing the type of every value is genuinely important.

Type also decides what INPUT() hands your program. In many settings, whatever a user types arrives as a string, even when it looks numeric, so a program that needs math must first convert "16" the text into 16 the number. Forgetting that conversion is why beginner calculators sometimes announce that 1 plus 1 is 11: the plus sign joined two strings instead of adding two numbers.

Key idea: the type changes what an operation does, so the same plus sign can add numbers or join text.

Naming variables well

You choose your variable names, and good names make code readable. A name like totalScore or userAge tells a reader what the box holds; a name like x or temp forces them to guess. Since code is read far more often than it is written, clear names are a kindness to your future self and your teammates. Most languages require names to start with a letter and forbid spaces, which is why programmers join words with capitals or underscores.

Key idea: descriptive variable names make code readable, because code is read far more often than written.

The AP arrow, and the classic swap problem

With this lesson you are firmly inside Big Idea 3, Algorithms and Programming (AAP), the largest slice of the exam at 30 to 35 percent of the questions. The exam's pseudocode writes assignment with an arrow instead of an equals sign, which makes the "gets" reading visible: score ← 10 means score gets 10. Here is the most famous assignment puzzle on the exam: swapping two variables. Suppose x holds 3 and y holds 8, and you want them exchanged. The tempting two lines fail:

x ← y
y ← x

Trace it. The first line copies y into x, so x becomes 8, and the original 3 is gone forever. The second line copies x, which is now 8, into y. Both variables end up 8. The fix is a third variable to hold the value that would otherwise be destroyed:

temp ← x
x ← y
y ← temp
Linexytemp
temp ← x383
x ← y883
y ← temp833

Now x holds 8 and y holds 3: swapped. The deep lesson is that assignment copies a value and overwrites what was there, so order matters and a value with no copy is lost.

Key idea: assignment overwrites, so swapping two variables needs a temporary third one to save a value before it is destroyed.

Variables store values, not formulas

One subtle rule prevents a whole family of bugs: an assignment stores the value computed at that moment, not a live formula. Trace this:

a ← 2
b ← 3
total ← a + b
a ← 10
DISPLAY(total)

Line 3 computes 2 plus 3 and stores 5 in total. Line 4 changes a to 10, but total does not react, because total holds the number 5, not the recipe "a plus b." The program displays 5, not 13. Spreadsheets update automatically; variables do not, and expecting spreadsheet behavior from code is a common early mistake.

Key idea: total ← a + b stores the result computed right then, and later changes to a or b never update it.

MOD: the remainder operator

AP pseudocode includes one arithmetic operator that may be new: MOD, the remainder after whole-number division. So 17 MOD 5 is 2, because 5 fits into 17 three times with 2 left over, and 10 MOD 2 is 0, because 2 divides 10 evenly. That last fact is the classic even-number test: a number n is even exactly when n MOD 2 equals 0. MOD also handles anything that wraps around. Five hours after 10 o'clock is (10 + 5) MOD 12, which is 15 MOD 12, which is 3 o'clock. Exam questions use MOD for evenness, wrap-around, and extracting digits, so it pays to be comfortable reading it.

Key idea: MOD gives the remainder, so n MOD 2 tests evenness and MOD makes clocks and other wrap-arounds easy.

Common misconceptions

  • "The equals sign in code means the two sides are equal." In most languages it means assignment, "the left box gets the right value." That is why score = score + 1 is valid.
  • "A variable can only be set once." Its whole point is that the value can change; a new assignment simply replaces the old value.
  • "The number 5 and the text '5' are the same." One is an integer you can do math on; the other is a string. Adding strings joins them, so "5" + "5" is "55," not 10.
  • "Variable names do not matter." Clear names make programs far easier to read and debug; vague names cost you and your teammates time.
  • "A variable stores the equation you typed." It stores only the value that equation produced at that moment. Change the ingredients later and the stored result stays frozen, unlike a spreadsheet cell.
  • "Naming a variable average makes the computer compute an average." Names mean nothing to the machine; they are labels for humans. The variable holds whatever value your code actually stores in it.

Recap

  • A variable is a named box that stores a value the program can read and change.
  • Assignment stores a value; read the equals sign as "gets," not "is equal to."
  • Trace code line by line, recording each variable's value, to understand it and catch bugs.
  • Common data types are integer, floating point, string, and Boolean.
  • Type changes what operations do, so adding strings joins them instead of doing math.

Sources

  1. College Board. (2023). AP Computer Science Principles course and exam description. College Board. apcentral.collegeboard.org β†—
  2. MDN Web Docs. (n.d.). Storing the information you need: Variables. Mozilla. developer.mozilla.org β†—
  3. MDN Web Docs. (n.d.). Variable. MDN Glossary. developer.mozilla.org β†—
  4. MDN Web Docs. (n.d.). Boolean. MDN Glossary. developer.mozilla.org β†—
  5. Khan Academy. (n.d.). Programming (AP/College Computer Science Principles). Khan Academy. khanacademy.org β†—
  6. Code.org β†—. (n.d.). Computer Science Principles curriculum. Code.org β†—. code.org β†—
  7. Malan, D. J. (2026). CS50x: Introduction to computer science. Harvard University. cs50.harvard.edu β†—
Key terms
Variable
A named place in a program that stores a value which can be read and changed.
Assignment
Storing a value into a variable, usually written with an equals sign meaning 'gets'.
Data type
The kind of value something is, such as a whole number, decimal, text, or true/false.
String
A sequence of characters treated as text, written inside quotes.
Boolean
A data type that can only be true or false, used when programs make decisions.
Concatenation
Joining strings end to end, the way the plus sign combines text instead of adding.

Lists and Loops

  • Explain what a list is and how items are accessed by index.
  • Describe how a loop repeats instructions.
  • Trace a simple loop that processes a list.

The big picture

One variable holds one value, but programs often need to handle many values at once, like every student's score or every song in a playlist. A list stores many values under one name, and a loop repeats an action for each of them. Together they let a few lines of code do an enormous amount of work.

Key idea: a list holds many values together, and a loop repeats work over them without writing the steps many times.

What a list is

A list (also called an array in many languages) is an ordered collection of values stored under a single name. If a variable is one labeled box, a list is a row of boxes sharing one label, numbered in order. A playlist, a class roster, and a shopping list are all naturally lists. Instead of ten separate variables for ten scores, you keep one list called scores holding all ten.

Key idea: a list is an ordered row of values kept under one name, like a numbered row of boxes.

Accessing items by index

Each item in a list has a position number called its index. Here is the surprise that trips up nearly every beginner: in most languages, counting starts at 0, not 1. So the first item is at index 0, the second at index 1, and so on. If a list colors holds "red," "green," "blue," then colors[0] is "red" and colors[2] is "blue." Think of the index as how many steps you move from the front of the row; the first item is zero steps in.

Key idea: list items are numbered by index starting at 0, so the first item is at index 0.

What a loop is

A loop is an instruction that repeats a block of code. Without loops, printing a list of 100 names would need 100 lines; with a loop, it takes a few. Repetition is also called iteration, and each single pass through the loop is one iteration. A loop is like telling someone "for every plate in the stack, wash it": you state the action once, and it applies to each item in turn.

Key idea: a loop states an action once and repeats it, so a few lines can process many items.

Two common kinds of loop

There are two shapes of loop you will meet constantly:

  • A for loop repeats a set number of times, or once for each item in a list. Use it when you know how many repetitions you need, such as "for each score in the list."
  • A while loop repeats as long as a condition stays true. Use it when you do not know the count in advance, such as "while the game is not over."

Both save you from copying code, but they answer different questions: a for loop asks "how many times," and a while loop asks "until when."

Key idea: a for loop runs a known number of times, while a while loop runs until a condition stops being true.

Worked example: summing a list

Suppose scores holds 4, 7, and 5, and we want the total. We keep a running total in a variable and add each item as the loop visits it:

total = 0
for each s in scores:
    total = total + s

Trace it, writing total after each iteration. Start with total at 0. First item is 4, so total becomes 0 + 4 = 4. Second item is 7, so total becomes 4 + 7 = 11. Third item is 5, so total becomes 11 + 5 = 16. After the loop, total is 16. This pattern, a variable that accumulates a result across a loop, appears in countless programs and is called an accumulator.

Key idea: a loop plus an accumulator variable can total or combine every item in a list.

The danger: infinite loops

A while loop that never becomes false runs forever, freezing the program. This is an infinite loop, and it is a common bug. If you write "while count is less than 10" but forget to increase count inside the loop, the condition never changes and the loop never ends. The fix is to make sure something inside the loop moves the condition toward becoming false, such as adding 1 to count each pass. Always ask: what will eventually stop this loop?

Key idea: a loop whose condition never becomes false runs forever, so ensure each pass moves toward stopping.

A warning about the AP exam: its lists start at 1

Here is a trap built into this Big Idea 3 (AAP) topic, and knowing it is worth points. Most real languages index from 0, as you just learned. The AP exam's pseudocode does not. On the official reference sheet, the first item of a list is at index 1, so if colors holds "red," "green," "blue," then colors[1] is "red" and colors[3] is "blue" on the exam. Neither convention is wrong; they are different agreements, like countries driving on different sides of the road. The skill is to check which world a problem lives in before answering. In this course, prose about "most languages" means 0-based, and anything written in AP pseudocode, with arrows and DISPLAY, is 1-based. One related detail: in the exam's 1-based world, LENGTH(list) is also the index of the last item, which makes loops from 1 to LENGTH(list) read naturally.

Key idea: AP pseudocode indexes lists from 1 while most languages index from 0, and exam answers must follow the exam's convention.

The AP list operations, traced

The exam gives you a small toolkit of list operations: APPEND adds an item to the end, INSERT pushes an item in at a chosen index, REMOVE deletes the item at an index, and LENGTH reports how many items the list holds. Watch them work, using the exam's 1-based indexing:

scores ← [4, 7, 5]
APPEND(scores, 9)
INSERT(scores, 2, 6)
REMOVE(scores, 1)
DISPLAY(LENGTH(scores))
After linescores holdsWhy
scores ← [4, 7, 5][4, 7, 5]three items to start
APPEND(scores, 9)[4, 7, 5, 9]9 joins the end
INSERT(scores, 2, 6)[4, 6, 7, 5, 9]6 enters at index 2; later items shift right
REMOVE(scores, 1)[6, 7, 5, 9]the 4 at index 1 is deleted; items shift left
DISPLAY(LENGTH(scores))[6, 7, 5, 9]displays 4, the current count

Two behaviors deserve attention. INSERT and REMOVE shift the neighbors, so every later item changes its index, and LENGTH is computed fresh each time it is called, so it reflects all the changes so far.

The loop patterns you can now read cover most exam questions about lists: the sum accumulator, the counter with a condition, and one more worth naming, the running maximum. To find the largest score, store the first item as the best so far, then let a FOR EACH loop compare every item against it, replacing it whenever a bigger one appears. On [4, 7, 5] the best-so-far goes 4, then 7, then stays 7, so 7 is the answer. Sum, count, and max are one family: a variable that survives the loop and collects the result.

Key idea: APPEND, INSERT, REMOVE, and LENGTH are the exam's list tools, and INSERT and REMOVE renumber everything after the spot they touch.

REPEAT n TIMES and REPEAT UNTIL

AP pseudocode writes its two loop shapes as REPEAT n TIMES, which runs a block a fixed number of times, and REPEAT UNTIL(condition), which keeps looping until the condition becomes true. Trace this doubling program:

x ← 1
REPEAT 3 TIMES
{
  x ← x * 2
}
DISPLAY(x)

x starts at 1, becomes 2 after the first pass, 4 after the second, and 8 after the third, so the program displays 8. A REPEAT UNTIL version would loop with the condition (x > 7) instead and stop at the same value. Notice the mirror logic: REPEAT UNTIL runs while its condition is still false and stops when it turns true, the reverse of the while loops described above, and a frequent source of flipped-logic mistakes on the exam.

Key idea: REPEAT 3 TIMES turns 1 into 8 by doubling, and REPEAT UNTIL stops when its condition becomes true, not while it is true.

Common misconceptions

  • "The first item in a list is at index 1." In most languages counting starts at 0, so the first item is at index 0. Forgetting this causes off-by-one errors constantly.
  • "Loops are only for advanced programs." Loops are among the most basic and most used tools in all of programming; almost every real program contains them.
  • "A while loop always runs at least once." If its condition is false at the start, the loop body may never run at all. Its check happens before each pass.
  • "You need a separate variable for each value." A list holds many values under one name, which is exactly what lets a single loop process them all.
  • "The AP exam indexes lists from 0 like most languages." The exam's pseudocode starts at index 1, so colors[1] is the first item there. Check which convention a problem uses before answering.
  • "LENGTH is always the index of the last item." That holds only in 1-based systems like AP pseudocode. In 0-based languages the last index is the length minus one, a constant source of off-by-one bugs.

Recap

  • A list stores many ordered values under one name, like a numbered row of boxes.
  • Items are accessed by index, which starts at 0 in most languages.
  • A loop repeats an action; each pass is one iteration.
  • A for loop runs a known number of times; a while loop runs until a condition is false.
  • An accumulator variable plus a loop can total or combine a whole list, but an unending condition causes an infinite loop.

Sources

  1. College Board. (2023). AP Computer Science Principles course and exam description. College Board. apcentral.collegeboard.org β†—
  2. MDN Web Docs. (n.d.). Looping code. Mozilla. developer.mozilla.org β†—
  3. MDN Web Docs. (n.d.). Arrays. Mozilla. developer.mozilla.org β†—
  4. MDN Web Docs. (n.d.). Loops and iteration. JavaScript Guide. developer.mozilla.org β†—
  5. MDN Web Docs. (n.d.). Loop. MDN Glossary. developer.mozilla.org β†—
  6. Khan Academy. (n.d.). Programming (AP/College Computer Science Principles). Khan Academy. khanacademy.org β†—
  7. Code.org β†—. (n.d.). Computer Science Principles curriculum. Code.org β†—. code.org β†—
Key terms
List
An ordered collection of values stored under one name; also called an array.
Index
The position number of an item in a list, starting at 0 in most languages.
Loop
An instruction that repeats a block of code.
Iteration
A single pass through the body of a loop.
While loop
A loop that repeats as long as a condition stays true.
Infinite loop
A loop whose condition never becomes false, so it runs forever and freezes the program.

Conditionals and Boolean Logic

  • Use if, else if, and else to make decisions in code.
  • Evaluate Boolean expressions with comparisons.
  • Combine conditions with AND, OR, and NOT.

The big picture

Programs feel intelligent because they make decisions: show this if the password is right, warn the user if the tank is low. That decision-making comes from conditionals, instructions that run only when a condition is true. Underneath them sits Boolean logic, the true-and-false reasoning that powers every choice a computer makes.

Key idea: conditionals let a program choose what to do based on whether something is true or false.

The if statement

The if statement is the heart of decision-making. It checks a condition, and if that condition is true, it runs a block of code; if not, it skips it. In plain form it reads like an English sentence: "if it is raining, take an umbrella." The condition is a question with a yes-or-no answer, and only a true answer triggers the action.

if temperature > 30:
    print("It is hot")

Here the message prints only when temperature is greater than 30. If temperature is 25, the condition is false and the line is skipped entirely.

Key idea: an if statement runs its block only when its condition is true, and skips it otherwise.

else and else if

Often you want an alternative when the condition is false. That is what else provides: a block that runs when the if condition was not true. And when there are several possibilities, else if (written elif or else if depending on the language) checks more conditions in turn.

if score >= 90:
    print("A")
else if score >= 80:
    print("B")
else:
    print("C or below")

The computer checks each condition top to bottom and takes the first one that is true, then skips the rest. So a score of 85 prints "B": the first test fails, the second succeeds, and the else is never reached. Order matters, because only the first matching branch runs.

Key idea: else gives a fallback, and else if adds more choices, with the first true condition winning.

Boolean expressions and comparisons

The condition inside an if is a Boolean expression, something that evaluates to either true or false. Most are built from comparison operators that compare two values:

OperatorMeansExample that is true
>greater than5 > 3
<less than2 < 9
>=greater than or equal to4 >= 4
==equal to7 == 7
!=not equal to7 != 8

Notice that checking equality uses a double equals ==, which is different from the single equals of assignment. A single = stores a value; a double == asks "are these equal?" Confusing the two is one of the most common beginner mistakes.

Key idea: a Boolean expression evaluates to true or false, and equality is tested with == , not the single = used for assignment.

Combining conditions: AND, OR, NOT

Real decisions often depend on more than one thing. Three logical operators combine Boolean values:

  • AND is true only when both parts are true. "If you are hungry AND it is lunchtime, eat."
  • OR is true when at least one part is true. "If it is Saturday OR Sunday, sleep in."
  • NOT flips a value: NOT true is false, and NOT false is true. "If it is NOT raining, walk."

For example, age >= 13 AND age <= 19 is true only for numbers that are both at least 13 and at most 19, that is, the teen years. Combining conditions this way lets a program express quite subtle rules from these three simple building blocks.

Key idea: AND needs both true, OR needs at least one true, and NOT flips true and false.

Worked example: tracing a decision

Suppose age is 15 and we run: if age >= 13 AND age <= 19, print "teenager"; else print "not a teenager." Check the condition: is 15 at least 13? Yes. Is 15 at most 19? Yes. Both parts are true, so AND is true, and the program prints "teenager." Now imagine age is 20: 20 is at least 13 (true) but not at most 19 (false), so AND is false and the else prints "not a teenager." Walking through each comparison is exactly how you predict what a conditional will do.

Key idea: to predict a conditional, evaluate each comparison to true or false, then combine them with the logical operators.

Truth tables: the complete map

Because Boolean values can only be true or false, you can list every possible combination in a small chart called a truth table. This is Big Idea 3 (AAP) material the exam leans on hard, and the whole table is worth internalizing:

aba AND ba OR b
truetruetruetrue
truefalsefalsetrue
falsetruefalsetrue
falsefalsefalsefalse

Read the rows and two facts jump out. AND is true in exactly one row, when both inputs are true. OR is false in exactly one row, when both inputs are false. NOT simply flips whichever value it receives. One subtlety: NOT (a AND b) does not mean both are false. It means the pair is not both-true, so it is true whenever at least one input is false. Being "not both" and being "neither" are different claims, and exam writers love the difference.

When an expression mixes operators, parentheses decide the order, and writing them in is always safest. NOT binds before AND and OR in most systems, so NOT a AND b means (NOT a) AND b rather than NOT (a AND b). On paper, evaluate the innermost parentheses first, replace each piece with true or false, and collapse outward one operator at a time, exactly like simplifying arithmetic.

Key idea: AND has one true row and OR has one false row, and NOT (a AND b) means "not both," which is weaker than "neither."

Nested conditionals in AP pseudocode

The exam's pseudocode has IF and ELSE but no separate else-if keyword. A chain is written by nesting a second IF inside the ELSE block:

IF (score >= 90)
{
  DISPLAY("A")
}
ELSE
{
  IF (score >= 80)
  {
    DISPLAY("B")
  }
  ELSE
  {
    DISPLAY("C or below")
  }
}

Trace it with score holding 85. The outer condition asks whether 85 is at least 90: false, so control drops into the ELSE. The inner condition asks whether 85 is at least 80: true, so the program displays B and the inner ELSE is skipped. Exactly one branch of the whole structure ever runs, which mirrors the else-if chains from above; only the layout differs.

Key idea: AP pseudocode builds else-if chains by nesting IF inside ELSE, and tracing 85 through this one displays B.

Conditionals that drive a robot

Exam questions often dress conditionals in a robot costume. A robot sits on a grid, facing one direction, and understands a few commands: MOVE_FORWARD() moves one square ahead, ROTATE_LEFT() and ROTATE_RIGHT() turn it 90 degrees in place, and CAN_MOVE(forward) asks whether the square ahead is open. The question shows code and asks where the robot ends up. The conditional logic is the same as with numbers:

IF (CAN_MOVE(forward))
{
  MOVE_FORWARD()
}
ELSE
{
  ROTATE_RIGHT()
}

If the path ahead is open, the robot advances; if a wall blocks it, the robot turns right and waits for the next instruction. Trace robot problems the same way you trace variables: track the robot's square and its facing direction after every single command, and never do two commands in your head at once.

Key idea: robot questions are ordinary conditionals where the state you trace is the robot's position and direction instead of a number.

Patterns the exam repeats

Three habits close out this topic. First, a range like "from 13 through 19" always needs two comparisons joined by AND, because a lone comparison checks only one boundary. Second, a Boolean variable already is a condition: IF (isSunny) means exactly the same as IF (isSunny = true), just cleaner. Third, remember from the variables lesson that in AP pseudocode the arrow assigns and = only compares, so there is no danger of accidental assignment inside a condition, a mercy real languages do not always grant.

Key idea: ranges need AND, a Boolean variable can stand alone as a condition, and in AP pseudocode = always compares.

Common misconceptions

  • "= and == are interchangeable." A single = assigns a value; a double == tests equality. Using the wrong one is a frequent bug.
  • "OR means exactly one." In programming, OR is true when at least one part is true, including when both are true. It is not "one or the other but not both."
  • "All the branches of an if-else can run." Only the first condition that is true runs; the rest are skipped, so order matters.
  • "AND and OR mean the same casual thing as in speech." They have precise definitions: AND needs both true, OR needs at least one true. Reasoning from the casual meaning leads to wrong conditions.
  • "NOT (a AND b) means both a and b are false." It only rules out the both-true case, so it is true whenever at least one is false. "Neither" would be NOT (a OR b).
  • "A math-style chain like 13 <= age <= 19 works in code." Most languages and the AP pseudocode need two comparisons joined by AND, one for each boundary of the range.

Recap

  • Conditionals let a program act only when a condition is true.
  • if runs a block when true; else is the fallback; else if adds more choices, first true wins.
  • Boolean expressions evaluate to true or false, often using comparison operators.
  • Equality is tested with ==, distinct from the single = of assignment.
  • AND needs both true, OR needs at least one true, and NOT flips a value.

Sources

  1. College Board. (2023). AP Computer Science Principles course and exam description. College Board. apcentral.collegeboard.org β†—
  2. MDN Web Docs. (n.d.). Making decisions in your code: Conditionals. Mozilla. developer.mozilla.org β†—
  3. MDN Web Docs. (n.d.). Boolean. MDN Glossary. developer.mozilla.org β†—
  4. MDN Web Docs. (n.d.). Conditional. MDN Glossary. developer.mozilla.org β†—
  5. Khan Academy. (n.d.). Programming (AP/College Computer Science Principles). Khan Academy. khanacademy.org β†—
  6. Code.org β†—. (n.d.). Computer Science Principles curriculum. Code.org β†—. code.org β†—
  7. Encyclopaedia Britannica. (n.d.). George Boole. In Britannica Biography. (Access via britannica.com β†—.)
Key terms
Conditional
An instruction that runs code only when a condition is true.
if statement
A conditional that runs a block when its condition is true and skips it otherwise.
else
A block that runs when the matching if condition was false.
Boolean expression
An expression that evaluates to either true or false.
Comparison operator
A symbol like >, <, or == that compares two values and yields true or false.
Logical operator
AND, OR, or NOT, used to combine or flip Boolean values.

Module 4: Procedures, Abstraction, and Algorithm Design

How programmers tame complexity by naming and hiding detail. You will learn to package steps into reusable procedures, use abstraction to think at a higher level, and reason about whether an algorithm is fast enough.

Procedures and Abstraction

  • Explain what a procedure is and why it reduces repetition.
  • Describe how parameters and return values work.
  • Define abstraction and give everyday examples.

The big picture

As programs grow, repeating the same steps everywhere becomes a nightmare to write and fix. A procedure packages a set of steps under a name so you can reuse them with a single call. Doing so is an example of abstraction, one of the deepest and most important ideas in all of computing.

Key idea: a procedure names a block of steps so you can reuse it, and that packaging is a form of abstraction.

What a procedure is

A procedure (also called a function or method) is a named, reusable block of instructions. You define it once, then call it by name whenever you want those steps to run. It is like a recipe you have written down: instead of relisting every step each time you bake, you just say "make the cookie dough" and follow the saved recipe. If ten places in your program need to greet a user, you write a greet procedure once and call it ten times.

Key idea: a procedure is a named block of steps you define once and call by name whenever you need it.

Why procedures matter

Procedures pay off in three concrete ways. They remove repetition, since shared steps live in one place. They make code readable, because a well-named call like calculateTax tells a reader what happens without showing the messy details. And they make fixes safe: if the logic is wrong, you correct it in the one procedure rather than hunting down every copy. Writing the same code five times means fixing the same bug five times; a procedure means fixing it once.

Key idea: procedures cut repetition, improve readability, and let you fix a bug in one place instead of many.

Parameters: giving a procedure input

A procedure becomes far more useful when it can work on different values each time. A parameter is a named input a procedure accepts, and the actual value you pass in is called an argument. A greet procedure with a name parameter can say hello to anyone: call greet("Ada") and it greets Ada; call greet("Grace") and it greets Grace. The parameter is like a blank in a form letter that gets filled in each time you send it.

Key idea: a parameter is a labeled input, so one procedure can operate on different values passed in as arguments.

Return values: getting output back

Many procedures compute a result and hand it back to the code that called them. That handed-back result is the return value. A procedure named square that takes a number and returns it multiplied by itself lets you write square(5) and get 25 to use elsewhere. Think of it as a vending machine: you put in an input (press a button), and it returns an output (the snack). A procedure can take inputs through parameters and give an output through its return value.

Key idea: a return value is the result a procedure sends back, so its output can be used by the rest of the program.

Abstraction: hiding the details

Abstraction means hiding complex details behind a simple interface so you can use something without understanding its inner workings. It is the single most powerful idea for managing complexity. The classic analogy is a car's steering wheel: you turn it to steer without knowing anything about the gears, linkages, and hydraulics underneath. The steering wheel is a simple interface hiding enormous complexity, and that is exactly what a good procedure provides.

Abstraction is everywhere in computing. When you call a procedure, you use its name and inputs without caring how it works inside. When you tap an app icon, you launch a program without seeing the code. Each layer hides the one below it, which is what lets people build enormous systems without holding every detail in mind at once.

Key idea: abstraction hides inner complexity behind a simple interface, like a steering wheel hiding a car's machinery.

Layers of abstraction

Computing is built as a stack of abstraction layers, each resting on the one beneath. At the bottom are electrical signals and binary; above that sit basic instructions, then programming languages, then procedures you write, then whole applications. A programmer writing an app rarely thinks about voltages, because the layers below are abstracted away. This layering is why a beginner can build something real without first mastering electronics: you work at your layer and trust the ones below.

Key idea: computing is a stack of abstraction layers, each hiding the details of the layer below it.

Procedures in AP pseudocode, traced

The College Board framework calls this topic procedural abstraction, and it sits in Big Idea 3 (AAP). Here is how the exam writes a procedure with a parameter and a returned result:

PROCEDURE square(n)
{
  RETURN(n * n)
}

result ← square(5)
DISPLAY(result)

Trace the call carefully. The line result ← square(5) pauses, hands 5 to the procedure, and waits. Inside, the parameter n now holds 5, so n * n computes 25, and RETURN sends 25 back to the paused line, which stores it in result. The display shows 25. RETURN does two jobs at once: it ends the procedure immediately and delivers the value to whoever called.

Calls can also nest. What does DISPLAY(square(square(2))) show? Work from the inside out: square(2) returns 4, then square(4) returns 16, so the display shows 16. Reading nested calls inside-out is a small skill the exam tests directly.

Key idea: a call hands arguments to the parameters, RETURN sends the result back to the paused caller, and nested calls evaluate inside-out.

A procedure with all three building blocks

The Create Performance Task, previewed in the final lesson, requires a procedure you wrote that contains sequencing, selection, and iteration: ordered steps, a conditional, and a loop. Here is one, and it reuses the counting pattern from the data lessons:

PROCEDURE countAbove(list, limit)
{
  count ← 0
  FOR EACH item IN list
  {
    IF (item > limit)
    {
      count ← count + 1
    }
  }
  RETURN(count)
}

DISPLAY(countAbove([4, 7, 5], 4))

Trace the call countAbove([4, 7, 5], 4). The parameter list holds [4, 7, 5] and limit holds 4. The loop visits 4 first: is 4 greater than 4? No, count stays 0. Next 7: yes, count becomes 1. Next 5: yes, count becomes 2. The loop ends and RETURN(count) hands back 2, which is displayed. One procedure, three structures, and it works for any list and any limit you pass in. That generality is the payoff of parameters.

Procedural abstraction carries one more superpower the framework highlights. When a procedure's inner workings improve, every caller benefits without changing a line. Suppose a faster way of counting is discovered. You rewrite the inside of countAbove once, and the hundred places that call it become faster instantly, because callers only ever depended on the name, the inputs, and the promised result, never on the details inside. That is the steering wheel's contract from earlier in this lesson, now applied to code you wrote yourself.

Key idea: countAbove([4, 7, 5], 4) returns 2, and a procedure combining sequencing, selection, and iteration is exactly what the Create Task expects.

Standing on libraries

Abstraction scales beyond your own procedures. A library is a collection of procedures written, tested, and documented by other people, ready to call. When a programmer draws a chart, sorts a list, or fetches a web page with one call, a library is doing the heavy lifting behind that simple name. The AP framework highlights libraries because they change what one person can build: instead of writing everything from voltage up, you assemble tested pieces and add only what is new. A library's public face is often called an API, an application programming interface: the documented set of procedures it offers to callers. The documentation matters as much as the code, since a library you cannot understand is a library you cannot safely use. Learning to read documentation and trust well-tested building blocks is part of thinking like a software engineer.

Key idea: libraries are collections of ready-made, documented procedures, and building on them is abstraction working at full scale.

Common misconceptions

  • "Procedures are only worth it for huge programs." Even a short program benefits, because a named block is clearer and any repeated logic gets a single home.
  • "A parameter and an argument are the same word." The parameter is the named input in the definition; the argument is the actual value you pass when you call it.
  • "Abstraction hides information you need." It hides details you do not need at the moment, letting you focus. You can always look inside when necessary.
  • "Every procedure returns a value." Some procedures just perform an action, like printing a message, and return nothing at all.
  • "RETURN prints the value on the screen." RETURN silently hands the value back to the caller; nothing appears unless the caller passes it to DISPLAY. Mixing up returning and displaying is a classic exam error.
  • "Defining a procedure runs it." A definition only stores the recipe. The steps run when, and only when, the procedure is called, and each call starts it fresh.

Recap

  • A procedure is a named, reusable block of steps you define once and call by name.
  • Procedures reduce repetition, improve readability, and let you fix bugs in one place.
  • Parameters are named inputs; the values passed in are arguments.
  • A return value is the output a procedure hands back to its caller.
  • Abstraction hides inner complexity behind a simple interface, and computing is built in layers of it.

Sources

  1. College Board. (2023). AP Computer Science Principles course and exam description. College Board. apcentral.collegeboard.org β†—
  2. MDN Web Docs. (n.d.). Functions: Reusable blocks of code. Mozilla. developer.mozilla.org β†—
  3. MDN Web Docs. (n.d.). Functions. JavaScript Guide. developer.mozilla.org β†—
  4. MDN Web Docs. (n.d.). Abstraction. MDN Glossary. developer.mozilla.org β†—
  5. MDN Web Docs. (n.d.). Function. MDN Glossary. developer.mozilla.org β†—
  6. Khan Academy. (n.d.). Programming (AP/College Computer Science Principles). Khan Academy. khanacademy.org β†—
  7. Code.org β†—. (n.d.). Computer Science Principles curriculum. Code.org β†—. code.org β†—
Key terms
Procedure
A named, reusable block of instructions; also called a function or method.
Call
To run a procedure by using its name, optionally passing in values.
Parameter
A named input a procedure accepts so it can work on different values.
Argument
The actual value passed to a procedure when it is called.
Return value
The result a procedure hands back to the code that called it.
Abstraction
Hiding complex details behind a simple interface so something can be used without understanding its inner workings.

Algorithms and Efficiency

  • Define an algorithm and give clear examples.
  • Compare algorithms by how their work grows with input size.
  • Explain why some problems are hard even for computers.

The big picture

An algorithm is a clear, step-by-step method for solving a problem, and it is the beating heart of computer science. The same problem can have several algorithms, some fast and some painfully slow. Learning to compare them, and to recognize that a few problems resist fast solutions entirely, is what separates a coder from a computational thinker.

Key idea: an algorithm is a step-by-step method to solve a problem, and different algorithms for the same problem can differ hugely in speed.

What an algorithm is

An algorithm is a finite sequence of well-defined steps that solves a problem or completes a task. A cooking recipe is an algorithm: precise steps in order that turn ingredients into a dish. Directions to a friend's house are an algorithm. The key traits are that the steps are clear enough to follow without guessing, and that the process eventually ends with a result. Algorithms existed long before computers; computers just carry them out at astonishing speed.

Key idea: an algorithm is a clear, finite set of steps that always leads to a result, like a recipe.

Many algorithms, one problem

Most problems can be solved more than one way. Suppose you want to find a name in a phone book. One algorithm is linear search: start at the first page and check every entry until you find it. Another is binary search: open to the middle, see whether the name is before or after, and repeat on the correct half, throwing away the rest each time. Both find the name, but binary search is dramatically faster on a large, sorted book. Choosing the better algorithm can matter more than any other decision in a program.

Key idea: a single problem often has several correct algorithms, and the choice between them can change speed enormously.

Efficiency: how work grows with size

Efficiency asks how the amount of work an algorithm does grows as the input gets bigger. This matters because an algorithm that is fine for 10 items may be hopeless for 10 million. We compare algorithms by the shape of that growth, not by exact seconds, because the shape is what dominates at large sizes.

Growth shapeWhat happens as input doublesExample
ConstantWork stays the sameGrabbing the first item in a list
LinearWork roughly doublesChecking every item once (linear search)
LogarithmicWork grows by just one more stepBinary search on sorted data
QuadraticWork roughly quadruplesComparing every item to every other item

The differences are staggering at scale. For a million items, a linear algorithm might take a million steps while a logarithmic one takes about twenty. That is why efficiency, not raw computer speed, is often what makes a program usable.

Key idea: we compare algorithms by how their work grows with input size, and that growth shape dominates at large scales.

Worked example: comparing searches

Imagine a sorted list of 1,000 names and you search for one. Linear search checks names one by one, so in the worst case it makes 1,000 checks. Binary search halves the list each step: 1,000, then 500, 250, 125, and so on, reaching the answer in about 10 checks, because you can halve 1,000 only about ten times before reaching one. Now picture a billion names: linear search could need a billion checks, but binary search needs only about 30. Same problem, wildly different work, purely because of the algorithm.

Key idea: halving the search space each step (binary search) turns a billion checks into about thirty, showing why algorithm choice matters.

Tracing binary search step by step

Watch the halving happen on a small sorted list of seven numbers, searching for 25. Positions are numbered 1 through 7, AP style:

[3, 8, 12, 17, 25, 31, 40]
StepStill possibleMiddle checkedResult
1positions 1-7position 4, value 1725 > 17, keep the right half
2positions 5-7position 6, value 3125 < 31, keep the left part
3position 5position 5, value 25found it

Three checks instead of the five a linear scan would have used, and the gap explodes as lists grow. Count it for one million sorted items: linear search may need 1,000,000 checks, while halving needs only about 20, because doubling 1 twenty times passes one million (2 to the 20th power is 1,048,576). One caution the exam loves: binary search demands sorted data. On an unsorted list, throwing away half the items is not justified, and the algorithm simply gives wrong answers.

Key idea: binary search finds an item in a million sorted values in about 20 checks, but it is only valid on sorted data.

When problems are just hard

Some problems have no known fast algorithm at all. A famous example is planning the shortest route that visits many cities and returns home, the traveling salesperson problem. For a handful of cities it is easy, but as cities are added the number of possible routes explodes so quickly that even the fastest supercomputer cannot check them all in any reasonable time. These are called intractable problems: solvable in principle, but not quickly at large sizes. When exact answers are out of reach, programmers use a heuristic, a practical shortcut that finds a good-enough answer without guaranteeing the perfect one.

Key idea: some problems have no fast solution at scale, so we settle for heuristics that give good-enough answers.

Reasonable versus unreasonable time

The AP framework, in Big Idea 3 (AAP), draws the efficiency line with two plain words. An algorithm runs in reasonable time when its work grows like the input size, or the size squared, or another polynomial: growth you can outrun with better hardware. It runs in unreasonable time when the work multiplies with every item added, doubling or worse, because that growth buries any hardware ever built. Brute force is the classic unreasonable case. Checking every subset of 20 items means 2 to the 20th power possibilities, about 1,048,576, which a laptop shrugs off. At 40 items it is about 1.1 trillion, and every single extra item doubles the total again. The traveling salesperson numbers grow even faster: 10 cities allow 181,440 distinct round trips, and 15 cities allow 43,589,145,600. Five more cities multiplied the routes by roughly 240,000. That is what unreasonable means: not slow, but hopeless at scale, which is exactly why heuristics earn their keep.

Key idea: reasonable time grows polynomially while brute force doubles with each added item, reaching billions of possibilities within a few dozen items.

Not everything is computable

There is an even deeper limit. A few problems cannot be solved by any algorithm whatsoever, no matter how much time or power you have. Computer scientists proved that certain questions are undecidable, meaning no general algorithm can answer them for every case. This is a profound result: computing is astonishingly powerful, but it is not infinitely so, and knowing where the edges are is part of understanding the field honestly.

Key idea: a few problems are undecidable, meaning no algorithm can solve them, marking a true limit of computing.

Randomness and simulation

The AP toolkit includes one more piece: RANDOM(a, b) produces a random integer from a through b, each equally likely. Randomness powers simulation, using a program as a simplified model of something real so you can experiment safely and cheaply. Here is a simulation of rolling two dice 600 times to see how often the total is 7:

sevens ← 0
REPEAT 600 TIMES
{
  roll ← RANDOM(1, 6) + RANDOM(1, 6)
  IF (roll = 7)
  {
    sevens ← sevens + 1
  }
}
DISPLAY(sevens)

Each pass rolls two dice and checks the total. Of the 36 equally likely pairs, exactly 6 add to 7, so 7 should appear about one sixth of the time, near 100 of the 600 rolls. Run the program and you might see 92 or 107, and that wobble is honest: real randomness fluctuates, and more trials tighten the estimate. Scientists use exactly this pattern, with far richer models, to study weather, traffic, and the spread of disease. A simulation trades some realism for the power to test thousands of tomorrows before lunch, and its answers are only as good as the model's assumptions.

Key idea: RANDOM plus repetition builds simulations, like 600 dice rolls landing near 100 sevens, that answer questions too big or risky to test in reality.

Common misconceptions

  • "A faster computer removes the need for a good algorithm." Growth shape dominates at scale, so a poor algorithm on a fast machine still loses badly to a good algorithm as input grows.
  • "If a program gives the right answer, its efficiency does not matter." Correctness and efficiency are separate. A correct but slow algorithm can be unusable on real-world data sizes.
  • "Every problem has a fast solution if you are clever enough." Some problems are intractable at scale, and a few are undecidable, meaning no algorithm can ever solve them.
  • "An algorithm must involve a computer." Algorithms are just step-by-step methods; recipes and directions are algorithms too, and they predate computers.
  • "A heuristic always finds the best answer." A heuristic trades the guarantee of the best answer for speed. It usually lands close, but "usually close" is precisely not "always best."
  • "Undecidable means no case of the problem can ever be solved." Individual cases often can be. Undecidable means no single algorithm exists that answers every possible case correctly.

Recap

  • An algorithm is a clear, finite sequence of steps that solves a problem.
  • One problem can have several algorithms that differ greatly in speed.
  • Efficiency measures how work grows with input size; the growth shape dominates at scale.
  • Binary search halving beats linear search enormously on large sorted data.
  • Some problems are intractable or even undecidable, marking real limits of computing.

Sources

  1. College Board. (2023). AP Computer Science Principles course and exam description. College Board. apcentral.collegeboard.org β†—
  2. Khan Academy. (n.d.). Algorithms (Computer science theory). Khan Academy. khanacademy.org β†—
  3. Khan Academy. (n.d.). Algorithms (AP/College Computer Science Principles). Khan Academy. khanacademy.org β†—
  4. MDN Web Docs. (n.d.). Algorithm. MDN Glossary. developer.mozilla.org β†—
  5. CS Unplugged. (n.d.). Searching algorithms. University of Canterbury. csunplugged.org β†—
  6. Clay Mathematics Institute. (n.d.). P vs NP. Millennium Prize Problems. claymath.org β†—
  7. Cook, W. (n.d.). Traveling salesman problem. University of Waterloo. https://www.math.uwaterloo.ca/tsp/index.html find source β†—
Key terms
Algorithm
A finite sequence of clear, well-defined steps that solves a problem or completes a task.
Linear search
Checking items one by one from the start until the target is found.
Binary search
Repeatedly halving a sorted list to find a target far faster than checking every item.
Efficiency
How the amount of work an algorithm does grows as the input gets larger.
Intractable problem
A problem solvable in principle but with no known way to solve it quickly at large sizes.
Heuristic
A practical shortcut that finds a good-enough answer without guaranteeing the perfect one.

Module 5: Computing Systems and Networks

How billions of devices form one worldwide network. You will see how data is broken into packets, addressed, and routed across a fault-tolerant Internet built on open, shared rules.

The Internet and How It Works

  • Explain how data travels the Internet in packets.
  • Describe IP addresses, DNS, and protocols.
  • Explain why the Internet is fault tolerant and scalable.

The big picture

The Internet is a worldwide network of connected computers that can pass messages to one another. It has no central control tower, yet billions of devices reach each other reliably. This lesson explains the clever, simple ideas that make that possible: breaking data into packets, giving every device an address, and agreeing on shared rules called protocols.

Key idea: the Internet is a global network with no central controller, held together by packets, addresses, and shared protocols.

Internet versus web

First, a distinction people often blur. The Internet is the physical and logical network, the cables, wireless links, and machines, that connects computers worldwide. The World Wide Web is just one service that runs on top of it, the system of linked pages you browse. Email, video calls, and online games are other services on the same Internet. The Internet is the road system; the web is one kind of traffic that travels on it.

Key idea: the Internet is the network itself, while the web is only one of many services running on it.

Packets: cutting data into pieces

When you send anything over the Internet, it is not shipped as one big blob. It is chopped into small chunks called packets, each carrying a piece of the data plus labels saying where it is going and where it belongs in the sequence. Packets travel independently, possibly by different routes, and are reassembled in the right order at the destination. Picture mailing a book by tearing out the pages, putting each in its own numbered envelope, and letting the postal system deliver them separately; the reader stacks them back in order using the numbers.

This packet approach has a big payoff: many messages can share the same cables at once, and if one packet is lost, only that small piece must be resent, not the whole message.

Key idea: data is split into numbered packets that travel independently and are reassembled at the destination.

Addresses and DNS

For packets to find their target, every device on the Internet has a numeric IP address, much like a postal address for a house. Packets are labeled with the destination IP so the network can route them there. But numbers are hard for people to remember, so the Domain Name System (DNS) acts as the Internet's phone book: you type a friendly name like example.com, and DNS looks up the matching IP address behind the scenes. Type a name, and DNS quietly turns it into the number the network actually uses.

Key idea: every device has an IP address, and DNS translates human-friendly names into those numeric addresses.

Protocols: the shared rules

Because the Internet connects countless different machines, they must agree on how to communicate. A protocol is an agreed set of rules for exchanging data, and open, shared protocols are what let any two devices talk regardless of brand or maker. A few you should know:

ProtocolJob
IPAddresses and routes packets to the right destination
TCPReassembles packets in order and resends any that are lost
HTTPRules for requesting and sending web pages
DNSTranslates domain names into IP addresses

TCP and IP work so closely together that they are often named as a pair, TCP/IP. IP gets packets to the right place; TCP makes sure they all arrive and are put back in order. Together they turn an unreliable pile of separate packets into a dependable message.

Key idea: protocols are shared rules, and open ones like TCP/IP let any two devices communicate reliably.

One click, start to finish

Here is the whole system working together, told as the story of a single click. You type example.com and press enter. First comes the DNS lookup: your device asks a DNS server for the address behind the name and gets back an IP address, say 93.184.216.34. Second, your browser composes an HTTP request, a short structured message that says, in effect, "GET me the main page." Third, the request is handed to TCP/IP for delivery: chopped into packets, each stamped with the destination IP and a sequence number, and released into the network, where routers pass each packet along whatever path looks best at that instant. Fourth, the server answers with an HTTP response carrying the page itself, and the response is far bigger than the request. A 3-megabyte photo alone is 3,000,000 bytes, and at roughly 1,500 bytes per packet that is about 2,000 packets for one image. Some arrive out of order. A few may vanish. TCP on your device notices every gap from the sequence numbers, requests the missing pieces again, reassembles everything in order, and only then hands the browser a perfect copy to draw on your screen.

Total elapsed time: often under half a second. The layering is the beautiful part. DNS only translates names. IP only routes packets. TCP only guarantees order and completeness. HTTP only speaks the language of requests and responses. Each layer does one job and trusts the others, which is abstraction, the idea from the procedures lesson, running the largest machine humans have ever built.

Key idea: one page load is DNS finding the address, HTTP asking, IP routing about 2,000 packets for a single photo, and TCP reassembling them perfectly.

Fault tolerance: surviving failure

One of the Internet's greatest strengths is fault tolerance, the ability to keep working even when parts fail. Because the network is a mesh with many possible paths between any two points, packets can route around a broken cable or a downed machine by taking another way. There is no single point whose failure stops everything. This is like a city's road grid: if one street is closed, drivers simply take a different route and still arrive. The Internet was deliberately designed this way so that damage to some parts does not bring down the whole.

Key idea: the Internet is fault tolerant because its mesh of many paths lets packets route around failures.

Scalability and openness

The Internet is also remarkably scalable, meaning it keeps working as it grows from thousands to billions of devices. It scales because it is decentralized: no central computer has to handle everything, so new networks can join by simply following the shared protocols. That openness, protocols anyone can use without permission, is why the Internet grew so explosively and why a new device or service can join without asking a central authority. The design values are the lesson here: keep the core simple, shared, and open, and let the edges innovate.

Key idea: the Internet scales to billions of devices because it is decentralized and built on open protocols anyone can adopt.

Bandwidth, the cloud, and computers working in parallel

Three more Big Idea 4 (CSN) terms complete the picture. Bandwidth is the maximum amount of data a connection can move in a fixed time, usually measured in bits per second. Higher bandwidth means the 2,000 packets of that photo arrive sooner; it is the width of the pipe, not the distance. The cloud just means someone else's computers: vast physical data centers full of servers where your files, photos, and messages actually live, reached over the Internet and connected across oceans by real undersea fiber cables. Nothing about it floats.

Finally, big jobs are split across many processors at once, which is parallel computing. The speedup has a hard limit set by whatever cannot be split. Suppose a job takes 60 seconds on one processor, and 20 of those seconds must run in order while the other 40 can be divided. With 4 processors the divisible part takes 40 divided by 4, which is 10 seconds, so the whole job takes 20 plus 10, which is 30 seconds. Add a thousand processors and the job still cannot beat 20 seconds, because the in-order part waits for no one. Distributed systems, many separate machines cooperating over a network, use exactly this math at world scale.

Key idea: bandwidth is capacity per second, the cloud is physical data centers, and parallel speedup is capped by the part of a job that cannot be split.

Common misconceptions

  • "The Internet and the web are the same." The Internet is the network; the web is one service running on it, alongside email, video calls, and games.
  • "Data travels as one whole piece." It is split into packets that move independently and are reassembled at the destination, which is what lets many messages share the cables.
  • "There is a central computer that runs the Internet." The Internet is decentralized with no central controller, which is exactly what makes it fault tolerant and scalable.
  • "If a cable breaks, the Internet stops." Thanks to many possible paths, packets route around failures, so local damage rarely stops the whole network.
  • "The cloud is not physical." Every cloud file sits on real drives in real data centers that use land, electricity, and water. "Cloud" is a soft name for other people's hardware.
  • "The Internet is mostly wireless." Wireless is usually only the first hop to a router. The long haul runs over physical fiber, including hundreds of undersea cables linking continents.

Recap

  • The Internet is the global network; the web is one service that runs on it.
  • Data is split into numbered packets that travel independently and are reassembled.
  • Every device has an IP address, and DNS translates names into those addresses.
  • Protocols are shared rules; open ones like TCP/IP let any devices communicate.
  • The Internet is fault tolerant and scalable because it is a decentralized mesh with many paths.

Sources

  1. College Board. (2023). AP Computer Science Principles course and exam description. College Board. apcentral.collegeboard.org β†—
  2. Postel, J. (Ed.). (1981). RFC 791: Internet Protocol. RFC Editor. rfc-editor.org β†—
  3. Eddy, W. (Ed.). (2022). RFC 9293: Transmission Control Protocol (TCP). RFC Editor. rfc-editor.org β†—
  4. Fielding, R., Nottingham, M., & Reschke, J. (Eds.). (2022). RFC 9110: HTTP semantics. RFC Editor. rfc-editor.org β†—
  5. Mockapetris, P. (1987). RFC 1035: Domain names - implementation and specification. RFC Editor. rfc-editor.org β†—
  6. MDN Web Docs. (n.d.). How the web works. Mozilla. developer.mozilla.org β†—
  7. Khan Academy. (n.d.). The Internet (Computers and the Internet). Khan Academy. khanacademy.org β†—
  8. Leiner, B. M., Cerf, V. G., Clark, D. D., Kahn, R. E., Kleinrock, L., Lynch, D. C., Postel, J., Roberts, L. G., & Wolff, S. (1997). A brief history of the Internet. Internet Society. (Access via internetsociety.org β†—.)
Key terms
Internet
The worldwide network of connected computers that can pass messages to one another.
Packet
A small chunk of data with labels for its destination and its place in the sequence.
IP address
A numeric address identifying a device on the Internet, like a postal address.
DNS
The Domain Name System that translates friendly names into numeric IP addresses.
Protocol
An agreed set of rules for exchanging data so different devices can communicate.
Fault tolerance
The ability of a system to keep working even when some parts fail.

Module 6: The Impact of Computing

Technology is never neutral. This closing module weighs the benefits and harms of computing - bias, the digital divide, privacy, and cybersecurity - and prepares you for the AP exam and the Create Performance Task.

Impacts of Computing: Benefits, Bias, and the Digital Divide

  • Weigh both beneficial and harmful effects of a computing innovation.
  • Explain how bias can enter software and data.
  • Describe the digital divide and why it matters.

The big picture

Computing reshapes how people live, work, learn, and connect, often for the better and sometimes for the worse, frequently both at once. A thoughtful person does not ask "is technology good or bad?" but "who does this help, who does it harm, and how could it be improved?" This lesson builds that balanced habit of mind.

Key idea: most computing innovations bring benefits and harms together, so the useful question is who is helped, who is harmed, and how it could be better.

Innovations cut both ways

Nearly every computing advance has a bright side and a shadow. Social media connects distant friends and gives a voice to the unheard, yet it can spread misinformation and harm mental health. Navigation apps save time and fuel, yet they can send heavy traffic down quiet residential streets. The point is not to reject technology or to cheer it blindly, but to see both effects clearly. An honest analysis names the benefits and the harms of the same innovation side by side.

Key idea: the same innovation usually produces benefits and harms at once, and both deserve to be named.

Intended and unintended effects

Creators design for an intended effect, but technologies almost always produce unintended ones too. Email was meant to speed communication; spam was an unwelcome side effect. A recommendation system meant to show you interesting videos can accidentally pull people toward more and more extreme content. Unintended consequences are not always negative, some are pleasant surprises, but they are hard to predict, which is exactly why testing with real, diverse users and watching for side effects matters so much.

Key idea: technologies produce unintended effects alongside intended ones, so creators must watch for consequences they did not plan.

How bias sneaks into software

People sometimes assume computers are perfectly objective, but software can be biased, meaning it systematically treats some groups unfairly. Bias usually enters through the data a system learns from. If a program is trained on examples that underrepresent or misrepresent a group, it will perform worse for that group. A face-recognition system trained mostly on lighter-skinned faces has been shown to misidentify darker-skinned faces far more often. The computer was not malicious; it simply learned from skewed data and passed the skew along.

Bias can also come from the choices of the people who build a system, what data to collect, what counts as success, whose needs to prioritize. Because these decisions are made by humans, human blind spots can become built into the software. Recognizing that computers are not automatically fair is the first step toward building systems that are.

Key idea: software can be biased, usually because it learns from skewed data or reflects the blind spots of its makers.

Measuring bias instead of guessing

Claims about bias can be tested, and the face-recognition example above comes from real measurement. In 2019 the National Institute of Standards and Technology, the U.S. measurement agency, tested nearly 200 face-recognition algorithms from dozens of companies. Many produced far more false matches for some demographic groups than for others. The size of the gap varied widely from product to product. Two lessons follow. First, bias is a measurable property of a system, not an accusation. It can be tracked and reduced like any other defect. Second, products differ, which means design choices matter. Better training data, deliberate testing across groups, diverse teams, and independent audits all shrink the gaps. The AP framework expects you to reason exactly this way, from evidence about who a system fails toward concrete fixes.

Key idea: bias can be measured, as NIST did across nearly 200 algorithms, and measured problems can be engineered down.

The digital divide

The digital divide is the gap between those who have good access to computers and the Internet and those who do not. Access is not equal: it varies with income, geography, and age. A student with fast home Internet and a laptop can research, apply to jobs, and take online classes; a student without them is shut out of those same opportunities. As more of life moves online, from schoolwork to healthcare to government services, this gap can widen existing inequalities rather than shrink them.

The divide is not only about owning a device. It also includes reliable connection, affordable service, and the skills to use technology well. Closing it is a real policy and design challenge, and it is one of the clearest examples of how computing's benefits are not shared equally.

Key idea: the digital divide is the unequal access to computing and the Internet, and it can deepen other inequalities as life moves online.

The divide, tracked over time

The divide is not a guess either; researchers have tracked it for decades. Pew Research Center's long-running surveys show that in 2000 only about half of U.S. adults used the Internet. Today the overwhelming majority do. That growth is real progress. Yet the same surveys show the remaining gaps follow familiar lines: adoption and home broadband still trail among lower-income households, rural communities, older adults, and adults with less formal education. The pattern repeats globally at a larger scale, where connectivity differs sharply between wealthy and developing regions. Watch how the gap moves, too. As basic access spreads, the divide shifts toward quality: fast versus barely functional connections, one shared phone versus a device per student, and confident skills versus first steps.

Key idea: decades of survey data show access climbing overall while gaps persist by income, geography, age, and education, and the divide shifts toward quality as basic access spreads.

Computing for good

The same power that causes harm can be aimed at large problems. Computing helps model climate change, speed medical research, coordinate disaster relief, and put the world's knowledge within reach of anyone connected. Crowdsourcing, gathering small contributions from many people over the Internet, has funded projects, mapped disaster zones, and built free encyclopedias. The lesson is that impact depends heavily on how a tool is used and who gets to use it, not on the tool alone.

Key idea: computing can tackle huge shared problems, so its impact depends on how and by whom the technology is used.

Worked example: why crowdsourcing scales

This lesson is Big Idea 5, Impact of Computing (IOC), which supplies 21 to 26 percent of the exam, and crowdsourcing is one of its named topics. The arithmetic explains its power. After a disaster, relief teams need fresh maps, so a satellite image of the region is cut into 10,000 small tiles for volunteers to review online. One person reviewing alone at 2 minutes per tile would need 20,000 minutes, about 333 hours, which is roughly 42 eight-hour days: help that arrives six weeks late. Now recruit 500 volunteers and give each just 20 tiles. That is 500 times 20, exactly 10,000 tiles, and each volunteer contributes only 40 minutes. The whole map can be finished in an evening. Real projects work this way. Wikipedia's millions of articles are written by volunteers. On citizen-science platforms like Zooniverse and NASA's projects, the public classifies galaxies and wildlife photos faster than any research team could.

Quality control also runs on simple logic. Each tile goes to three volunteers, and majority agreement decides:

agreeCount ← 0
FOR EACH review IN tileReviews
{
  IF (review = "damaged")
  {
    agreeCount ← agreeCount + 1
  }
}
IF (agreeCount >= 2)
{
  DISPLAY("tile marked damaged")
}

If tileReviews holds ["damaged", "damaged", "fine"], the loop counts 2, the condition 2 >= 2 is true, and the tile is marked. One careless volunteer cannot corrupt the map, because the crowd checks itself.

Key idea: 500 volunteers doing 20 tiles each cover 10,000 tiles in an evening, and majority voting keeps crowd work trustworthy.

Who owns the work: legal and ethical concerns

The framework's last impact topic follows you straight into the Create Task. Software, images, music, and writing are intellectual property, protected by copyright the moment they are created. Using someone's code or media without permission can be both unethical and illegal. Licenses are the permission layer. Open-source licenses invite anyone to use and improve code under stated conditions. Creative Commons licenses do the same for images, music, and text, each one spelling out what is allowed. The working rules are simple: check the license before using material, follow its conditions, and credit the creator. On the AP Create Task, code written by others must be attributed, and uncredited copying is treated as plagiarism. Giving credit costs one line; taking credit falsely can cost the score.

Key idea: creations are automatically copyrighted, licenses like open source and Creative Commons grant conditional permission, and the Create Task requires attribution.

Common misconceptions

  • "Technology is either good or bad." Most innovations are both at once. The useful analysis weighs benefits against harms rather than picking a side.
  • "Computers are perfectly objective and fair." Software can be biased when it learns from skewed data or reflects its makers' blind spots. Fairness must be designed in, not assumed.
  • "Everyone has equal access to technology." The digital divide means access varies with income, geography, and skills, and this gap can widen other inequalities.
  • "Side effects only happen with careless design." Even well-built systems produce unintended consequences, which is why creators must watch for effects they did not plan.
  • "Crowdsourcing means asking a few experts." It gathers small contributions from many ordinary people, and overlap plus majority checking, not individual expertise, is what makes the result reliable.
  • "Software bias requires a biased programmer." Bias usually arrives through skewed data and unexamined choices. No ill intent is needed, which is exactly why deliberate measurement matters.

Recap

  • Most computing innovations bring benefits and harms together and deserve balanced analysis.
  • Technologies produce unintended effects alongside their intended ones.
  • Software can be biased, usually from skewed training data or its makers' blind spots.
  • The digital divide is unequal access to computing that can deepen other inequalities.
  • Computing can address large shared problems, so impact depends on how and by whom it is used.

Sources

  1. College Board. (2023). AP Computer Science Principles course and exam description. College Board. apcentral.collegeboard.org β†—
  2. National Institute of Standards and Technology. (2019). NIST study evaluates effects of race, age, sex on face recognition software. NIST News. nist.gov β†—
  3. Pew Research Center. (2024). Internet, broadband fact sheet. Pew Research Center. pewresearch.org β†—
  4. Zooniverse. (n.d.). About the Zooniverse. Zooniverse.org β†—. zooniverse.org β†—
  5. NASA. (n.d.). Citizen science projects. NASA Science. science.nasa.gov β†—
  6. Wikipedia. (n.d.). Wikipedia: About. Wikimedia Foundation. en.wikipedia.org β†—
  7. Khan Academy. (n.d.). Computing innovations (Computers and the Internet). Khan Academy. khanacademy.org β†—
Key terms
Intended effect
The result a technology's creators designed it to produce.
Unintended effect
A consequence a technology produces that its creators did not plan.
Bias
When software systematically treats some groups unfairly, often from skewed data.
Digital divide
The gap between those with good access to computing and the Internet and those without.
Crowdsourcing
Gathering small contributions from many people over the Internet to accomplish a large task.
Training data
The examples a system learns from, whose skew can pass bias into the software.

Cybersecurity, Safe Computing, and the AP Exam

  • Explain common cybersecurity threats and defenses.
  • Describe safe-computing habits for everyday life.
  • Summarize the AP CSP exam and the Create Performance Task.

The big picture

Because so much of our lives lives online, keeping information safe is everyone's concern, not just experts'. This final lesson covers the core ideas of cybersecurity, the practical habits that keep you safe, and then what to expect from the AP exam and the Create Performance Task so you can finish the course with a clear plan.

Key idea: cybersecurity protects information and systems, and simple habits go a long way toward keeping you safe.

Common threats

Understanding a few common threats helps you recognize and avoid them:

  • Malware is harmful software, such as viruses, that damages devices or steals data. It often arrives through a sketchy download or attachment.
  • Phishing is a trick where a message pretends to be from someone you trust to fool you into revealing a password or clicking a bad link. A fake "your account is locked" email is a classic example.
  • A data breach happens when a company's stored information is stolen, exposing many users' data at once, which is why a leak somewhere else can affect you.

The common thread is deception and unauthorized access. Attackers usually rely on tricking a person rather than on some cinematic feat of code, which means an alert human is a strong defense.

Key idea: most attacks rely on deception, so recognizing malware, phishing, and breaches is a real defense.

How encryption protects you

Encryption scrambles data using a secret key so that only someone with the right key can read it. If intercepted, encrypted data looks like meaningless noise. This is what the padlock and HTTPS in your browser mean: your connection to the site is encrypted, so a snoop on the same network cannot read your password or card number. Think of encryption as a lockbox: anyone can carry the box, but only the holder of the key can open it. It is the single most important tool for keeping data private as it travels.

Key idea: encryption scrambles data so only a key holder can read it, which is what HTTPS uses to protect your connection.

A cipher you can run by hand: Caesar

The oldest famous cipher, named for Julius Caesar, replaces each letter with the letter a fixed number of steps later in the alphabet. The shift amount is the key. Encrypt the word CODE with a shift of 3, one letter at a time:

C + 3 → F
O + 3 → R
D + 3 → G
E + 3 → H

CODE becomes FRGH

Decryption is the same walk backward: shift each letter of FRGH three steps earlier and CODE returns. The alphabet wraps around at the end, and MOD from the variables lesson describes the wrap exactly. Number the letters A = 0 through Z = 25. Then Z shifted by 3 is 25 + 3 = 28, and 28 MOD 26 = 2, which is C. So ZAP encrypts to CDS: Z wraps to C, A slides to D, P slides to S.

Now the security lesson: Caesar is fun and hopeless. There are only 25 possible shifts, so an attacker just tries all of them and spots the one that produces readable text, a brute-force attack a computer finishes instantly. Modern encryption keeps the same skeleton, an algorithm plus a secret key, but uses key spaces so enormous that trying every key would take longer than the age of the universe. Security lives in the size of the key space, not in the cleverness of the scramble.

Key idea: Caesar shifts each letter by the key, so CODE becomes FRGH under shift 3, and its 25 possible keys show why tiny key spaces fail.

How strangers share secrets: public keys

One puzzle remains. A shift cipher needs both sides to know the secret key in advance, but you and an online store have never met. How do you agree on a secret while eavesdroppers watch every message? The answer is public-key encryption, and a lockbox analogy captures it without any math. The store manufactures padlocks that anyone can snap shut but only the store's single key can open. It hands out open padlocks freely; that is the public key, and hiding it is unnecessary. You put your message in a box, click the store's padlock shut, and send it. Everyone on the network can see the locked box, and nobody but the store can open it, because snapping a lock shut and opening it are different powers. Your browser does exactly this during the HTTPS handshake: it uses the site's public key to agree on a fresh shared secret, then the two sides encrypt the whole conversation with that secret.

Key idea: public-key systems separate locking from unlocking, so strangers can start a private conversation while everyone watches the wires.

Authentication and strong passwords

Authentication is proving you are who you claim to be, usually with a password. Weak or reused passwords are a leading cause of break-ins, so a few rules matter: make passwords long, avoid reusing the same one across sites, and consider a password manager to keep track of many strong ones. Even better is multi-factor authentication (MFA), which adds a second proof, like a code sent to your phone, so a stolen password alone is not enough to get in. That second factor blocks most account takeovers.

Key idea: strong, unique passwords plus multi-factor authentication stop most account break-ins.

Safe-computing habits

A short set of everyday habits prevents the majority of problems:

  • Think before you click. Do not open unexpected links or attachments, especially those creating urgency or fear.
  • Keep software updated. Updates patch security holes; delaying them leaves known doors open.
  • Use unique passwords and MFA. This limits the damage when any single site is breached.
  • Verify before you trust. If a message seems off, confirm through a channel you know is real rather than the one it arrived on.

Key idea: think before clicking, keep software updated, use unique passwords with MFA, and verify suspicious messages.

The AP exam: what to expect

The AP Computer Science Principles assessment has two parts. The first is the end-of-course exam, a set of multiple-choice questions taken on paper or computer that test the concepts across all five Big Ideas, the very ideas this course covered. The second is the Create Performance Task, a program you build yourself and submit before the exam. Together they determine your score, so both the ideas and the project matter.

Key idea: the AP CSP assessment combines a multiple-choice exam on the Big Ideas with a program you create and submit.

The exam by the numbers

Here is the shape of the assessment, so nothing surprises you. The end-of-course exam gives you 70 multiple-choice questions in 2 hours, and it counts for 70 percent of your AP score. Some items are multi-select, marked clearly, where exactly two answers must be chosen. The Create Performance Task counts for the remaining 30 percent and is completed with dedicated class time before exam day, so it cannot be crammed. Question weight follows the Big Idea percentages from Lesson 1, which means Big Idea 3, Algorithms and Programming, at 30 to 35 percent, and Big Idea 5, Impact of Computing, at 21 to 26 percent, together supply more than half the exam. Every code question uses the AP pseudocode you have practiced all course: the assignment arrow, DISPLAY, REPEAT, FOR EACH, IF and ELSE, and procedures. Scores arrive on the 1 to 5 AP scale. The strategy that follows from the numbers: trace code carefully, know the impact vocabulary precisely, and treat the Create Task as a third of your grade, because it is.

Key idea: 70 questions in 120 minutes make 70 percent of the score, the Create Task makes 30, and programming plus impacts dominate the question count.

The Create Performance Task

The Create Performance Task asks you to design and build a program of your own choosing and to explain how it works. You submit your code, a short video showing the program running, and written responses about your design. Certain elements are expected in the program, and knowing them shapes what you build:

  • A clear purpose for the program, stated plainly.
  • Use of a list (or similar collection) to manage data, showing you can store many values together.
  • A procedure you wrote that takes a parameter and includes an algorithm with sequencing, selection, and iteration, that is, ordered steps, a conditional, and a loop.
  • A call to that procedure, and a written explanation of how it works.

Notice that these requirements map directly onto skills from earlier modules: lists and loops, conditionals, and procedures with parameters. If you understood those lessons, you already have the building blocks. The best approach is to start early, pick a project you find genuinely interesting, and build it in small, tested steps, exactly the iterative process from the very first module.

Key idea: the Create Task rewards a program with a clear purpose, a list, and your own procedure using sequencing, selection, and iteration.

Common misconceptions

  • "Hackers mostly break in with brilliant code." Most attacks rely on tricking a person, through phishing or a reused password, so human alertness is a major defense.
  • "A strong password alone keeps me safe." Passwords leak in breaches, which is why multi-factor authentication, a second proof, blocks most takeovers.
  • "HTTPS makes everything I do completely safe." HTTPS encrypts the connection, but it does not protect against clicking a bad link, weak passwords, or malware on your device.
  • "The Create Task needs a huge, complex program." It rewards clear use of core skills, a purpose, a list, and your own procedure, not size. A focused project done well is the goal.
  • "HTTPS means the site is trustworthy." The padlock only says the connection is encrypted. Scam sites use HTTPS too, so the lock protects your data in transit while saying nothing about who is on the other end.
  • "A letter-scrambling cipher is secure enough." Caesar's 25 possible keys fall to brute force instantly. Real security comes from key spaces too large to search, not from the scramble looking confusing.

Recap

  • Common threats, malware, phishing, and data breaches, mostly rely on deception.
  • Encryption scrambles data so only a key holder can read it; HTTPS uses it to protect connections.
  • Strong, unique passwords plus multi-factor authentication stop most break-ins.
  • Safe habits: think before clicking, update software, use MFA, and verify suspicious messages.
  • The AP assessment pairs a multiple-choice exam with a Create Task featuring a purpose, a list, and your own procedure using sequencing, selection, and iteration.

Sources

  1. College Board. (2023). AP Computer Science Principles course and exam description. College Board. apcentral.collegeboard.org β†—
  2. College Board. (n.d.). AP Computer Science Principles exam. AP Central. apcentral.collegeboard.org β†—
  3. College Board. (n.d.). AP Computer Science Principles assessment. AP Students. apstudents.collegeboard.org β†—
  4. Cybersecurity and Infrastructure Security Agency. (n.d.). Recognize and report phishing. CISA Secure Our World. cisa.gov β†—
  5. National Institute of Standards and Technology. (n.d.). Back to basics: Multi-factor authentication. NIST. nist.gov β†—
  6. MDN Web Docs. (n.d.). HTTPS. MDN Glossary. developer.mozilla.org β†—
  7. MDN Web Docs. (n.d.). Encryption. MDN Glossary. developer.mozilla.org β†—
  8. Khan Academy. (n.d.). Online data security (Computers and the Internet). Khan Academy. khanacademy.org β†—
Key terms
Cybersecurity
The practice of protecting information and systems from unauthorized access and harm.
Phishing
A trick where a message pretends to be trustworthy to fool you into revealing information.
Encryption
Scrambling data with a secret key so only someone with the key can read it.
Authentication
Proving you are who you claim to be, usually with a password.
Multi-factor authentication
Adding a second proof of identity, such as a phone code, on top of a password.
Create Performance Task
The AP CSP project in which you build and explain your own program.

Open the interactive version with quizzes and progress →