AP® Computer Science Principles · Big Idea 1 · Topic 1.2

Program Inputs and Events

An input is any data a program receives from outside itself. An event is a signal, like a mouse click or sensor reading, that the program detects and responds to by running specific code.

A program that never receives anything from outside itself can only ever do the one fixed thing its code says. Input is what makes a program useful: a number to calculate with, a click to react to, a photo to filter. Whatever form input arrives in on the outside, tactile taps, sound waves, images, typed text, it gets converted into the same kind of thing on the inside: data represented as bits, stored in variables the program can check and act on.

Events are how most interactive programs actually receive input. The system is always watching for things like a mouse click, a key press, or a sensor reading. The instant one happens, the system packages it as an event with details attached, such as which key, or the x and y position of the click, and hands it to a small block of code called an event handler that's registered to respond to exactly that kind of event. The handler runs, maybe updates a variable or redraws part of the screen, then control returns to waiting.

This is why event-driven programs don't run top to bottom like a sequential list of instructions. Instead the program sits idle until an event fires, runs the matching handler, then goes back to waiting, possibly for years across many different events arriving in any order. This connects forward to how programs produce output: once an event handler processes input, the next question is always what the program does with that data and what it shows or sends back out.

Key terms

input
Any data a program receives from outside itself, from a person, sensor, file, or another program.
event
A detected occurrence, like a click or key press, that triggers a specific piece of code to run.
event handler
A block of code registered to run automatically whenever a specific kind of event occurs.
event driven
A program structure where code runs in response to events as they occur, not strictly top to bottom.

Watch it explained

  1. How it worksHow do tactile, audio, visual, and text inputs all arrive as the same kind of data inside a program?
  2. How it worksWalk me through what happens the instant a mouse click generates an event in a running program.
  3. Going furtherWhat changes about the order statements run in when a program is event driven rather than sequential?
  4. Common mistakeWhy isn't every input to a program something a human typed?

Check yourself

Your turn1 of 2
A program is running and receives 14 mouse click events, then 13 keyboard key-press events, in that order. Counting only these events, how many total input events has the program received?

End of topic.