|
|
|
|
|
|
The first part of defining a finite state machine is to provide a way in which to keep track of the current state. Because there are only two states in this problem, we can use a single Boolean state variable, called exclamEncountered. When the variable is TRUE, the machine is in one state; when the variable is FALSE, it is in the other. (In our traffic light example, we would define two char variables eastWest and northSouth to be the state variables.) |
|
|
|
|
|
|
|
|
|
Next, we have to determine which state the machine is in. For this, we use an If-Then-Else structure with one branch for each possible state. |
|
|
|
|
|
|
|
|
|
if (exclamEncountered)
.
. // Test for each transition rule from the state where
.
// exclamEncountered == TRUE
else
.
.
. // Test for each transition rule from the state where
// exclamEncountered == FALSE |
|
|
|
|
|
|
|
|
|
Within each state branch, we test for each transition rule that starts from that particular state. There are two rules that start from the exclamation-mark-encountered state and one that starts from the no-exclamation-mark-encountered state. Associated with each transition rule is some action that may be as simple as switching to another state, or much more complex. |
|
|
|
|
|
|
|
|
|
if (exclamEncountered) // State == ! encountered
{
if (currChar == =) // Rule: If currChar is =,
{
count++; // increment count
exclamEncountered = FALSE; // and switch states
} |
|
|
|
|