Sometimes, programs use variables in precise ways. It's often convenient to categorize these special variables based on their use - on the role they play in a program - rather than on their type (e.g., int
or double
). Two special kinds of variables are introduced or elaborated in this section: flags and accumulators.
A flag is a variable that stores the program's current condition, mode, state, or configuration. That is, it's a small amount of memory that "remembers" what the program is doing at some point in time. Flags are usually set at one location in a program and then tested at a different location or at another time. The program's behavior - what it does - depends on the value saved in the flag when the program tests it.
Computer scientists often use a visual diagramming language, called a state diagram, to help them represent and understand the dynamic nature of a program. They use flags to help convert the state diagrams into computer programs. We'll use the example of a simple stopwatch to demonstrate the connection between a state diagram and the corresponding computer code; the code will also illustrate the concept of a flag variable.
bool stopped = true; . . . if (stopped) { // code to start the watch stopped = false; } else { // code to stop the watch stopped = true; } |
|
(a) State Diagram | (b) Pseudo Code |
true
: the watch is stopped or not running when the program begins. Pressing the button toggles the watch between running or not running - between being stopped and not being stopped.Flags that represent conditions with only two possible states are conveniently implemented as type bool
. The flag's name, that is, the variable's name, is chosen to reflect the states or conditions that the flag controls. In the previous example, we could have named the flag running and flipped the order of the statements in the if-statement. If a flag controls more than a single state or condition, then a behavioral of type int
is appropriate.
The word accumulate means "to gather or pile up especially little by little." This definition nicely describes how a program uses an accumulator variable (or just "accumulator" for short). Accumulators may accumulate any kind of data, so accumulator variables may be of any appropriate data type. They are very often used in loops and gather or accumulate data during each iteration of the loop. Accumulators must begin in a known state, usually "empty." Programmers initialize the accumulator variables, usually to zero, above and outside the loop.
int n; int count = 0; ... while (...) { cin >> n; count++; } |
|
(b) | |
double sum = 0; ... while (...) { double score; cin >> score; sum += score; } | |
(c) | |
double balance = 0; ... while (...) { if (...) balance += amount; else balance -= amount; } | |
(d) | |
(a) |