AP® Computer Science A · Unit 2 · Topic 2.2
Boolean Variables and Flags
A boolean flag is a variable that stores the answer to a yes-or-no question so your code can remember it later. You set it true the moment the event happens, then check it after the loop ends.
A loop only sees one element at a time, so it has no memory of what happened three iterations ago unless you give it one. A flag is a boolean variable, often started as false, that you flip to true the instant the condition you care about becomes true. Once it is true it just stays true, quietly carrying the answer forward through every remaining pass of the loop, until you finally ask about it with an if statement after the loop finishes.
The mechanism is just an assignment sitting inside an if inside the loop. Each pass checks the current element; if it matches what you are watching for, the flag gets set to true. Nothing resets it on the next pass, because reaching into the past is exactly the point. If you are only checking for one occurrence, you never need to set it back to false inside the loop.
This connects directly to the rest of unit 2 because a flag is really just a condition's result given a name and a lifespan longer than one line. Where you declare and reset the flag matters as much as where you set it true: initialize it before the loop that tracks it, and only reset it if you genuinely want to forget the past, such as starting a fresh check on a new array. Mixing this up is the most common source of logic bugs with flags, and it sets up later topics like nested loops and string processing, where a flag often reports back on an entire inner loop at once.
Key terms
- flag
- A boolean variable used to record whether some event has occurred so far.
- boolean
- A data type with only two possible values, true and false.
- short-circuit
- The behavior where a logical expression stops evaluating once the result is already determined.
- initialization
- The first assignment that gives a variable its starting value before a loop runs.
Watch it explained
- How it worksHow does a flag variable remember something that happened earlier in a loop?
- Worked exampleTrace a flag that turns true the first time a negative appears in 4, 9, -2, 7.
- Common mistakeWhy isn't if (found == true) any better than writing if (found) by itself?
- Going furtherWhat changes when the flag gets reset inside the loop rather than before it?
Check yourself
End of topic.