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.

140 <strong>Computer</strong> <strong>Programming</strong> <strong>Concepts</strong> <strong>and</strong> <strong>Visual</strong> <strong>Basic</strong><br />

■ NESTED LOOPS<br />

The statements inside of a Do loop can consist of another Do loop. Such a configuration is referred<br />

to as nested loops <strong>and</strong> is useful in repeating a single data-processing routine several<br />

times.<br />

EXAMPLE 5<br />

Modify the program in Example 2 to allow the user to look through several lists of names. Suppose we<br />

have several different phone directories, the names of which are listed in the file LISTS.TXT. (For<br />

instance, the file LISTS.TXT might contain the entries CLIENTS.TXT, FRIENDS.TXT, <strong>and</strong> KIN-<br />

FOLK.TXT.) A sought-after name might be in any one of the files.<br />

SOLUTION:<br />

The statements in the inner Do loop will be used to look up names as before. At least one pass through<br />

the outer Do loop is guaranteed <strong>and</strong> passes will continue as long as the name is not found <strong>and</strong> phone lists<br />

remain to be examined.<br />

Private Sub cmdDisplay_Click()<br />

Dim foundFlag As Boolean, fileName As String<br />

Dim nom As String, phoneNum As String<br />

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

foundFlag = False<br />

nom = “”<br />

Do While (foundFlag = False) And (Not EOF(1))<br />

Input #1, fileName<br />

Open fileName For Input As #2<br />

Do While (nom txtName.Text) And (Not EOF(2))<br />

Input #2, nom, phoneNum<br />

Loop<br />

Close #2<br />

picNumber.Cls<br />

If nom = txtName.Text Then<br />

picNumber.Print nom, phoneNum<br />

foundFlag = True<br />

End If<br />

Loop<br />

Close #1<br />

If foundFlag = False Then<br />

picNumber.Print “Name not found.”<br />

End If<br />

End Sub<br />

COMMENT<br />

1. In Appendix D, the section “Stepping Through a Program Containing a Do<br />

Loop: Section 5” uses the <strong>Visual</strong> <strong>Basic</strong> debugging tools to trace the flow<br />

through a Do loop.<br />

2. When flagVar is a variable of Boolean type, the statements<br />

True Then <strong>and</strong> If flagVar = False Then<br />

can be replaced by<br />

If flagVar Then <strong>and</strong> If Not flagVar Then

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

Saved successfully!

Ooh no, something went wrong!