19.12.2012 Views

Computer Programming Concepts and Visual Basic David I. Schneider

Computer Programming Concepts and Visual Basic David I. Schneider

Computer Programming Concepts and Visual Basic David I. Schneider

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

■ FLAGS<br />

A flag is a variable that keeps track of whether a certain situation has occurred. The data type<br />

most suited to flags is the Boolean data type. Variables of type Boolean can assume just two<br />

values—True <strong>and</strong> False. Flags are used within loops to provide information that will be utilized<br />

after the loop terminates. Flags also provide an alternative method of terminating a loop.<br />

EXAMPLE 4<br />

The following program counts the number of words in the file WORDS.TXT <strong>and</strong> then reports whether the<br />

words are in alphabetical order. In each execution of the loop, a word is compared to the next word in the<br />

list. The flag variable, called orderFlag, is initially assigned the value True <strong>and</strong> is set to False if a pair of<br />

adjacent words is out of order. The technique used in this program will be used in Section 6 when we study<br />

sorting. Note: The statement in line 7, word1 = “”, is a device to get things started. Each word must first<br />

be read into the variable word2.<br />

WORDS.TXT contains the following winning words from the U.S. National Spelling Bee:<br />

“cambist”, “croissant”, “deification”<br />

“hydrophyte”, “incisor”, “maculature”<br />

“macerate”, “narcolepsy”, “shallon”<br />

Object Property Setting<br />

frmWords Caption Word Analysis<br />

cmdAnalyze Caption Analyze Words<br />

picReport<br />

Private Sub cmdAnalyze_Click()<br />

Dim orderFlag As Boolean, wordCounter As Integer<br />

Dim word1 As String, word2 As String<br />

‘Count words. Are they in alphabetical order?<br />

orderFlag = True<br />

wordCounter = 0<br />

word1 = “”<br />

Open “WORDS.TXT”For Input As #1<br />

Do While Not EOF(1)<br />

Input #1, word2<br />

wordCounter = wordCounter + 1<br />

If word1 > word2 Then ‘Two words are out of order<br />

orderFlag = False<br />

End If<br />

word1 = word2<br />

Loop<br />

Close #1<br />

picReport.Print “The number of words is”; wordCounter<br />

If orderFlag = True Then<br />

picReport.Print “The words are in alphabetical order.”<br />

Else<br />

picReport.Print “The words are not in alphabetical order.”<br />

End If<br />

End Sub<br />

[Run, <strong>and</strong> press the comm<strong>and</strong> button.]<br />

Processing Lists of Data with Do Loops 139

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!