An Introduction To Programming Using Visual Basic 2010
An Introduction To Programming Using Visual Basic 2010
An Introduction to
Programming Using
David I. Schneider
with
Microsoft<!
Visual Studio®2010
Express Edition DVD
Help is here. Now.
VideoNotes are quick video tutorials that show you how to solve a
problem step-by-step as if you were in your instructor's office.
With the purchase of a new copy of this textbook, you immediately
have access to Video Notes ~ tutorials and the Student Solutions Manual.
Use a coin to scratch off the coating and reveal your student access code. Do not use a
knife or other sharp object as it may damage the co de.
Note to Instructors: VideoNotes and an Instructors Solutions Manual for this title are available in the Instructor
Resource Center. Contact your Pearson representative 1j you do not have IRC access.
IMPORTANT: The access code on this page can only be used once to establish a subscription to the
premium content for Schneider, An Introduction to Programming Using Visual Basic
2010, Eighth Edition. If the access code has already been scratched off, it may no
longer be valid. If this is the case, follow steps 1-3 and select "Get Access" to purchase
a new subscription.
Some Common Commands
(keyl +key2 meam "llold down keyl while pressing key2.")
(l<.e)•l/key2 means "Release keyl before pressing key2.")
Controls
Tab Cycle forward through controls
Shift+ Tab Cycle backward through contro ls
Double-clic k obJect Create a template for object's default e\·ent procedure
arrow key Move selected control in the Form Designer
Crrl +arrow key Move selected control to align with another contro l
Shift+amiU.' key Resi ze selected control in the Form Designer
Delete Remove the se lected control
Toolbox
Click on upright push pin Collapse Toolbox into a tab at left side of the screen
Click on reclining push pin Keep Toolbox permanent ly displayed
AN INTRODUCTION
TO PROGRAMMING USING
EIGHTH EDITION
David I. Schneider
University of Maryland
Prentice Hall
Boston Co lu mbus India napo lis New York San Francisco Upper Sadd le River
Amste rdam Cape Town Dubai Lond on Mad rid Milan Munich Paris Montrea l Toro nto
Delhi Me x ico C ity Sao Paulo Sydney Hong Kong Seou l S ingapore Taipe i Tokyo
Vice President and Ed ito ri a l Director, ECS: Marcia J. Horto n
Executive Ed ito r: Tracy Dunkelberger
Ass istant Editor: Melinda Hagge rty
Editoira l Ass istant: A llison Michae l
Vice President, Production : Vince O 'Brien
Sen ior Managing Editor: Scott Disa nno
Producti on Li aison: Irwin Zucker
Production Edi tor: Sangee tha Parthasara thy, Laserwords
Seni or Ope rations Specialist: A lan Fisc her
Art Director: Kenn y Beck
Cove r Des igner: Laura C. Ierardi
Cove r Image:© lmages.co m/Corbis/M ark Shave r
A rt Editor: G reg Dull es
Media Editor: Daniel Sand in
Co mpositi on/ Full -Se rvice Projec t Manage ment: Lase rwords, Inc.
10 9 8 7 6 5 4 3 2 I
Student Edition
Prentice Hall ISBN-1 3: 978-0- 13-212 856-8
is an imprint of ISBN-1 0: 0-13-21 2856-X
In tructor Edition
-------
PEARSON
www.pearsonhighered.com
ISBN-1 3: 978-0- 13-255 284-4
ISBN-1 0: 0-13-2 55284- 1
. .
. · Guide to VideoNotes ·
,,,. .
www.pearsonhighered.com/Schneider · ..... " . .. .
Chapter 4 Decisions
Relational and Logica l Operators 105
If Blocks 112
Select Case Blocks 132
Grading Sys tem (Rep resentative Exampl e of Homework Exercise 27) 141
Chapter 7 Arrays
Filling Arrays 26 1
Array Methods 263
UNQ 282
Presidents (Repre entative Example of Homework Exercise 35 ) 294
Two-Dimensional Arrays 320
Chapter 10 Databases
Introduction to Databases 45 8
Querying Tables 464
Editing Databases 479
Richard's Ca tering (Represe nta ti ve Example of Programming Project 1) 487
vii
v iii • Gu ide to App licat ion Top ics
General Interest
Animati on , 443, 449 O ld McDona ld H ad a Farm, 188
America n H ea rt Assoc ia ti o n recomm endati on, 155 Pa lind rome, 252, 28 1
Anagram, 293 Phases of the moon , 424
Ana lyze grades, 246 Phys ic ian 's abbrevia t ions, 142
Analyze a S hakespea re sonnet, 280 Pig latin , 127
Bachelo r degrees conferred, 344 Populati on growth , 229
Body Mass l ndex , 1 73 Popu lation of large c ities, 467,474 , 482, 564-8, 572
Caffe ine absorpt ion, 25 1 Pres ident ia l eligibili ty, 15 2, 559
Ca lcu late age, 88, 89, 128 Principa l languages , 449
C hain-lin k se ntence, 28 1 Proverbs, 215
C loud iness desc ri ptors, 140 Quiz, 113, 126, 127, 134, 189
College ad mi ss ions, 157 Qwerty words, 242
College cred its, 305 Rad ioactive decay, 229, 241
Co llege majors, 448 Rating of hurri canes, 173
Earli est co ll eges , 300, 303, 387 Spread of an ep idemi c, 453
C rayola crayo ns, 279, 365 S upreme Court justices, 3 16,317, 354,356 ,365,56 0
Declarat ion of Indepen dence, 97 The Twe lve Days of C hri stmas, 3 17
Determi ne day of week, 97 Times Squa re ba ll , 424
Dialing a telephon e, 347 Training heart rate, 82, 173
Distance between c ities, 320,32 1, 560 U .S . cities, 3 12
Distance from a storm, 82 U .S. presiden ts, 127, 134, 142, 263, 264, 278, 279,
Draw flags, 446, 449
285,293 ,352,35 3,356,3 64,365, 386,409
Famous peop le, 3 18 U.S . Senate, 387,397
Freshma n li fe goa ls, 448 U.S. states, 141 ,244,245,249, 250,268 ,279,28 2,
Game of Life, 346 287,3 14, 3 15,350, 358,359 ,365,36 7,384, 386,
GPA, 214 516,550
Idea l weight, 24 1 Un ited Nations, 294, 296, 297, 299, 474, 560
Language trans latio n, 342 Un ive rsity rankings, 320, 329
Leap yea rs, 127, 174 Voting machine, 452
Month ly prec ipitati on, 330 Vowe l words, 166
Movies, 127, 145, 2 19, 478, 479,4 5 Weather beacon, 11 5
Nutritio na l content of foods, 322
Mathematics
A reas of geo metric shapes, J 41, 173, 52 7 Cu rve grades, 342
Calculat e a range , 227, 250, 280, 534 Factoriz ation, 22 7
alc ulate a su m, 240, 278, 279, 280, 283, 38 1 G reatest common divisor, 227
Calcu late an average , 84, 127, 174, 188, 240, 246, Magic sq uares, 330
263,26 ,278, 279,280 ,293,33 0,3 42, 38 1, 435, Mean, 280, 342
488,507 ,53 4 Med ian, 294, 330
Calcu lato r, 100, 520, 534 Projectil e mot io n, 67, 252
Calcu late with fraction , 507, 516 Quad rat ic formu la, 156
Coeffic ient of restituti on, 227 Standard dev iati on, 250, 280, 342
Con ve rt percenta ge to dec imal, 83 Tempera ture con ve rsion, 16 1, 227, 424, 559
Conve rt units of length, 100,341 ,409
Guide to VideoNotes v
Preface xiii
Acknowledgments xix
Summary 53
3.2 Strings 68
Summary 98
ix
X
• Co ntents
Summary 154
Programming Projects 154
Summary 214
Programming Projects 214
Summary 251
Programming Projects 251
Summary 340
8 .3 XML 382
Summary 396
Summary 450
Summary 486
Summary 535
Summary 571
Appendic es 575
Appendix A ANSI Values 575
Index 699
PREFA CE
ince its introdu ction in 199 1, Visual Bas ic h as beco me one of the world 's most wid e-
S ly used programmin g languages. The latest incarnation, Visual Bas ic 2010, further re-
fines the language and ex tends fea tur s such as Language Integrated Que ry. Visual Bas ic
programme rs are enthusias tica ll y embrac ing VB 2010's powerfu l capabilities . Likewise,
stude nts lea rning their first programmin g language will find VB 20 10 the ideal too l for
und erstanding the deve lop ment of co mpu te r programs.
My obj ectives in writing this tex t are as follows:
1. To develop focused chapters. Rather than cove ring many topics superficially, I con -
centrate on important ones and cover them thorough ly.
2. To use examjJles and exercises that students can relate to, apjJreciate, ancl feel comfort-
able with. I frequently use real data. Example do not h ave so many embellish -
ments that they distract students from the programmin g techniques illustrated.
3. To produce compactly written text that students will find both readable ancl informative .
The main po ints of each topic are discussed first, and then peripheral details are
presented as co mments.
4. To teach good programming practices that are in step with modern programming method-
ology . Problem-so lv ing techniqu es and structured programm ing are discussed ea rl y
and used through out the book. The style follows object- oriented programmin g
principles.
5. To jJrovide insights into the major ajJplications of computers.
VideoNotes. VideoNotes a re step-by-s tep video tu torials spec ifica lly des ign ed to enhance
the programming conce pts prese nted in the eighth edition. Stud ents can view the entire
problem-sol ving process outside the classroo m, when they need help the most. A
Vid eoN ote icon in the margin of the tex tbook alerts the reader that a topic is discussed in
a video. A lso, a G uide to Vid eoN otes in th e front of the book summarize the difD rent
videos fo und in the tex t . N ea rly 50 VideoN otes for this edition are avai lable at www.pear-
so nhighered .co m/schneider. See the Stud ent Resources secti on later in the Preface for in-
formation on how to access VideoN ote .
Exercises for Most Sections. Each section that teaches programmin g has an exe rcise se t.
The exe rcises reinforce the understandi ng of the key ideas of the section, and they challenge
the student to ex plore applications. Most of th e exercise se ts requ ire the stud ent to trace
programs, find errors, and write programs. The answers to all the odd-numbered exercises in
C hapters 2 through 8 and se lected odd -numbered exercises from C hapters 9, 10, 11, and 12
are given at the end of the text. Screen captures accompany most programming answers.
xiii
x iv • Preface
at the end
Practice Problems. Practice Problems are ca refully selected exe rc i es located
ing the exer-
of a section, just before the exe rcise se t. Co mplete solution s are given follow
confusi ng o r are
c i e set. The practice problems ofte n focus o n points that are poten t ially
them. Read rs should seriousl y attemp t
best apprec iated after th e stud ent has worked on
o n to the exerc ises.
the prac tice problems and tud y the ir olution s before mov ing
ming
Programming Projects. Beginni ng with C hapter 3, eve ry ch apter co nta ins program
in the business
projects. These projects refl ec t the va riety of ways that comput ers are used
-interes t top ics. The large num-
co mmunit y, and they a lso prese nt some games and general
to adap t th e
ber and range of d ifficulty of the program ming projects prov id e flex ibility
in later chapter s
co urse to the student s' interest s and ab ili ties. Some program m ing projects
can be ass igned as end-of- the-sem ester projects.
points of
Comme nts. To avo id breakin g the flow of the present ation, ex tensio ns and fine
n.
new top ics are deferred to the "Comm ents" portion at the end of each sectio
ming app li-
Case Studies. Each of the three case studies focuses on an impo rtant program
top-dow n ch arts
cation . The problem are analyzed and the programs are develop ed with
from the co mpani on webs ite at
and pseudocode. The programs can be down loaded
http://www.pearson highere d.com/schne ider.
s are
Chapter Summaries. At the end of each of C h apters 2 through 12, the key concept
stated and th e importa nt t rms summarized'.
on how to
"How To" Append ix. Append ix B prov ides a compact, step-by- tep referenc e
carry out sta ndard tasks in the Visual Basic env ironme nt.
r is locat-
Append ix on Debugging. The discussion of Visual Basic's sophist icated debugge
cove r this top ic.
ed in Append ix 0, allow ing the instru ctor flex ibility in decid ing when to
Studen t R esourc es
nd Vid oN t tut rial i l at d at www.pearsonhighered
of the book to
.com/sc hneider . S tud ents must use the access ca rd located in the front
Preface • XV
register and access the online material. lf no access card is provid ed, stud ents can purchase
access by go ing to www.pearsonhighered.com/schne ider and selecting "purchase access to
premium content. " Instructors must register on the site to access the material.
The following content is ava ilable through the Premium Web site:
• VideoN otes: Pearson 's new visual tool des igned for teaching key programming concepts
• Stud ent Solutions Manu al: All the answers to th e odd -numbered exe rcises (along with
scree n cap tures ) will be ava ilable for download in a solutions manual in pdf form at.
• All programs in th e book and all tex t fil es and databases needed for the exercises.
Notice: This book contains many screen captures. When you run one of the programs
downloaded from the webs ite, what yo u see on your monitor might not look exactl y like
the screen capture shown in the book. To make them appea r the same, you must ch eck
that your monitor is set to display 96 DPI (Dots Per Inch). To determine and/o r change
the DPl setting for your monitor, see th e first item und er "Co nfiguring the Windows Envi-
ro nment" in Appendix B on pages 584- 5. A lso, there may be slight differences due to the
version of Wind ows be ing used. See page 3.
1. A secti on on using radio buttons, check boxes, and list boxes for selection h as
bee n added to C hapter 4. (Mu ch of this material was previously in C hapter 9.
N ow it appea rs alongs ide If and Select Case blocks. )
2. A secti on on using loops with list boxes has been add ed to Chapter 6. (This sec-
t ion prese nts man y operations on lists, such as searching, summing, and finding
max imum values. )
New Concepts
1. C hapter 3: Implicit line continu ation. (The und erscore line-continu ation ch arac-
te r is rarely needed in VB 20 10.)
2. C hapter 3: Date data type. (This data type enables us to crea te so me interesting
programs, such as a program that tells use rs whether they are e ligible to run for
pres ident in 20 12. See Exe rcise 20 on page 152.)
3. C hapter 3: Se nding output to the printer. (This optional material demonstrates
h ow to produ ce a major type of output with Visual Bas ic.)
4. C hapter 7: The ReadAllLines method for filling an array with the contents of a
tex t file. (This powerful method allows us to place the contents of a tex t fil e in an
a rray without hav ing to use repea ted ReDim Preserve statements.)
xvi • Preface
5. Chapter 7: Language Integrated Query. (This recent addition to Visual Basic and
other .NET languages provides a standardiz ed way to spec ify queries for a variety
of data sources. In this textbook, LINQ is used to sort, ea rch , and filter informa-
tion from arrays, text files, XML files, and databases. This approach enables stu-
dent to write concise , higher- leve l code focused more on problem so lving than
on data-struc ture manipulat ion. Instructors wishing to teach a more e lementary
or traditiona l course ca n om it or reduce the use of LINQ. The textbook presents
most of the sta ndard operations on arrays and sequentia l file with and without
LINQ.)
6. C hapte r 8: The Set operators Concat, Union, Intersect, and Except are used to
manage data from text files. (These ope rato rs allow us to perform tasks that previ-
ous ly requ ired complicat ed algorithm s.)
7. C hapter 9: Too lTip control. (This control gives us a capability possessed by near-
ly eve ry commerci al Window app lication.)
8. C hapter 11 : Auto- Imp lemented properties. (This new-to-VB -2010 concept sim -
plifies the creation of classes.)
Other Changes
1. The version of Visual Bas ic has been upgraded from Vi ual Basic 2008 to Visual
Basic 2010, and releva nt new fe ature of Visual Basic 2010 h ave been added.
2. The rea l-life data in the exa mp les and exe rcise have been upd ated and revised.
3. So me new large co llections of data have been added. For instance, data on eve ry
Supreme Co urt justice (pa t and present) are contai ned in both a text file and a
database.
4. Named co nstants are introd uced earli er (Chapter 3).
5. The use of input va lid ati on has been increased (Chapter 4 on).
6. Function procedures are presented before ub procedure s (Chapter 5 ). With this
change, students begin learning about general procedure s with a familiar and s-
sential construct. Also, the instructor has the optio n of omitting the concep t of
passing by refe rence.
7. The use of text fi les for input h as been postponed until C h apter 7.
8. Tables are displayed in OataGridV iew controls rather than in list boxes (Chapter
7 on).
9. Many new business app lications have been added. ee the Guide to Applicatio n
Top ics on page vii.
10. The OpenFileO ialog control is discussed ea rlier (Chapter 8, Text Files).
11. The discussion of mu ltiple-form programs in Chapte r 9 has been expanded to an
entire section.
12. Databases are connected to programs with the Visual Basic wizard rather than
with code (Chapter 10).
Preface • xvii
1. G uid e to A pplicatio n Topics. (This section prov ides an index of programs that
dea l with va rio us topics including Business, Mathemat ics, and S ports.)
2. A complete solu tion manua l in pdf format. (The manual will conta in the code fo r
eve ry programming exe rc ise along with a screen capture of the o utput.)
1. Screen captures h ave bee n add ed to the programs in the answer section of the
book.
2. All th e answer to the odd -numbered exercises (along with scree n captures ) will
be ava ilable fo r download in a solutions manu al in pdf fo rmat.
3. Nearly 50 Vi cleoNotes are ava ilable at www.pea rsonhighered.com/schne ider.
VideoN otes are Pea rson 's new visual tool des igned for teaching key programming
concepts and techniqu es. A Vid eoN ote icon in the margin of the textbook a lerts
the reader when a topic is discus edin a video. See the Stud ent Resources sectio n
earlier in this Preface fo r info rmatio n on how to access VideoN o tes.
AcKNOW LEDGME NTS
any talented instruc~ors and programmers provided h e lpful comm ents and co ns tru e~
M tive suggestio ns durmg the va n o us edtttons of dus text, and I am most grateful fo r
th e ir contributions. The current edition benefited grea tly from the va luable co mmen ts of
th e fo llowing rev iewers:
G.W. Willis, Bay lo r U niversity
Jaygarl H ojun, Iowa S tate University
Teresa Peterman, G rand Valley S tate University
Joel We inste in, Northeastern U niversity
Daniel E. Turk, Colorado State University
Paul Norrod , Lo ra in County Commun ity College
Cynthia Brown , Portland S tate U niversity
Karen A rlien , Bismarck S tate College
Ron Conway, Bowling G reen S tate Unive rsity
Phil Larsch an , Tulsa Community College
Ca rol Roberts, U ni ve rsity of Ma ine at O rono
Ma rkita Price, U niversity of Missouri- Columbi a
Josh Pauli , Dakota tate University
Many people are invo lved in the successful publi ca tion of a book. I wish to thank the
dedica ted team at Pear on whose suppo rt and d iligence made this textbook poss ible, espe-
c ia lly Melinda H aggerty, Ass istant Edi tor of Computer Science, and Scott Disanno,
Senio r Ma nag ing Ed itor.
I also exp ress my thanks to John Tarcza, a talented programmer, who helped with the
develop ment of the book and prov ided va lu able insights and ca refu l proofreading. I would
like to thank Jeremy Schne ide r and Rob Teaga rd en for the ir helpfu l proofreading. Pro-
du ction editor Irwin Zucker did a fantastic jo b produ c ing the book and keeping it o n
ched ule. I am grateful to Jo hn Russo of the Wentwo rth Institute of Techno logy fo r pro-
d uc ing th e VideoN otes that accompa ny the book. The skill and grac iou ness of the tea m
at Lase rwo rds made for a pleasant production process. Copyedito r Bob Lentz contributed
many suggestions for improv ing the book's qu ali ty.
I extend special thanks to my editor Tracy Dunkelberge r. H er ideas and enthusiasm
helped immen sely with the preparation of the book.
XIX
UsiNG THIS BooK FoR A SHORT
OR CONDENSED COURSE
This book prov ides more than enough material for a fu ll-se mester co ur e. For a shorter course,
it will be necessa ry to bypass some sections. The following syllabu prov ides on e poss ible way to
present an abbrev iated introduct ion to programming.
1
Pas ing by reference ca n be o mitted or just me ntioned briefl y. In C hapters 6 th ro ugh 12, By Ref is used
o nl y in Example 6 of Section 7.3 (Arrays of Structures ) and in the C hapter 7 case study. In both of those
progra ms it is used to obtain input.
2
ections 8.1 and 8.2 are independe nt of each other.
xxi
AN INTR ODU CTIO N
TO PRO GRA MMI NG USIN G
1
2 • Chapter 1 An Introd uct io n to Comput ers and Problem So lving
Questio n: What are the meanings of the terms "hardware" and "softwar e"?
g a ll periphe r-
Answer : Hardware refers to the physica l co mponen ts of the comput er, includin
ical and electric a l devices . Program s
als, the central processing unit, disk drives, and a ll mechan
are referred to as software.
Questio n: What are the meanings of the terms "program mer" and "user"?
s on a compu te r.
Answer : A programmer is a person who so lves prob lems by writing program
he writes and te ts the
After ana lyz ing the problem and deve loping a plan for so lving it, h e or
1.1 An Introduction to Computers • 3
program that instructs the computer how to carry out the plan. The program might be run
many times, either by the programmer or by other . A user is any per on who uses a program.
While working through this tex t, you wi ll funct ion both a a programmer and as a user.
ll U.N. (E][][l[I D
o Yes g Yes
No No
Mouse Actions
Hover: Linger the mouse at a particular place and wait for a message (such as a tooltip) to
appear.
Drag an object: Move th mouse po inter until it is at the obj ect, press the left mouse button
and hold it down, move the mouse pointer until the obj ect moves to where you want it to be,
and finally, release the mouse button. (Sometimes this whole act ivity is called drag-and-drop.)
Right-clic k: Press and release the right mouse button once.
Click: Press and relea e the left mouse button once. (so metimes referred to as single-click or
left-click)
Double-cl ick: C lick the left mouse button twice in quick succession.
Note: A n important Windows conventio n is that clicking selects an obj ect so you can give
Windows further direction about it, but double-cli cking tells it to perform a default operation .
For exa mple, double-cli cking on a folder will open that folder.
File: Either a program file or a data fil e. Its name typically consists of letters, digits, and spaces.
The name of the file is also called the base name.
Extension of a file name: O ne or more letters, preceded by a period, that identify the type of
file. For exa mple, files created with Word have the ex tension doc or docx.
Filename: The combinat ion of the base name, the period, and the ex tension. The only char-
acters that cannot be used in filenames are \ , /, :, *, ?, <, > , ", and I. Filenames are not case
se nsit ive.
Folder: A container ho ld ing files and other folders. Folders also are known as directories.
Subfolder: A fo lder contained inside another folder.
Path: A sequence of folders, separated by backslashes ( \ ), where each folder is a subfolder of the
fo lder preceding it. Paths are used to identify the locations of fo lders and files. A n exa mple is:
Programs\C h07\Text_ Files_ for_ Exercises
Filespec: An abbrev iation of file specification, it is the combinatio n of a drive letter followed by
a colon , a path , and a filename. A n exa mple is:
In practice, yo u rarely hav to type a filespec, since both Windows and Visual Bas ic prov ide
Browse fac ilities that loca te files and fo lders for you.
Root folder (also known as the base folder): The highest fo lder on a disk. It co ntains all the
other fo lders on the disk and can also contain fil es . The fil espec of the root folder of yo ur hard
dri ve is most likely C: \ .
Windows Explorer: A program used to view, organize, and manage the fo lders and files on
your d isks. The de tails are presented in Appendix B in the section Manage Files and Folders with
W indows Explorer. To invoke Windows Exp lorer, right-click the Wind ow Start butto n a nd
click on Explore or Open W indows ExfJlorer in the context menu th at appears.
Displaying File Extensions: By default, Window shows only the base names of files. The fo l-
lowing steps configure Window to also display the ex tensions. (In this boo k we assume that
exte nsions are always show n) .
Windows XP
1. From Windows Exp lorer, click on O ptions in the Tools menu to disp lay the Folder Op tions
d ialog box.
6 • Chapter 1 An Introduct ion to Compute rs and Prob lem So lving
dvanced !3ettings :
Rles and Folders ,...
[Pl Ahv-a', • shmv icons . never thumbnails r--;
[ ] AJwa)~ !3ho•. • menu!3
[{] Display file icon on thumbnails -
f'Jl Display "ile size infom1ation in folder tips
[ ] Display the full path in the title bar Passic theme on~·)
Hidden files and folders
o Don show hidden files , folders . or drives
) Show hidden files . folder.> . and drives
~ Hide empty drives in the Computer folder
[ ] Hide extensions for known tile types I
0 Hide protected operating so1n,iem files (Recommended) ~
[ Restore Defaults ]
..____O_K______,) [ Cancel
1.3 will
2. C li ck on the View tab in the dialog box . (A dialog box similar to the one in Fig.
appear.)
click on
3. lf there is a check mark in the box next to "Hide ex tensions for known file types,"
the box to remove the check mark.
4. C lick on the OK button to close the Folder Options d ialog box.
input, necessary to obtain the output. The last step is to determin e how to process the input to
obtain the desired output- that is, to determine what formulas or ways of doing things can be
used to obtain the output.
This problem-solving approach is the sa me as that used to solve word problems in an alge-
bra class. For exa mple, conside r the following algeb ra prob lem:
The fi rst step is to determine the type of answer requested. The answer should be a number giving
the speed in miles per hour (the output ). (SJJeed is also called velocity. ) The information needed to
obtain the answer is the d istance and time the car has traveled (the in put). The formula
speed = distance/tim e
is used to process the dista nce trave led and the t ime elapsed in order to dete rmine the peed.
That is,
speed = 50 miles/2 hours
= 25 miles/hour
c___
lnp-ut ___,/ • .___/-Proce-ssing ___,/ • /.____
Out-put ---'
We de termine what we wa n t as outpu t, ge t the needed inpu t, and process the input to pro-
du ce the des ired output.
In th e chapte rs that fo llow we discuss how to write programs to carry out the preceding
operations. But first we look at the general process of wr it ing progra ms.
Program Planning
A baking rec ipe prov ides a good exa mp le of a plan. The ingred ien ts and the amounts are deter-
mined by what is to be baked. That is, the output determines the infJut and the processing. The
recipe, or plan, reduces the number of mistakes you migh t make if you tried to bake with no
plan at all. Although it's difficult to imagine an architect build ing a bridge or a factory without
a deta iled plan , man y programmers (pa rticularly students in their first programmin g cour e ) try
to wri te programs without fir t making a careful plan. The more complicated the proble m, the
more complex the plan may be. You will spend much less time working on a program if yo u
dev ise a carefull y though t out step-by-s tep plan and tes t it before actually writing the program.
Many programmers plan the ir programs using a sequence of steps, referred to as the
program developmen t cycle. The following step-by-step process will enab le yo u to use yo ur
t ime efficiently and help you design error-free programs that prod uce the desired output.
the nex t section, we discuss three popular methods used to develop the logic plan: flo wcharts,
in to a
pseudocode, and top-down charts. These tools help th e programm er break a problem
seq uence of small tasks the compute r can perform to solve the problem. Planning also involves
correct.
using represent ative data to test the logic of the algorithm by hand to ensu re that it is
3. Design the interface: Select the objects (text boxes, buttons, etc.).
cre-
Determi ne how the input will be obtained and how the output wi ll be displayed. Then
ate buttons and
ate objec ts to receive the inpu t and di play the output. A lso, create appropri
menus to allow the user to co ntrol the program.
4. Code: Translate the algo ri thm into a program ming language.
is
Coding is the technica l wo rd fo r wr iting the program. During th is stage, the program
compute r. The program mer uses the a lgo rithm
written in Visua l Basic and entered into the
devised in Step 2 along with a knowledge of Visual Basic.
5. Test and debug: Locate and remove any erro rs in the program.
of cor-
Testing is the process of finding errors in a program, and debugging is the process
the program is
recting erro rs that are found. (An error in a program is called a bug.) As
will be
typed, Visua l Bas ic points o ut certa in kinds of program errors. Other kinds of errors
is executed ; ho wever, many errors due to typing
detected by Visual Ba ic when the program
Basic language rules can be
mistakes , flaws in the algorithm , or incorrec t use of the Visual
such an error
uncove red and corrected only by careful detect ive work. An example of
wou ld be using addition when multiplic ation was the proper operatio n.
6. Complete the documentation: O rga nize all the material that describes the program.
date, to
Docume ntation is intended to allow another person, or the program mer at a late r
(comme nts) consists of statemen ts in the
understa nd the program. Internal documen tation
program that are not executed but point out the purposes of various parts of the program.
and
Docume ntation might also consist of a deta iled descriptio n of what the program does
, doc-
how to use it (for instance, what type of input is expec ted) . For commerc ial programs
on-line help. Other types of documen ta-
umentat ion includes an in truction manu al and
were used to construc t the
tion are the flowch art , pseudocode, and hierarch y chart that
ent
program. A ltho ugh documen tatio n is listed as the last step in the program developm
cycle, it should take place as the program is be ing coded.
Of th e program des ign too ls ava ilab le, three popu lar o n es a re the fo ll o
wing:
Flowch arts: G raphica lly dep ict the log ica l ste ps to ca rry o ut a tas k and
sh o w h o w the steps
re late to each oth e r.
Pseudo code: Uses English -li ke phrases with some Visua l Bas ic te rms to o
utline the task.
Hierarc hy charts: S h o w h ow the diffe rent pa rts o f a progra m re late to each
o the r.
Flowcharts
A flowch art con sists of specia l geometri c symbo ls connec ted by arro ws.
Within each symbol is a
phrase presenti ng th e act iv ity at th at step. The sh ape of the symbo l indica
tes the type o f o pe ratio n
th at is to occur. Fo r instance, the pa rallelog ram denotes input o r o utput.
The a rrows connec ting
the symbo ls, ca lled flowline s , sh ow the progres ion in which the steps
take place. Flo wcha rts
sh o uld "flow" from the top of th e page to the bo tto m. A ltho ugh th e symbo
ls useJ in fl owcha rts are
standa rdized , no stand ards ex ist fo r the amo unt of deta il req uired within
each symbo l.
Start
- ------~ input
Set stamps =
sheets /5 ------1L__ P_ro_c_es-si-ng_ _
~'---p-ro_c_es-si-ng_ _
Round stamps
up to next ------
whole number
------- ~ output
Pseudocode
al co mpute r code (hence ,
Pse ud ocode is an abb rev ia ted pla in English ve rsio n of actu
d by English -like sta te-
pseudocode). The geo metric symbo ls used in fl owch arts a re replace
mo re like co mpute r code
ments that o utline the proce s. A s a res ult, pse ud ocode loo ks
o n the steps require d to
than does a fl o wch a rt . Pse udocod e a llows th e progra mm e r to focus
r langua ge . The progra mm er can
so lve a pro ble m rather tha n on h ow to use the co mpute
res tricted by the rules of
d sc ri be the a lgo rithm in Vi ua l Ba ic-like fo rm witho ut be ing
ly tra nsla ted in to the Vi ua l
Visu al Bas ic. When the pse ud ocode is co mple ted, it ca n be easi
Bas ic la nguage .
1.4 Progra mmin g Too ls
• 11
Hierarchy Chart
The las t programmi ng too l we'll discuss is th e hiera rchy
chart , which shows the overall pro-
gram struct ure. Hiera rchy charts are also called struct
ure charts, HIPO (Hierarchy plus Input -
Process-Ou tput) charts, top-d own chart , or VTO C
(Visual Table of Cont ents) charts. All
these names refer to plann ing diagra m that are simila
r to a comp any's organ izatio n chart .
Hiera rchy charts depic t the orga nizati on of a progra
m but omit the specific processing
logic. They describe what each part, or modu le, of the
progra m does and they show how the
modu le relate to each other. The detail s on how the tTtodu
le work, howeve r, are omitt ed. The
chart is read fro m top to botto m and from left to right.
Each modu le may be subdivided into a
succession of subm odules that branc h out und er it. Typic
a lly, after the activities in the succes-
sion of ubmo dules are carried out, the module to the right
of the origin al module is co nsidered.
A quick glance at the hierarchy chart revea ls each task
perfor med in the program and where it
is performed. Figure 1.5 shows a hierarchy chart for the
postage-stamp proble m.
Postage-stamp
program
Read Calculate
sheets Display
stamps stamps
Decision Structure
The postage-s ta mp probl e m was solved by a se ries of
instru ction s to read data, perform calcu -
lation s, and display result . Each step was in a sequ ence;
that is, we moved from one line to the
nex t witho ut skipp ing ove r an y lines . This kind of struct
ure is ca lled a seque nce struc ture.
Man y probl ems, howeve r, requir e a decision to deter
mine wheth er a se ri es of instru ction s
should be execu ted. If the answe r to a ques tion is
"yes, " then on group of instru ction s is
Probl em So lving
12 • Chap ter 1 An Introd uctio n to Com pute rs and
No Yes
cond ition
true?
ture.
FIGURE 1.6 Pseud ocod e and flowc hart for a decis ion struc
Start
No Yes
street
even?
Display
Display
Eastbound
Westbound
End
Street
direction
program
FIGURE 1.9 Hierarchy chart for the numbered New York City streets problem.
Repetition Structure
A programm ing structure that executes instructions many times is called a repetition structure or
a loop structure. Loop structures need a test (or condition) to tell when the loop should end. With-
out an exit condition, the loop would repeat endlessly (an infinite loop ). One way to control the
number of times a loop repeats (often referred to as the number of passes or iterations) i to check a
condition before each pass through the loop and continue executing the loop as long a the condi-
tion is true. See Fig. 1.10. The solu tion of the next problem requires a repetition structure.
Is
No
condition
Discussion: The average grade equals the um of all grades divided by the number of students. We
need a loop to read and then add (accumula te) the grades for each student in the class. In ide the
loop, we also need to total (count) the number of students in the class. See Figs. 1.11 to 1.13 .
Input: Student grades.
Start
read next
grade
display the
answer
Class
average
problem
Processing: Find the sum of th e grades; co unt th e numbe r of stud e nts; ca lcula te
ave rage
grade = sum of grades/ numbe r of stude nts.
Output: Average grade.
Comments
1. Trac ing a flowch a rt is like play ing a boa rd ga me . W e beg in a t the S ta rt sy mbo l and
proceed
fro m symbo l to symbo l until we reach the End symbo l. At a n y time , we will be a
t just on e
sy mbo l. ln. a boa rd ga me, the pa th take n de pe nds o n th e result of spinning a spinne
r or
ro lling a pa ir of dice. The pa th ta ken through a flowc h a rt de pends on the input.
2. The a lgo rithm sh o uld be tes ted a t the fl o wc h a rt stage befo re be ing cod ed
into a pro-
gra m. Diffe re nt da ta sh o uld be used as input, a nd the o utput c h ecked. This
p rocess is
kno wn as desk checking . The tes t d a ta sh o uld includ e n o n ta nd a rd d a ta as
we ll as
t ypica l d a ta.
3. Flowc h a rts, pse ud ocode, a nd hierarc hy ch a rts a re unive rsa l proble m-so lving
too ls. They
ca n be used to constru c t programs in an y compute r language , no t just Vi sual Basic.
4. Flowch a rts are used through out this text to provid e a visualiza tio n of th e flo
w of ce rta in
progra mming ta ks a nd Visua l Bas ic contro l tru ctures. Majo r exa mples of pseudoco
de a nd
hi e ra rc h y ch a rts appea r in the case studies.
5. Flowcha rts a re time co nsuming to write and difficu lt to update . Fo r this reaso n
, profess io na l
progra mme rs a re mo re likely to favo r pse udocode and hi e rarchy cha rts. Because fl
owcha rts
so clearly illustrate the log ica l flow of program ming techniqu es, h owe ve r, they a
re a valu-
a ble too l in the educa tion of progra mme rs.
16 • Chapter 1 An Introductio n to Computers and Problem So lving
6. There are man y styles o f pse udocode. So me programm ers use an outline fo rm, whereas oth-
ers use a form that looks almost like a programm ing language. The pseudocod e appea ring in
t he case studie of this tex t focuses on the primary tasks to be perfo rmed by the p rogram and
leaves many of the routine details to be completed du ring the coding process. Several
Visua l Bas ic keyword , such as lf, Else, Do , and While, are used ex tensive ly in the
pse ud ocode appearing in this tex t.
Visual Basic, Controls ,
and Events
17
18 • Chapter 2 Visua l Basic, Controls, and Events
Figure 2.2 show how an eq ui va lent Visua l Ba ic prog ra m ge ts its info rmat io n . The boxes
may be filled in an y o rd er. When the use r clicks o n a box wit h t he mo use , the c urso r moves
to th at box. The use r ca n e ithe r type in new info rmation o r ed it th e ex isting info rm ati on.
When sa tisfied th at a ll the info rma ti on is co rrec t, th e use r clicks on the Write to Database
button. The boxes will clea r, and t he data fo r ano the r pe rso n ca n be ente red. Afte r a ll n ames
~· Vu'ashington
State : DC
Phone:
h ave been entered, the user clicks o n the Exit button. ln. Fig. 2.1, the prograrn
is in control; in
Fig. 2.2, the user is in control!
1. You literally draw the user interface, mu ch like using a paint program
.
2. Perhaps mo re importa nt, when you're done drawing the interface, the
buttons , text boxes,
and oth er objects that you have placed in a blank window wi ll automa tica
lly recogni ze user
action uch as mouse movem ents and button cl icks. That is, the seq uence
of procedu res
executed in you r program is control led by "events " that the user initiates
rather than by a
predete rmined seq uence of procedu res in your program.
ln any case, only after you des ign the interfac e does anythin g like traditio
nal program ming
occur. Objects in Visual Basic recogni ze events like mouse clicks; how the
object respond to
them depend s on the instru ctions yo u write. You always need to write instruct
ions in order to
make controls respond to events. This makes Visua l Basic program ming
fundam entally differ-
ent from traditio nal program ming. Programs in trad itiona l program ming languag
es ran from the
top down. For these program ming languages, exec ution sta rted from the
first line and moved
with the flow of the program to differen t parts as needed. A Visua l Bas ic
program works differ-
ently. Its core is a set of independ ent groups of instruct ions that are ac tivated
by the eve nt they
have been told to recogni ze. This event-d riven method ology is a fundam
ental sh ift. The use r
decides the o rder in which things happen , not the programmer.
Most of the program ming instruct ions in Visua l Basic that tell your
program how to
respond to events like mouse clicks occur in what Visua l Basic ca ll event fJrocedu
res. Essentially,
an ything exec utab le in a Visual Basic program either is in an event procedu
re or is used by an
event procedu re to help the procedu re carry out its job. ln fact, to stress that
Visua l Basic i fun-
dament ally differen t from traditio nal program ming languages, Microso ft uses
th e term project or
afJjJlication, rathe r than program , to refer to the combin at io n
of program m ing instruct ions and
user interfac e that makes a Visua l Basic program possible. H re is a summa
ry of the teps you
take to design a Visual Ba ic program:
Tool bar
Get Started te WS
I(}J New ProJ~ct .•
Welcome
t65 Op~n ProJed ...
The process for in voking Visual Bas ic varies lightly with the edition of Visual Bas ic
installed on the compu ter. To invoke Visual Bas ic from a computer that h as Visual Bas ic
Express installed, click the Windows Start button, hover over All Programs, and then click on
Microsoft Visua l Bas ic 20 10 Express. With the o ther editio ns of Visua l Bas ic, hover over All
Program , hover over Microsoft Visual S tudio 201 0, and then click on Microsoft Visual Studio
2010 in the sh ort list that is revea led.
Figure 2.3 shows the top h alf of the creen after Visual Bas ic is invo ked. A Menu bar and a
Toolbar are at the very top of the sc ree n. These two bars, with minor vari ations, are always pre-
se nt while you are working with Visua l Bas ic. The rema inder of the screen is ca lled the Start
Page. Some tasks can be initiated fro m the Menu bar, the Toolbar, and the Start Page. We will
usua lly initiate them fro m the Menu bar or the Toolbar.
The first item on the Menu bar is File. C lick on File, and then click o n New Project to pro-
du ce a N ew Project dialog box . Figure 2.4 shows the N ew Project dialog box produced by Visual
Bas ic Express.
The Wind ows Fo rms Applica ti o n ite m should be selected in the ce nter list. If this is not the
case, click on Windows Fonns A pplication to elect it. Note: The number of items in the list will
va ry depe nding on the ed ition of Visual Bas ic you are using.
The name of the program, initially set to Wind owsApp lica ti onl , can be specified at this
time. S ince we will have a chance to change it later, let's just u e the n ame Wind owsA pplica-
tion1 for now. C lick on the OK button to invoke the Visua l Bas ic programming env iro nment.
See Fig. 2.5. The Visual Basic programming environment is referred to as the Integrated Devel-
opment Environment o r IDE.
Ve ry likely, yo ur screen will look different than Fig. 2.5. The IDE is extremely configurable.
Each window in Fig. 2.5 can have its loca tion and size altered. New windows can be d isplayed
in th e IDE, and any wind ow ca n be closed or hidden behind a tab. Fo r instance, in Fig. 2. 5 the
Toolbox window is hidden behind a tab. The View menu is used to add additional windows to
the IDE. If you would like your screen to look exactly like Fig. 2.5, click on Reset Windows Layout
in the Windows menu , and then click on Yes.
New Project
l
So rt by: Defau lt
Installed Te mplates
~
Type: Visual Basic
mdows Forms Application
flftil:ffltl Visual Basic
A project for creating an application with a
Online Templates V'/indows user interface
Ve Class Library Visual Basic
~
ve WPF Browser Application Visual Basic
FIGURE 2.4 The Visual Basic New Proj ect dialog box.
22 • Chapter 2 Visual Basic, Controls, and Events
Menu bar
Toolbar
• f1 X
Forml System .Windo ws. Forms.Fo ...
Form
:: 11 l:.]
St artPositio WindowsDefaultl • ~
Ta g
lffi Forml
TopMost False
Sizing handle
FIGURE 2.5 The Visual Basic integrated development environment in Form Designer mode.
The Menu bar of the IDE display the menus of commands you use to work with Visual
Basic. Some of the menus, like File, Edit, View, and Window, are common to mo t Windows
app lication . Others, such as Project, Data, and Debug, prov ide commands spec ific to program-
ming in Visual Basic.
The Toolbar holds a collection of buttons that carry out standard operations when clicked.
For exa mple, you use the fifth button, which looks like a stack of three diskettes, to save the
files assoc iated with the current program. To reveal the purpose of a Toolbar button, hover the
mouse pointer ove r it. The little informat ion rectangle that pops up is called a tooltip.
The Document window currently holds the rectangu lar Form window, or form for short.
The form becomes a Window window when a program is executed. Most informat ion dis-
played by the program appea r on the form. The informat ion usually is di played in control
that the programmer has placed on the form. You can change the size of the form by dragg ing
one of its sizing handles.
The Properties window is used to change how objects look and react.
The Solution Explorer window displays the files assoc iated with the program and provide
access to the commands that pertain to them. (Note: If the Solution Explorer or th e Properties
window is not vis ible, click on it in the View/Other Windows menu.)
The Toolbox holds icons rep rese nting object (ca lled controls) that can be placed on the
form. If yo ur screen does not show the Toolbox, hover the mouse over the Toolbox tab at the
left side of the screen. The Toolbox will slide into view. Then click on the pushpin icon in the
title bar at the top of the Toolbox to keep the Toolbox permanently displayed in the IDE.
(Note: If th re is no tab marked Toolbox, click on Toolbox in the View/Other Windows menu.)
The controls in the Toolbox are grouped into ca tegories such as All Windows Forms and
Common Controls. Figure 2.6 shows the Toolbox after the Common Controls group ha been
expanded . Most of the control discussed in this text can be found in the list of common con-
tr l . (Y u n brain d cripti n fa ntr l by h v ring them u e ver th ntrol.) The
four control discussed in this chapter are text boxes, labe ls, buttons, and list boxes. In order to
see all the group names, co llapse each of the groups.
2.2 Vi sual Basic Controls • 23
~ :.......-
~ Comb oBox
~ DateTim eP icker
A Label
A LinkLa bel
- ListBox
,,,
', List 'ie'-'1'
IL MaskedT extBox
I'VlonthC alend ar
___J
~ Notifylcon
1 A
;;: ., Num ericUpDo wn
PictureBox
fill:! ProgressBar
0 Radio Button
~ Rich TextBox
8b~ TextBox
Text boxes: Yo u use a text box to get info rmat ion fro m t he use r, referred to as input, o r to dis-
play inform at ion produced by the program, referred to as output.
Labels: You place a labe l near a text box to te ll the use r what type of information is d isplayed VidcoN otc
C = :J
Sizing handles
2. C lic k a n ywhere o n the fo rm o utsid e the rec tangle to dese lec t the tex t box.
id to be
3. C li c k o n the recta ngle to resto re the h a nd les. An o bj ect sho wing its h a ndles is sa
o ther prop-
selected . A se lected text box can h ave its width a lte red , loca tio n c h anged , and
e rti es modified .
. The
4. Mo ve the mo use arro w to the h andle in the ce nter of the righ t side of th e tex t box
move
c urso r sho uld c ha nge to a d o uble a rrow (~) . H o ld d own th e left mo use button, a nd
th e tex t
the mo u e to the right. The text bo x is stre tched to the right. S imila rl y, grabbing
the left . Yo u
box o n the left sid e and mov ing the mo use to the left stre tch es the text box to
lle r. S teps 1 a nd 4 a llo w yo u to place a
a lso ca n use the ha ndles to make th e text box sma
uld no w be se lected ;
tex t box of a n y width an ywhe re o n the fo rm. Note: The tex t box sho
tex t box to
tha t is, its sizing h andles sho uld be sho wing. If no t , click anywhe re insid e the
se lect it.
a n a lte rnative
5. Press the d e le te key, DEL, to remo v the tex t box from the fo rm . S tep 6 g ives
way to place a tex t bo x of a n y width a t a n y loca tion o n th e fo rm .
an y place o n
6. C li ck o n the tex t box icon in the Too lbox . Th en mo ve the mo use po inte r to
thin lines.)
t h e fo rm. (Whe n over the fo rm, the mo use po inte r becomes a pa ir of crossed
te a rectan -
H o ld down the left mo use button, and drag the mo use o n a di agona l to gen e ra
r th e width
gle . R e lease th e mo use button to obta in a selected text box. Yo u ca n n ow a lte
w be se lected. If no t , click a n ywhe re
a nd loca tio n as befo re. Note: The tex t box sh o uld no
insid e the text box to se lect it.
es wind ow by
7. Press F4 to acti va te the Prope rti es wind ow. [Yo u a lso ca n activa te the Prope rti
se lecting
clic king o n it, clicking o n the ProjJerties Window b utto n ( ....J ) o n the Toolbar,
ProjJerties W indow fro m the View menu , o r clicking o n the text box wi th t h e right mo use
ow (ca lled
butto n a nd selecting ProjJerties .] See Fig. 2.8 . The first line o f the Prope rti es wind
is th current na me of the tex t box. The
the Obj ect box) reads "Tex tBox l tc ." TextBox l
o f pro p rties e ithe r
first two butto ns be lo w the Obj ect box permit you to v ie w the list
t h e up- and
grouped into categories o r a lphabe tica lly. U se t h e up- and do wn -arro w keys (o r
Properties Propertie
TextBoxl System .Windows. Forms. T e>.'tBox Text Bo xl System.Windo ws.Forms.T extBox Object
box
MaxLength 32767
Acc e.sibleDe.cript ion MinimumSize 0, 0
Acc essibl eName Modifi ers Friend
Acc e.sibleRole Default Multiline False
PasswordCha r
BackColor D Win dow Rea dOnly False
B l eft
TextAiign Left TextAiign Description
Text Text pane
The text associated with the control. The text associated with the control.
down-scroll arrows) to move through the list. The left column gives the property names,
and the ri ght column gives the current settings of the properties. W discuss four properties
in this walkthrough .
Note 1: The third and fourth buttons below the Object box, the Properties button and the
Events button, determine whether properties or events are di played in the Properties win-
dow. Norma ll y the Propertie button is highlighted. If not, cli ck on it.
Note 2: If the Description pane is not visible, right-cl ick on the Properties window, then
click on Description. The Description pane describes the currently highlighted property.
8. Move to the Tex t property with the up- and down-arrow keys. (A lternatively, scroll until
the property is visible, and click on the property.) The 0 xt property, which determines the
words disp layed in the text box, is now highl ighted. C urrently, there is no text di splayed in
the Settings box on the right.
9. Type your first name. Then press the Enter key, or click on another prope rty. Your name
now appears in both the Settings box and the tex t box. See Fig. 2.9.
c _. David Properties
l extBoxl System.Windows.Fo rms..TextBox
Tabind ex 0
David TabStop True
Tag
I
TextAii gn
Davrfl E!LJ
Left
lext
The text ass.o ciated with t he co ntro I.
10. C lick at the beginning of your name in the Tex t Settings box, and add your title, uch as
Mr., Ms., or The Honorab le. (lf you mistyped your name, you can eas ily correct it now.)
Then, press Enter.
11. Use the up-a rrow key or the mouse to move to the ForeColor property. This property deter-
mines the color of the information displayed in the tex t box.
12. li ck on the down arrow in th e right part of the Settings box, and the n click on the C us-
tom tab to display a election of colors. See Fig. 2.10. C lick on one of the co lors, such as
blue or red. Notice the change in the color of you r name. (Note: The sixteen wh ite boxes at
the botto m of the grid are used to create custom colors. See item L und er "Manage Vi ual
Basic ontro ls" in Appendix B for deta ils.)
13. Se lect the Font property with a single click of the mouse. The current font is named
Microsoft Sans Seri f.
14. C lick on the ellipsis ( . . . ) box in the right part of the Settings box to display a di alog box.
See Fig. 2. 11. The three lists give the current name (Microsoft Sans Serif) , current style
26 • Chapter 2 Visual Ba ic, Controls, and Events
Cu stom
111 111 11
111 111 11
FIGURE 2.10 Setting the ForeColor property.
Font
Effects Sample
[ ] Strikeout
A.aBbYyZz
[ ] Underline
Script:
Westem
(Regular), and current size (8) of the font. You can change any of these attributes by click-
ing on an item in its list o r by typing into the box at the top of the list. C lick o n Bold in the
style list, and click on 12 in the ize list. N ow click on the OK button to see you r name di -
played in a large r bold font. The text box will be longer so that it can accommo date the
larger font.
15. C lick on the text box and res ize it to be about 3 inches wid e.
Visual Basic programs consi t of three parts: interface, values of propertie , and code. Our
interface consists of a form with a single object, a text box. We h ave se t a few properties fo r
the text box-the text (namely, your name), the foreground color, the font style, and the
fo nt size. In Section 2.3, we discuss how to place code into a program. Visual Basic endows
2.2 Visual Basic Contro ls • 27
certa in capabilities to programs that are independent of any code we will write. We will
now run the ex isting program without adding any code in order to experience these capa-
bilitie .
16. C lick on the Start Debugging button ( ) on the Toolbar to run the program. [Alternative ly,
you can press FS to run the program or can click on Start Debugging in the Debug menu .]
After a brief delay, a copy of the fo rm appears that has ne ither the form nor the tex t box
selected .
17. Your name is highligh ted. Press the End key to move the cursor to the end of your name. N ow
type in your last name, and then keep typ ing. Eventually, the words will scroll to the left.
18. Press H o me to return to the beginning of the tex t. Yo u have a min iature word processo r at
your disposal. You ca n place the curso r anywhere you like in order to add or delete tex t. Yo u
can drag the cursor across tex t to select a block, place a copy of the block in the C lipboa rd
with Ctrl + C, and th en duplica te it elsewhere with C trl + V.
19. C lick on the Sto/J Debugging button ( ) on the Toolbar to end the program. [A lternatively,
you can end the program by clicking on the form's Close button ( J J) or press ing
Alt + F4 .]
20. Select the text box, act ivate the Prope rti es window, select the ReadO nly property, cl ick on
the down -a rrow button , and finally click on True. N o tice that the background color i now
gray.
21. Run the program, and try typing into the tex t box . Yo u can 't. S uch a text box is used fo r
o utput. O nly code ca n d isplay info rmation in the tex t box.
(Note: In this tex tbook, wheneve r a tex t box wil l be used on ly fo r the purpose of display ing
o utp ut , we will always se t the ReadO nly property to True.)
22. End the program.
23. Let's now ave the program on a disk. C lick on the Toolbar's Save A ll button ( ) to save
the work done so far. (Alternatively, you ca n click on Save All in the File menu.) You will be
prompted fo r the name of the program and the path to the fold er where you want the pro-
gram to be saved. Type a name, such as "VBdemo". You ca n either type a path o r use Browse
to locate a fold er. (Thi folder wi ll automat ically be used the n ext t ime you click on the Save
A ll button .) The files fo r the program will be saved in a subfolder of the selected fold er.
Important: If the "Create directory for so lutio n" check box is checked , then click o n the
check box to unch eck it. Finally, click on the Save button.
24. C reate a new program as before by clicking o n New Project in the File menu. [A lternati ve ly,
you ca n click on the New Project button ( ), the first button on the Too lbar, or you ca n
cl ick on New Project in the S tart Page.] A N ew Project d ialog box will appea r.
25. G ive a n ame to the project, such as MyProgram, and then click on the OK button .
26. Place three text boxes on the form. (If you use the double-click technique, move the tex t
boxes so that they do not ove rlap.) N o tice that they have the names Tex tBox l , Tex tBox2 ,
and TextBox3.
27. Run the program. No tice that the curso r is in Tex tBox l. We say th at Tex tBox l has the
focus. (This mea ns that Tex tBox l is the currently selected object and an y keyboard act ions
will be se nt di rectly to th is object.) A n y tex t typed will display in th at tex t box.
28. Press Tab once. N ow, Tex tBox2 has the focus. When you type, the characters appea r in
Tex tBox2.
28 • Chapter 2 Visual Ba ic, ontro ls, and Events
29. Pres Tab severa l times, and then press Shift+ T ab a few times. With Tab, the focu cycles
through the objects on the form in the o rd er they were created. With S hift+ T a b, the foc us
cycles in the reverse ord er.
30. End the program yo u created.
31. We would now like to return to the first progra m. C lick o n Open Project from the File menu .
An Open Project dialog box will appear stating that "You must choose to e ither save or d is-
card changes in the current project before opening a project." There is no need to save this
program, so click on the Discard button. Then a second Open Project dia log box will
appear.
32. Navigate to the fo lder correspo nding to the program you saved ea rlier, double-cli ck on the
fo ld er, and double-cli ck on the file with ex tension sln. You h ave now re loaded the first pro-
gram.
Note: As an a lternat ive to using the Open Project dialog box in Steps 31 and 32 to return
to the first program, click on the Start Page tab at the top of the Documen t window, and
click on the program in the Rece nt Projects part of the S tart Page.
33. If you do not see the Form Des igner for the program, do uble-click on Fo rm1.vb in the Solu -
tion Explorer.
34. Click on Close Project in the File menu to close the program.
A Button Walkthrough
1. C lick on the New Project button to sta rt a new program. (Give a name, such as ButtonPro g,
to the program , and click o n the OK button.)
2. Doub le-cl ick on the Button ico n in the Too lbox to place a button o n the form. (The But-
ton icon is the second icon in the Co mmon Co ntrols group of the Too lbox.)
3. Move the butto n to the center of the form.
4. Act ivate the Properties window, highlight the Text property, type "Please Push Me", and
press Enter. See Fig. 2.12. The button is too small.
Properties • 0 X
a... Forml
Butlonl 5y 5tem . \~ i ndo w s . F or m~ . B utton
11
~~ .... · .n ..... ·~
Tag
g Please Push
0 ··. u ...... (j TE:Xt: Pl!ea<Se Push Me
TatAiign M icl el l eC enter
Text
The tE:Xt: assoc iated with the control.
5. C lick on the button to se lect it, and then widen it to acco mmodate the phrase "Please Push
Me" on one li ne.
6. Run the program, and cl ick on th butt n. Th butt n appea r to move in and then out. In
Section 2.3, we will write code that is executed when a button is cl icked o n .
7. End the program and se lec t the button.
2.2 Visual Basic Controls • 29
8. From the Properties window, edit the Text setting by inserting an ampersand(&) before the
first letter, P. Press the Enter key, and notice that the first letter P on the button is now
underlined. See Fig. 2.13 . Pressing A lt+ P while the program is running causes the same
event to occur as does cl icking the button. H owever, the button will not appear to move in
and out. Here, P is referred to as the access key for the button. (The access key is always
spec ified as the character following the ampersand.)
9. C li ck on Close Project in the File menu to close the program.
1.1 .§] -/
Tag
----------------------
£lease F'ush Me
&P~ease PlUsh rli~ ~ n
TextAiign Middl eCenter
lfext:
Th e text ass ociated ~lith th e c: o ntro I.
A Label Walkthrough
1. C lick on the New Project button to begin a new program. Fee l free to keep the default
name, such as WindowsApp licationl .
2. Double-click on the label icon to place a labe l on the form. (The label ico n is a large letter
A.) Move the labe l to the center of the form.
3. A ctivate the Properties wind ow, highlight the Tex t property, type "Enter Your Phone Num-
ber:", and press Enter. (S uch a label is placed next to a text box into which the user wil l
type a phone number.) Notice that the label widened to acco mmodate the text. This hap-
pened because the AutoS ize property of the label is se t to True by default.
4. C hange the AutoS ize property to False. Pre s Enter. Notice that the label now has eigh t siz-
ing handles when selected.
5. Make the labe l narrower and longer until the words occupy two li nes.
6. Activate the Properties wind ow, and click on the down arrow to the right of the se tting for
the TextAlign property. Experiment by clicking on the various rectangles and observing
their effects. The co mbination of sizing and alignment permits you to design a labe l eas ily.
7. Run the program. Nothing happens, even if you click on the labe l. Labels just sit there. The
use r cannot change what a labe l displays unless yo u write code to make the change.
8. End the program.
9. C lick on Close Project in the File menu to close the program.
2. Place a list box on the form. (The list box icon is the ninth icon in the Common
Controls
gro up of the Toolbox. )
a Text
3. Press F4 to activate the Propertie s window and notice that the list box does not have
property. The word ListBox 1 is actu ally the se tt ing for the Name property.
4. Also place a tex t box, a button, and a labe l on the form.
5. C lick on the Object box just be low the t itle bar of the Properties window. The
name of the
that
form and the names of the four control are displayed . If you click on one of the names,
obj ect wi ll become se lected and its propertie s displayed in the Properties window.
6. Run the program . Notice that the word ListBox l has disappeared, but the words Buttonl
will
and Labell are still visible. The list box is comp letely blank. In subsequ ent sections, we
write code to place information into the li t box.
7. End the program and then click on Close Project in the File menu.
fo rm frm frmPayroll
button btn btnComp ute Tota l
label lbl lblAddress
list box lst lstO utput
text box txt txtC ity
g in
To change the name of the form, change the base name of the file Forml.v b appearin
the Solu tion Explorer
the Solution Exp lorer. To make the change, right-clic k on Forml. vb in
as frm-
window, click on Rename in the context menu that appea rs, type in a new name (such
keeps the
Payroll. vb), and press the Enter key. Importa nt: Make sure that the new filename
extensio n "vb".
prop-
The name of a control is changed from the control's Properties window. (The Name
controls and
erty is always the third property in the alphabet ized list of properties.) N ames of
r but
forms must begin with a letter and ca n include numbers and und erscore ( _ ) characte
cannot include punctuation marks or spaces.
I.
The N ame and Text properties of a button are both initially set to somethin g like Button
other property, and
H oweve r, changing one of these properties does not affect the se tting of the
property
similarly for th e N ame and Text properties of forms, tex t boxes, and labe ls. The Text
of a form specifies the words appearin g in the for m's title bar.
Fonts
New
The default font for controls is Microsoft Sans Serif. Two other useful fonts are Courier
and Wingdings.
2.2 Vi ual Basic Controls • 31
Courier New is a fixed-w idth font; that is, each ch aracter h a the same width. With such a
fon t, the letter i occupi es the same space as the letter m. Fi xed-width fo nts are used with tables
wh en info rmation is to be aligned in columns.
The Wingd ings font consists of assorted small pictures and symbols, each correspond ing to
a ch aracter on the keyboa rd. Fo r instance if o ne of the character %, (, 1, or J is typed in to th e
Text etting of a control whose Fo nt is Wingd ings, the contro l will display a be ll, phone, open
fo lder, or smiling face, respectively.
To view the character set for a Windows fo nt, click on the Windows Start button in the
Wind ows task ba r and successively click on A ll Programs, A ccessories, System Tools, and Cha r-
acter Map. A rectangular array of characte rs wi ll appear. After selecting th e fo nt, click on any
ite m to enlarge it. You can inse rt the keyboa rd character for the item in to the C lipboa rd by
pressing the Select button and then the Copy button. To place th e character into the Tex t prop-
erty of a contro l hav ing that font, just move the cursor to the Settings box for the Tex t property
fo r that co ntrol and press C trl + V.
Auto Hide
T h e Auto Hid e featu re allows yo u to make more room for th e Document window of the screen
by hiding windows (such as the Toolbox, Solu tio n Exp lo rer, or Properties window). Let's illus-
trate the featu re with a wa lkth rough using the Toolbox wind ow. W e start by discuss ing the sit-
uat ion where the feature is disabled.
1. If the Toolbox window is currently visible and the pushpin icon in the wind ow title is ver-
tical, th en the A uto Hide fea ture is disabled. (If the Toolbox window is not v isible, cl ick on
Toolbox in the m nu bar's View menu . If the pushpin icon is horizo ntal, then click on the
icon to make it ve rtical.) When the Auto Hid e feature i di ab led, the Toolbox window
stays fixed and is a lways ready fo r use.
2. C lick the mouse cur or somewhere outside the Toolbox window and no te that the Too lbox
window stays fixed.
3. C lick o n the pushpin ico n to make it ho rizo nta l. The Auto Hide feature i now enabled.
4. Move the mouse cursor somewhere outside the Too lbox windo w and no te that the window
!ides into a tab o n the left ide of the screen. The name and icon of the Too lbox window
appea r o n the tab.
5. H over the mo use curso r ove r the tab. The window slides into view and is ready for use.
Note: W e recommend that you keep the Toolbox, Solu ti on Exp lorer, and Prope rties win-
dows disp layed unless you are crea ting a program with a ve ry large form and need extra
pace.
other and fro m t he sides of t he fo rm . Snap lines are ho rizo ntal and vert ical line segments that Pos iti o ning
and a ligning
help you a lign co ntro ls. The Format menu is used to align contro ls, ce nter controls ho rizon- controls
ta lly and ve rtically in a fo rm , and make a group of selected control the sa me size.
appear.
3. Drag the button toward the upper-rig ht corner of the form until two short line segments
See Fig. 2.14(a). The button is now a comfortable distance from the two sides of the form.
y line
4. Place a second button be low the first button and drag it upward until a proximit
le distance apa rt.
appea rs between the two buttons. The buttons are now a comfo rtab
5. Res ize and pos it ion the two buttons as shown in Fig. 2.1 4(b) .
See
6. Drag Button2 upward until a blu e line appea r a lo ng the botto ms of the two buttons.
s are now
Fig. 2.14(c). This blue line is ca lled a snap line. The bottoms of the two button
aligned.
the
7. Continu e dragg ing Button2 upward until a purple snap line appears just underne ath
The midd les of the two buttons are now
words Buttonl and Butto n2. See Fig. 2. 14(d).
tell us
aligned. If we were to continue dragging Button2 upward , a blue snap line would
when the tops were aligned . Step 10 shows another way to align the controls .
I Button1 J ·'
+ - Proxim .ity Button 1
line
Button2
(a) (b)
I I J J
I Button 1
l I Button2 J Snap
line
l
Button 1
J
j
Button2
t I
(c) (d)
the mouse
8. C lick on Buttonl and then ho ld down th e C trl key and click on Button2. After
button is relea ed, both butto n will be selected.
a group
Note: This process (called selection of multiple controls ) can be repeated to select
of any number of controls.
set the
9. With the two buttons still selected, press F4 to open the Prope rti es window. Then
ltered for both
ForeColo r property to Blue. N otice that the ForeColo r property has been a
in
buttons at the same time. Actua ll y, any property that is co mm on to eve ry control
selec ted multiple controls can be se t simultan eously for the entire group.
10. With the two buttons still se lected, open the Format menu in the Menu
bar, h ove r over
Align, and click on Tops. The tops of the two buttons are now a ligned. Precisely , Buttonl
(the first button se lected) will stay fixed, and Butto n2 will move up so that its top is align ed
with the top of Buttonl.
The most common uses of the ubmenus of the Format menu are as fo llows:
Align: A lign middles or correspo nding sid es of a group of selec ted contro ls.
Make Same Size: Make the width and/or he ight of a group of se lected contro ls the sa me.
2.2 Vi ual Basic Controls • 33
Horizontal Spacing: Eq ualize the ho rizontal spac ing between a group of three or mo re selected
controls arranged in a row.
Vertical Spacing: Equalize the vertical spac ing betwee n a group of three or more selected con -
tro ls arranged in a column.
Center in Form: Center a se lected co ntrol e ither horizo ntally or ve rtica ll y in a fo rm.
When multiple con trols ar selected with the C trl key, the first control selected (called the
primary control of the group) will h ave white sizing h andles, while th other contro ls will have
black sizing h and les. A ll alignment and sizing statements initiated from the Format menu wdl
keep the primary control fixed and will a lign (or size ) the other controls with respect to the pri-
mary con tro l.
Afte r multip le contro ls h ave been selected, they ca n be dragged as a group and deleted as a
group. Exe rc ises 35 and 36 show how the arrow keys can be u ed to move and size a contro l.
The arrow keys also can be u ed to move and size multiple contro l as a group.
A gro up of co ntro ls a lso can be se lec ted by cli cking the mouse o utside the contro ls, drag-
ging it across the con tro ls, and releas ing it. The Select A ll command fro m the Edit menu (o r
t he key comb inatio n C trl + A) ca uses all the co ntro ls on the form to be s lected. Alth ough
these meth ods are easy to apply, th ey do no t allow the programm er to des ign ate the primary
control.
Comments
1. W hile you a re wo rking on a program, t he program res ides in memo ry. Remov ing a program
fro m me mo ry is referred to as closing the program. A program is automat ically closed when
you begin a new program. A lso, it can be closed directly with the Close Pmject command
fro m the File menu.
2. Three useful properties that h ave not b en discussed are the following:
(a) BackColo r: This property specifies the background colo r for th e fo rm o r a contro l.
(b) Visible: Setting the Visible property to False ca uses an obj ect to disappear when the
program is run. The obj ect can be made to rea ppear with code.
(c) Enabled: Setting the Enabled property of a co ntro l to Fa lse restricts its use. It appears
grayed and canno t rece ive the focus. Co ntrols sometimes are disa bled temporarily if
they do no t apply to the current state of the program.
3. Most properties ca n be et or altered with code as the program is running instead of be ing
prese t from the Properties window. For instance, a butto n ca n be made to d isappea r with a
line such as Buttonl. Visible = False . The deta il are presented in Section 2.3.
4. If you inadve rtently double-click on a fo rm, a window conta ining text wil l appear. (The
first line is Public C lass Forml.) This is the Code Editor, which is discussed in the nex t
34 • Chapter 2 Visual Bas ic, Contro ls, and Events
section. Press C trl + Z to undo the addition of this new code. To return to the Form
Des igner, click on the tab at the top of the Documen t window labeled "Forml. vb [Design] ."
5. We have seen two ways to place a control onto a form. Another way is to ju t click on the
con trol in the Toolbox and then click on the location in the form where you would like to
place the contro l. A lternative ly, you can just drag the control from the Toolbox to the loca-
tion in the form.
6. Figure 2.9 shows a small down-a rrow button on the right side of the Tex t property setting
box . When yo u click on that button, a rectangula r box appears. The se tting for the Tex t
property ca n be typed into this box instead of into the Settings box. This method of spec i-
fy ing the setting is especially usefu l when you want the button to have a multiline caption.
1. What is the difference between the Tex t and the N ame properties of a button ?
2. The first two group names in the Toolbox are All Windows Forms and Common Controls.
How many groups are there?
EXERCISES 2.2
1. C rea te a form with two buttons, run the program, and click on each button. Do you notice
anything different about a button after it has been clicked ?
2. While a program is running, a contro l is said to lo e focus wh en the focu moves from that
contro l to another control. Give three ways the use r can cause a control to lose focu .
In Exercises 3 through 24, carry out the task.
3. Place "C HEC KIN G A CCOUNT " in the title bar of a form.
4. C reate a tex t box containin g the words "PLAY IT, SAM" in blue letters.
5. C reate a tex t box with a ye llow background.
6. C reate a text box named txtGreetin g and containing the word "HELLO" in large italic letters.
7. C rea te a label containin g the sentence "After all is said and done, more is aid than done."
The sen tence should occupy three lines, and each line should be centered horizonta lly in
the label.
8. C rea te a read-only tex t box co ntaining the words "Visual Basic" in bo ld white letters on
a
red background.
9. C rea te a text box named txtLanguage and containin g the words "Visual Bas ic 2010"
in
Courier N ew font.
10. C reate a ye llow button named btnPush and containing the word "PUSH ".
11. C rea te a white button containin g the word "PUSH" in large italic letters.
12. C reate a button containin g the word "PUSH" in bold letters with the letter P underline
d.
13. C reate a button containin g the word "PUSH" with the letter H as the access key.
14. C reate a label containin g the word "ALIAS" in white on a blue backgroun d .
15. C reate a label named lblAKA and containin g the ce ntered italicized word "A LIAS".
16. Place "BALANC E SHEET" in the title bar of a form having a ye llow backgroun d .
17. C reate a label containing "VISUAL" on the fir t lin and "BA IC" n the s cond line.
Each word should be right-justified.
2.2 Visual Bas ic Controls • 35
18. C reate a form n amed frmHello whose t itle bar reads "H ello World".
19. C reate a label conta ini ng a picture of a d iskette. (Hint : U se the W ingd ings character < .)
Make the diskette as large as po sible.
20. C reate a labe l containing the bold word "ALI AS" in the Co urier N ew font.
21. C reate a list box with a ye llow background.
22. C reate a list box that will be invisible when the program is run.
23. C reate a form named frm Yellow with a ye llow backgro und .
24. C reate a button containing a picture of a red bell. (H int: U se the W ingd ings charac ter %. )
Make the bell as large as possible.
I n Exercises 25 through 30, create the interface shown in that figure. (These exercises give
you practice creating controls and assigning properties. The interfaces do not necessarily
correspond to actual programs.)
25. 26.
D ... Dynami c Duo GJI @J ~~ D::; Ent er Name ~~ @J ![}[]
Batman arne:
H obitn Enter
27. 28.
aJ Fill the Blan • ~~ @J I[]!] ll Sim il arit> •
29. 30.
ll,. Um le:'5 •d·•..- ice ~~ B I[};[]
The three most important
things in life are
OJ Be kind
OJ Be kind
[I] Be kind
Henrl James advice t o
his nephe•N
31. C reate a rep lica of your bank check on a form . Words common to all checks, such as "PAY
T O THE O RDER OF", should be contained in labe ls. Items spec ific to your checks, such as
yo ur name at the top left, should be contained in tex t boxe . Make the check on the screen
resemble your personal check as much as possible. Note: Omit the account number.
32. C reate a replica of your campus ID on a form. Words that are on all student IDs, such as the
name of the college, should be conta ined in labe l . Informat ion specific to yo ur ID, such as
36 • Chapter 2 Visual Bas ic, Contro ls, and Even ts
your name and student ID number, should be contained in tex t boxes. S imulate yo ur pic-
ture with a tex t box co ntaining a smiling face-a size 24 Wingdings J.
33. Consider the form shown in Exe rcise 25. A ssume the Batman button was add ed to the form
before the Robin button. What is the tab index of the Robin button ?
34. Consider the form shown in Exercise 26. Assume the first contro l added to the form was
the label. What is the tab index of the label?
The following hands-on exercises develop additional technique s for manipulat ing and access-
ing controls placed on a form.
35. Place a tex t box on a form and se lect the text box. What is the effect of press ing the va ri-
ous arrow keys?
VideoNote
36. Place a text box on a fo rm and select the tex t box. What is the effect of pressing the va ri-
Moving a textbox
ous arrow keys while holding down the Shift key?
(Homework)
37. Repeat Exerci e 36 fo r selected multiple contro ls.
38. Repea t Exercise 35 for selected multiple controls.
39. Place a labe l and a list box on a fo rm and change their font sizes to 12 at the same time.
40. Place a button in the ce nter of a form and select it. Hold down the C trl key and press an
arrow key. Repeat this process for each of the other arrow keys. Describe what happens.
41 . Place a label and a tex t box on a form with the label to the left of and above the text box.
Select the label. Hold down the C trl key and press the down- arrow key twice. With the
C trl key still pressed, press the right- arrow key. Describe what happens.
42. Place two button on a form with one button to the right of and below the other button .
Select the lower button, hold down the C trl key, and press the left-arrow key. With the Ctrl
key still pressed, press the up-arrow key. Describe the effect of pressing the two arrow keys.
43. Experimen t with the A lign command on the Format menu to determine the difference
between the center and the middle of a contro l.
44. Place four large buttons vertically on a form. U se the Format menu to make them the same
size and to make the spac ing between them uniform.
45. Place a label and a tex t box on a form as in Exercise 26, and then lower the label slightly
and lower the text box until it is about one inch lowe r than the label. U se the mouse to
slowly raise the text box to the top of the form. Three snap lines will appear along the way:
a blue snap line, a purple snap line, and finally another blue snap line. What is the signifi-
cance of each snap line?
46. Place a tex t box on a form, select the text box , and open its Properties window. Double-click
on the name (not the Settings box) of the ReadOnly property. Double-click aga in. What is
the effect of double-cli cking on a property whose possible settings are True and False?
47 . Place a button on a form, select the button, and open it Properties window. Double-click
on the name (not the Settings box ) of the ForeColor property. Double-click repeated ly.
Describe what is happening.
to the button
1. The text is the words appea ring on the burton , whereas the name is the des ignation used to refer
have the same va lue, such as Button 1. H owever, each ca n be changed independen tly of
in code. In itia lly, they
the other.
Toolbox after
2. T he Toolbox in the Exp ress Edition of Vis ual Bas ic conta ins 11 groups. Figure 2. 15 shows th e
editions of Visual Bas ic the Toolbox co ntains 12 groups.
each group has been collapsed. Note: In the other
2.3 Visual Basic Events
• 37
Toolbox
All Windows Forms
Common Controls
Conta iners
Menus & Too lbars
Data
Compone nts
Printing
Dialogs
WPF Interoperabili
Visu al Basic PowerPacks
G~e~ l ,
1. Create the in terface; that is, generate, pos ition, and size the objects.
2. Set properties; th at is, co nfigure the appea rance of the objects.
3. Write the code that executes when eve nts occur.
Section 2.2 covered Steps 1 and 2; th i section is devoted to Step 3. Code consist of state
ments
that carry out tasks. Writing code in Visual Bas ic is a sisted by an autoco mpletion system
ca lled
lntelliSe nse that redu ces the amount of memoriza tion needed and helps prevent errors.
In this
section, w limit ourselves to statemen ts that change properties of a control or the form
wh ile a
program is runn ing.
Propert ies of co ntro ls are changed in code with statemen ts of the form
where controlN ame is the na me of the co ntro l, jJroperty is one of the properties of
th co n-
tro l, and setting is a va lid setting for that prope rty. Such stateme nts a re ca lled assignm
ent
stateme nts. They ass ign va lues to prope rties. H ere are three examp les of as
ignment
statemen ts:
1. The statemen t
txtBox. Text = "Hello"
where the three dots (that is, the ellips is) represe nt
System .Even tArgs
ByVal sende r As System . Objec t , ByVal e As
FIGURE 2.16 The interface for the event procedu re walkth rough.
1. C reate the interface in Fig. 2.16 in the Form Designer. The Name
properties of the form,
tex t boxes, and button should be set as shown in the Object column
. The Tex t property of
the form shou ld be se t to Demon stratio n, and the Text property of
the button should be set
to C hange Color to Red . N o properties need be se t for the text boxes.
2. C lick the right mouse button an ywhere on the Form Design er, and
click on View Code. The
Form Designer lDE is replaced by the Code Editor IDE (also known
as the C ode view or the
Code window). See Fig. 2.17.
~ My Proj ect
En d Class
::::J frmDemo.vb
11
End Sub
btnRe d_C li ck. This proced ure is
The first line is the heade r for the eve nt proced ure named
the butto n is clicke d, the code
invoke d by the event btnRe d.Clic k. That is, whene ver
betwee n the two lines just shown will be execu ted.
5. Type the line
txtFir st.Fo reCol or Color .Red
bet First
.) tct5econcl
.---- .---- -
Comm on All
.
This fea ture of lntelli Sense is referred to as Compl ete Word
1
2.3 Visua l Basic Eve nts
• 41
Anch or
App _ndT i GetCh a rln d exF romP os iti on
...zJ Aut o( ompl Cust on,So ur c GetChildAtP oi nt ='
....J Au oC ompl t Mod
GetC ontain erC o ntro I
....J Aut oCo mpl t So urc
GetF irstC h a rln d exF rom Lin e
Bad -Co lo r GetFi rstC h a rln d exOfCu rrent li n e
Bo rd rS I Getli n eFrom Ch a rln d ex
Brtn gToFront GetP osition From Ch a rln d ex
Ca nF oc u ~ HasChildren
Ca nS I ct
Height
Co mm o n All Com mon All
ct txtFirst.
7. Retu rn to the Form Des igne r and sele
s win dow. The
the toolbar at the top of the Prop ertie
8. C lick on the Events butt on ( f ) in desc ribes the
displaye d, and the Des crip tion pan e
63 even ts as ocia ted with text boxes are ts. Only a few
alarmed by the large num ber of even
currentl y sele cted eve nt. (Do n't be
to the Leav e even t. See Fig. 2.2 1.
even t are used in this boo k.) Scro ll
Properties
txt f irst Syst em. Wind ows. Form s. TextBox
KeyPress
KeyUp
Layo ut
Leave EJ!_j
Location Ch anged
MarginCh anged
Modifi edCh ang ed -- -- --~
leav e
e
Occurs when th e control is no long er th
activ e co ntrol of t he form .
ow.
FIGURE 2.21 Even ts displayed in the Properties wind
End Sub
( ... ) Han dles txtF irst .Le ave
Priv ate Sub txtF irst _ Lea ve
.Bla ck
txtF irst .Fo reC olo r = Col or
End Sub
.Te xtC han ged
ang ed( ... ) Han dles txtF irst
Priv ate Sub txtF irst _ Tex tCh
.Blu e
txtF irst .Fo reC olo r = Col or
End Sub
End Cla ss
rma tio n abo ut
ove r the curso r ove r the word "ForeCo lo r". Visual Bas ic now disp lays info
10. H Bas ic.
trates ano ther help feat ure of Visual
the foregro und colo r prop erty. Thi s illus
11. Run the prog ram by press ing FS.
llo" h as been typed.
box. In Fig. 2. 22, the blue word "He
12. Typ e ome thin g into the first tex t typi ng- that is, whe n -
whe never it is read y to acce pt
(Re call that a text box has the focu s
ever it contain a blinking cur r.)
me blac k. Wh en
C lick on the seco nd text box . The con tent of the first text box will beco
13. the even t Leav e
first text box lost the focu ; that is,
the seco nd text box was click ed, the
2.3 Vi ual Bas ic Event
• 43
btnO ne_C lick is the name of the eve nt proced ure, and
btnOn e.C lick ident ifies the event t hat
invok es the proce dure. The n ame ca n be changed
at will. Fo r instan ce, the heade r ca n be
chang ed to
Opening a Program
be
p le cont ains a program. These programs can
Beg in ning with the next chap ter, each exam s xiv- xv of the
boo k. See the discussion on page
dow n load ed from the Pearson website for this ic env i-
program tored on a disk into the Visual Bas
Preface for deta il . Th process of load ing a 7-2-3
ram. Let 's ope n the dow n load ed prog ram
ronm ent i refe rred to as open ing the prog then displ ays U.S.
to e nte r a fi rst n ame , and
from C hapt e r 7. Tha t prog ram allows you
Pres iden ts hav ing that first nam e.
~ My Proje ct
[> bin
fm1Pr esid ents.v b
I Display Presidents
l
President James Madison
President James Monroe
President James Polk
President James Buchanan
I
President James Garfield
President James Carter
--
The program just executed uses a tex t fil e named USPres. txt. To view the text fil e, open the
folder bin, open the subfo lder Debug, and click on USPres. txt. (lf the bin folder is not visib le,
click o n the Show All Files button. If USPres.txt is not listed in the Debug ubfo ld er, click the
Refresh butto n and reopen the folders. After read ing C hapter 7, you will und erstand why tex t
files are placed in the Debug subfold er of the bin fo lder.) The first line of the fil e gives th e name
of the first president; th e second line gives the name of the second president, and so on. To
close the text fil e, click on the close button ( X ) on the USPres.txt tab.
Comments
1. The Visual Basic ed ito r automatica lly indents the statements inside procedures. ln thi
book, we indent by two spaces. To instru ct yo ur ed ito r to indent by two spaces, se lect
O fJtions from the Tools menu, and unch ck the "Show a ll settings" box in the Options win-
dow that appears. Expand "Tex t Editor Basic" o r "Text Editor", click o n "Editor", enter 2
into the "Indent size:" box, and click on OK.
2. The event controlName. Leave is raised when the spec ified co ntro l loses the focus. Its coun-
terpa rt is the eve nt concrolName.Enter which is raised when the spec ifi ed co n trol ge ts the
foc us. A related state ment is
controlNarn e.Focus()
object.Tex t = setting
the exp ress ion fo r setting must be surround ed by quotatio n marks. (Fo r instance, lblName.
T ext = "Name".) For prope rties where the proper setting is o ne of the words True o r Fa lse,
th ese words should not be surround ed by quotation marks.
5. Names of ex isting event procedures assoc iated with an object are not automat icall y
changed when you rename the object. Yo u must change them yourself. H owever, the event
46 • Chapter 2 Visual Basic, Controls, and Events
-
that invokes the procedur e (and all other reference s to the control) wi ll change automati
cally. For exa mp le, suppose an event procedur e is
Private Sub btnOne_ Cl i ck( . . . ) Handles btnOne . Click
btn One .Text = "Press Me"
End Sub
you
and , in the Form Designer, you change the name of btnOne to btnTwo. Then, when
return to the Code Editor, the procedure will be
There w ere buil d erro rs. Would you li ke to continu e and run th e last
successfu l buil d?
_es_
' - - -Y ___,] l____N_o_ _J
0 Do not show this di alog aga in
8. Each contro l ha a favored event, called the default event, whose event procedure template
can be generated from the Form Designer by double-clicking on the control. Table 2.2
shows
is the
some contro ls and their defau lt vents. The most common event appear ing in th is book
The
C lick event for a button. The TextC hanged eve nt for a text box was used in this section.
ed in Section 4.4, and the Load event
Selected lndexCh anged event for a list box is introduc
book.
for a form is introd uced in Section 7.1. The C lick event for a label i never used in this
form Load
button C lick
labe l C lick
list box ele tedlndexChang d
text box TextChanged
2.3 Visual Ba ic Events • 47
9. Fo nt properties, such as the name, sty le, and size, are usually spec ified at des ign t ime. The
setting of the properties ca n be displayed in code with statements such as
l stBox.I tems.Add(txtB ox.Font.Name )
lstBox.Items . Add ( txtBox.Font.B old )
l stBox. Items.Add ( txtBox.Font . Size)
H oweve r, a font's name, style , and size properties cannot be altered in code with statements
of the form
t xtBox . Font.Name "Courier New"
tx tBox . Font.Bold True
t xtBox . Font . Size 16
10. When you make changes to a program, asterisks appear as superscripts on the tabs labeled
"frmN ame.vb [des ign]" and "frmN ame.vb" to indicate that so me part of the program has
not been saved. The asterisks disappea r when the program is saved o r run.
Note: lf the program has been saved to disk, all fi les for the program wi ll be automat ica lly
upd ated on the disk whenever the program is saved o r run.
11. You ca n eas ily change the size of the fo nt used in the current program's ode Edito r. Just
ho ld down the C trl key and move the mo use's scroll wheel.
12. Notes on IntelliSe nse:
(a) Whenever an item in an lntell iSense drop-down list is se lected, a too ltip describ ing the
item appea rs to the right of the item.
(b) From the situation in Fig. 2. 18, we can display txtFirst by double-click ing on the high lighted
item, pressing the Tab key, or pr ss ing the Enter key. Another option is to press the period
key. In this case, both the name txtFirst and the dot following it will be displayed. Note: The
period key option works only if the selected item is always fo llowed by a dot in code.
(c) Inte ll iSense drop-down lists have tabs labe led Common and All. When the All tab is
selected, every possible co ntinu at ion cho ice appea rs in t he list. W hen the Common tab
i selected, on ly the most freq uen tly used co nt inuat ion cho ices appear.
(d) Occasionally, the lntell iSense drop-down list will cover some of yo ur program. If you
ho ld down the t rl key, the drop-down list wi ll become transparent and allow you to
see the cove red- up code.
1. Describe the event that invokes the fo llow ing event procedure.
Private Sub btnCompute_ Click() Handles txtBox.Leave
t xtBox. Text = "Hello world"
End Sub
2. Give a statement that wi ll prevent the use r from typ ing into txtBox.
EXERCISES 2.3
I n Exercises 1 through 6, desc ribe the contents of the text box after the button is click ed.
1. Priv ate Sub btnOutput Click( ... ) Handles btnOutput.Cl ick
tx t Box.Text = "Hello"
End Sub
48 • Chapter 2 Visual Bas ic, Contro ls, and Eve nts
In Exercises 7 through 10, assume that the three objects on the form were created in the
order txtFirst, txtSecond , and lblOne. Determin e the output displayed in lblOne when the
program is run and the Tab key is pressed. Note: Initially, txtFirst has the focus.
7. Private Sub txtFirst Leave( ... ) Handles txtFirst. Leave
lblOne.F oreColor = Color.Gre en
lblOne.T ext = "Hello"
End Sub
In Exercises 17 through 28, write a line (or lines ) of code to carry out the task.
17. Display "E.T. phone ho me." in lblTwo.
18. Display "Play it, Sa m. " in lblTwo.
19. Display "The stuff that dreams are made of." in red letters in txtBox .
20. Disp lay "Life is like a box of c hoco la tes." in txtBox with blu e lette rs o n a go ld back-
gro und.
21. Disable txtBox.
22. C hange the words in the form's title bar to "H e llo World."
23. Make lb1Two disappear.
24. C hange the co lo r of the letters in 1b1Name to red.
25. Enab le the disabled button btnO utco me.
26. Give the focus to btnCo mpute.
27. G ive the focus to txtBoxTwo.
28. C h ange the backgroun d color of the fo rm to Wh ite.
29. Describe the Enter event in yo ur own wo rds.
30. Describe the Leave event in your own wo rds.
31. The label co ntro l has an event called DoubleC lick that is ra ised by doub le-cl icking the left
mouse button. Write a simple program to test this vent. Determine whether yo u can ra ise
the DoubleClick eve nt without also ra ising the C lick eve nt.
32. W rite a simple program to demonstra te that a button 's C lick eve nt is ra ised when you press
the Enter key whi le the button has the focus.
In Exercises 33 t hrough 38, th e interface and initial properties are specified. Write a pro-
gram to carry o ut the stated task.
33. When one of the three buttons is pressed, the words on the button are d isp layed in the text
box with the stated al ignm ent. Note: Re ly on lnte lliSense to provid you with the proper
ettings for the TextAlign property.
50 • Chapter 2 Visual Bas ic , Contro ls, a nd Eve nts
[ Right Justify
37. When the use r moves the focus to one of the three small text boxes at the bottom of the
fo rm , an approp riate saying i displayed in the large text box. Use the say ings "llike li,~e, it's
something to do."; "The future isn 't what it u ed to b ."; and "Tell the truth and run.
38. The user can d isable or enable the text box by clicking on the appropriate butto n . After the
user clicks the Enab le button, the tex t box should rece ive the focus.
BE J
EJE J •
FIGURE 2.26 Form for Exe rcise 39. FIGURE 2.27 Form for Exercise 40.
40. S imulate a traffic light with three small squ are tex t boxes placed vertically on a form. See
Fig. 2.2 7. Initially, the bottom tex t box is so lid green and the other text boxes are da rk gray.
When the Tab key is pressed, the midd le text box turns ye llow and the bottom text box turns
dark gray. The next time Tab is pressed, the top text box turns red and the midd le text box
turns dark gray. Subsequent press ing of the Tab key cycles through the three colors. Hint: First
place the bottom text box on the form, then the middle text box, and finally the top text box.
41. Use the sa me form and properties as in Ex rc ise 34, with the captio ns fo r the buttons
rep laced with Vanish and Reappea r. C li cking a button sho uld prod uce the stated r sult.
42. A form contains two text boxes and one large label between them with no preset caption.
When the first text box rece ives the focus, the labe l reads "Enter your fu ll name." When the sec-
ond text box rece ives the focus, the label reads "Enter your phon number, including area code. "
52 • Chapter 2 Visual Basic, Contro ls, and Eve nts
43. The form contains a single read-only tex t box and two buttons. When the user clicks on
one of the buttons, th e se ntence "You just clicked on a button. " is displayed in the tex t box.
The program should consist of a single event procedure.
44. The fo rm contains two tex t boxes into which the use r types information . When the u er
cl icks on one of the tex t boxes, it beco mes blank and its contents are displayed in the other
tex t box . Note: A tex t box can be cleared with the statement txtBox. Clear () or the state-
tnen t txtBox. Text = ""
1. T he event is raised when txtBox loses the foc us since txtBox .Leave is the event fo llow ing the keyword Hand les.
T he name of the eve nt procedure, btnCo mpute_C lick, ca n be an ything; it plays no role in dete rmining the
act ion that raises the eve n t.
2. Th ree poss ibi lities are
txtBox.Enable d = False
txtBox.ReadO nly = True
txtBox.Visib le = False
CHAPTER 2 SUMMARY
1. The Vi ual Ba ic Form Designer displays a form that can hold a collection of controls for
which various properties can be set. Some exa mples of contro ls are tex t boxes, labels, bu t-
tons, and list boxes. Some useful properties are Tex t (se ts the tex t displayed in a contro l) ,
N ame (used to give a meaningful name to a control) , Font.N ame (selects the name of the
font u eel), Font.S ize (sets the size of th e tex t displayed), Font.Bold (displays boldface text),
Font.ltalic (displays italics text) , BackColor (se ts the background color) , ForeColor (sets
the color of the text) , ReadO nly (determines whether tex t ca n be typed into a tex t box
when the program is running), Tex tAlign (sets the type of alignment for the tex t in a con-
tro l), Enabled (determines whether a contro l can respond to user interaction), and Visible
(dete rmines whether an obj ect can be een or is hidden) .
2. A n event procedure is invoked when something happens to a specified obj ect. Some events
are object.Click (object is clicked) , object.Tex tC hanged (a change occurred in the value of
the obj ect's Tex t property), object. Leave (object loses the focus), and object. Enter (object
rece ives th e focus). Note: The statement object.Focus() moves the focus to the specified
object.
3. lntelliSense prov ides a host of features that help you write code.
4. Tab order, the ord er in which the user moves the focus fro m one contro l to another by press-
ing the Tab key while the program is running, can be set from the Properties window.
Variables, Input,
and Output
3.1 Numbers 54
• Arithmetic Operations • Variables • Incrementing the Value of a Variable • Built-In
Functions: Math .Sqrt, Int, Math.Round • The Integer Data Type • Multiple
Declarations • Two Integer-Valued Operators • Parentheses • Three Types of Errors
• The Error List Window
3.2 Strings 68
• Variables and Strings • Option Exp licit and Option Strict • Using Text Boxes for
Input and O utput • Auto Correction • Concatenation • String Properties and
Methods: Length Property and ToUpper, ToLower, Trim, Ind exOf, and S ubstring
Methods • The Empty String • Initial Value of a String • Widening and Narrowing
• Internal Documentation • Line Continuation • Scope of a Variable
3.3 Input and Output 85
• Formatting O utput with Format Functions • Using a Masked Text Box for Input
• Dates as Input and Output • Getting Input from an Input Dialog Box • Using a
Message Dialog Box for O utput • Named Constants • Sending O utput to the Printer
Summary 98
53
54 • Chapter 3 Variab les , lnput, and O utput
3.1 Numbers
Much of the data processed by computers consist of numbers. In co mputerese, numbers are
called numeric literals. This section discusses the operations that are pe rfo rmed with numbers
and th e ways numbers are displayed.
Arithmetic Operations
The fiv e stand ard a rithm e tic o pe rati o ns in Visua l Bas ic are additio n, ubtractio n, multi pli-
ca tion , di v isio n , and ex po n entia tio n . Additio n , subtrac tio n, and di v isio n are den oted in
Visua l Bas ic by th e stand ard sy mbo ls+, -, and/, respect ive ly. H oweve r, the n o ta tio ns for
multi plicatio n and expon enti ati o n differ fro m the c usto ma ry mathema ti ca l n o tatio n s as
fo llo ws:
(The asterisk [*] is the upper ch aracter of the 8 key. The care t [A] is the upper ch aracter of th e 6
key. )
O ne way to show a number on the screen is to d isplay it in a list box. If n is a number, th en
the instruction
lstBox.Items . Add(n)
displays the number n as the las t item in the list box. Add is called a method. (G enera lly, a
meth od is a process that performs a task for a particular o bj ect.) If the parentheses contain a
combination of numbers and arithmetic operations, the Add method ca rri es out the ope rations
and displays the result. Another im portant method is Clear. The statement
lstBox.Items.Cle a r()
Example 1 The fo llowing program applies each of the fi ve arithmetic operations. Pre-
ceding th e program are the fo rm des ign and a table ha wing the names of the obj ects on t he
fo rm and the se ttings, if any, for properties of these obj ects. This form des ign is a lso u' ed in t he
discuss ion and exa mples in the rema inder of this section .
The word "Run" in the phras ing [Run ... ] indicates that the Start Debugging button o r FS
shou ld be pressed to execute the program. N oti ce that in the output 3 / 2 is displayed in dec imal
fo rm. Visual Bas ic never displays numbers a fracti ons. In the evaluation of 2 * (3 + 4 ), th e
operation inside the parentheses is calculated first.
Note: All programs appearing in exa mples and case studies are provid ed on th e companion
website for this book. See the discuss ion on page xv for deta ils.
3.1 N um be rs • 55
Compute
a... 3 -l -1 l = I @) 1
-S':'C..- 1
5
1
6
1.5
9
1-4
Compute
Variables
In applied mathe matics prob le ms, qua nt ities are referred to by n ames. Fo r insta nce, conside r
th e fo llowing high sch oo l alge bra proble m: "If a ca r trave ls a t 50 miles per h our, how fa r wi ll it
t rave l in 14 ho urs? Also, h ow many h ours are required to travel 4 10 m iles?" The so lu t ion to this
proble m uses the well-known fo rmula
[Run, and then click on the button. T he following is displayed in the list box.]
700
8. 2
S kip the second, third , and fo urth lines of the event proced ure for now. We wi ll return to
them soon. T he sixth line sets the speed to 50, and the seventh line sets the time elapsed to 14.
The e ighth line mu ltiplies the va lue fo r the speed by the va lue fo r the time e lap eel and sets the
distance to this product. The nex t line d isplays the an wer to the distance-t raveled question.
The three lines before the End S ub statement answer the time-requ ired qu estion in a similar
manner.
The names speed, timeElapsed, and distance, which hold va lues , are referred to as variables.
Consider the variable timeElapse d. In the seventh line, its value was se t to 14. In the e leventh
line, its va lue was changed as the result of a computat ion. On the other hand, the variable speed
had the same value, 50, th roughout the program.
In ge neral, a va riable is a name that is used to refer to an item of data. The va lue ass igned
to the variable may change during the execut ion of the program. In Visual Basic, variab le
VideoNotc names must begin with a letter or an und erscore, and can consist o nly of letters, digits, and
Numbers und ersco res. (The shortest variab le n ames co nsist of a single lette r.) Visual Basic does not
distingui h between uppercase and lowe rcase letters used in va riab le names. So me examp les
of variab le names are total, numberOfCars, taxRate_2010, and n . As a co nv entio n , we write
variable names in lowe rcase letters except for the first lette rs of each addit io na l word (as in
gracleOnF irstExam). This convent ion is called camel casing.
If var is a variable and n is a numeric literal, then the statement
v ar = n
assigns the number n to th e var iab le var. S uch a state ment is an oth er xa mp le of an assignmen t
statement .
A variab le is declared to be of a certa in type depending o n the sort of data that can be
ass igned to it. The most ve rsa t ile type for hold ing numbers is called Double. A variable308 of type
Double can hold who le, fract ional, or mixed numbers between about -1.8 · 10 and
308
1.8 · 10 . Dim sta tements (also called declaratio n statement s) declare the names and types of
the va riab les to be used in the program. The second, th ird, and fourth lines of this event proce-
dure declare three variab les of type Doub le and give them t he names speed, timeElapsed , and
distance. Variab les must be declared before va lues ca n be assigned to them.
In general, a statement of the form
declares a va riab le named varName to be of type Double. Actua lly, the Dim state ment causes
the comput r to se t a ide a locat io n in me mo ry refe renced by varName. S ince varName i a
3.1 Numbers • 57
numeric va riab le, the Dim state ment ini tially places t he number ze ro in that memo ry loca-
ti o n. (We say that zero is the initial value o r default value of th e variable. ) Each subsequent
ass ignmen t statement h av ing varName to the left of the equ al sign wi ll change the valu e of the
numbe r.
Th e init ia l va lu e ca n be se t to a va lu e o t he r tha n zero. To spec ify a no nzero initia l
va lu e, fo llo w t h e declaratio n state ment with a n equ a l sign fo llowed by the initia l va lu e .
The sta te men t
declares the specified variab le as a va riable of type Double and gives it th e ini tial value 50.
The statement
looks into thi s memo ry locat io n fo rth current valu e of the variable and d isplays t hat valu e in
the list box.
In te lliSe nse prov id es ass istance with bo th declaration and ass ignment statemen ts. Con-
sid er the pa ir of statemen t
In the first statement, Intel! iSe nse will sugges t the wo rd "A " after you type "Dim interestRate ",
and will suggest the word "Double" after you type "Do u" . In the second statement, lntelliSense
will sugge t the word "interestRat e" after you type "inte".
A co mbination of li terals, variab les, and arithmetic operations that ca n be eva lu ated to
yie ld a number is called a numeric express ion. Express io ns are eva luated by replac ing each
vari ab le by its va lu e and ca rrying out the ari thmetic. Some examples of exp ress ions are
2 * di tance + 7, n + 1, and (a+ b) / 3.
Example 2 The fo llowing program di plays the default va lue of a variable and the valu e
of an express io n:
[Run , and then click on the button . T he fo llowing is di splayed in the list box .]
0
3
25
var = expression
58 • Chapter 3 Va ri ables, Input, and O utput
first evaluates the express ion on the right and then ass igns its va lue to the vari able on the left.
For instance, the event procedure in Example 2 can be written as
The expression a* (2 + b) is evaluated to 25, and then this valu e is ass igned to the vari able c.
var = var + 1
is meaningful. It first eva luates the ex press ion on the right (that is, it adds 1 to the value of the
vari able var) and then ass igns this sum to the variable var. The effect is to increase the va lue of
the variab le var by 1. In terms of memory loca tions, the statement retrieves the va lue of var
from var's memory location , uses it to compute var + 1, and then places the sum back into var's
memory location. This type of calculatio n is so common that Visual Bas ic provides a special
operator to ca rry it out. The statement var = var + 1 can be replaced with the statement
var += 1
var += n
The terms insid e the paren theses ca n be numbers (as shown) , numeric variab lls, or numeric
express ions. Exp ress ions are first eva luated to produ ce the mput.
Example 3 The following program eva lu ates each of the fu nctions fo r a pec ific inp ut
given by the va lu e of the variable n:
[Ru n, and then click on the Compute button . The fo ll owing is displayed in the list box.]
2.6
6
6.8
Example 4 The fo llowing program eva lu ates each of the preceding funct ions within an
express ion:
[Run, and then click on the butto n. The fo llowing is disp layed in the list box.]
4
8
0.667
and can be ass igned onl y who le numbers from about -2 billion to 2 billio n. Intege r var iables
are co mmo n ly used for counting.
60 • Chapter 3 Va riab les, Input, a nd O utput
Multiple Declarations
nt. Fo r in tance,
Severa l variables of the sa me type can be decla red with a single Dim stateme
single stateme nt
the two Dim sta tements in Exa mp le 2 can be rep laced by the
Dim a, b As Do ub l e
Example 5 The follow ing program convert s 41 inch es to 3 feet and 5 inches.
.C lick
Private Sub b t nCompu t e _ Cli c k( ... ) Handle s btnCom pute
Dim totalin c hes , fe e t , inches As Intege r
t otalinc hes = 41
feet = to t alinc hes \ 1 2
i n c hes = t otalinc he s Mod 12
l stResu l t s.Items .Add ( feet )
l stResu l t s . I t ems .Add(in c hes)
End Sub
box.]
[Run, and then click on the button. The follow ing is displaye d in the list
3
5
Parentheses
ion. When there are
Parenth eses should be used when needed to clarify the meanin g of an express
the order expone ntiation , multipli ca-
no parentheses, the arithme tic operatio ns are petform ed in
i on. In the event of a
tion and ord inary division, intege r division, Mod, and add it ion and subtract
parenth ese liberally,
tie, the leftmost ope ration is carried out first. See Table 3. 1. Note: If you use
you will not have to rely on the precedence table for arithmetic operations. For instance, write
(2*3) + 4i nstead of 2 * 3 + 4.Write (2 i\ 3) + 4instead of 2 A3 + 4.
Parentheses ca nnot be used to ind icate mul tiplicat ion , as is common ly done in algebra. For
instance, the expression x(y + z) is not va lid. It must be written as x * (y + z).
Also, a ye llow arrow wi ll appear at the left side of the li ne of code that ca used the error. A t that
po int, you should end the program.
A third type of error is called a logic error. Such an erro r occurs when a program does not
perform th e way it was intended. For instance , the line
a v erage = firstNum + secondNum I 2
is syn tac tically correct. H oweve r, an incorrect value will be generated, since the correct way to
calculate the average is
a v erage = ( fi r stNum + second Num) I 2
Logic errors are th e most difficult type to find. Append ix D d iscusses debugging too ls that ca n
be used to detec t and correct logic erro rs.
Example 6 The following program co ntains three errors. Note: Line 1 co nta ~ns the Pub-
lic C lass statement and line 2 is a blank line. T herefore, the Private Sub statement is in line 3
and the Dim statemen t is in line 4.
[Run, click on the button, and click on the No button in the error di a log box that appears. ]
·~X
Error List
3 Errors f 0 tVarning s i) 0 Mes,sage
Comments
1. Declaring variables at the beginning of each event procedure i regarded as good programming
practice, because it makes programs ea ier to read and helps prevent certain types of error .
2. Keywords (reserved words) cannot be u ed as names of variables. Fo r in tance, the state ments
Dim private as Double and Dim sub As Double are not valid.
3. Names given to variables are sometimes referred to as identifiers.
4. In math courses, literals are referred to as constants. H owever, the word "constant" has a special
meaning in programm ing languages.
5. Numeric literals used in express ions or ass igned to variab les must not contain commas, dollar
signs, or percent signs. A lso, mix ed numbers, uch as 8 1/2, are not allowed.
6. A lthough requesting the square root of a negative number does not terminate the execution
of the program, it can produce unexpecte d resu lts. For instance, the statement
lstBox.It ems.Add (Math.Sq rt(-1))
8. When n is halfway between two success ive who le numbers (such as 1.5 , 2.5, 3.5, and 4.5 ),
then it round to the neares t even number. For instance, Math. Round (2.5) is 2 and
Math.Rou nd (3.5) i 4.
9. In scientific notatio n, numbers are written in the form b · lOr, where b is a number of mag-
nitude from 1 up to (but not includ ing) 10, and r is an integer. Visual Basic di plays very
large number in scientific notation, where b · lOr is written as bEr. (The letter E is an
abbrev iation for exponent.) For instance, when the state ment lstBox. Items .Add ( 123 *
10 A15) is executed, 1. 23 E+ 17 is displayed in the list box.
10. If the tota l number of items added to a list box exceeds the number of item that can bed is-
played, a vertical croll bar i aut matica lly added to the li t box.
11. When you first enter a stateme nt such a Dim n As Double, a green sq uigg le will appear
under the variable name and the Error List window wi ll record a warning. The squ igg le
3.1 Nu mbers • 63
merely indicates that the variable has not yet been ass igned a va lue.
If the squiggle i still
presen t after the en tire event proced ure has been entered, this will
te ll you that the va ri ab le
was never used and that the declara t ion statement should be remove
d.
1. Evalua te 2 + 3 * 4.
2. Explain the d iffe rence betwee n the ass ignmen t statemen t
varl = var2
and the ass ignmen t statement
var2 = varl
3. Co mplete the tab le by filling in the va lue of each va riable after each
li ne is execut ed.
a b c
Privat e Sub btnEv aluate Click ( ... ) Handle s btnEv
aluate .Click
Dim a, b, c As Double
0 0 0
a = 3
3 0 0
b = 4
3 4 0
c = a + b
a = c * a
ls tResu lts .I tems.A dd(a - b)
b = b * b
End Sub
y = 3 * X
X - y + 5
lstRe sults .Item s.Cle ar()
lstRe sults .Item s.Ad d(x + 4)
y - y + 1
End Sub
30.
bal inter withD r
61. The fo llowing steps calculate the price of an item after a 30% reducti on:
(a) Declare all variables as type Double .
(b) Ass ign the value 19.95 to the variable JJrice.
(c) Ass ign the va lue 30 to the variable discountPercent.
the variab le
(d) A ssign the value of (discountPercent divided by 100) times price to
markdown.
(e) Decrease price by markdown.
(f) Display the value of price (rounded to two decima l places ) in a list box.
of units of goods
62. The followin g steps ca lculate a company's break-e ven po int, the number
the compan y must manufacture and sell in order to break even :
(e) A sign the value fi xedCos ts divided by (the difference of price PerUnit and costPerUnit)
to the variable breai<EvenPoint .
(f) D i play the va lue of the variable breakEvenPoint in a list box.
63. The follow ing steps calculate the balance after three years when $ 100 is depos ited in a sav-
ings acco unt at 5% interest co mpounded annu ally:
(a) Declare all variables as type Double.
(b) A sign the value 100 to the variable balance.
(c) Increase the va riable balance by 5% of its va lu e.
(d) Increase the variable balance by 5% of its value.
(e) Increase the va riable balance by 5% of its value.
(f) D i play th va lu e of balance (rounded to two dec ima l places ) in a list box.
64. The follow ing steps calcu late th e balance at the end of three year when $ 100 is depos it d
at the beginning of each yea r in a sav ings account at 5% interest co mpounded annu ally:
(a)Declare all va riab le as type Do uble.
(b)Ass ign the value 100 to the variable balance .
(c)Increase the variable balance by So/o of its va lu , and add 100.
(d)Increase th e va riable balance by 5% of its va lue, and add 100.
(e)Increase the variab le balance by So/o of its va lue.
(f)Disp lay the va lue of balance (round ed to two dec ima l places ) in a list box.
65. The fo llowing steps calculate the balance after 10 years when $ 100 is depos ited in a savings
account at 5% interest compound ed annu a lly:
(a) Declare a ll va riab les as typ Double.
(b) As ign the va lue 100 to t he variable balance .
(c) Multiply the variable balance by 1.05 ra ised to the l Oth power.
(d) D isp lay the va lue of balance (round ed to two dec imal places ) in a list box.
66. The fo llow ing steps calculate the percentage profit from the sa le of a stock:
(a) Declare all va riables as type Double.
(b) Ass ign the va lue 10 to the variable fJurchase Price.
(c) Ass ign the va lu e 15 to the va riable sellingPrice .
(d) A ss ign , to the vari able percentPro fit , 100 times th va lu e of the difference between
sellingPrice and purchase Price d ivided by fJurchasePri ce .
(e) Display th e va lue of the variable percentProfit in a list box.
In Exercises 67 through 72, write a program to solve the problem and display the answer in
a list box. The program should use variables for each of the quantities .
67. S uppose each acre of farmland produces 18 tons of co rn. H o w man y tons of corn can
be
prod uced on a 30-acre fa rm ?
68. S uppose a ball is thrown stra ight up in the air with an initial ve locity of 50 feet per second
and an ini tial he igh t of 5 feet. H ow high will the ba ll be after 3 seco nds?
Note: The he ight after t econds i given by the ex pres ion - 16t 2 + v t + h , where v is
0 0 0
the initia l velocity and h0 is the initia l he ight.
69. lf a ca r left Washingt on , D.C., at 2 o'clock and arrived in N ew Yo rk at 7 o'clock, what
was
its ave rage speed ? Note: New Yo rk is 233 miles from Washingt on.
70. A motorist wants to determine her gas mileage. At 23,3 52 miles (on the odo meter)
the
ta nk is fi lled. A t 23,695 miles the tank i fill ed aga in with 14 ga llons. H ow many miles pe r
ga llo n did the ca r average between the two fillings?
68 • Chapter 3 Variables, Input, and O utp ut
a b c
3.2 Strings
strings. Senten ces,
The most commo n types of data processed by Visua l Bas ic are numbers and
, and social security
phra es, words, letters of the alphabe t, name , telepho ne number s, addresse
e of ch aracters that is
numbers are all exampl es of strings. Formall y, a string literal is a sequenc
d in text boxes and
treated as a single item. S tring litera ls can be ass igned to vari ables, displaye
nation (d enoted by&).
list boxes, and combin ed by an operatio n called concate
ass igns the string literal xy . . . z to the variabl e and the statement
or
l 'i( l...;a...J
Optio ns
_-Jl [
..___o_ K Ca ncel
Show all settings
and
and
Example 2 The fo llow ing progra m add s two numb ers suppl ied by
the user.
Second
number: 55
Compute Sum
Sum : 100
Auto Correction
The A u to Corre ction featur e of lntelliSe nse sugges ts
correc tions when erro rs occur and allows
yo u to se lect a correc tion to be app lied to the code.
When an inva lid statem ent is entered, a
blue squigg ly erro r line appea rs under th e incorr ect
part of the statem ent. If the squigg ly line
has a short red lin e segme nt at its right end, the A uto
Corre ction featur e is ava ilable fo r the
error. Whe n you h over the curso r ove r the sq uigg ly line,
a sma ll Error Co rrectio n Optio ns box
(~ ) appea rs. C lickin g on the small box produ ces an Au
to Corre ction helpe r box that descri bes
the error and makes a suggestion fo r fixing it. Figure 3.2
shows a typ ical A uto Corre ction h elper
box for a data-t ype-c on vers io n error. If you click on
the line begin ning "Replace," the change
will be made for you.
72 • Chap ter 3 Varia b les, In put, a nd O utput
Concatenation
g cons isting of the strin g jo ined together. The
Two strin gs can be comb ined to form a new strin
is repre sented by an am per and ( &) . For
jo ining ope ratio n is called conc atena tion and
inat ion of tr ings and ampe rsands that can be
insta nce, "good" & "bye" is "goodbye". A comb
essio n. The ass ignm ent state ment and the Add
evalu ated to fo rm a strin g is called a strin g expr
them or d isplay ing them .
meth od evalu ate exp ressio ns before ass igning
The statement
will appenJ the value of strVar2 to the end of the current value of strVar. The same result ca n
be acco mplished with the statement
String Properties and Methods: length Property and ToUpper, Tolower, Trim,
lndexOf, and Substring Methods
We h ave seen that controls, such as tex t and list boxes, have propertie and methods. A control
placed o n a form is an exa mple of an obj ect. A string is also an obj ect, and, like a control, has
both properties and meth ods that are specified by following the string with a period and the
n ame of the property or method. The Length property gives th e number of characters in a
tring. Th e ToUpper and ToLower meth ods co nvert a string to uppercase and lowercase char-
acte r . The Trim method de letes a ll lead ing and trailing spaces from a string. The Substring
method ex tracts a seq uence of consecutiv e ch aracters fro m a string. The Ind exOf method
ee1 rche for the first occurrenc e of one string in ano ther and gives the pos ition at which the
first occurrenc e is fou nJ .
If str is a string, then
str.Leng th
str.ToUp per
str.ToLow er
str.Trim
is the string with all spaces removed from the front and back of th e string. Fo r instance,
In Visual Bas ic, the position of a character in a string is identified with one of the numbers
0, 1, 2, 3, ... . (In this textbook we will see several instances of enum erati on beginning with 0
instead of 1.) A substring of a string is a sequ ence of consecutiv e ch arac ters from the string. For
instance, consider the string "Just a mo ment". The substrings "Jus", "mom", and "nt" beg in at
positions 0, 7, and 11 , respective !y.
If str is a tring, then
str.Subst ring(m, n)
is the substring of str consisting of 11 characters beginning with the character in pos ition m of str.
If the co mma and the number 11 are omitted , then th e substring starts at pos itio n m and contin-
ues until the end of str. The value of
str.Index 0f(str2)
74 • Chapter 3 Va ri ab les, In put, and O utput
str2, n) , where n
The Index Of method has a useful exte nsion. The va lue of str. IndexO f (
n n or greater. For
is an integer, is the position of the first occurre nce of str2 in str in po itio
instance , the va lue of "Missi ssippi" . IndexO f ( "ss", 3) is 5.
s also can be
Like th e num eric function s di scussed before, string properti es and method
app lied to variables and exp ress ions.
Example 5 The fo llow ing program uses variab les and expressions with th e propert y and
method s just discussed .
lick
Private Sub btnEva luate Click( . .. ) Handle s btnEva luate.C
Dim str1, str2, str3 As String
str1 = "Quick as "
str2 = "a wink"
lstRes ults.Ite ms.Cle ar()
lstResu lts.Item s.Add( str1.Su bstring (O, 7))
lstResu lts.Item s.Add( str1.In dexOf( "c" ))
lstResu lts.Item s.Add( str1.Su bstring (O, 3))
lstRes ults.Ite ms.Ad d((str1 & str2) .Subst ring(6, 6))
lstRes ults.It ems.A dd((str l & str2) .ToUpp er)
lstResu 1ts.Ite ms.Ad d(str1. Trim & str2)
str3 = str2.Su bstring (str2.L ength 4)
lstResu 1ts.Item s.Add( "The averag e " & str3 & " lasts .1 second ." )
End Sub
box.]
[Run, and then click on the button. The fo llow ing is di played in the list
Quick a
3
Qui
as a w
QUICK AS A WINK
Quick asa wink
The averag e wink lasts .1 second .
Example 6 The follo wing program parses a name. The fifth line locates the pos ition,
n charact ers, and
call it n, of the space separati ng the two names. The first nam e will contain
the last name wi ll cons ist of all charact er to the right of the nth charact er.
lick
Private Sub btnAna 1yze_ Click( ... ) Handle s btnAna lyze.C
Dim fullNam e, firstNa me, lastNam e As String
Dim m, n As Intege r
fullNam e = txtNam e.Text
3.2 trings • 75
t of the form
is va lid . However, a narr owin g tate men
intV ar = dblV ar
Dim m As Inte ge r
m 2 3
m = 6 I 2
o r iden tify-
use va riables of type Integer fo r coun ting
In orde r to avo id such erro rs, we prim arily
ing pos ition s.
Internal Documentation
nt of the pro-
io n of com men ts that spec ify the inte
Prog ram doc ume ntat io n is the inclus l port ions of the
the tas ks perf orm ed by indi v idua
gram, the purp ose of the va riabl es, and S uch a state -
t, beg in the line with an apos trop he.
prog ram. To crea te a co mm ent state men is exec uted .
is co mpl ete ly ign o red whe n the prog ram
men t appe a rs gree n on t he sc ree n and addi ng an
. A line of code can be doc ume nted by
Com me nts are so met imes ca lled rem arks ne. The Com men t
rma t io n , aft er the e nd of the li
apos trop he, fo llowed by the desi red info used to com -
butt o n ( "l ) o n the Too lba r ca n be
Out butt on ( ·=:: ) a nd th e Unc omm ent
of code .
men t and unco mm ent selec ted bloc ks
line Continuation
Tho u ands of char acte rs can be typed in
a line of code. lf you use a state men t with
acte rs than can fit in the window, Visu more ch ar-
al Basic scro lls the Cod e Edit or towa rd
need ed. However, mos t programmers pref the righ t as
er havi ng lines that are no longe r than
the Cod e Editor. A long state men t can the widt h of
be split acros two or more lines by endi
(exc ept the last) with an und ersco re ch ng each line
arac ter ( _ ) prec eded by a space. For insta
nce, the line
Dim quo tati on As Stri ng= "Goo
d code is its own bes t doc ume
ntat ion. "
can be writ ten as
Dim quo tati on As Stri ng "Goo d code is its own " &
"be st doc ume ntat ion. "
( Push Me
Comments
ng the mo use
rmin e the type of a variab le by letti
1. From the Cod e Edit or, you can dete Thi s feat ure of
unti l a too lt ip giving the type appe ars.
poin ter hov e r ove r the vari able name
lnte ll iSen se is ca lled Qui ck Info .
mm ers use a pre-
Va riab le nam es shou ld desc ribe the role of the var iable. A lso, so me progra
2. wou ld use nam es
type of a vari ab le. For examp le, they
fix, such as dbl o r str, to iden tify the t need ed in Visu al Basic
Thi s nam ing con ven tio n is no
like dbll nterestRate and strFirstN ame. Mic rosoft.
t 1, and is no longer reco mm nde d by
for the reason men t ioned in Com men
ber into a text box
use r friend ly. If the use r types a num
3. The func tion s C lnt and C Ob! are the va lues of
or inse rts com mas as sepa rato rs,
and precedes it with a doll ar sign llar sign and /or
lnt( txtB ox.T ex t) and CD bl(tx tBox .Tex t) wi ll be the num ber with the do
C
com mas rem oved.
es use r type spaces
adin g data from a tex t box . Som etim
4. The Trim met hod is useful wh n r hav oc elsewhe re in
s are rem oved, they can cause
at the end of the input. Unles the pace
the program.
For inst ance, th e
tr for cast ing a va lue to a strin g valu e.
5. The re are seve ra l a ltern atives to CS
state men t
strV ar = CSt r(db lVa r)
3.2 Strings • 79
(a) These funct ions make state ments less clutte red,
and therefore eas ier for begin ning pro-
gram mers to read.
(b) Whe n an inco rrect conv ersio n is detec ted by
the Code Ed ito r, the Aut9 Correction
helper box recommend s and imple ments the use of
the CStr, CDb l, and C lnt function .
34. The following steps comp ute the pr ice of ketch up:
(a) Decla re all variables used in steps (b)- (d).
(b) Ass ign "ketc hup" to the va riab le item.
(c) Assig n 1.80 to the variab le regularPrice.
(d) Ass ign .27 to the va riab le discount.
"
(e) D isp lay the phrase "1.53 is the sa le price of ketch up.
t:
35. The following steps display a copyright sta temen
(a) Decla re the variab le used in step (b).
(b) Ass ign "Pren tice H all, Inc." to the vari able publish
er.
(c) Display the phras e "(c) Prent ice H all , Inc."
Compute Distance
Compute THR
The distance of the storm is 0.25 miles . Your T H R is 161 beats per minute .
Sample outpu t of Exercise 39. FIGURE 3.4 Sampl e outpu t of Exerc ise 40.
FIGURE 3.3
0.6 pounds were lost . The Yankees won 56.66 7 percent of their
games .
FIGURE 3.5 Sam ple outp ut of FIGURE 3.6 Sam ple outp ut of
Exer cise 41.
Exer cise 42.
42. Wri te code to read the nam e of a
base ball team, the num ber of gam es won
of ga mes los t, and disp , and the num ber
lay the nam e of the team and the pe rce
ple run is show n in Fig. 3.6. ntage of gam es won . A sa m-
verage
score :
5
Dim x As Dou ble = "23" Repl ace "'2 "' with 'CDbl("23")'.
ext) '.
dblV ar txtB ox.T ext Repl ace 'txtBox.Text' with 'COb !( txtB ox.T
Replace '2 & 3' with 'CDb l(2 & 3)'.
dblV ar = 2 & 3
3.3 Input and Outpu t
• 85
FUNCTION
STRING VALUE
Forma tNumb er(1 + Math .Sqrt( 2), 3)
2.414
Forma tCurre ncy(-1 000)
($1,00 0.00)
Form atPerc ent(". 05")
5.00%
9L_ == ==
(a) (b)
l 'Y 1- .n. J
Inpu Mask
Preview:
[ OK l[ Cance l )
Toda y
c Bi rth Data
l= I[§J I. --"'2. .I
Compute Data
ente r 4/6/1992
[Ru n, clic k on the button, ente r Emm
a Smith into the first inpu t dialog box, and
into the seco nd inpu t dia log box.]
Title Consolation
OK
Named Constants
prog ram xecu -
a prog ram uses a spec ia l con stan t whose value doe n ot cha nge duri ng
Ofte n nam e of a mas ter
imu m wage, the sales tax rate, and the
tion . So me exampl es mig h t be the min
3.3 Input and O utput
• 91
whe re 100
va lues of x and y are spec ified in poin ts,
page of the begi nning of the string. (The po ints from the left
c inde nt all text by abou t 25
poin ts are abou t one inch .) Visual Basi left side
will be prin ted x + 25 po ints from the
side of the page. The begi nnin g of the tring wi ll be
. Two diffe rent ways of spec ifyin g the font
and y poin ts from the top ide of the page
give n in the example that follows.
5. Place the state men t
Prin tDoc ume nt1 . Prin t()
t will
on's C lick eve nt procedur e. (Thi s state men
in anot her eve nt proced ure, such as a butt
be prin ted.)
ca use all of the tex t spec ified in step 4 to
ts are as follows. The state men t
Some exa mp les of DrawStri ng state men
150)
Me .Fon t, Bru shes .Dar kB1 ue, 100,
gr.D raw Stri ng( "HELLO WORLD" ,
inch es from
g the form's font in dark blue lette rs 1.25
prin ts the words HELLO WO RLD usin men ts
the top of the page. The pa ir of state
the left side of the page and 1.5 inch es from
r New" , 12, Fon tSty le .Bol d)
Dim font As New Fon t ( "Co urie 150)
fon t, Bru shes .Dar kBlu e, 100 ,
gr.D rawS t ring ( "HELLO WORLD" ,
bold Co urier N ew font.
produce the same outpu t usin g a 12-po int s you
Prin tPre view Dial og cont rol, whic h allow
Visual Bas ic prov ides a control, called the step :
end it to the prin ter. Just fo llow two
to ee how outp ut will look befo re you
cont ro l in the All Windows Forms or Prin
ting grou p
1. Double-click on the Prin tPrev iewDialog 1 in the
with the defau lt name Prin tPrev iewDialog
of the Too lbox. (Th e cont rol will appear
Designer.)
co mpo nent tray at the bott o m of the Form
2. Place the pair of state men ts
Prin tPre view Dial og1 .Do cum ent
= Prin tDoc ume nt1
wDi alog ()
Prin tPre view Dia log1 .Sho
tatem ents
button's C lick even t procedu re. These
in anot her eve nt proced ure, such as a di splayed
ume ntl _PrintPage even t proced ure to be
ca use the text spec ified in the Prin tDoc ow's
nt procedu re is invo ked . The prev iew wind
in a "Print prev iew" window whe n the eve
too lba r co ntains a mag nifying-g la s butt
on ( p T)
that allows you to zoom in on the text.
Comments
1. A va ria tion of the DateD iff functi on discu sed ea rlie
r is DateD iff (Date inter val . Year,
d1, d2) whi ch gives the numb er of yea rs (so
rt o f) betwe en the two da tes. It is of limite d
va lue, since it only uses the year pa rts of the two dates
in its co mp uta tion.
2. The sectio n "Use the Printe r" in A ppe ndix B shows
h ow to print a progra m and a fo rm .
EXERCISES 3.3
t produ ced by the lines of code.
In Exerc ises 1 throu gh 4 8, deter mine the outpu
1. txtOu t put.T ext Form atNu mber (l234 .56, 0)
16. txtO utpu t . Text Form atCu rrenc y(32 * (10 A 2))
29. txtO utpu t.Tex t "The likel ihoo d of Head s is " &
Form atPe rcen t(l I 2, 0)
, 4)
30. tx t Outp ut.Te xt "Pi = " & Form atNu mber (3.14 1592 6536
64. Pop up a message dia log box with "Taking R isks Prove rb" in the title bar and th e message
"You can 't steal second base and keep o ne foot on first."
In Exercises 65 and 66, write an event procedure with th e header P r ivate Sub bt n com -
and h aving one, two, or th ree lines for each
pute cl i ck ( ... ) Handle s b t nComput e . Click,
step.-Lines that display data should use the given va riable names.
65. The following steps calcu late the percent increase in the cost of a typical grocery basket of goods:
(a) Decla re all variab les used in the steps that follow.
(b) Assign 200 to the variab le begOfYearCost.
(c) Req uest the cost at the end of the yea r with an input dialog box, and a sign it to the
va riable endOfYearCost.
(d) Ass ign (endOfYearCost- begOfYearCost) / begOfYearCost to the variab le JJercentlncrease .
(e) Display a sentence giv ing the percent increase for the year.
(Test the program with a $2 15 end -of-yea r cost. )
66. The following steps calculate the amo unt of money ea rned in a wa lk-a-tha n:
(a) Declare a ll var iab les used in the teps that follow.
(b) Request the amou nt pledged per mile fro m an input dia log box, and ass ign it to the
variab le pledge.
(c) Request the number of miles walked from an input dia log box, and ass ign it to the vari-
ab le miles.
(d) Disp lay a sentence giving the amo unt to be paid.
(Tes t the program with a pledge of $2.00 per mile and a 15-mile walk.)
67. Write a program that requests a year in a masked tex t box and then displays th e nu mber of
days in the year. Hint: Use the A ddYears method and the DateDiff functio n.
68. Write a program that calculates the number of days since the Declaration of Independence
was ratified (7/4/1776).
69. Write a program that reques ts a date in a masked text box, and then displays the day of the
wee k (such as S und ay, Mo nday, ... ) for that date.
70. Write a program that req uests a date as input and then displays the day of the week (such as
S und ay, Monday, . .. ) for that date ten years hence.
71. Write a program that reques ts a mo nth and a yea r as input and then displays the number of
days in that month. Hint: Use the AddMonths method.
72. Write a program that req uests the use r's da te of bi rth and th en disp lays the da y of the
week (such as S und ay, Mo nd ay, . . . ) o n which th ey will h ave (or h ad) the ir 21 st
birthday.
73. Design a form with two text boxes labeled "Name" and "Phone number". Then wr ite an
eve nt procedure that shows a message d ia log box stating "Be sure to include the area code!"
when the second text box receive the foc us.
74. Write a program to calcu late the amount of a se rver's tip given the amo unt of the bill and the
percentage tip obta ined via input dialog boxes. T he output should be a complete sentence
that reiterates the inputs and gives the resulting tip, as shown in Fig. 3.14 on the nex t page.
75. When P dollars a re depos ited in a sav ings acco unt at interest ra ter co mpo und ed a nnu -
a lly, the ba lance aft er n yea rs is P ( 1 + r)". W rite a program to req ues t the principal P VideoNote
Mortgage
and the inte res t ra ter as input, a nd co mp ute the ba lance after 10 yea rs, as sh own in
ca lcu lator
Fig. 3. 15 on the next page. (H omework)
98 • Chapter 3 Variab les, Input, and O utpu t
Principal:
Compute Balance
Enter Data
76. Write a program to print the list of Interne t lingo in Fig. 3 .16.
PLS Please % of
TAFN That's all for now Rank Countr y WW Users
HHOK Ha, ha - only kidding 1 USA 16.0%
FWIW For what its worth 2 China 11.9%
IMO In my opinion 3 Japan 6.5%
FIGURE 3.16 Output of Exercise 76. FIGURE 3.17 Output of Exercise 77.
age of worldwide
77. Write a program to print the top three ranking counties by the percent
Interne t u er they contain as shown in Fig. 3.17.
CHAPTER 3 SUMMARY
numbers, strings,
1. Three types of literals that can be stored and processed by Visual Basic are
and dates.
the content of a
2. Many Visual Bas ic tasks are carried out by method s such as C lear (erases
ts a string to
text box or list box), Add (places an item into a list box), ToUppe r (conver
Trim (remove s lead ing and trailing
uppercase), Tol ower (converts a string to lowercase ),
and gives its pos i-
spaces from a string), lndexO f (searches for a specified substrin g in a string
from a string).
tion if found), and Substrin g (produces a sequence of consecutive charact ers
ion is&, con-
3. The arithmetic operations are +, -, *,/,A,\ , and Mod. The only string operat
, variab les, function s, and operat ions
catenat ion. An expression is a combin ation of literal
that can be evaluat ed.
letter or an under-
4. A variable is a name used to refer to data. Variable names must begin with a
score and may contain letters, digits, and underscores. Dim stateme nts declare variables,
Summ ary
• 99
12. The Date data type fac ilitates comp utatio ns invo lving
dates.
13. An input dialog box is a windo w that pops up and
displays a message fo r the user to respon d
to in a tex t box. The respo nse is ass igned to a
variable.
14. A message dialog box is a wind ow that pops up
to display a message to the user.
15. Named constants sto re va lu es that canno t change durin
g the execu tion of a progra m. They
are decla red with Cans t statem ents.
l= 1-£1 -~J
ll _. Calcu lator l = I @) l,...tJ J a ~ A -1 Auto Repai r
@)
21 D 77
Cost of parts
and supplies :
84.55 Bill
J
21 ll 77
w
= 1 617
Custo mer
Labo r cost
Paz:ts cost
Tota l cost
John oe
$ 1 22.50
$88 . 78
$211 . 28
Yards : 20
( Determine Composition of Change ) The metric length is
8 kilometers
Feet : 2 65 meters
Quarters : 3 Dimes :
73.5 centim eters .
Inches : 4
Nickels : Cents : 3
meters into a whole number of kilomet ers and meters. The number of centime
ters should
be d i played to on e dec imal place. The needed formulas are as foll ows:
Location : Milwaukee . WI
Meals and entertainment : 19 .10
Lodging : 675.35
Taxi fares : 45
FIGURE 3.22 Form with sample data for Program ming Proj ect 5.
FIGURE 3.23 Output for sample run of Program ming Proj ect 5.
De cis ion s
103
104 • Chap ter 4 Dec isio ns
ANSI Values
riter porti on of the keyb oa rd ca n produ ce two
Each of the 4 7 diffe rent keys in the cente r typew ba r
ng 1 for the character prod uced by the space
chara cte rs, fo r a tota l of 94 characters . Addi m 32 to 126.
chara cters are numb ers rang ing fro
makes 95 characters. Associate d with these A.
lu es of the chara cte rs, are give n in Appe nd ix
These va lu es, calle d the A N SI (or ASC II) va
Table 4.1 shows a few of them .
Chr (n)
I va lue n. If str is any stri ng, th en
is the strin g cons isting of the character with ANS
As c ( s t r )
tx t Bo x. Tex t = Chr (6 5)
state ment
displays the lette r A in the tex t box, and the
txtB ox.T ext = 32 & Chr( 176) & " Fah renh eit"
disp lays 32° Fahrenh eit in the text box.
The quot atio n-m a rk char acte r ( • ) can
be plac ed in to a strin g by usin g C hr(3
4 ). Fo r exam -
ple, after the sta tem ent
tx tBo x.Te xt = "Ge orge " & Chr( 34) & "Bab e"
& Chr( 34) & " Ruth "
is exec uted , the text box cont ains
Geo rge "Bab e" Ruth
Relational Operators
The relat iona l operator less than ( <)
can be app lied to num bers, strings, and
ber a is sa id to be less than th e num date s. The num -
ber b if a lies to the left of b on the Vidco Notc
insta nce, 2 < 5, -5 < -2, and 0 < num ber line. For
3.5. Relati onal
The strin g a i sa id to be less than the anJ logical
strin g b if a prec ede b a lpha bet ica lly whe
ANS I tab le to a lpha betiz e the ir valu n usin g the operators
es. For insta nce, "cat " < "dog", "car
"cat " < "cat a log". Digits prec ede uppe t" < "cat", and
rcase lette rs, whic h prec ede lowerca e lerte
ar com pared work ing from left to righ rs. Two strin gs
t , char acte r by char acte r, to dete rmin e
prec ede the other. The refore, "9W " < wh ich one shou ld
"bat ", "Do g" < "cat ", and "Sales-9 9"
The date dl is sa id to be less than < "Sa les-r etail ".
the date d2 if dl prec ede d2 chro no
insta nce, # 12/7 /194 1 ;;- < #6/6 / 1944#. log ica lly. For
Tab le 4.3 shows the d iffe rent re latio nal
operato rs and thei r mea nings.
lt!1:J!IIM Relational operators .
Visual Basic Num eric String Date
Nota tion Meaning Meaning Meaning
equa l to identical to sa me as
<> not equa l to different from
< different than
less than precedes alphabet ica ll y
> precede chro nolog ica ll y
greater than foll ows alphabeticall y
<= foll ow chro nologica ll y
less than or equa l to precedes alphabetically precedes chro nologica lly
or is identi ca l to or is the same a
>= greater than or equa l to fo ll ows alphabetica lly fo llows chro nologica ll y
or is iden tica l to or is the same as
SOlUTION
(a) True. The no tatio n <= mea ns
"less than or equa l to." Tha t is, the cond it io n i tru e
vide d e ithe r of the two c ircum stan ces pro-
ho lds. The seco nd o ne (equal to) ho lds.
(b) False. The nota tion < mea ns "stri
ctly less than " and no num ber ca n be
itse lf. stric tly less than
106 • Cha pter 4 Dec ision s
To de term ine
s, num eri c ope rato rs, and func tio ns.
Con ditio ns also ca n in vo lve vari able ress ion s and then
first eva luat e the num eric or strin g exp
whe ther a con d ition is tru e o r false,
e o r false.
dec ide if the resul ting asse rtion is tru
(a) (a + b) < 2 * a
(b) (c.Length - b) = (a/2 )
(c) c < ("good" & d )
SOLUTION
ditio n is true.
valu e of a + b is 7 and the valu e of 2 *a is 8. Because 7 < 8, the con
(a) The
- b is 2, the sam e as (a / 2) .
(b) True , beca use the va lu e of c.Le ngth
the AN SI tabl e.
e" is fal e, beca use "h" follows "g" in
(c) The co ndit ion "hello" < "goo dby
logical Operators
e con side red so far.
more complex con ditio ns than thos
Prog ram min g situ atio ns ofte n require variable, n , is stric tly
to stat e that t he va lue of a num eric
Fo r insta nce, supp ose we would like
ic con ditio n is
betw een 2 and 5. The proper Visual Bas
con dl Or cond 2
ditio n
) is tru e. O therwise , it is fa lse. The con
is tru e if eith er condl or cond 2 (or both
Not con dl
l is true.
is true if cond l i false, and is fa lse if cond
4.1 Relationa l and Logical Operators
• l07
Example 3 Supp ose the nume ric varia ble n has value 4 and the
string variable answ has
value "Y". Dete rmine whet her each of th follow ing
cond itions is true or fa l e.
(a) (2 < n) And (n < 6)
(b) (2 < n) Or (n = 6)
(c) Not (n < 6)
(d) (answ = "Y") Or (answ = "y")
(e) (answ = "Y") And (answ = "y")
(f) Not ( answ = "y")
(g) ((2 < n) And (n = 5 + 1)) Or (answ ="N o")
(h) (( n = 2) And (n = 7)) Or (an w = "Y")
(i) (n = 2) And ((n = 7) Or (answ = "Y"))
SOLUTION
(a) True, because the cond ition (2 < 4) and ( 4 < 6) are both true.
(b) True, because the co nditio n (2 < 4 ) is true. The fact that the cond ition ( 4 = 6) is fa lse
does not affect the conclusion. The only requireme
nt is that at least one of the two cond i-
tions be true.
(c) False, because ( 4 < 6) is true.
(d) True, because the first co nditio n become ("Y"
= "Y") when the va lue of answ is substi-
tuted for answ .
(e) False, because the second cond ition is false.
Actu ally, th is comp ound cond ition is fa lse fo r
eve ry va lue of answ.
(f) T ru e, because ( "Y" = " y") ts
· £1a lse.
(g) False. In th is logica l expression, the comp
ou nd cond ition ( (2 < n) And ( n = 5 + 1))
and the simple cond ition (answ = "No" ) are joine
d by th logica l opera to r Or. Beca use
both these cond itions are false, the tota l cond ition
is false.
(h) True, because the secon d Or clause is tru e.
(i) False. Co mparing (h) and ( i) shows the
necessity of using paren theses to specify the
inten ded gro uping .
Dim x As Integ er = 5
txtBo x.Te xt = CStr ((3 + x) < 7)
strin g
with ing. To gene ralize, if strVar2 is anot her
is true if and only if the valu e of strVar ends
variable, then the exp ression
(1)
- strV ar2. Len gth) = strV ar2
strV ar.S ubS trin g(st rVa r.len gth
A Boolean-Valued Function
box or
e if a va lue inpu t by the user, say in a text
The lsNu meri c func tion is used to dete rmin
mpu tatio ns. The value of
inpu t d ialog box, can be used in num eric co
Comments
1. A cond ition in vo lvin g num eric vari
ables is diffe rent from an algebraic truth
(a + b) < 2 *a, cons . The assertion
idered in Example 2, is not a va lid alge braic
for all va lues of a and b. W hen enco unte truth beca use it isn't tru e
red in a Vi ual Basic prog ram, however,
considered true if it i corr ect for the curr it will be
ent va lues of the varia bles.
2. Con ditio ns evaluate to eith er True
or False . Th ese two valu es ofte n are ca lled
trut h valu es of the cond ition. the possible
3. A cond ition such a 2 < n < 5 shou
ld neve r be used, beca use Visual Bas ic will
ate it as inte nded. The corr ect cond ition not evalu-
is (2 < n ) And (n < 5).
4. A com mon erro r is to replace the cond
ition Not (n < m) by the condit ion (n
corr ect rep lace men t is ( n > = m). > m). The
. Ass ume a = 2
whether the con ditio n is true or false
In Exe rcises 7 th rough 18, dete rmin e
and b = 3.
7. 3*a =2 *b
8. (5- a)* b < 7
9. b <= 3
10. a/\b = b/\a
11. a/\ (5 - 2) > 7
12. 3E- 02 < .01 *a
13. (a < b) Or (b < a)
14. (a *a < b) Or Not (a* a <a )
15. Not (( a< b) And (a < (b +a) ))
)
16. Not (a < b) Or Not (a < (b +a)
( b < a) And ( 2 * a < b))
17. ( (a = b) And (a * a < b * b) ) Or (
a< b) Or (b =a + 1))
18. ((a = b) Or Not (b <a )) And ((
.
e whether the con ditio n is true or false
In Exercises 19 through 3 0, dete rmin
19. "9W" < > "9w"
20. "Inspector" < "gadget"
21. "Ca r" < "Train"
22. "]" >= "]"
23. "99" > "ninety-nine"
24. "B" > " ?"
")
25. ("Duck" < "pig") And ("p ig" < "big
26. "Duck" < "Duck" & "Duck"
"))
27. N ot ( ("B" = "b") Or ("Big" < "big
28. # 7/4/177 6# >= # 7/4/ 1776#
29. #6/17/1775# <= # 7/4/177 6#
30. (7 < 34) And ("7" > "3 4")
are equi vale nt -
e whether or not the two con ditio ns
In Exercises 31 thro ugh 40, dete rmin ables appearin g
se for exac tly the sam e valu es of the vari
that is, whether they will be true or fal
in them.
31. a < = b; (a < b) Or (a = b)
32. Not (a < b); a > b
33. (a= b) And (a< b); a< > b
b) And (a <> c)
34. Not ((a = b) Or (a= c)) ; (a< >
35. (a < b) And ((a > d) Or (a> e));
And (a > e) )
( (a < b) And (a > d )) Or ( (a < b)
<> b) Or (a <> b +c)
36. Not (( a= b +c) Or (a= b)) ; (a
a > b)O r( a >c ))
37. (a< b + c)O r( a = b + c);N ot((
(a= b)
38. Not (a >= b); (a< = b) Or N ot
(a = b)
39. Not (a >= b); (a <= b) And Not
(a = b) Or ((b =c ) And (a= c))
40. (a = b) And ((b =c ) Or (a= c));
4.1 Relati onal and Logical O perato rs
• lll
4.2 If Blocks
a cert ain cond i-
on a course of actio n base d on whe ther
An If bloc k a llows a program to d cide
tion is t rue or false .
If Block
A bloc k of the form :
Video Note
If hloc ks If con diti on Then
acti on 1
Else
acti on 2
End If
Each actio n
cause the program to take action 1 if cond
ition is tru e and action 2 if condition is fa l e.
n cont inue s
ents . Afte r an actio n is take n, exec utio
consists of one or more Visual Basic tatem char t for an If block.
cont ains the pseudocode and flow
with the line after the If block. Figure 4.1
No Yes
k.
FIGURE 4.1 Pseu doco de and flow char t for an If bloc
II ~
Maximum l = I @l !;. ~- .I
OBJECT PROPERTY
aj A Quiz [EJ [@ ][ID SETTING
frmQ uiz Tex t A Qu iz
How many gallons does a lblQ uest io n A utoS ize Fa lse
ten-ga llon hat hold?
Tex t How man y ga llons does a
Evalu ate Answer ten-ga llo n hat ho ld ?
txtA nswe r
btnEva lu ate Tex t Eva luate Answ ~ r
txtSo lution Read O n ly True
on the button. ]
[Run , type 10 into the tex t box, and cl ick
in the
Thi impo rtan t type of If bloc k appea rs
The Else pa rt of an If bloc k can be omitted.
nex t exa mp le.
g-j Qu otati o n l= @)
is (Y/ N)? N
Do you know what the game of skittles
De mit ion
OK
[Press OK.]
Display Quotation
lick
k( • .. ) Han dles btn inte rpr et.C
Priv ate Sub btn inte rpr et_ Clic
'Int erp ret a wea ther bea con
Dim col or, mod e As Stri ng
col or = mtb Col or.T ext
mod e = mtb Mod e.Te xt
If mod e = "S" The n
If col or = "B" The n
VIEW"
t xtFo rec ast. Tex t = "CLEAR
Els e 'col or - "R"
txtF ore cas t.Te xt = "RA IN AHEAD"
End If
•mod e = 'F
11
Els e
If col or = "B" The n
txtF ore cas t.Te xt = "CLOUDS DUE"
Els e 'col or = "R"
II SNOW AHEAD II
txtF ore cas t.Te xt
End If
End If
End Sub
t boxe , and click on the butt on.]
[Run , type R and S into the mas ked tex
Mode (S or 5
( Interpret Beacon I
RAIN .HEA.D
[Run, type 9500 and 8000 in to the text boxes, and click on the button
.]
Costs : 95
Revenue : 8
Elself Clauses
A n ex tension of th e If block allows for more than two possible alterna
tives with the inclusion
of Elself clauses . A typical block of th is type is
If c onditi on 1 Then
a c tion 1
Elseif condi tion 2 Then
a c tion 2
Elseif condi tion 3 Then
a c t i on 3
Else
a c t i on 4
End If
Visual Bas ic ea rches fo r the first true condit ion, carries out its action
, and then skips to the
statement fo llowing End If. If none of the condit ions are true, then
Else's action is carried out.
Execution then contin ues with the statement following the block.
In genera l, an If block can
contai n any numbe r of Else If clauses. As before, the Else clause is
option al.
Example 6 The fo llowing program redoes Exa mp le 1 so that the progra m reports
if the
two numbe rs are equal.
Privat e Sub btnFin dLarg er_ Click( .. . ) Handle s btnFin
dLarg er.Cli ck
Dim numl, num2 As Double
numl CDbl (txtFir stNum . Text)
num2 = CDbl (txtSec ondNu m.Tex t)
11 8 • C hapter 4 Dec isions
[Run, type 7 into both tex t boxes, and press the butto n.]
Rrst numbe r: 7
Second numbe r: 7
[Run , type 12345 .67 and 543.2 1 into the top two text boxes and click
on the button.]
a .. R:CA. 1 axes
The fo llowing exa mple illustrates the fact that when an If block
contains Else lf clauses,
Visua l Ba ic executes the act ion correspo nd ing to the first condit ion
that is sa tisfi ed and ignores
all subseq uent cla uses-e ven if they also sa ti fy the conditi on.
Example 8 The fo llowing program assumes that the use r wi ll gradu ate (that
is, has a
GPA of 2 or more) and dete rmines if the user wi ll gradu ate with honors
.
Privat e Sub btnDe termin e_ Click( . .. ) Handle s btnDe
termin e . Click
Dim gpa As Double = CDbl ( txtGPA . Text )
Dim honors As String
If gpa >= 3 . 9 Then
honor s= " summa cum laude. "
Elseif gpa >= 3. 6 Then
honor s= "magn a cum laude. "
Elseif gpa >= 3 .3 Then
honors = " cum laude. "
Elseif gpa >= 2 Then
honors = " "
End If
txtOut pu t.Text "You gradua ted" & honors
End Sub
120 • Chapt er 4 Dec isions
[ Determine Honors J
can be sh o rte n ed to
If boolV al Then
ca n be sh o rte n ed to
d.Clic k
Priva te Sub btnAd d_ Click ( . . . ) Handl es btnAd
tNum . Text) And IsNum eric(tx tSeco ndNum .Text) Then
If IsNum eric(t xtFirs
+ CDbl (txtSe condN um.Te xt))
t x tSum. Text = CStr (CDbl (txtFi rstNu m.Tex t)
Elsei f Not IsNum eric ( txtFir stNum .Text) Then
If Not IsNum eric(tx tSeco ndNum .Text ) Then
has an impro per entry ." )
Messa geBox . Show( "Each text box is empty or
4.2 l f Blocks
• l 21
Else
Mess ageB ox .Show ( "The first text box
is empt y or has an impr oper entry ."
)
End If
Else
Mess ageB ox . Show ( "The secon d text box
is empt y or has an impr oper entry ."
)
End If
End Sub
~~ ~ Addit ion = @) ~ I
Rrst number: J
Second numbe r: two l··· ~ ,j
' lj
( OK ]
Comments
1. Care shou ld be taken to make If blocks easy to
und erstand. Fo r instan ce, in Fig. 4.2, the
block on the left is d ifficu lt to fo llow and shoul
d be rep laced by the clearer block on th e
righ t.
End If
End Sub
2. Impr ove the bloc k
If a < b Then
If c < 5 Then
txtB ox.T ext "hel lo"
End If
End If
EXERCISES 4.2
butt on
outp ut displayed in the text box whe n the
In Exer cises 1 thro ugh 12, dete rmin e the
is click ed.
) Han dles btnD ispl ay.C lick
1. Priv ate Sub btnD ispl ay_ Clic k( ...
Dim num As Dou ble = 4
If num < = 9 Then
txtO utpu t.Te xt "Les s than ten. "
Else
If num = 4 Then
txtO utpu t.Te xt "Equ al to four ."
End If
End If
End Sub
Han dles btnD ispl ay.C lick
2. Pr ivat e Sub btnD ispl ay_ Clic k( ... )
Dim gpa As Dou ble = 3 . 49
txtO utpu t.Cl ear( )
If gpa >= 3.5 Then
txtO utpu t.Te xt = "Hon ors "
End If
txtO utpu t.Te xt &= "Stu dent "
End Sub
) Han dles btnD ispl ay.C lick
3. Priv ate Sub btnD ispl ay_ Clic k( ...
Dim a As Dou ble = 5
txtO utpu t.Cl ear( )
If ( 3 * a - 4) < 9 Then
txtO utpu t.Te xt "Rem embe r, "
End If
txtO utpu t.Te xt &= "tom orro w is anot her day. "
End Sub
4.2 If Blocks • 123
10. Pr i vate Sub btnD i splay_ Click( ... ) Handles btnDispl ay.Click
Dim num As Double = 5
If num < 0 Then
txtOutpu t.Text nnegn
Else
If num = 0 Then
txtOutpu t.Text "zero"
Else
txtOutpu t .Text "positive "
End If
End If
End Sub
12. Pr i vate Sub btnCompu te_ Click( ... ) Handles btnComp ute.Click
))
Dim dateOfBi rth As Date= CDate(In putBox(" Enter your date of birth."
4.2 If Blocks • 125
a = 5
End If
18. If (j 7) Then
b = 1
Else
If (j <> 7) Then
b = 2
End If
End If
d?"
Tex as and Cal i forn ia com bine
19. mes sage = "Is Alas ka bigg er than
answ er = Inpu tBox (me ssag e)
"Y") Then
If (ans wer .Sub strin g ( O, 1) =
answ er = "YES "
End If
"y") Then
If (ans wer .Sub strin g(O , 1)
answ er = "YES "
End If
If (ans wer = "YES ") Then
txtO utpu t.Te xt "Co rrec t"
Else
txtO utpu t.Te xt "Wro ng"
End If
) is the Stat ue of Lib erty ?"
20. mes sage = "How tall (in feet
fee t= CDb l(Inp utBo x(m essa ge))
If (fee t <= 141) Then
lstO utpu t. Item s .Add ("No pe")
End If
If (fee t > 141) Then
If (fee t < 161) Then
lstO utpu t. Item s .Add ("Cl ose" )
Else
1st0 utpu t . Item s .Add ("No pe")
End If
End If torc h.")
ue is 151 feet from base to
1st0 utpu t.Ite ms. Add ( " The stat
shou ld be
h to tip the serv er in a resta uran t. The tip
21. Wri te a program to dete rmin e how muc
15% of the chec k, with a mini mum of $1.
ls and 60
l for ord ers of less than a half-dozen bage
22. A bage l shop charges 75 cents per bage ests the num -
or more. Wri te a program that requ
ce nts per bage l for ord ers of a half-dozen bage l
l cost . (Test the program for orde rs of four
ber of bage ls orde red and disp lays the tota
and a dozen bagels.)
rs of 100
for sma ll orders or at 20 cents each for orde
23. A store sells widgets at 25 cents each and disp lays the tota l
num ber of widgets orde red
or more. Write a prog ram that requests the
5 and 200 widgets.)
cost . (Test the program for purchases of for each
for the first 100 cop ie and 3 cents per copy
24. A copy cent er charges 5 ce nts per copy and disp lay
ests the num ber of copies as inpu t
addi tion al copy. Wri te a program that requ
quan titie 25 and 125.)
the tota l cost . (Tes t the program with the
should
the first Ronald McD onald ?" The program
25. W rite a quiz program to ask "Wh o was y othe r answ er.
Scot t" and "N ice try." for an
d isp lay "Co rrec t." if the answer is "Willard
4.2 If Blocks • 127
26. S uppose a program has a button with the caption "Quit". S uppose also that the N
ame prop-
erty of this button is bmQuit. Write a btnQuit_ Click event procedur e that gives the
user a
second chance before ending the program. The procedur e should use an input
box to
reque t that the user confirm that the program should be terminated , and then end the
pro-
gram only if the user respo nds in the affirmati ve.
27. Write a program that requests three scores as input and d isp lays the ave rage
of the two
highest sco res.
28. Write a program to hand le a sav ings-acco unt withdraw al. The program should request
the
current balance and the amo unt of the withdrawal as input and then disp lay the new
ba l-
ance . If the withdraw a l is greate r th an the original balance, the program sh ould
display
"Withdr awal denied." If the new balance is less than $ 150, the message "Balance
below
$ 150." also should be displayed.
29. A superma rket sells app les for $1.70 per pound. Write a cashier's program that requests
the
number of pounds and the amo unt of cash tendered as input and displays the change
from
the transacti on. If the cash is n ot eno ugh, the message "I need $x.xx more." should
be d is-
played, where $x.xx is the differenc e between the total cost and the cash. (Tes t the program
with six pounds and $20, and four pounds and $ 10.)
30. Write a program that req uests a word (with lowercase letters ) as input and
trans lates the
word into pig lat in. The rules fo r trans lating a word in to pig latin are as fo llows:
(a) If the word begin with a group of consona nts, move them to the end of
the word and
add ay. For instance, chifJ becomes ipchay.
(b) If the word begins with a vowe l, add way to the end of the word. For instance,
else
becomes elseway.
31. Fede ra l law requ ires that ho urly employees be paid "time-and- a- ha lf" fo r work
in exce of
40 hours in a week. For example, if a person's ho urly wage is $8 and he works 60 hours
in a
week, hi s gross pay should be
(40 X 8) + (1.5 X 8 X (60- 40)) = $560
Write a program that request as input the num ber of hours a person works in a given
week
and his hourly wage, and then disp lays his gross pay.
32. The cu rrent calendar, called the Gregoria n cale nd ar, was introd uced in 1582.
Every yea r
divisib le by four was declared to be a leap yea r, with the excep tion of the yea rs ending
in 00
(that is, those d ivisible by 100) and not divis ible by 400. For instance, the yea rs 1600
and
2000 are leap years, but 1700, 1800, and 1900 are not. Write a program that requests
a yea r
as input and states whether it i a leap yea r. The program should not use any variables
of
type Date. (Test the program on the yea rs 2008, 2009, 1900, and 2000.)
33. Create a form with a text box and two buttons captioned Bogart and Raines.
When Bogart
is first pressed, the se ntence "I came to Casablan ca for t he waters." is d isplayed in the
text
box. The next time Bogart i pressed, the sentence "I was misinformed." is disp layed.
When
Ra ines is pressed, the se ntence "But we' re in the middle of the dese rt." is disp layed. Run
the
program and then press Bogart, Raines, and Bogart to ob tain a dia logue.
34. Write a program that allows the user to use a button to toggle the co lo r of
the text in a text
box between black and red.
35. Write a program that allows the u er ten tries to answer the question , "Which
U.S. Presiden t
was born on July 4 ?" After three inco rrect guesses, the program sh ould d isplay the
hint,
"He once said, 'If yo u don't say anything, you won't be ca lled upon to repeat it ."' in
ames-
sage box. After eve n incorrec t guesses, the program sho uld give the hint, "His ni ckname
was 'Silent Ca l. "' The number of guesses sho uld be displayed in a text box. (See Fig.
4.3.)
Note: Calvin Coolidge was born on July 4, 1872 .
128 • Chapte r 4 Decisions
ll ~ Hide and Seek ~~ ~ lrn::J frmHid eSeek Text Hide and Seek
lblLanguage Text VB 20 10
1000 .
03 )4
(1 + ~ = 1000. 1.0075
4
= $ 1,030.3 4.
APY ~ (l +: r-
for a stated interes t rate r co mpoun ded m times per year is defined
by
1
4.2 If Blocks
• 129
Bank 1 Bank 2
Annual rate of interest : 17 J.SB
Number of compo unding periods : 2 5 Determine
Best Bank
APY: 3.7 o.
·'• 3.7 n
Best bank : Bank
Yes
20000?
Set tax =
.02 *Income Yes No
income :s
50000?
4.2
Solu tion s to Practice Problems
a
shing pos itio n in a horse race into
Exa mp le 1 Th e foll owing program con ve rts the fini n, Vis ual Bas ic
.../ from txtP os itio
iab le position is ass igned a va lue
descriptive phrase. Aft er the var t valu e and execut es the succeed-
firs t Cas e clau se who se valu e list con tains tha
sea rches for the ing Cas e Else
the valu e of position is grea ter tha n 5, the n the stat ement fo llow
ing stat em ent . If
is exe cut ed.
PROPERTY SETTING
OBJECT
ll
Rnishing position
(1. . 3. . ..):
Evaluate Position
Place
Example 2 In the fo llowing var iation of Example 1, the va lue lists specify ranges
of val-
ues. The first va lue list provides anothe r way to stipula te the numbe
rs 1, 2, and 3. The second
value list covers all numbe rs from 4 on .
Privat e Sub btnEv aluate _ Click( . . . ) Handle s btnEv
aluate .Click
e~~r.be f~ ~ r g pos~t~ons ~n a ~orse rae
Dim positi on As Intege r
positi on= Cint (txtPo sition .Text)
Selec t Case positi on
Case 1 To 3
txtOut come. Text "In the money. Congr atulat ions."
Case Is >= 4
txtOut come. Text "Not in the money ."
End Selec t
End Sub
[Run, type 2 into the text box, and click on the button .]
ll .J
Finishing position
(1. . 3... .):
Evaluate Position
1. a litera l;
2. a variab le;
3. an express ion;
4. an inequ ality sign preceded by Is and followed
by a litera l, var iable, or expression;
txtOu tput
Text
ReadO nly
Days in Month
True
Evaluate
selector
Yes
Action 1
Yes
Action 2
Yes
Action n
Perform
action of
last resort
Dim dl , d2 As Date
Dim numb erOfD ays As Integ er
Selec t Case month
Case 9, 4 , 6, 11 eptcm b :r, Apr~l, J•me, and Novem ber
numb erOfD ays = 30
Case 2 F bruar y
dl = CDate ( "l/1/ " & yr)
d2 = dl.Ad dYea rs(l)
If Date Diff( Date inter val . Day, dl, d2)
366 Then
numb erOfD ays 29
Else
numb erOfD ays = 28
End If
Case Else 'all the rest
numb erOfD ays = 31
End Selec t
134 • Chap ter 4 Decis ions
aj Co
Month (1 - 1
Year: 2 12
[Run , type "Woodrow" into the tex t box, and click on the button .]
a_. Qu iz
Interpret .Answer
Example 5 The following program has the string selector any tring.Substrinf (0 , 1) . In the
sample run , only the first action was carried out, even though the value of the elec~or was
in both
of the first two value lists. Visual Basic stops looking as soon as it find s the value of the
selector.
OBJECT PROPERTY SETTING
a... Analyze First Character [E]I ~ I~
frrnAn alyze Text Analyze First
Enter a string : C haracter
lblEnter Text Enter a string:
Analyze txtString
btnAnalyze Text Analyze
txtResult ReadO n ly True
" ? @ \ or
End Select
End Sub
[Run, type "Sund ay" into the tex t box, and click on the button.]
Analyze
Comments
less than o r equa l to the
1. In a Case clause of the fo rm Case b To c , the valu e of b shou ld be
va lue of c. Otherwise, the clause is meanin gles .
e list, is acc idental ly omit-
2. If the word Is , which should preced e an ineq uality ign in a va lu
ted, the edito r will automa tica lly inse rt it when checki ng the line.
type a the e lector. For
3. The items in th e va lue list must evalu ate to a literal of the sa me
instance, if the selecto r eva lu ated to a string va lue, as in
EXERCISES 4.3 .
Case Is < 6
price 0
Case 6 To 17
price 3.75
Case Is >= 17
price 5
End Select
txtOutp ut.Text "The price is " & FormatC urrency (price)
End Sub
(8.5, 17)
(7, 5, 11. 2)
Case Else
txtOu tput.T ext "Nope"
End Selec t
End Sub
End Se le c t
End Sub
8. Privat e Sub btnDis play_ Click( ... ) Handle s btnDi splay. Click
Dim num1 As Double 5
Dim num2 As Double = 2
Select Case numl
Case 3 <= num1 <= 10
txtOu tput.T ext = "betwe en 3 and 10."
Case num2 To 5; 4
txtOu tput.T ext "near 5."
End Select
End Sub
4.3 Se lect ase Blocks • 139
In Exe rcises 13 through 18, suppose the selector of a Select Case block, word, evaluates to
a String value. D etermine whether the Case clause is valid.
13. Case nunn & 11
til 11
14. Case "hello" , Is < "goodbye"
15. Case 0 To 9
16. Case word <> 11
No"
17. Case "abc".Substri ng(O, 1)
18. Case Is <> .. Non
140 • Chapter 4 Decisions
In Exercises 19 through 22, rewrite the code using a Select Case block.
19. I f a = 1 Then
txtOutput. Text "one"
Else
If a > 5 Then
txtOutput. Text "two"
End I f
End If
20. I f a = 1 Then
lstOutp ut . Items .Add ("lambs")
End If
If ((a< = 3) And (a< 4)) Then
lstOutp ut.Items.A dd("eat")
End I f
If ((a= 5) Or (a> 7)) Then
lstOutp ut. Items .Add ("ivy")
End If
22. I f a = 3 Then
a = 1
End If
If a = 2 Then
a = 3
End If
If a = 1 Then
a = 2
End If
23. Table 4.5 gives the terms used by the N ationa l W ea the r Se rv ice to describe the degree of
cloudiness. Write a program that requests the pe rce ntage of cloud cove r as input a nd th e n
di p lays th e app ro priate descriptor.
0-30 clear
31- 70 pa rtly cloudy
71-99 cloudy
100 ove rcast
4.3 Select Oase Blocks • 141
24. Table 4.6 sh ows the location of books in the library stacks according to the ir call numbers.
W rite a program that requ es ts the ca ll number of a book as input and d isp lays th e location
of th e book.
25. Figure 4. 7 sh ows some geometr ic shapes and formulas for the ir areas. Write a program th at
requests the user to select one of the shapes, req uests the appropriate lengths, and then
gives the area of the figure.
G }
Circle Parallelogram Kite
3.1 41593 * r " 2 I* h (I * w) I 2
26. Break-Even Analysis. S uppose a ce rtain prod uct se lls for a dollars per unit. Then the reve nue
fro m se lling x un its of the product is ax do llars. If the cos t of produc ing each unit of the
product is b do llars and the company has o verhead cos ts of c do llars, th en the tota l cos t of
producing x units of the product is bx + c do llars. (Note: Revenue is the amount of money
rece ived fro m the sa le of the produ ct. The va lues of a, b, and care ca lled the marginal rev-
enue , marginal cost, and fixed cost respec tive ly. The break- even po int is the va lu e of x for
which the revenu e equa ls the total cos t.) Write a program that req uests the marginal rev-
enu e, marginal cost, fixed cos t, and number of units of the product produ ced and so ld (x)
and then displays one of the fo llowing three outputs: PROFIT, LOSS , o r BREAK EVEN.
27. Write a program that reques ts an exam score and ass igns a letter grade with the scale
90-100 (A ), 80-89 (B) , 70-79 (C ), 60- 69 (D) , 0- 59 (F). (Tes t the program with the
grades 84, 100, and 57.) VideoN ote
28. Table 4.7 conta ins information on several states. Write a program that requests a state and G rad ing
system
category (flower, motto , and nickname ) as input and displays the requested info rmation. lf ( Ho mewo rk )
the state or category requested is not in the table, the program sh ould so inform the use r.
ac before mea ls
ad li b free ly as needed
bid tw ice daily
gtt a drop
hs at bedtime
q id four times a clay
ts beginni ng
31. Write a program that, given the last name of o ne of the six recent presiden
The program might
with Carter, displays his sta te and a colorful fact abo ut him. (Hint:
drink served in
need to request further informa tion.) (Note: Carter: Georgia ; The only soft
code name
the Carter White H ouse was Coca-C o la. Reagan : Ca lifo rnia; His Secret Service
his 85th birthday by parachu ting
was Rawhid e. George H. W. Bush: Texas; H e ce lebrated
imitatio n of Elvis Pre ley.
out of an airp lane. C linton: Arkan a ; In co llege he d id a good
Obama: Illino is;
George W. Bush : Texas; He once owned the Texas Rangers base ball tea m.
He was the e ighth left- hand ed pres ident.)
box and then clicks
32. Write a programs in which the user enters a number into a masked text
or one of three
on the appropri ate button to have e ither one of three pieces of humor
i no t between 1
insu lts disp layed in a text box below the buttons. If the num ber entered
Some poss ible bits of humo r are "I can
and 3, the masked text box sho uld be clea red . (Note:
He's not coming h o me,"
resist everyth ing except temptat ion," "I just hea rd from Bill Bailey.
ible insults are
and "Addin g people to a late software project makes it later." Some poss
friends than an
"H ow much would you charge to haunt a house?" "I bet you have no more
alarm clock," and "When yo ur IQ rises to 30, sell.")
a .. Question naire
Tasks button ~
~ di<kho"
Edito r.
FIGURE 4.9 Cl ick on Edit Items to invok e the String Colle ction
St ri ng Co llectio n Edi or
Case Else
daysinMo nth = "31"
End Select
txtDays.T ext = daysinMo nth
End Sub
aj umb er of Day s
Select a month :
January
February
March
( Determine Number of Days )
April
May
June
Ju~· Number of days: 31
August
Se~ember
tet;;.I4M
November
December
A
1 jJ a nu a~
A l
I - 1 January
2
3
7
fill handle
2 February
3 March
4 4 April
5 5 May
6 6 Jun e
7 7 July
8 8 Augus·
9 9 Sep ember
10 10 October
11 11 Nov ember
12 12 Decem ber
I
(a) (b)
Example 2 The fo llowing program presents a list of famous movie lines spo ken by lead ing
male actors. After the user makes a selection and clicks on the butto n, the actor is identified.
The numberin g of the lines allow the Select Case block to be simpli fied .
Private Sub btnDeterr nine_ Click( ... ) Handles btnDeter rnine.Cli ck
Dim actor As String = ""
Select Case lstLines. Text.Sub string(O , 1)
Case 11
1 11 ,
11
2 11
[Run, click on one of the lines in the list box, and then click on the button.]
ltem is Nothing.
When no item in a list box is highligh ted, the va lue of lstBox.S elected
item that has been
A lso, the stateme nt lstBox . Selecte ditem = Nothin g dese lects any
se lected. By default, only one item at a time can be se lected in a list box.
c ~.J Benefit> ~v1enu GJ I G I[][ ] frmM enu Tex t Bene fits Men u
Text Prescri ptio n Drug
chkD rug
Prescription Drug Plan {S33.15) P lan ($39.1 5)
Tex t Den tal P!an ($10 .81)
Dental Plan i. 1 .&1) chkD enta l
Text Visio n Plan ($2 .25)
chkVi sio n
u 'Vision Plan {S2.25) chkM edic a l Text Med ical Plan ($5 5.52)
Text Dete rmin e Tota l
btnDeterm ine
Mon thly Cos t
Text Tota l mon thly cost:
lblTo tal
Read O nly True
txt Tota l
Tota l morrth~t cost :
e . Clic k
k( ... ) Han dles btnD eter .min
Priv ate Sub btnD eter .mi ne_ Clic
Dim sum As Dou ble = 0
If chkD rug . Che cked The n
sum += 39.1 5
End If
If chk Den tal.C hec ked The n
sum += 10.8 1
End If
If chk Vis ion. Che cke d The n
sum += 2.25
End If
If chk Med ical .Ch ecke d The n
sum += 55.5 2
End If
txtT ota l.Te xt For. mat Cur renc y(su m)
End Sub
butt on.]
[Run, sele ct plan s, and then click on the
-/
1
Prescription Drug Plan ( l9.1 5)
0 Dental Plan {S1 .&1)
2] Vision Plan (S2.25)
f'i] Medical Plan {S55.5 )
4.4 lnput via Use r Selecti ons
• 149
When a check box has the focus, the spacebar can be used to check
(or uncheck) the box.
In addit ion, the state of a check box can be toggled from the keyboa
rd without first setting the
foc u to the check box if yo u crea te an access key for the check box
by includ ing an amper a nd
in the Text prope rty. (At run time, acce s keys appear underlined
after the A lt key is pressed.)
For instance, if the Tex t prope rty for the Den tal Plan in Exa mp le
4 is set as "&Den tal Plan",
then the user can check (or unchec k) the box by press ing A lt + D.
Bold Obliq m
Bfects Sample
Strikeout
L-J Underline a BbYylz
Scnpt:
Nest em
) Hand les _
Priva te Sub check Box_ Check edCha nged( ...
kedC hange d,
chkD rug.C hecke dChan ged, chkD ental. Chec
edica l . Check edCha nged
chkV ision. Check edCh anged , chkM
Di sum As Doub le
If chkD rug. Check ed Then
urn+ = 39.15
End If
If chkD enta l.Che cked Then
urn+= 10 . 81
End If
If chkV ision .Chec k ed Then
.3 Uffi += 2 .2 5
End If
If c hkMe dical. Chec ked Then
sum += 55 . 52
End If
t x tTo t al.Te xt Form atCur renc y(sum )
End Sub
Comments
a single item fro m a list of options.
1. Both list boxes and rad io butto ns can be used to select
short lists (at mos t seven optio ns)
As a rule of thum b, rad io butto ns should be used with
nd list boxes shou ld be used with. long lists.
es unchec ked. Such is not the case
2. When the u er clicks on a checked check box, it becom
cked with code or by clicki ng on
with a radio button . A radi o butto n can only be unche
anoth er radio butto n.
EXERCISES 4.4
In Exercise s 9 through 12, write one or more lines of code to carry out the task.
9. Set the caption for Rad ioButton1 to "Yes".
10. C lear the small rectangu lar box of CheckBox 1.
11 . G uarantee that CheckBo x1 is checked .
12. Turn off RadioBu tton2.
In Exercise s 13 and 14, determin e the state of the two radio buttons after Button
1 ts
clicked.
13. Private Sub Buttonl _ Click( ... ) Handles Buttonl . Click
RadioBu ttonl.Ch ecked True
RadioBu tton2.Ch ec ked = True
End Sub
14. Private Sub But t onl_ Click( ... ) Handles Buttonl .Click
RadioBu ttonl.Ch ecked False
RadioBu tton2. Checked = False
End Sub
15. Suppose that a group box has two radio buttons attached to it. lf the sta tement
GroupBo xl .Visib le = False
is executed , will the rad io buttons also vanish ? Test your answe r.
16. Create a form with two group boxes, each hav ing two radi o buttons attached
to it. Run the
program and confirm that the two pair of radio buttons ope rate indepe ndently of
each
other.
17. A compute r dealer offers two basic compute rs, the Deluxe ($1000) and the
S uper ($ 1500).
The custome r can order any of the following add itional options: upgraded video
card
($200) , internal modem plus Wi-Fi ($30), or 1 GB of added memory ($120) . Write
a pro-
gram that compute s the cost of the compute r system se lected. See Fig. 4.13.
18. Write a program to book an airline flight. See Fig. 4.14 on the next page. If the sa me
ai rport
is selected from the two list boxes, the user shou ld be informed immedia te ly that the depar-
ture and arriva l airports must be different. If no airport has been selected from one or
both
of the list boxes when the button is clicked, then the user shou ld be to ld what informat
ion
must be supplied. Use message boxes to inform the user of problems.
15 2 • Chapte 4 Decisions
From : To :
Super
AUS AUS
" Deluxe
mal BOS
BWI BWI
[{] Upgraded Video Card DFW DFW
JFK JFK
LAX
lntemal Modem Wi-Fi MIA
ORD
1 GB additiona l memory SFO
1. /
Possibl e outcom e of Exercis e 17. FIGURE 4.14 Possibl e outcom e of Exercis e 18.
FIGUR E 4.13
preside ntial candid ates. See
19. W rite a program that a llows you to vote for one of two
sho uld d isplay your vote.
Fig. 4.1 5. When the Cast Vote button is clicked on, the tex t box
for neither ." hou ld
In the event that neither radio button is on, the senten ce "You voted
appear in the text box.
Poss ible output for FIGURE 4.16 Possibl e o utp ut for Exercis e 20.
FIGUR : 4.15
Exercis e 19.
states that "No Per-
20. rticle II , Sectio n 1, C lause 5 of the Constitution of the United States,
S tates at the time of the
s n except a natural bo rn C itizen , o r a C itizen of the United
nt; n ith r ha ll any
dopt ion of this Consti tution, hall be eli gibl e to the Office of Preside
atta ined to the Age of thirty fiv e Yea rs,
Perso n be eligible to that Office who shall not have
" Write a progra m that deter-
nd been fourtee n Years a Reside nt within the United States.
in 2012. (Note: A nat-
' ines if a person is eligib le to run for Pres ident of the United State
t he U.S. gove rnmen t. A
ural born citizen is a per on who is born within the jurisdic tio n of
Day, 1/2 1/2013 .) See
2012 candid ate for preside nt must achi eve age 35 by Inauguration
Fig. 4.16. Hint: Use the AddYears method.
the section . When the
21. rite a program that u es the form in Fig. 4. 8 at the beginn ing of
has been made from both
button is clicked, the program sh ould first determ ine if a selecti on
sho uld appear telling the
the list box and the group of radio button . If no t, a message box
ns have been made, the
ser which types of selectio ns have not been made. If both selectio
essage "Inform ation Processed" shou ld be displayed.
4.4 lnput v ia User Se lectio ns
• 153
a J Co lo rs
CHAPTER 4 SU MMARY
as dete r-
r with each num ber from 0 thro ugh 255
1. T he fu ncti on Chr associates a characte
m ned by the ANS I table. The func tion
Asc is the inverse of the Chr func tion .
<> ,<= , and >=.
2. T e relational operators are <,> ,=,
, Or, and Not.
3. T e prin cipa l logical operators are And
ators (ar ith-
g literals, variables, func tion s, and oper
4. A condition is an expr essio n invo lvin
evaluate d as e ither True or False.
m tic, relat iona l, or logical) that can be
e.
of Boolean data type is e ithe r True or Fal
5. T e valu e of a vari ab le or expression
r more con-
depe ndin g on the truth va lues of on o
6. A n If block decides wha t actio n to take If state men t
ion, the If, Elself, and Else parts of an
d tions. To allow several courses of act
can cont ain othe r If state men ts.
es-
actio ns depe nd ing on the value of an expr
7. Select Case block selects from one of several selec tor.
sion, called the selector. The entri es in the
value lists should h ave the same type as the
to se lect
s prov ide an effic ient way for a prog ram
8. List boxes, radio buttons, and check boxe
amo ng a set of possible opti ons.
enta l
l = I @) l,_.a -..~J
aJ We lcome to Edd ie's Eq uipm ent
ing Project 1.
FIGURE 4.20 Form layout and sample outp ut for Programm
Prog ramm ing Projects
• 155
a~ M enu
o Regu lar ( .1 9)
L Burgers w/ cheese ( .79)
w/ bacon ( .79)
w/ bacon and chee se (5.19)
Compute Cost
Choices for Drinks of Meal
o Soda (1.69)
[ ] Drinks
Bottled Wat er (1. 9) Cost of meal:
6.
FIGURE 4.23 For m for P rogr amm ing P roje ct
Prog ramm ing Proje cts
• 157
Fries
-1 [-2) 0 3[6] ~
I
0 1010-1190 [10) 1 [2) 0 4 [8)
0 [0) 4 [8)
1200-1350 [11 )
2[ 1 5 [10] 1 [2)
1360-1600 [12]
Maximum of 40points
Miscellaneous
Essay
eography
Very good [1 ] Socioeconomic
~ State resident [1 0) disadvantage [20)
o Excellent [2]
Underrepresented
I
state county [6) Outst anding [3)
Men in nursing [5}
J Underrepresented
state [2)
Leadership and Service a Scholarship athlete [20)
Alumni State [1 )
J Legacy (parents , Regional [2) Provost's discretion [20]
~ stepparents ) [4]
7.
FIGURE 4.25 Sam ple run of Prog ram min g Proj ect
plan .
You have opted out of the retirement
You will be enrolled in the retirement plan.
(b)
(a)
of Prog ramm ing Proj ect 8.
FIGURE 4.26 Poss ible outp uts for part s (a) and (b)
G en er al Pr oc ed ur es
Summary 214
159
160 • Cha pt r 5 G enera l Procedures
~~ ~ / /
Funct ion FtoC( ByVal t As Doubl e ) As Doubl
e
FIGURE 5.1 Heade r of the FtoC Functi on proced ure.
Doub le
Func t ion FtoC ( ByVa l t As Doub le ) As
Cels ius
'Con vert Fahr enhe it temp eratu re to
Re t urn (5 I 9) * (t - 32)
End Func tion
the butto n.]
[Ru , type 212 into the text box, and then click on
Convert to Celsius
Temperature (Celsius)
1
There arc excep t ions to this rule. For instan ce,
if Type 1 is a nume ric data type, then parameter
have any num eri c data type that is wider th an Type can
Type / . In this book , the two da ta types will alway
same. S imila r considerations app ly to Retum Data s be the
Type and Type I
164 • Cha pt r 5 G eneral Procedures
Parameters
Us .r-Defined Functions Having Several
seco nd func tion ,
The~ llow ing two Fun ctio n proc edur
es have more than one para mete r. In the
ema tical form ulas will look
one- lette r names have beenused fo r the para mete rs so that th e math
s of thes e para-
names are not desc ripti ve, the mea ning
fa mili ar and be easy to read. Because the
men ts.
mete r are spe lled out in com men t state
Dou ble
ble , ByV al hrs As Dou ble ) As
Fun ct i on Pay( ByV al wage As Dou ove rtim e
-and -a-h alf for
'Cal cula te wee kly pay with time
Dim amo unt As Dou ble
Sel :! ct Case hrs
C3. se Is <= 40
amou nt = wage * hrs
Ca se Is > 40
*wa ge* (hr s- 40))
amou nt= (wa ge* 40) + ((1. 5)
End Sel e ct
Re t urn amo unt
End Fun ct i on
,
As Dou ble , ByV al r As Dou ble
Func t. ion Futu reV alue ( ByV al p n As Inte ge r ) As Dou ble
ByV al c As Inte ger , ByV al
E.amings : 688.75
Example 4 The follo wing prog ram uses the Func tion
respo nses show n whe n the prog ram is run, proc edur e Futu reValue. Wit h the
the prog ram com putes the bala nce in a savi
whe n $ 100 is depos ited for fi ve yea rs at ngs acco unt
4% inte re t co mpo unde d quar terly. Inte
times per year at the rate of 1% per inte rest is earn ed four
rest period. The re wi ll be 5-4, or 20, inte
rest perio ds.
OBJECT PROPERTY
11 _. Bank Depo sit GJ I ~ IE![] frmB ank
SETTING
Tex t Bank Depos it
Amount of bank deposit : lblA mou nt Tex t A mou nt of bank depo s it:
txtA mo unt
Annu al rate of intere st : lblRa te Tex t Ann u al rate of interes t:
txtR ate
Numb er of times interest lblN umC omp A utoS ize Fa lse
is compound ed per year:
Text N umb er of tim es interest
is co mpo unde d per yea r:
Number of years : txtN um Co mp
lblN umY rs Tex t N umb er of yea rs:
Compute Balance txtN umY rs
btnC omp ute Tex t Com pute Ba lance
Balan ce : lblBa lance Tex t Bala nce:
txtB a lance Read O nl y True
166 • Cha pte 5 Gen eral Proced ures
e.C lick
ck( ... ) Han dles btn Com put
Priv a l e Sub btnC omp ute_ Cli
a ban k dep osi t
'Fi n d the futu re val ue of
Am oun t.Te xt)
Dim p As Dou ble = CDb l (txt
Rat e . Tex t)
Dim r As Dou ble = CDb l (txt
Num Com p.Te xt)
Dim c As Inte ger = Cin t (txt
Num Yrs . Tex t)
Dim n As Inte ger = Cin t (txt
ure Val ue( p, r, c, n)
Dim bal an ce As Dou ble = Fut
Cur ren cy( bala nce )
txt ala nc e.T ext = For mat
End S b
Dou ble ,
al p As Dou ble , ByV al r As
Fun ct i on Futu reV alue ( ByV al n As Inte ger ) As Dou ble
ByV al c As Inte ger , ByV
a ban k sav ing s acc oun t
'Fin d the futu re val ue of
dep osit ed
'p pri nci pal , the amo unt
of int ere st in dec ima l form
'r ann ual rate
st is com pou nde d per yea r
'c num ber of tim es int ere
'n num ber of yea rs
Dim i As Dou ble 'int ere st rate per per iod
ere st is c omp oun ded
Dim m As Inte ger 'tot al num ber of tim es int
i "' r I c
m ., c * n
Re t urn p * ((1 + i) A m)
End •un ctio n
on .]
tex t boxes, and then clic k on the butt
[Run , type 100, .04, 4, and 5 into the
Number of years : 5
Compute Balance
Balance : ~1 22.
Parameters
User-Defined Functions Having No
any para met ers.
A Fun ctio n procedu re needn't have
ral
on to dete rmine the tota l cost of seve
Example 5 The follo win g prog ram allo ws a per then clic ks on
The user ente rs the data for a pu rcha se in th top two text box es and
pL rchases. furt her pur chase . Aft er
use r can con tinu e to ente r data for
t e Purchase This Item butt on. The
5.1 Fu nctio n Proc edur es
• 167
whe ther
lean -va lued functi on to dete rmi ne
Ex mple 6 The foll owing program uses a Boo e exa mpl es of vowel
t by the user is a vow e l wo rd- tha t is, con ta ins eve ry vowe l. Som
a word inpu ure IsVo welWo rd exam-
"d ialogue". The Fun ctio n pro ced
words are "seq uoia", "facetious", and l is fou nd to be missi ng.
the wor d for vow e ls one at a time and term inates whe n a vowe
ines
erm ine . Cli ck
_ Cli ck( ... ) Han dle s btn Det
Pri v te Su b btn Det erm ine
Di wor d As Str ing
per
wo d = t xtW ord .Te xt.T oUp
ord ) The n
If IsV owe lWo rd(w vow el."
t xtO u t pu t.T ext wor d & " con tain s eve ry
El o e eve ry vow el."
_xtO utp ut. Tex t wor d & " doe s not con tain
En If
End Sub
lean
al wor d As St rin g ) As Boo
Fun ctio n IsV owe lWo rd( ByV
If wor d .Ind exO f( "A" ) =
- 1 The n
Ret ur n Fal se
E d If
- 1 The n
I [ wor d .Ind exO f( "E" )
Ret ur n Fal se
En d If
- 1 The n
I wor d .Ind exO f( "I " )
Ret urn Fal se
E'ld If
- 1 The n
I f wor d . Ind exO f( "O" )
Ret u rn Fal se
En d I f
- 1 The n
If wo r d. Ind exO f ( "U" )
Ret u rn Fal se
nd I f
etu rn Tru e 'Al l vow els are pre sen t.
End Fun c tio n
box , and click on the but ton.]
[Ru n, type a word into the top text
Comments
you call the fun ct ion.
bee n defin ed, Inte lliS ens e helps
1. A fter a Fun ctio n proced ure has di plays the fun c-
ctio n' nam e, and Parame ter ln~
fun
Wo rd Complet ion helps type the the arguments, a
met ers. As soo n as you type in the left par enth esis precedi ng
tion 's para , names, and type s of
ing info rma tion abo ut the num ber
Pa ram eter lnfo ban ner appears giv
5.1 Func tion Proce dures
• 169
Ca se Is <= 100 00
Re tur n 0.0 3 * inc om
e
Ca se Els e
Re tur n 300 + (0. 05
* (in co me - 100 00) )
End Se lec t
End Fu nct ion
Do ub le
al x As Do ub le) As
Fu nc tio n Tr ipl e(B yV
3
Dim num As Do ub le
Re tur n num * x
En d Fun cti on
lic k
nd les btn Ou tpu t.C
tpu t_ Cl ick ( . . . ) Ha
9. Pr iva t e Su b btn Ou
g "b eau ty"
Dim wo rd l As St rin
g = "ag e" wo rd2 ))
Dim wo rd2 As St rin e" & La st( wo rdl ,
ho w( Fir st( wo rdl , wo rd2 ) & "b ef or
Me ss a ge Bo x.S
En d Sub
g
As St rin g) As St rin
st( By Va l wl As St rin g, By Va l w2
Fu nc ti o n Fir
If wl < w2 Th en
Re tur n wl
El s e
Re tur n w2
En d If
En d Fu nc tio n
g
As St rin g) As St rin
st( By Va l wl As St rin g, By Va l w2
Fu nc tio n La
If wl > w2 Th en
Re tur n wl
El s e
Re tur n w2
En d If
En d Fu nc tio n
lic k
nd les btn Ou tpu t.C
tpu t Cl ick ( ... ) Ha
10. Pr iva te Su b btn Ou
er 84
Dim num l As In teg
er 96
Dim num 2 As In teg
2) Th en
If IsA nA (nu ml , num
Sho w ("A av era ge ")
Me s sag eB ox .
El se
ot an A av era ge ")
Me ssa geB ox .Sh ow ("n
En d If
En d Su b
As Bo ole an
Va l n2 As In teg er)
tio n IsA nA (By Va l nl As In teg er, By
Fu nc
>= 89 .5 Th en
If ((n l + n2) I 2)
Re tur n Tru e
Els e
Re tur n Fa lse
En d If
En d Fu nc tio n
al num 2 As Do ubl e )
num l As Do ubl e , ByV
Sub Dis pla ySu m( ByV al
ure .
FIGURE 5.3 Pas sing arg um ent s to a pro ced
Arguments
Variab les and Expressions as ),
can be lite rals (as in Fi g. 5.3
h fu nct ion calls, the arg um ent s in S ub pro ced ure calls
Jus t as wit
va riab les, o r express ion .
End Sub
.]
[Run, and clic k on the but ton
pla y .Cl i ck
Cli ck( ... ) Han dles btn Dis
Pri vat e Sub btn Dis pla y_ sta tes .
den siti es of
'Ca lcu late the pop ula tion
lstD ens ity. Item s.C lea r()
ble , a As Dou ble
Dim s As Str ing , p As Dou
s "Ha wa ii 11
p = 12 7 519 4
a = 64 7 1
a)
Cal cul a teD ens ity( s, p,
dd( "" )
1stD ens ity. Item s.A
s "Al ask a"
p =
663 661
a = 591 000
a)
Ca1 cul ate Den sity (s, p,
End Sub
arg uments
rl---la}
Cal cula teD ens ity( s, p,
a As Dou ble
pop As Dou ble , ByV al are
al sta te As Stri ng , ByV al
Sub Cal cula teD ens ity( ByV
parameters
eters
Sub Procedures Having No Param
hav e any par ame ter . A
pro ced ur s, a re not req uired to
Sub pro ced ure s, li ke Fun ctio n vid e a des crip tion of a
ame terl ess Sub pro ced ure can be use d to g ive inst ruc tio ns o r pro
par
pro gra m.
5.2 Sub Proced ures, Part I
• 179
Display Density
~
is program displays the
p1Jiation density of the last state
become part of the United States .
Example 4 In the following progra m, the Sub proce dure FirstP art
calls the, Sub proce-
dure Secon dPart. After the statements in Secon dPart
are executed, execu t ion cont inu es with
the remai ning statem ents in the ub proce dure Fi rstPa
rt before return ing to the eve nt proce-
dure. The form co ntain s a butto n and a list box.
Comments
r the
s on the main flow of a comp lex task and defe
1. Sub procedur es allow prog ramm ers to focu is meth od of prog ram
use them liberally. Th
details of impleme ntati on. Mod ern programs edur e shou ld
own design. As a rule, a Sub proc
construction is known as mod ular or top-d smal l.
ed tasks, and should be kept relative ly
perform on ly one task, or seve ral close ly relat
r-
a commen t state men t desc ribin g the task pe
2. The first line insid e a Sub proc edure is often this
seve ral commen t state men ts are devo ted to
fo rmed by the Sub procedur e. If necessary, all varia bles used by
also reco mme nds that
purpose. Con vent iona l prog ramm ing prac tice this tex t , we
men ts with their mea nings. In
the Sub procedu re be listed in com men t state -
adhe re to it on ly whe n the varia bles are espe
give seve ral examp les of th is prac tice, but
ciall y num erous or lack desc ripti ve name .
tion
ion and Para mete r Info help us write a func
3. In Sect ion 5. 1, we saw that Word Complet S ub proc edur e calls . (Of
same ass istan ce for
call. T hese Inte lliSe nse features prov ide the Sub proc ed ure has
Info work only whe n the
course, Word Completi on and Para mete r
already been crea ted.) See Fig. 5.5 .
,
k(By Val send er As Sy stem . Obje ct
Priv ate Sub btnA ddNu mber s Clic
Di splay Sum ( l , 2)
Dim x As Dou ble 3
Dim y As Dou ble = 4
Disp lay Sum <I
As Dou ble) !
IDi splay Sum (num l As Dou ble, num2
the
called Sub procedur es had to be writt en in
4. In early versions of Bas ic, state men ts that
fo rm
, ... , argN )
Ca l l Proc edur eNam e(ar gl, arg2
es are often referred to as Call state men ts.
The refore, state men ts that call Sub procedur
5.2 Sub Proced ures, Part 1 • 181
In Exercis es 1 through 20, determi ne the output displaye d when the button
is clicked .
1. Private Sub btnDis play_ Click( ... ) Handle s btnDis play.C lick
Piano (88)
End Sub
2. Privat e Sub btnDis play_ Click( ... ) Handle s btnDis play.C lick
'Openin g line of Moby Dick
FirstL ine ("Ishm ael")
End Sub
Sub Answe r ()
ted in the north ern")
lstOu tput.I tems. Add(" Becau se they were inven
als go clock wise. ")
lstOu tput.I tems. Add(" hemis phere where sundi
End Su b
Sub Qu estio n ()
wise? ")
lstOu tput.I tems.A dd("W hy do clock s run clock
lstOu tput.I tems. Add(" ")
End Su b
btnDi splay .Click
8. Priva t e Sub btnDi splay_ Click ( ... ) Handl es
Answe r()
Que s tion ()
End Su b
Sub Answe r ()
lstOu tput.I tems. Add(" The answe r is 9W.")
)
lstOu tput.I tems. Add(" What is the quest ion?"
End Sub
pla y . Cli ck
Cli ck( ... ) Han dles btn Dis
13. Pri vat e Sub btn Dis pla y_
HowMan y(2 4)
.")
lstO u t put .Ite ms .Ad d(" a pie
End Sub
Int ege r)
Sub How Man y(B yVa l num As
Wha t (num)
ked in" )
lstO u tpu t.It em s . Add ("ba
End Sub
ege r)
Sub Wha t(B yVa l num As Int
& " bla ckb ird s")
lstO u tpu t.It em s.A dd( num
End Sub
pla y.C lick
Cli ck( ... ) Han dles btn Dis
14. Pri vat e Sub btn Dis pla y_
'Go od adv ice to foll ow
Adv i c e()
End Sub
Val d As Dat e)
Sub Dis play Typ eOf Day (By
I f IsW eek end Day (d) The n
."
txtO utp ut.T ext "To day is a wee ken d day
El se
txtO utp ut.T ext "To day is a wee kda y . "
En d I f
End Sub
5.2 Sub Proce du res, Part I
• 185
Else
txtO utpu t.Tex t "You faile d the exam ."
End If
End Sub
Sub Tea ()
txtO utp ut.T ext "Tea for " & nurn
End Sub
sal ar y = 830 89
for " & cit y &
200 8, the ave rag e sal ary
lstO u tpu t.It em s . Add ("In & "." )
ma tCu rren cy( sala ry, 0)
" res ide nts was " & For
cit y = "Ha rtfo rd"
sal ar y = 460 00 for " & cit y &
200 8, the ave rag e sal ary
lstO u tpu t.It em s.A dd( "In & "." )
ma tCu rren cy( sala ry, 0)
" res ide nts was " & For
End Sub
put sho wn in a list box.
es 29 thro ugh 32, wri te a pro gra m tha t displays the out
In Exe rcis pro ced ure s usin g
two line s of the out put sho uld be displaye d by one or mor e Sub
The last
eve nt pro ced ure .
data passed by variables from an
29. (Assume tha t the following
is disp laye d.)
tak en by the Hig her
vey of col leg e fres hme n
Acc ord ing to a 200 8 sur
te:
Edu ca t ion Res ear ch Ins titu
y inte nd to maj or in bus ine ss.
16 . 7 p erc ent sai d the sci enc e.
nd to maj or in com put er
1 per c ent sai d the y inte
"W hat is you r date
e tha t the curr ent date is 12/3 1/2010, the labe l for txtB ox read
30. (Assum is clicked.)
1984 into txtB ox before btn Display
of birt h ?", and the user ent ers 2/3/
.
You are now 26 yea rs old
for 982 4 day s.
You h ave liv ed
the user types
t the labe l for txtB ox read s "W hat is your favorite num ber?", and
31. (Assume tha
ked. )
7 into txtBox before btn Display is clic
num ber wit h its elf is 14.
The s um of you r fav ori te is 49.
ori te num ber wit h its elf
The p rod uct of you r fav
disp laye d.)
32. (Assu me tha t the fo llow ing is
In a rec ent yea r, Spa nis h
den ts too k a cou rse in
823 tho usa nd col leg e stu Fre nch
den ts too k a cou rse in
206 tho usa nd col leg e stu
. " The prim ary verse,
a prog ram to disp lay thre e ve rses of "Old Mc Don ald H ad a Farm
33. Wri te in a Sub proce-
les sub stit uted for the anim als and sounds, sho uld be con tain ed
wit h var iab to the Sub procedure:
foll owing anim al and sou nd pa irs
dure. The prog ram sho uld pass the uld be
k. The first verse of the out put sho
lam b, baa; duck, quack; firefly, blin
. Eyi eyi oh.
Old McD ona ld had a farm
had a lam b. Eyi eyi oh.
And on his farm he
a baa baa the re.
Wit h a baa baa her e, and
, eve ryw her e a baa baa .
Her e a baa , the re a baa
ld had a farm . Eyi eyi oh.
Old McD ona
est the per-
ram to com pute tips for serv ices rend ered . The program sho uld requ
34. Wr ite a prog t and pass this info rma -
bill , and the percent age tip as inpu
son 's occ upation, the amo unt of the run is sho wn in Fig. 5.6.
the person and the tip. A sample
tion to a Sub procedure to display
e grades to a
ram tha t requ ests thre e grad es as inp ut and the n passes the thre
35. Wri te a prog Fig. 5.7.
displays the high est two grade . See
Su b proced ure tha t dete rmines and
num eric grad e on
a pro gram tha t requ ests a stud ent 's first name, last name and the
36. W rite e and se me ter
ms, and the n uses a Sub pro ced ure to display the stud ent 's nam
three exa
5.2 Sub Proce dure , Part l
• 189
a G atu it ies a G ad es
FIGURE 5.6 Samp le run of Exerc ise 34. FIGURE 5.7 Samp le run of Exerc ise 35.
a .. G ades
a ~ o.rd:;
Rrst grade : 8,3
Robert Smith : B
Passing by Value
the wo rd ByVal,
g in S ub proc edur e were prec eded by
In Sect ion 5.2, all para mete rs appe arin we ay that th e
ich stan ds for "By Valu e." Wh en a variable is passed to such a para mete r,
wh a l va lue after
that is passed by va lue will reta in its o rigin
varia ble is "passed by valu e." A variable e of the corr e-
of wha t chan ges are mad e to the valu
the Sub proc edur e term in ate -reg ardl ess
edure. Examp le 1 ill ustrates this feature.
spon ding para mete r inside the S ub proc
)
Sub Tr iple ( ByV al num As Dou ble
'Tri ple a num ber
from Sub proc edu re" )
lstRe s u l ts.It ems .Ad d(nu m & "
n um = 3 * num
from Sub proc edu re" )
lstRes ult s .Item s.Ad d(nu m & "
End Sub
wing is disp layed in the list box. ]
[Run , and then click the butt on. The follo
2 from e v ent proc edu re
2 f rom Sub proc edu re
6 from Su b p r oced u re
2 f rom e v ent proc e dure
s the
ory loca tion s are invo lved. Figure 5.10 show
Whe n a varia ble is passed by value, two mem time the Sub proc e-
ram in Example 1 exec utes. At the
statu s of the memory loca tion s as the prog the Sub pro-
loca tion for the para mete r is set as ide for
dure i called, a temp orary seco nd mem ory Afte r the com pleti on of
t is copied into that loca tion.
cedure's use and the valu e of the argumen in it is lost.
loca tion is released, and the va lue
the Sub procedure, the temporary memory
5.3 Sub Proced ure , Part ll
• 191
Passing by Reference
Ano the r way to pass a varia ble to a S ub
proc edur e is "By R efe re n ce." In this case
is prec eded by t h e k eywo rd ByR ef. S uppo the pa ra me te r
se a varia ble, ca ll it arg, ap pears a a n
p roce dure ca ll, and its co rresp ondi ng pa a rgum e nt in a
ra m e te r in the S ub proc edur e 's h eade r,
ced ed by ByR ef. Afte r the S ub proc edur ca ll it par, is pre-
e h as bee n exec uted , arg will h ave wha
h ad in th e S ub p roce dure. teve r va lu e par
In Exam ple 1, if the h ead e r of the S ub
proc edur e is ch a n ged to
Sub Trip le(B yRe f num As Dou ble)
PROPERTY SETTING
OBJECT
k
. . . ) Han dles btnC omp ute. Clic
Priv ate Sub btnC omp ute Clic k(
bers and
'Thi s prog ram requ ests two num
and the ir sum.
'dis play s the two num bers
Di m x, y As Dou ble
GetN umb ers(x , y)
Dis play Sum (x, y)
End Sub
Compute Sum
and Constants
lifetime and Scope of Variables
ced ure wit h a Dim
or con stan t is dec lare d insi de a Functio n, Sub , or eve nt pro
Wh en a vari ab le portion of mem -
of mem ory is set as ide to hol d the valu e of the va riable. Th at
stat eme nt, a por tion nt is reac hed . The life tim e
s End Functio n or End Sub stat eme
ory is rele ased whe n the procedure' ory. (A vari able 's va lue can
or con stan t is the peri od dur ing whi ch it rem ains in mem
of a vari able able or con stan t is the
life tim e, but it alw ays hol ds some va lue. ) The scope of a vari
cha nge ove r its ced ure wit h a
m tha t can refe r to it. A vari able or con tan t declared in a pro
portion of the progra l con stan t and is said to have
Val , or ByR ef key word i a local var iabl e or a loca
Dim , Ca nst, By ables or con stan ts dec lare d
can not be acc esse d out side the proced ure .) Wh en vari
local sco pe. (It two differe nt obj ects.
t pro ced ures hav e the ame name, Visual Bas ic trea ts the m a
in two differen s-le vel sco pe and can be
d out side of a pro ced ure has clas
A var iab le or con stan t declare de an If o r a Select Cas e blo ck
pro ced ure. A var iab le or con stan t declare d insi
refe rred to by any od progra mm ing practice
el sco pe and can not be accesse d o utside the blo ck. Go
has block -lev r a variab le, this
sco pe of a vari able o r con stan t be as sma ll as poss ible . Fo
d icta te th at the inco rrec tly or acc ide nta lly.
whi ch its valu e can be mo difi ed
redu ces t he num ber of places in
to the par t
the fact tha t variab les are loca l
Example 4 Th e follow ing progra m illu stra tes the variable x in
whi ch the y res ide. Th e variab le x in the eve nt pro ced ure and
of th e progra m in han dles the m as if the ir nam es
differe nt variab les. Visual Bas ic
th e Sub proced ure are trea ted as tim e the Sub pro ced ure i
ara te, suc h as xbt nD ispl ay_ C lick and xTrivial. A lso, eac h
we re sep 0.
de the Sub proced ure is rese t to
call ed, the valu e of variab le x insi
Dis pla y .C lic k
Cli ck( ... ) Han dle s btn
Pri vat e Sub btn Dis pla y_
nat ure of var iab les
'De mo nst rate the loc al
Dim x As Dou ble = 2
& " eve nt pro ced ure " )
lstR e sul ts.I tem s.A dd( x
Tri via l()
& " eve nt pro ced ure " )
lstR esu lts. Ite ms .Ad d(x
Tri via l()
& " eve nt pro ced ure " )
lst Res ult s.It em s.A dd( x
End Sub
Sub Tr ivi al ()
Dim x As Dou ble
& " Sub pro ced ure " )
lst Res ult s.It em s.A dd( x
5.3 Sub Procedures, Part ll
• 195
X = 3
lstRe sults .Item s.Ad d(x & " Sub proc edur e" )
End Sub
Displcrl Resu~s
: event procedure
: Sub procedure
., : Sub procedure
: event procedure
: Sub procedure
J : Sub procedure
: e\rent procedure
Debugging
Progr ams with S ub proce dures are eas ier to debu
g. Each S ub proce dure can be check ed indiv id -
ually before being place d into the program. VideoN ote
In Appe nd ix 0, the sectio n "Step ping through a Debugg ing
Program Cont ainin g a Gene ra l Proce dure:
Chap ter 5" uses the Visua l Basic debugge r to trace proceJu res
the flow through a program and observe the
interp lay b tween argum ents and param eters.
Comments
1. In this textb ook, passing by refe rence is used pr
imar ily to acquire input .
2. Whe n an argum ent that is a litera l or an expre
ss ion is pa sed to a proce d ure, there is no d if-
feren ce betw een passing it by refere nce and passin
g it by va lue. Only a var iable argum ent
can po ibly have its va lu e chan ged by a S ub proce
dure.
EXERCISES 5.3
mon th is the monthly rate of interest applied to the balance at the beg inning of the month.
Each month the redu ctio n of principa l eq ua ls the monthly payment minus th e in terest
pa id. A t an y time, th e ba lance of th e mo rtgage is the amo unt sti ll owed; that is, the a mo unt
req uired to pay off the mortgage. The end of month ba lance is ca lculated as [beg inning of
mo n t h ba lance] - [redu ction of principal] .
14. Write a program to determine a person 's weekly pay, wh re they rece ive ti me-and -a- halffo r
overtime wo rk beyo nd fo rty hours. See Fig. 5.17. The p rogram should use the event proce-
dure shown in Fig. 5. 18 .
g .J Weekly Pay
2. S ince scme is a stri ng va ri ab le, its d eFa ult va lu e is the keywo rd Noth ing. Th e ass ignme n t oF Nothing roa n a rgu-
ment makes Visua l Basic ne rvo us. ThereFore, to keep Visua l Basic happy, we will ass ign th e empty st ring to
S tring va ri ab les t hat a re p<~ssed to proced ures . That is, we will c ha nge the FirsL lin e ins id e th e eve nt procedure
to Dim state As String = " .. .
S ince the deFa ul t va lue oF the n ume ri c va ri ab le /JO/J is 0, Visua l Bas ic has no iss ue wit h pass in g tha t va lu e ro
a S ub proced ure.
202 • Cha pter 5 Ge nera l Procedures
Top-Down Design
an eve nt proced ure
soft war e usu all y req uire s larg e programs. Wr itin g the cod e for
Ful l-fea tured pro gra mm ers
ic pro gra m mig ht pos e a com plic a ted pro ble m. On e me tho d
in uch a Visual Bas div ide it into sma ller, less co m-
a com p lica ted pro ble m mo re und erst and able i to
use to mak e bre ak up a large prob-
s. Rep ea ted ly usin g a "div ide- a nd -co nqu e r" app roach to
plex subp rob lem ent is par t of a
sub pro blem s is call ed step wis e refi nem ent . Ste pwi se refinem
lem into ma ller , in wh ich the mo re ge neral
gra ms kno wn as top -do wn des ign
large r met hod ology of writ ing pro nem ent occ ur be low. Top-
top of the des ign and tasks rep rese ntin g the ir refi
tasks occ ur nea r the anc e progra mm ing pro-
stru ctu red pro gra mm i ng eme rged as tec hn iques to enh
dow n des ign and in. Th ey also pro duc e
use lead s to pro gram s tha t are eas ier to read and ma inta
ductivity. The ir and correc t.
few er init ial erro r , wit h the se erro rs bei ng eas ier to find
programs con tain ing like lih ood of intr odu cin g new
en suc h pro gram s are late r mo difi ed , the re is a mu ch sma ller
Wh
erro rs. or mo dul es, tha t
top -do w n des ign is to bre ak a pro ble m into ind ivid ua l tasks,
Th e goa l of m. First, a pro ble m is re rate d
udo cod e, flow cha rts, or a progra
ca n eas il y be tran crib ed into pse t rem a in too co mp lex are
ple r pro ble ms dep icte d as mod ules. An y mod ules tha
as sev e ral sim sma lles t mo dul es can
her. Th e pro cess of refi ning mo dul es con tinu es unt il the
bro ken dow n furt tion of wh at task s
. Eac h stag e of refi nem ent add a mo re comple te spe c ifica
be cod ed directly the ge ner al to the spe cifi c.
in top -do wn des ign is to go from
mu st be perfo rmed. Th e ma in idea be pic ture d using a hie rarc hy
pro cess of div idin g and o rgan izing a pro ble m into tasks ca n
Thi s :
ign, cer ta in criteria sho uld be met
cha rt. Wh en using top -down des
le size .
able and em pha size mall mo du
1. Th e des ign hould be eas ily read ch art.
l to specifi c a you read down the
2. Mo du les proceed from gen era
Tha t is, the y sho uld perfo rm
e mod u les, as mu ch as pos s ible, sho uld be single min ded.
3. Th
on ly a sing le we ll-defin ed ta k. , and any re lati ons hip s
sho uld be ind epe nde nt of eac h oth er as mu ch as poss ible
4. Mod ules
ed.
amo ng mod ules shou ld be specifi
tes th is process.
Th e follow ing exa mpl e illu stra
m tha t giv es
1 5. 19 is the beg inn ing of a hie rarc h y ch art for a pro gra
-./' Examp le Figu re
loan , the dur atio n (in years),
e inp uts are the am oun t of the
info rma t ion abo ut a car loan. Th t and the amo unt of inte rest
rate . Th e out put con sist s of the mo nth ly pay men
and the inte rest a ining the inp u t, mak-
t mo nth . In the bro ade st se nse , the progra m call s for obt
paid fo r the firs as the first row of a
, and disp lay ing the out put . Fig ure 5.19 shows these task s
ing calcu lati ons
hie rarc hy cha rt.
Car
loan
Display
Make
Get results
calculations
input
for the car loan pro gram .
FIGURE 5.19 Beg inn ing of a hier arch y cha rt
5.4 Mod ular Des ign
• 203
Car
loan
I
Calculate Apply
number of payment
month s formula
FIGURE 5.20 Hiera rchy chart for the car loan progr am.
Structured Programming
A prog ram is sa id to be struc tured if it meet
s mode rn tand ards of prog ram de ign. A ltho
there is no fo rmal defin iti on of the term struc ugh
tured prog ram, co mput er cient i t agree that
such prog rams should have modu lar des ign and
use only the three types of logic al struc tures di
cussed in C h apter 1: eque nces , dec ision s, and s-
loops.
Sequ ence s: S tatements are exec uted one after
ano th er.
Decisions: O ne of seve ral blocks of program cod
is exec uted based on a test for some cond ition
.
Loops (itera tion) : O ne or more state ments are exec
uted repea tedly as lo ng as a spec ified cond i-
t ion is tru e.
s, decisions,
a ll prog rams be writ ten using sequence
S tru ctu red prog ramm ing requires that such a GaT os,
is allowed. All o ther logic a l cons truc ts,
and loops. Nes ting of such state men ts char t that flows
ed prog ram can be pictu red using a flow
are no t allowed. The logic of a stru ctur of a fl ow-
ruct ured bran chin g (G aTos ). The port ion
smo othl y from top to bott om with out unst ther efor e, is not
equivale nt of a GoTo state men t and,
char t sh own in Fig. 5.2l (a ) cont ains the s from the top
of the flow char t in whic h the log ic flow
struc ture d . A correctly struc ture d vers ion
to the bott om appe ars in Fig. 5.21 (b).
Let Let
b= a + c a = b+ c
Let
b= a + c
No
Let
b= a + c
g
Advantages of Structured Programmin
to crea te corr ect prog rams that are
easy to writ e, debug,
The goal of struc ture d prog ramm ing is a lo ng with a
a close r look at the way mod ular des ign,
unde rstan d , and chan ge. Let us now take
ribu tes to atta inin g these goals.
limi ted num ber of log ical struc tures, cont
1. Easy to write .
to look at
er's prod uctiv ity by allow ing him or her
Mod ular design increases the prog ramm ng, the prog ramm er
ils later. Duri ng the actu a l codi
the big pictu re first and focus on the deta t an enti re
prog ram and does not have to thin k abou
works with a man agea ble chun k of the
com plex program.
ility for a
le large program, ach taki ng respo nsib
Seve ral programmers can work on a sing
spec ific mod ule.
writ e than
rams requ ire sign ifica ntly less time to
Studies h ave show n that struc ture d prog
stan dard programs.
iring the
ram can be reu ed in o th er prog rams requ
Ofte n , procedures writ ten for one prog d, beca use
ing a prog ram, but reliab ility i enh ance
ame task. N ot only is time aved in writ be used m
d and debu gged. A proc edur e that can
reused procedur es wi ll already be teste
man y programs is said to be reus able .
5.4 Mod ular Design
• 205
2. Easy to debug.
Because each procedure is pecialize d
to perform just one task or seve ral rela
cedu re can be checked indi vidu ally to ted tasks, a pro-
dete rmin e its reliab ility. A dum my prog
driver, is set up to test the procedure. ram, ca lled a
The driv er con tains the min imu m defi
to call the proc edur e to be tested. For nitio ns needed
insta nce, if the procedure to be tes ted
the driver program ass igns d iverse va is a func tion ,
lues to the arguments and then exam
spond ing func tion retu rn va lu es. The ines the corre-
argumen ts should con tain both typical
ca e va lues. and spec ial-
The program can be tested and debugged
as it is bein g des igned with a tech n ique
stub programming. In th is tech niqu kno wn as
e, the key even t procedures and perh
sma ller procedure are cod ed first. Dum aps som e of the
my procedures, or stub s, are wr itten for
ing procedu res. Init ially, a stub procedu the remain-
re might con sist of a message box to
the proc edu re has been called, and ther indi cate that
eby conf irm that the procedure wa
right t ime. Late r, a stub migh t simply call ed at the
disp lay va lues passed to it in orde r to con
that the procedure was call ed, but also firm not only
that it rece ived the co rrec t valu es from
proced ure. A stub also can ass ign new the calling
va lues to one or more of its para met ers
eith er inpu t or co mpu tat ion. Thi s prov to imulate
ides grea ter con trol of the con ditio ns
The stub proced ure is alway simpler be ing tes ted.
than the actual procedure it rep rese nts.
stub prog ram is only a skeleton of the Alth oug h the
fina l program, the program's stru ctur
deb ugged and tested. (Th e stub prog e can sti ll be
ram con sists of some coded procedur
procedu res.) es and the stub
O ld -fa hion ed unst ruct ured program
s con ist of a sequence of inst ru ctio
grouped for specific tasks. The logic of ns that are not
such a prog ram is clut tere d with deta ils
difficu lt to follow. Nee ded tasks are and therefore
easily left out and cru cial details eas
Tricky parts of the program ca nno t be ily neglected.
isolated and exa min ed. Bugs are diffi
becau e they mig ht be present in any cult to loca te
part of the program.
3. Easy to understand.
The inte rcon nec tions of the proced ures
revea l the modu lar design of the prog
ram.
The mea ning ful procedure names, alon
g with re leva n t com ments, ide ntify the
formed by the modules. tasks per-
The meaningful var iab le names help
the prog rammer to reca ll the purpose
4. Easy to change. of each va riab le.
Object-Oriented Programming
An obje ct is an encapsul at ion of data
and code that ope rates on the data. Like
hav e prop erties, respond to met hod s, con trols, objects
and raise eve n ts. The mos t effe ctive type
for com plex prob lems is call ed obje of prog ram min g
ct-oriented design. A n obje ct-o rien
viewed as a coll ection of coop e ratin g ted prog ram can be
object . Man y mod ern prog ramme rs use
tion al stru ctur ed prog ram min g alon g a blend of tradi-
with obj ect-orie nted des ign.
Vi ual Basic. NET was the first vers ion
of Visua l Basic that was truly obje ct orie
every ele men t such as a con trol or a strin nted; in fact,
g is actually an object. Thi s book illustrate
s the building
206 • Cha pter 5 Gen eral Procedures
A Relevant Quote
Dirk Gen tly's Holistic Detective Age
ncy, by Do u-
io n wit h a few para grap hs from
W e end this sect
198 7:
glas Ada m , S imo n & Sch uster,
to teac h any thin g to anybody?"
"W hat rea lly i the poin t of tryin g up and dow n the
murmur of ymp athe tic approva l from
Thi quest ion eemed to provoke a
table. and somethi ng, the
i th at if you rea lly wan t to und erst
Richard con tinu ed, "Wh at l mea n ort it out in your own mind.
is to try and exp lain it to som eon e else . Tha t forces you to
best way th ings down into
mor e low and dim -w itted your pupil , the more you have to brea k
And the By the time you've
mor e simp le idea s. And that 's rea lly the esse nce of prog ram ming.
more and e can dea l with , you've
littl e steps that eve n a stup id mac hin
sorted out a complicated idea into y lear ns more than the pupil.
ly lear ned som ethi ng abo ut it yourself. The teac her u uall
ce rtain
Isn't that true?"
Payroll information .
IliN IIt • Yr. to FIC A Inco me C heck
Cu rren t Tax W h. A mou nt
Dat e Ea rnin gs Tax
Nam e Ea rn ings
$ 163.44 $ 1,433.29
$90,329 .00 $132.27
A l C lark $1,729.00
lt!1:J!IW 2009 Fede ral income tax withheld for a marri ed perso
n paid weekly.
Adjusted Weekly Income Income Tax Withheld
$0 to $303 $0
Over $303 to $4 70 10% of amou nt over $303
Over 4 70 to 1,455
$ 16.70 + 15o/oofa moun t over $470
Ove r $1,455 to $2,272
164.45 + 25% of amou nt ove r 1,455
Over $2,272 to 4,165
$368.70 + 28% of amount ove r 2,2 72
Over $4,1 65 to$7 ,321
898.74 + 33% of amou nt over $4,1 65
Over 7,321
1,940.22 + 35% of amou nt over $7,32 1
Give payroll
inform ation
nt Procedure
Pseudocode for the Display Payroll Eve
VAL IDA TE data (Fun ctio n Dat aOK)
Inpu tDa ta )
INP UT emp loyee data (Sub procedu re
(Fun ctio n Gross_Pay)
CO MP UTE CU RRE NT GRO SS PAY
DATE (Fun ctio n Tota l_Pay)
CO MP UTE TOT AL EAR NIN GS TO
A_Tax )
CO MP UTE FIC A TAX (Fun ct ion FIC
WIT HH ELD (Fun ct ion Fed_ Tax )
COM PUT E INC OME TAX
Adjust pay for with hold ing allowa nces
If emp loyee is sing le The n
ELD (Fun ctio n Tax S ingle)
CO MP UTE IN CO ME TAX WIT HH
Else
D (Fun ctio n Tax Mar ried)
CO MP UTE INC OM E TAX W ITH HEL
End If
(Fun cti on Net _Ch eck )
CO MP UTE PAYCHEC K AM OU NT
(Sub procedur e Sho wPa yroll )
DISPLAY PAYROLL INF ORM ATI ON
Houm•wage :
Number of withholding
allowances:
Total pay prior to this week:
Marital Status
Single Married
I
I
Display Payroll Next Employee Quit
lf;1:J!JJ:M Objects and initial properties for the weekly payroll program.
Objec t Prope rty Settin g
frmPay ro ll Tex t Week ly Pay ro ll
lblN ame Text Emp loyee name :
txtN ame
lblWage Text Hourl y wage:
txt Wage
lblHo urs Tex t Numb er of hours worked:
txtHo urs
lblAII owan ces Au toS ize False
Tex t Numb er of wi thh o lding all owan ces:
txtAll owan ces
lbiPri orPay Tex t Tota l pa y pri o r to this week:
txtP riorPay
grpM arita l Tex t Marit a l S tat us:
radS ingle Tex t S ingle
radM arri ed Tex t Marri ed
btnOi splay Tex t Display Pay ro ll
brnN ex t Text ex t Employee
brnQu it Tex t Qu it
lstRes ults Fo nt Couri er New
210 • Chap ter 5 Gene ral Proced ure
a .. Week ly ayroll
l = I @] /-t:S d
~
Doub le ) As Doub le
Func tion TaxS ingle ( ByVa l adjPa y As
'~ask 2: Comp ute fede ra ax 1thh eld for cing le perso n .
Sele ct Case adjPa y
Case 0 To 138
Retu rn 0
Case 138 To 200
Retu rn (0.1 * (adj Pay- 138))
Case 200 To 696
Retu rn 6.2 + 0.15 * (adjP ay - 200)
Case 696 To 1279
Retu rn 80.6 + 0 .25 * (adjP ay - 696)
Case 1279 To 3338
1279)
Retu rn 226.3 5 + 0.28 * (adjP ay
Case 3338 To 7212
Retu rn 802.8 7 + 0.33 * (adj Pay- 3338)
Case Is > 7212
7212)
Retu rn 2081 .29 + 0.35 * (adjP ay -
End Sele ct
End Func tion
5.5 A Case Stud y: Wee kly Payroll
• 213
Comments
a l secu rity ben efit
bee n take n to avo id co mpu ting soci
1. In the func tion FIC A_Tax , care has makes sure an
inco me in exc e s of $10 6 ,800 per yea r. The logic of the prog ram
tax on ng a give n wee k is
cro ses th e $ 106,800 thresho ld duri
empl oyee whose inco me fo r the year -date ea rnin gs.
$ 106,800 and the ir previous yea r-to
taxe d only on the diffe renc e betw een
inco rpo rate t he tax
TaxS ingle use Se lect Case bloc ks to
2. The two func tion s Tax Married and tax with held . The
fo r the amo unt of fed eral inco me
brac kets give n in Tables 5.5 and 5.6 C ase clause . Thi s
er limi t of each Cas e clau se is the sa me as th e lower li mit of the nex t
upp func ti on, will be
ay, such as 138.50 in the Tax Sin gle
ensures th at frac tion a l va lue fo r adjP
er sala ry rang
prop erly trea ted as part of the high
CHAPTER 5 SUMMARY
procedu res or oth er
a prog ram that is acce ssed by eve nt
1. A general procedur e is a po rtio n of procedur es and Sub
of gen eral proc edu res are Function
gen eral proc edu res. The two types
procedures .
ders and end ing with
bloc ks beg inni ng with Fun ctio n hea
2. Fun ction procedur es are defined in e in an exp ress ion and
ti on is exe cuted by a refe renc
End Fun ctio n stat eme nts. A func
retu rns a valu e.
end ing with End S ub
Sub proc edur es are defi ned in bloc ks beg inni ng with Sub headers and
3. of the na me of
nts. A Sub proc edu re is acce ssed (called) by a tate men t con sisti ng
stat eme
the proc edu re.
t must mat ch the
4. ln any proc edu re, the argumen
ts app eari ng in the ca lling tate men
The y nee d not
eme nt in num ber, type , and orde r.
parameters of the ub o r Functio n stat
h ave the sam e names.
ins in memo ry. (Th e
t i the peri od duri ng whi ch it rem a
5. The lifetime of a vari able or con stan s some valu e. )
ove r its lifetim e, but it alw ays hold
valu e of the vari able might cha nge
that can re~ r to it. A vari-
6. The scope of a va riable or con
stan t is the po rtio n of the prog ram
ha local scope and is
o r con stan t dec lare d insid e a Functio n, Sub , o r eve nt proc edu re
able
visible only inside the procedu re.
s into sma ller sub prob-
u lar design to refin e large prob lem
7. Structured fJrogramming uses mod e , dec isio ns, and
thre e log ical stru ctur es of sequ enc
lem s. Prog rams are cod ed using the
loop s.
JECTS
CHAPTER 5 PROGRAMMING PRO ld ente r the
prog ram to dete rmi ne a stud ent' s GPA . See Fig. 5.25 . The use r hou
1. Wri te a then clic k on the
ber of cred it hours for a co urse, and
grad e (A, B, C, D, or F) and the num r all his or her
sho uld then repe at this process fo
Record This Course butto n. The user k on the Calculate
bee n reco rded, t he user sho uld clic
courses. Aft er all the cour es hav e ality po ints fo r a
butt on. A Fun ctio n proc edu re sho uld be used to calc ulate the qu
G PA
to Exa mpl e 5 in Sec tion 5.1.
course. Hin t: Thi s prog ram is sim ilar
ks ($ 1.25) . Wri te a
s ($1.75) , fries ($2.00) , and soft drin
2. A fas t-fo od vendor sells pizza slice the qua ntit y of eac h
bill. The prog ram ho uld requ est
prog ram to com pute a cust ome r's ctio n proc edu re, and
ca lcul ate the tota l cost with a Fun
item o rd ered in a ub procedu re, in Fig. 5.26 .
ized bil l. A sample outp ut is sho wn
use a S ub procedu re to disp lay an item
Prog ram min g Proj ects
• 215
Customer name:
(Last , First) Smith. William
Inv oi ce Num ber : SM4 .:.01
Process Order
Oear Order Form
Quit
l!'r~J
g~ Five, Six, Pick up 5 ick5
= @] Hoo ray
217
218 • Chap ter 6 Repetition
6.1 Do l oop s
t a seq uenc e of
ctur es in programming, is used to repea
A loop , one of the most impo rtan t stru variables
repe titio n, or pass, the sta teme nt ac t upon
state men ts a num ber of time s. At each
whose values are chang ing. cond ition
men t eith er as long as or unti l a ce rta in
The Do loop repeats a seq uenc e of state t foll ows the
ence of state men ts, and a Loop state men
is true. A Do state men t precedes the sequ ile" or the word
, preceded by either th e word "Wh
seq uenc e of state men ts. The cond ition
"Loop".
"Un til", follows the word "Do" or the word
No
condition
Execute
Do Whi le c ondi ti on is t rue state ments
stat eme n t ( s ) within
Loop the loop
Execute
statements
that follow
the loop
OBJECT PROPERTY
a:} 6-1 -2 GJ1 8 I~ frm Mov ie
SETTING
Text 6-1-2
btnD isp lay Text Disp lay a Mov ie Q uota tion
Display a Movie Quot ation
txtQ uota ti on Read Only True
Cas e 3
ks. "
quo tati on= "Th at's all fol
End Sel ect
on
txtQ uot a ti on. Tex t = quo tati
End Sub
C ~' 6-1-2 ~~ @)
-
~
J
l Disp lay a Movi e Quotation
l~~J
6-l- 2
OK button .]
[Type 3 into the box and clic k on the
cj 6-1 -2
red
age of a sequ enc e of num bers ente
Example 3 The follow ing prog ram find s the aver - 1 to indicate the end
The user sho uld type in the num ber
by the user from inpu t dialog boxes. ente red , there is the pos-
ialog box appears before the loop is
of data entry. S ince the first inpu t d
ped.
sibility that the enti re loop will be skip
e.C lick
ck( ... ) Han dles btn Com put
Pri vat e Sub btnC omp ute_ Cli
Dim num As Dou ble = 0
Dim cou nt As Inte ger = 0
Dim sum As Dou ble = 0 " &
ter a non neg ativ e num ber.
Dim prom pt As Str ing = "En te ent erin g num ber s."
"En ter -1 to term ina
))
num = CDb l (Inp utB ox( pro mpt
Do Wh ile num <> -1
cou nt += 1
sum += num
))
num = CDb l (Inp utB ox( pro mpt
6.1 Do Loops
• 22 1
Loop
If cou nt > 0 Then
Mes sage Box .Sho w( "Av erag e: "
& sum I coun t)
Else
Mes sage Box . Show ( "No num bers
were ente red. " )
End If
End Sub
Ave rage : 85
Execute
state ment s
within
the loop
Do
stat eme nt ( s)
Loop Unt il con diti on is true No
condition
Execute
state ments
that follow
the loop
FIGURE 6.2 Pseu doco de and flowchar t for a Do loop
with the cond ition tested at the botto m.
222 • Cha pter 6 Rep et iti on
le formula.
tities for whic h we migh t not know a simp
Do loop s allow us to calc ulate useful quan
PROPERTY SETTING
OBJECT
a':} 6% Inter est ~[@] [}[] frmMi llion aire Text 6% lnter est
lblA mou nt Text Amo un t depo sited :
Amount deposited : txtA mou nt
btnC alcu late Tex t Calc u late Years to
Beco me a Mi ll iona ire
Calculate Years to Become a Millionaire
txt Whe n Rea dOn ly Tru e
Cli ck
k( ... ) Han dles btn Cal cul ate.
Priv ate Sub btn Cal cula te_ Clic
be orne a mill~onair
'Com pute yea rs re~ ~red to
num Yea rs As Inte ger
Dim bala nce As Dou ble ,
t.Te xt)
bal anc e= CDb l (txt Am oun
Do Whi le bala nce < 1000 000
bala nce += 0.06 * bala nce
num Yea rs += 1
Loo p
txtW hen .Tex t "In " & num Yea rs &
lion dol lars ."
" yea rs you wil l hav e a mil
End Sub
6.1 Do Loops
• 223
a ... 6% Interes
Amount deposited : I}
Comments
1. Be care ful to avo id infin ite loops-t
hat is, loops that are neve r ex ited . The
is infin ite, because the fo llow ing loop
cond ition "balance < 1000" wi ll always
can be avo ided by initi alizing intRate with be true. This logic erro r
a valu e grea ter than 0.
Priv ate Sub btnB utto n_ Clic k(
... ) Han dles btnB utto n.C lick
An 1nf1 n1te loop
Dim b a l ance As Dou ble = 100,
intR ate As Dou ble
Do Whi le bala nce < 1 000
bal a nce = (1 + intR ate) * bala
nce
Loop
t x tBa l ance .Tex t = Fo rma tCu rren cy( bala nce)
End Sub
n
If ans wer .To Upp er = "Y" The
con tinu e = "Ye s"
Els e
con tinu e "No "
End I f
Loo p
EXERCISES 6.1
but ton is clic ked on.
ne the out put disp laye d whe n the
In Exe rcises 1 thro ugh 6, dete rmi
lick
. .. ) Han dles btn Dis pla y.C
1. Pri vat e Sub btn Dis pla y_ Cl i ck(
Dim num As Inte ger = 3
Do Wh ile num < 15
num + = 5
Loo p
txtO utp ut.T ext CSt r(nu m)
End Sub
lick
.. . ) Han dles btn Dis pla y.C
2. Pri vat e Sub btn Dis pla y_ Cli ck(
Dim num As Inte ger = 3
Do
num = 2 * num
Loo p Un til num > 15
txtO utp ut.T ext CSt r(nu m)
End Sub
lick
. . . ) Han dles btn Dis pla y.C
3. Pri vat e Sub btn Dis pla y_ Cli ck(
Dim tot al As Dou ble = 0
Dim num As Inte ger = 1
Start
Set
F= 2
Set
T= N
Set
N = M mod N
Increase Set
F by 1 M= T
Set
N = N/F
End
End
FIGURE 6.4 G reat est com mon divi sor.
FIGURE 6.3 Prim e fact ors.
ses the butt on , val-
trat e the grow th of mon ey in a savi ngs acco unt . Wh en the user pres
30. Illus to calculat e the
are obta ined from text boxes and used
ues fo r A mou nt and Inte rest Rat e w.
bles . U se the form design sho wn belo
num ber of years unti l the mon ey dou nce, whe re r is
yea r is ( 1 + r ) times the prev ious bala
Not e: The bala nce at the end of each
l form .
the ann u al rate of inte rest in dec ima
PROPERTY SETTING
OBJECT
D Com p ou nd Inte rest GJI 8 lrnJ frml nterest Tex t Com pou nd
Inte rest
Tex t Am o un t:
Amount : lblA mou nt
txtA mou nt
Interest rate : A utoS ize Fa lse
[Allnual) lblR ate
Tex t Inte rest rate:
Determine Years [A nnu al]
txt Rate
Doubling time : Tex t Dete rmin e Year s
btnD eter min e
[Years) A uto ize Fa l e
lblD oubl
Tex t Dou blin g time :
[Yea rs]
Rea dO n ly True
txtD oub le
6.1 Do Loops
• 229
In Exe rcis es 31 throug h 38, wri
te a progra m to answer the que
stio n.
31. A person bor n in 198 0 can
claim, "I will be x yea rs old in
the yea r x squared." Wh at is the
va lue of x?
32. Th e world pop ula tion reac
hed 6.83 bill ion peo ple in Jan uar
rate of 1.1 2% eac h yea r. Ass um y 201 0 and was grow ing at the
ing tha t the popu lati on wi ll con
rate, wh en will the pop ula tion tinu e to gro w at the sa me
rea ch 10 bill io n ?
33. Str ont ium -90 , a rad ioac tive
e lem ent tha t is par t of the fall o
a half-life of 28 years. Thi s mea ut from nuc lea r exp los ion s, has
ns tha t a give n qua ntit y of tron
tive par ticl es and decay to one- tium -90 wi ll em it rad ioac-
half its size eve ry 28 yea rs. H ow
100 gra ms of st ron tium -90 to dec man y yea rs are req uired fo r
ay to less tha n 1 gra m ?
34. The consum er price index (CP
I) ind ica tes the ave rage price
serv ices. It is cus tomaril y tak en of a fix ed ba ket of goods and
as a measur e of infl at ion and is
pen sion s. Th e C PI was 9.9 in July freq uen tly used to adju st
1913 , was 100 in Ju ly 1983, and
Thi s mea ns tha t $9. 90 in Ju ly 191 was 215.35 in July 2009.
3 had the sa me pur cha sing pow
and the sam e pur cha sing pow er er as $ 100 .00 in Jul y 1983,
as $2 15.35 in July 2009. In 200
tim e sinc e 1955. H owe ver, for 9, the C PI fell for the first
mos t of the pre ced ing 15 yea rs
rate of 2.5 % per yea r. A sum ing it had gro wn at an ave rage
tha t the C PI will rise at 2.5 % per
yea r will the July CP I have at yea r in the future, in wha t
leas t dou bled from its Jul y 2009
CP I will be 1.025 times the CP leve l? Not e: Eac h yea r, the
l for the previous yea r.
35. Wh en you bor row mo ney
to buy a ho use or a ca r, the loan
equ al mo nth ly pay men ts inc orp is paid off wit h a seq uen ce of
o rati ng a stat ed ann ua l inte res t
The am oun t borrowed is call ed rate co mp o und ed mo nth ly.
the princifJal. If the ann u al inte
the mo nth ly inte rest rate is .06 rest rate is 6% (o r .06) , the n
/12 = .005. At any tim e, the
am oun t still owed. Th e bal anc e balance of the loan is the
at the end of eac h mo nth is calc
end of the prev ious mo nth , plus u late d as the bala n ce at the
the inte rest due o n tha t bala nce
pay men t. For inst anc e, wit h an , and min us the mo nth ly
ann u al inte rest rate of 6%,
[new bal anc e J = [prev ious bal
anc e J + .005 · [prev io us
= 1.005 · [pre vio us bala nce J - [ mo nth bal anc e J - [ mo nth ly pay me nt J
ly pay men t].
Sup pos e you borrow $ 15 ,000 to
buy a new ca r at 6% inte rest com
your mo nth l y pay me nt is $29 0.0 po und ed mo nth ly and
0. Aft er how ma ny mo nths wil
Th at is, afte r how man y mo nth l the ca r be half paid off?
s wi ll the bala nce be less tha n ha
36. An annuity is a seq uen ce of lf the principal?
equa l periodic payments. On e
plan, con sists of mo nth ly paymen type of annuity, called a savings
ts into a sav ings accoun t in ord
futu re purchase. Suppose you dec er to ge nerate mo ney for a
ide to depos it $ 100 at the end of
accou nt paying 3% inte rest com eac h mo nth into a sav ings
pou nded mo nth ly. The mo nth ly
.0025, and the bala nce in the acc inte rest rate wi ll be .03/ 12 or
ou nt at the end of eac h mo nth
will be com put ed as
[ba lan ce at end of mo nth J = (
1.0 025 ) · [ba lan ce at end of pre
vio us mo nth ] + 100.
Aft er how man y mo nth s will
the re be mo re tha n $30 00 in
mo ney will be in the acc oun t at the acc o unt , and h ow mu ch
tha t tim e ?
37. An annuity is a seq uen ce of
equal periodic payments. For one
mo ney is deposited into a ban k type of ann uity, a large amo unt of
accoun t and the n a fixed amo unt
Sup pose you deposit $ 10,000 into is wit hdr awn eac h mo nth .
suc h an accoun t pay ing 3.6 % inte
and the n withdraw $60 0 at the rest com pou nde d mo nth ly,
end of eac h mon th. The mo nth
or .003, and the balance in the acc ly inte rest rate will be .036/12
oun t at the end of eac h mo nth will
be com put ed as
[ba lanc e at end of mo nth J = (
1.0 03) · [ ba lan ce at end of prev
ious mo nth J - 600 .
Aft er how man y mo nth s will
the acc oun t con tain less tha n
am oun t in the acc oun t at tha t $60 0, and wh at will be the
time?
38. Red o Exerci e 37 wit h the
am oun t of mo ney depos ited bein
g inp ut by the use r.
230 • Ch apt er 6 Rep etit ion
6.1
Solutions to Practice Problems
e.
sho uld be executed at least onc
b, the con d ition is che cked at th e bottom if the loop
1. As a ru le of thum the first li ne to Do and replace
with the stat eme n t con tin ue = " Yes " , or cha nge
2. Either precede the loop "Ye s" .
p Un til con tin ue <>
theL oop stat eme ntw ith Loo
1 1
2 4
3 9
4 16
5 25
'Ad d 1 to 1.
i += 1
Loo p
End Sub
xt Loop
General Form of a For . .. Ne
gra m of the form
In gen era l, a po rtio n of a pro
Vidc oNo te
~ To n ,.__ _ _ _ _ term
For ... Next loop>
I !+
For i As nlmi / ),u<~1 '/'c = m
inating value
counter variable ~
initial value
body
stat eme nt( s)
Nex t
Set
counter variable
to initial value
For i As numD ataTy pe m to n
state ment (s)
Next
Is
counter variable Yes
> terminating
value?
No
Execute
statements
within loop
Increment
counter
variable
Execute
statements
following
the loop
FIGURE 6.5 Pseud ocode and flowc hart of a For . . . Next loop.
The cou nter variable can be any nume ric variable. The
most comm on single- letter names are
i, j , and I<; however, if appro pri ate, the name should sugges
t the purpo e of the count er variable.
The count er vari ab le, and any variable decla red inside
a For .. . N ext loop, has block -level
scope; that is, the va ri able canno t be referr ed to by code
outsid e of the loop.
232 • Cha pter 6 Rep etiti on
ing
300 ,000 in the year 2010 and is grow
Example 1 Suppose the population of a city is the popu latio n eac h
rate of 3% per yea r. The follo win g prog ram disp lay a tab le show ing
at the
year unt il 2014.
PROPERTY SETTING
OBJECT
~~ 8 ~~ frmP op ulati on Tex t Popu latio n Gro wth
ll -' Pop ulat ion Growth
btnD isplay Tex t Disp lay Populati on
Display Population j lstTab le Fon t Couri er New
Display Population
2 010 3 00,0 00
2 011 3 0 9 ,000
2 01 2 3 18, 2 70
2 01 3 32 , 818
2 0 14 33 7,6 53
6.2 For ... Nex t Loops
• 233
OBJECT
~I B
D~ For index = 0 Ton 5tep s PROPERTY
I@J frm lndex Text
SETTING
For inde x = 0
n: s: To n tcp s
IbiN Text n:
Display Values of Index
txt End
~
Is! Values
- IbiS Text s:
txtS tep
btnD isp lay Text Disp lay Va lu e
of lndex
lstVa lues
kwa rds:
a word as inp ut and d isplays it bac
Example 3 The foll owing progra m accepts
PROPERTY SETTING
OBJECT
Wri te Bac kwa rds
~~ ~ Write Backwards ~~ ~ 1@ 3 frmBackwards Tex t
Ent er wo rd :
lblW ord Tex t
Enter word : txt Wo rd
Tex t Rev erse Lett ers
btnR eve rse
Reverse Letters Rea dOn ly Tru e
txtB ackw ards
ing
inf o As Str ing ) As Str
Fun ctio n Rev erse (By Val
As Str ing =
1111
Reverse Letters
ZEUS
J
Pri vat e Sub btn Dis pla
y _ Cli c k( ... ) Ha ndl es
Dim r ow, en try As Str btn Dis pla y.C lic k
ing
lst Ta ble . Item s . Cle ar ()
For j As Int ege r = 1
To 3
row
For k As Int ege r 1 To 3
236 • Chapter 6 Repetition
Ne xt
)
l stT abl e . I t em s.A dd( row
Ne xt
End Sub
.]
[Run, and click on the but ton
[ Display Tab le I
1 X 2 = 2 1 X 3 = 3 1
1 X 1 =1
2 X 1
3 X 1
=2
=3
2 X 2
3 X 2
=
=
4
6
2 X 3
3 X 3
=
= :I
Left factor
t t Ri ght factor
e Eq uiv ale nt
Lo cal Typ e In f e r enc
S t and ard De cla rat ion
To 3 For i = 1 To 3
For i As Int eg er = 1 For i = 1 To 3 Ste p
0.5
1 To 3 Ste p 0.5
For i As Do ubl e =
Dim cou nt = 5
r 5
Dim cou nt As Int ege =
Dim rat e = 0.0 5
0 . 05
Dim rat e as Do ubl e = Dim nam e = "Fr ed"
Str ing = " Fre d"
Dim nam e As Dim d = #6 / 4 / 201 0#
#6 / 4 / 201 0#
Dim d as Da te =
Local type inferenc e was added to Visual Bas ic beca use it is needed fo r
LINQ (Language
INtegra ted Query) , an innovat ive language feature that unifies the manipu
lation of diverse col-
lections of data. LINQ is introdu ced in C hapter 7 of this book and is used
extensiv ely from then
on . By necessit y, we rely on local type inferenc e when using LINQ. Althou
gh we do not use
local type inferenc e in the declara tio n of ordinar y variables, you may feel
free to do so if you
prefer and your instruct or pe rmits.
Local type inferenc e is also known as duck typing. This name comes from
the well-kn own
quote, "If it walks like a du ck, and quacks li ke a duck, then it is a duck."
Comments
1. Fo r and N ext stateme nts must be paired. If one is miss ing, the syntax checker
will compla in
with a wavy underli ne and a message such as "A 'For' mu st be pa ired with
a 'Nex t' ."
2. Consid er a loop beginni ng with For i = m To n S tep s. The loop wi ll
be execute d exac tly
once if m equ a ls n no matter what va lu e s has. The loop will not be execute
d at a ll if m i
greate r than n and s is pos iti ve, or if m is less than n and s is negative.
3. The va lue of the counter variab le should not be altered within the body
of the loop; doing so
might ca use the loop to repeat indefinitely or have an unpredi ctable number
of repetitio ns.
4. N oninteger S tep va lues in Fo r ... N ex t loops ca n result in unexpe
cted outcom es. For
instance, if you run Exampl e 2 with n = 2 and s = .1, the las t num be r displaye
d will not be
2 as intend ed. In ge neral, the use of counter variables of type Do uble is poor
program ming
practice and should be avo id ed. From now on, all counter variables appea
ring in this book
will have type Integer.
5. Visual Ba ic provides a way to abort an iteration in a For ... Next loop.
When the tatemen t
Continu e For is encoun tered in the body of the loop, executio n immedi
ately jumps to the N ext
stateme nt. A n a11alogo us stateme nt continu e Do is ava ilable for Do loops. Typicall
y, Continu e
For and Continu e Do stateme nts appear inside conditio nal structur es such as
If blocks.
6. Vi ual Bas ic provides a way to back o ut of a For . . . N ex t loop. When
the stateme nt Exit
For is encoun tered in the body of the loop, executi on jumps immedi
ate ly to the tatemen t
followin g the N ex t stateme nt.
7. Counte r va riab les and variables declared inside For . .. N ex t loops have
block-level scope;
that is, they cannot be referred to by code outside the loops.
8. A ny type of loop can be nested inside another loop. For example, Fo r ...
N ex t loops can be
nested insid e Do loops and vice ve rsa. Also, Do loops can be nested inside
other Do loops.
EXERCISES 6.2
1. Priv ate Sub btnDis play_ Click( ... ) Handle s btnDis p l ay . Click
For i As Intege r = 1 To 4
lstBox . Items . Add (" Pass #" & i)
Next
End Sub
Click
2. Privat e Sub btnDis play_ Click( ... ) Handle s btnDi splay.
For i As Intege r = 3 To 6
lstBox .I tems.A dd(2 * i )
Next
End Sub
Click
3. Privat e Sub btnDis play_ Click( ... ) Handle s btnDi splay.
For j As Intege r = 2 To 8 Step 2
lstBox . Items. Add(j)
Next
lstBox .I tems.A dd("Wh o do we apprec iate?" )
End Sub
splay. Click
4. Privat e Sub btnDi splay _ Click( ... ) Handle s btnDi
For countd own As Intege r = 10 To 1 Step -1
lstBox . Items.A dd(cou ntdown )
Next
lstBox .I tems.A dd("bl astoff ")
End Sub
Click
5. Privat e Sub btnDis play_ Click( ... ) Handle s btnDi splay.
Dim num As Intege r = 5
For i As Intege r = num To (2 * num - 3)
lstBox .I tems . Add (i)
Next
End Sub
splay. Click
6. Privat e Sub btnDis play_ Click( .. . ) Handle s btnDi
For i As Intege r = -9 To -1 Step 3
lstBox .Item s.Add( i)
Next
End Sub
Cli c k
7. Privat e Sub btnDis play_ Click( ... ) Handle s btnDi splay.
'Chr (l49) is a large dot
Dim string OfDots As String
For i As Intege r = 1 To 1 0
stringO fDots &= Chr(14 9)
Next
txtBox .Text stringO fDots
End Sub
6.2 For ... Nex t Loops
• 239
If i = 13 The n
i = 12
End If
lstB ox. Item s.A dd( i)
Nex t
End Sub
pla y . Cli ck
Cli ck( ... ) Han dle s btn Dis
14. Pri vat e Sub btn Dis pla y_
4 Ste p 0.5
For j As Int ege r = 1 To
l s tBo x.It em s.A dd( j)
Nex t
End Su b
loop.
the pro gra m usin g a For . .. Nex t
In Exe rcis s 15 and 16, rew rite
y.C lick
ck( ... ) Han dle s btn Dis pla
15. Pri va t e Sub btn Dis pla y_ Cli
Dim num As Int ege r = 1
Do Whil e num <= 9
lstB ox. Item s.A dd( num )
num += 2 'Ad d 2 to val ue of num
Loo p
End Sub
pla y.C lick
Cli ck( ... ) Han dle s btn Dis
16. Pri va te Sub btn Dis pla y_
")
ls t Box . Item s .Ad d ("h ello
Ad d(" hel lo" )
ls t Box .Ite ms.
hel lo" )
ls t Box .Ite ms. Ad d("
llo" )
lstB ox. Item s.A dd( "he
End Sub
t loop to car ry out the
a pro gra m con tain ing a For ... Nex
In Exe rcis es 17 thro ugh 3 7, wri te
stat ed ta k.
17. Display the eve n num bers
fro m 1 thro ugh 100 in a list box.
hun dred pos iti ve integers.
18. Find the sum of the first one
ut di alog boxes.
Fin d the ave rage of five num be rs obt ained from the use r with inp
19.
di alog boxes.
Fin d the largest of fi ve num bers obt ained from the user wit h inp ut
20.
1/3 + 1/4 + · · · + 1/100.
21. Find the va lue of 1 + 1/2 + lay a stri ng of n la rge
e intege r (cal l it n) and the n disp
22. Ask the use r to inp ut a pos itiv te histog ram s, as
Not e: C hr( l49 ) is a larg e dot. Str ings of dot s can be used to crea
doc .
in Fig. 6. 11 on page 242. reci ate by 15 %
DeJ mciatio n . A rule of thu mb stat es tha t cars in per a nal use dep
23. Automobile e showing the va lue of
chased for $20,000. Produce a tabl
eac h yea r. Suppose a new car is pur
t fiv e years.
the car at the end of eac h of the nex
6.2 For ... Nex t Loops
• 241
a_. I ntere st
ll _. I d ea l Weig h s l = I·@) ,,....~ J
Display Growt h of Money
( Display Ideal VI/eights
]
~.MOUNT ~.MOUNT -1 r--- -
Y:::A:;<
S IY-~ ~
INE :;<:::S T
COY-~ OT.JN:>
fE IG'HT
'iE IG'HT
WOY..:::N
-rr: rGHT
M.:. N
I
INE :;<:::ST
1 02 109. 0 120 . 0
-? 1,05 0.00 ;?1,0 5 0.00
2 63 11 £ . 5 124. 0
:;;>1, 100.0 0 -? 1,10 2 . 5 0
64 116 0 12a. o
-?1,1 5 0 . 00 :;;;1,1 5 7.6 3
0
63 119. 5 132. 0
:;;;1,2 00 . 00 -?1, 21 5 5 1
66
0
123 . 0
11 -? 1,2 5 0.00
:; > 1,30 0 . 00
-?1,2 76.2 3
67 12.0 . .5
1 36.0
140. 0
~
-? 1,34 0.10
68 130. 0
~:: : J
-? 1,3 5 0 . 00 -? 1,40 7 . 10
69 133. 5
-?1, 400 . 00 ;? 1,47 7.4 6
70 137. 0 1 5 2.0
;?1,4 50.00 -? 1, 55 1.33
71 140. 5 156 .0
FIGURE 6.6 Outp ut of Exerc ise 26. FIGURE 6. 7 Possib le ou tput for Exerc ise 2 7.
_I = 1 @] 1~ ,.j
ll Ar n ity [= /§JL -~ ll .,. Car Loa n [
2015 n, 877 .. 94
2016 $9,3 34 . 19
2:01 7 $10, 834_ 74
2 0 18 $12 , 380 . 93
2:019 $13, 974 . 14
I = I @] ~~ J a~ ista-g ra ~
1 = l @] I. -~- -'
D.,. S p ly & De and
Beginning year: 2' (}7
Displcrt Soybean Projections
Ending year: 2· 1])
35. You are offered two salary option s for ten days of wo rk. Option
1: $ 100 per day. O ption 2:
$ 1 the first day, $2 the second day, $4 the third day, and so on,
with the amoun t doubli ng
each day. Determ ine which optio n pays better.
Exerci ses 36 and 37 sh ould use the follow ing Functi on proced
ure.
Functi on Day0fW eek(By Va1 d As Date) As String
Dim str As String = Forma tDateT ime(d, DateFo rmat.L
ongDa te)
Dim n As Integ er= str.Ind exOf( ",")
Return str.Su bstrin g(O, n)
End Functi on
36. Reques t a yea r as input and th en display the date of the
first Tu esday of that yea r.
37. Reques t a yea r as input and then d isp lay th e dates of the first
Tu e days of each mo nth of
that year.
is the index numbe r of the item curren tly highlig hted in lstBox.
If no ite m is h igh li ghted, the
va lu e of Se lected Ind ex is - 1. The statem ent
1stBo x.Se1e ctedin dex = -1
The val ue of
lstB ox.I t e ms(n )
of the list are of a data type called Obje ct. A
is the item of l tBox hav ing index n. The elements
type ca ting must take place when ever an
va lue of any type may be added to the list. However,
variab le or is conc atena ted with anoth er
elem ent of the list is ass igned to a nume ric or string
va riab le or Iitera l. For instan ce, the statement
txtBo x.Te x t = CStr (lstB ox.It ems( O))
a. U.S. States
States :
Dela•.-.•are ...
Penm:;1vania
New Jersey - Hawaii
Georg ia Alaska
Connecticut Arizona
Massachusetts New Mexico
M ar1~ and Oklahoma
South Carolina Utah
New Hampshire \'U'yorning
Virginia Idaho
New York Washington
North Carolina Montana
6.3 List Boxes and Loops
• 245
PROPERTY SETTING
OBJECT
D_. Ana lyze Grad es EEJI @) IE![] frm Grad es Text A nalyze G rades
lblG rade Text G rade:
lstGrades
Grade : txtG rade
btnR ccord Text Reco rd G rade
Reco·d Grade btnC alcul ate Text Calc ulate Average
and High est G rade
Calcu late Average lblAverage Text Ave rage grade:
and Hirhest Grade Read On ly Tru e
txtA verage
lblHighest Tex t High est grade:
Average grade :
txtH ighest Read Only True
Highest grade : lstG rades
l
[ Record Grade
I 76
~
SJ
Calculate Average
and Highest Grade
J ~
91
!16
Average grade: S7.13
Highest grade : S.6
EXERCISE~ 6.3
of
. De ter mi ne the con ten ts
1 thr oug h 6, ass um e tha t lstB ox is as sho wn below
In Ex erc ises
is exe cut ed.
the tex t box aft er the cod e
Bac h
Bee th ove n
Ch o_Ein
JlU.fkle
T ch aikovsky
90
60
6.3 Li t Boxes and Loops
• 249
1
Th e fil e Rose bowl. tx t (foun d in the fo lder
Prog rams \ C h06 \ Tex t_Files_for_Ex ercises) conta
names of the Rose Bowl winn ers in the o rder ins the
th e ga mes were played. Copy the co nte nts of
and Pa te th em in to the Strin g Collection Ed the tex t fi le
itor of lstBo x.
2
The file S tates. txt (fo und in the folde r Programs
\ C h06 \ Text_ Files_ for_ Exerc ises ) conta ins the
of the states in the o rder they joined th e uni on. name
250 • Chap ter 6 Repe titio n
CHAPTER 6 SUMMARY
1. A Do loop repe ated ly exec utes a
b lock o f stat e me nts e ith e r as lo n g
ditio n is true . The con dit io n ca n as o r unti l a ce rta in co n -
be c h ecke d e ithe r at the top of the
loop o r a t t h e bo tto m .
2. A For . .. Next loop repe ats a b lock
of state men ts a fixed num be r of time
a sum es an initi al va lue a nd inc rease s. The counter variable
s it by o n e afte r each pass thro ugh the
the term inat ing va lue. A ltern ativ e loop unti l it reac h es
inc re men t va lues can be spec ified
with the Step keywo rd .
3. Vi sual Bas ic uses local t)•pe infer
ence to infe r the d ata type of loca l var
o ut an A s cla use by look ing a t the iab le decl ared with -
data type of the initi a lizat io n exp ress
ion.
4. The item s in a list box a re as
ig n ed index numbers rang ing from
min us 1] . Loo ps can use t h e ind ex 0 to [num be r of it m s
num be rs to extr act info rma tio n from
list box es.
5. A flag is a Boo lean va ria ble used
to indi ca te whe the r a cert a in eve nt
ta in situ a ti o n ex ists. h as occu rred o r a ce r-
ks the coffee.
bod y 24 hours afte r the person drin
(b) The amo unt of caffeine in the a cup of coffee at
of coffee at 7 a.m . and the n drin ks
(c) Sup pose the person drin ks a cup will be in the bod y
the nex t day. How muc h caffeine
the end of eac h hour unt il 7 a. m.
at the end of the 24 hours?
ble due to inflatio n.
Rule of 72 is used to app rox ima te the tim e required for prices to dou
2. The double in 72/r yea rs.
Rul e of 72 estimates tha t prices will
If the inflatio n rate is r%, then the 12 yea rs. Wri te a pro-
6% , prices double in abo ut 72/6 or
For instance, at an infl atio n rate of to 20% , the prog ram
test the acc urac y of this rule. For eac h interest rate from 1%
gram to for prices to
the roun ded valu e of 72/r and the actu al num ber of yea rs required
sho uld disp lay eac h yea r.) See Fig. 6.13.
sum e pric es increase at the end of
double at an r% infl atio n rate. (As
up into the
ram to prov ide info rma tion on the height of a ball thro wn stra ight
3. Wr ite a prog the init ial velo city, v
inp ut the initial height, h fee t, and
air. Th prog ram sho uld requ est as n by the formula
ball (in feet) afte r t eco nds is give
feet per seco nd. The height of the llows:
to be prov ided by but ton s are as fo
h + v t - 16t feet. The four opti ons
2
reac h its max imum
Det erm ine the max imu m heig ht of the ball. Not e: The ball will
(a)
heigh t afte r v/32 seco nds. te the height
ine app rox ima tely whe n the ball will hit the gro und. Hin t: Calcula
(b) Det erm pos itiv e num ber.
ne whe n the height is no longer a
afte r eve ry .1 seco nd and dete rmi
nd for five seco nds or
(c) Disp lay a tabl e sho win g the
height of the ball eve ry qua rter seco
.
unt il it hits the ground. See Fig. 6.14
(d) ui t.
Initial Velocity:
Initial Height : 5 ~eet I seco nd)
34
~eet )
Determine ~proximate Tlme j
Determine Maximum Height
~--------------
--~
ll Until Ball Hits The Grou nd
~----D-i-sp_I~_·_T_a_b_le____-J) [ Quit
I DE !E IGH T
0 . 00 5.0
0 .2 5 12 . 5
0 . 50 18 . 0
0 .75 21. 5
1. 00 23. 0
1. 2 5
1 .5 0 20 . 0
1. 75 15 . 5
2. 00 9. 0
2.2 5 0.5
g Pro ject 3.
FIGURE 6.14 Sam ple Out put for Pro gram min
to a Salv age V a l e o 0
Description Year of
c omputer
of item : purc ha<:e : Estim ated life of
Cost : 15
item l)oear<:):
Straight-U ne Meth od
Doub le- Declining-Bala nce Meth
od
Description : computer
Year of purchase : 1 B
Cost : " 1..5
E..<:timated life : 5
Meth od of depreciation : straight-lin
e
No
Calculate
middle
Yes Set
flag = True
Set first=
middle + 1
257
258 • Chap ter 7 Arrays
As Dou ble
Dim stud ent2 9 As Stri ng , grad e29
'Ana lyze exam grad es
ter name of stud ent #"
Dim pro ptNa me As Stri ng = "En
= "En ter grad e for stud ent #"
Dim prom ptGr ade As Stri ng
& D, "Nam e" )
stud en t D = Inpu tBox (pro mptN ame
omp tGra de & D, "Gra de" ))
grad eD= CDbl (Inp utBo x(pr
ame & 1, "Nam e" )
stud en t 1 = Inpu tBox (pro mptN
CDbl (Inp utBo x(pr omp tGra de & 1, "Gra de" ))
grad el
End Sub
30 D im
y lo ng. Wha t's mos t frust rat ing is that the
This prog ram is go ing to be unco mfo rtabl as if they hould
ining inpu t are very similar and look
state men ts and 30 pairs of state men ts obta d be we l-
t ion fo r the man y relat ed varia bles woul
be cond ense d into a loop. A shor th and nota
com e. It wou ld be nice if we co uld just write
les and
will treat studenti and grade i a two variab
Of course, this will not work . Vi ual Ba ic lues of the
the end of the loop, they will h ave the va
keep reass ignin g new va lues to them. At
thirt ieth stud ent.
7.1 C reating and Acc essin g A rrays
• 259
0 0
grad es 87 92
87
92
0
of the Cod e Edi-
an ord inar y vari ab le, an arra y declared in the Dec lara tion s section
As with , and any values as igned
visible to all proced ures in the form
tor is cla s-level. Tha t is, it will be vari able s dec lared inside a
r the proced ure term inat es. Array
to it in a procedure wi ll persist afte ure is ex ited.
ure are loca l to tha t pro ced ure and cease to ex i t whe n the proced
pro ced
es of the
str ing array con sist ing of the nam
The foll ow ing prog ram creates a .
the prog ram
re 7.2 shows the array crea ted by
fi rst four Super Bow l winners. Figu
Jets hief
Pack ers Pack ers
team Nam es
e 1.
FIGURE 7.2 The a rray team Nam es of Exa mpl
PROPERTY SETTING
OBJECT
D Earl-; Super Bowls ~@] [};!] frmB owl Tex t Earl y S upe r Bowl
Num ber from 1 to 4:
Numberfrom 1 to 4: [ Vl/ho Won? I lblN u mbe r
mtb Num ber
Tex t
Mas k 0
btnW hoW on Tex t Wh o W on ?
Winning team : Tex t Win ning team:
lblW inne r
txt Win ner Rea d O n ly True
on.C lick
ck ( ... ) Han dle s btnW hoW
Pri vat e Sub btnW hoW on_ Cli
ing
Dim t eam Nam es(3 ) As Str
Dim n As Int ege r
s int o the arr ay
P ace Sup er Bow l Win ner
7.1 Creating and Accessing Arrays • 26 1
[Run, type 2 into the masked text box, and click on the button.]
The keywo rd MyBase is imilar to the Me keywo rd and refers to the fo rm. Exa mple 2 uses the
frmBowl_Load procedure to improve Examp le 1.
Example 2 The fo llowing variatio n of Exa mple 1 makes teamNames a clas -leve l array
and ass igns values to the elements of the array in the event procedure frmBowl_Load.
declare an a rray hav ing upper bound N and a signs valueO to arrayName(O), value 1 to
arrayName(l ), value2 to arrayName(2), .. . , and valueN to arrayName(N). For instance, in
Example 2, the Dim statement and frmBowl_Lo ad event procedure can be replaced by the
single line
Note: Yo u cannot use a li t of values in braces to fill an array if an upper bound has been
specified for the array. For instance, the fo llowing line of code is not va lid :
Text Files
The two eth ods we have u ed to fill an array are fine fo r small arrays. H oweve r, in practice
arrays can be quite large . One way to fill a large array is to use a simple data file known as a
text file . Text files ca n be created, viewed, and modified with sophi ticated word processors
such as Word, o r with e leme ntary word processo rs such a the Windows acces a ries W o rdPad
and Notepad. They differ from files normally created with Word in th at they h ave no fo r-
matt ing (such as line spac ing and font style ). They are pure tex t and no thing e lse-hence the
name text file. For instance, a text file that co uld be used to fill the array in Example 1 wo uld
look as f llows:
Packers
Packers
Jets
Chiefs
The text files needed fo r exercises in this book h ave been created for yo u and are in th e
material you downloaded from the compan ion website. They are contained in a subfolder
(named Text_Files_for_ Exerc i es ) of the appropriate ch ap ter folder. Each text file ends with the
extension ".txt".
The isual Basic IDE provides simple ways to create and ed it text fi les. The deta ils can be
found in Appendix B. C hapter 8 shows how to create text files program matically.
A statement of the form
where filespec refers to a text file, declares a string array whose size equals the number of lines in
the file, and fills it with the contents of the file. A numeric array can be filled with a text file by
first filling a temporary string array with the file and then using a loop, along with C lnt o r CDbl,
to transfer the numbers into the numeric array. (See Example 3.) Note: ln Section 7.2, we pre-
sent a way to fill a numeric array with the contents of a numeric tex t file without using a loop.
The Solu tion Explorer window ha the name of the program as its first line. If only a few
entries appear in the Solution Exp lorer, you can click on the Show All Files button ( ~) at the
7.1 rearing and Accessing Arrays
• 263
top of th e Solutio n Exp lorer wind ow to display all the fi les and
subfo lders. O ne subfo lder is
named bin. The folder bin h as a subfo lde r named Debug. lf the filespec
above consists only of a
filename (that is, if no pa th is given) , Visual Bas ic will look for
the fi le in the Debug subfo lder
of the progra m 's bin fo lder. Throu ghout this book, we assume that
every text file accesse d by
a progra m is located in th e progra m 's bin \Debug folder. Ev ery
progra m down loaded from the
compa nion website h as th i fea ture. When you write a progra m
that uses o ne of the tex t files
fro m a Text_Fi les_for_ Exerc ises fo lde r, you sho uld use Windo ws
Explorer to place a copy of the
text fil e into the program 's bin \Debug fo lder.
Array Methods
Both nu meri c and string arrays have the Co unt, Max , Min, First,
and La t metho ds. 1 The value
of arrayName.Co unt is the size of the array, arra)>N ame. Max is the VideoNo te
h ighe t va lue (alpha bet ically
or numeri cally), arrayName. Min is the lowest value, arrayName. Array
First is t he first e lement of the merhods
array, and arrayName.La t is the last elemen t. Note: The
upper bo und of the array is
arra)>Name.Co unt- 1. Table 7.1 shows some va lues with the array
from Exa mp le 1.
Example 3 The file A gesAtl naugur al. txt giv s the ages at inaugurat ion of
the 44 U. .
pres id ents. The first fo ur line conta in the data 57 , 61 , 57, 57- th
age fWa hingto n , Ad ams,
Jeffer on , and Madiso n at the ir inaugu rat ions. (To see the co ntents
of the fi le in a text edito r,
locate the file in the bin \Debug fo lder of t he Solutio n Explo rer and
double -click on the fi le. You
ca n remove the text edi to r by cl ick ing the X symbo l on its tab.)
( Display Values J
rc--
Obama : 47
Washington: 57
Obama : 47
Oldest age : 69
Youngest age : 42
Average age : 54.84
Average age : 54.84
Visual Basic allows you to declare an array wit hout spec ifying an upper bound with a state-
ment of the fo rm
Dim arrayName( ) As DataTyp e
Later, the size of the array can be spec ified with a ReOim statemen t. (N o va lues can be ass igned
to the e lemen ts of the array until a size is spec ified.)
The Re Dim statement h as on e shortco ming: It ca u es t he array to lose its current contents.
That is, it rese ts a ll string va lues to No th ing and resets all nu meric va lues to 0. Th is situation
ca n be remedied by foll owing ReOim with th e keywo rd Prese rve. The ge nera l fo rm of a ReOim
Prese rve statement is
ReDim Pre s e rv e array Name(m )
Of course, if you make an array smaller than it was, data at the end of the array will be lost.
Example 5 T h e following program reads the names of the winn ers of the fi rst 44 S uper
Bowl games from a tex t fi le and places th em into an array. The use r can type a tea m's name into
a text box and then d isplay the numbers of th e S uper Bowl games won by that tea m. The use r
has the option of adding winners of subseq uent games to t he array of winners. The program uses
th e fi le SBWinners. txt, whose lines con ta in the names of th e winners in order. Tha t is, th e first
four lines of the file co nta in the names Packers, Packers, Jets, and C hiefs.
Dim teamNames() As String
Dim numGames As Integer
9
10
13
1
40
43
Add Winner of Game 45
Flag Variables
keeps track of
The Boolean variable no Wins in th e btnDisp lay_C lick proced ure of Examp le 5
are used within
wh ethe r a certa in situatio n h as occurred. Such a varia ble is called a flag. Flags
lso prov ide an
loops to provide info rmat io n that will be utilized after the loop term ina tes. Flags a
a lte rnat ive meth od of terminat ing a loop.
The first line of the Fo r .. . Next loop a lso could h ave been wr itten as
Example 6 The follow ing variat ion of Examp le 4 ca lculates the max imum
value with a
Funct ion proced ure. Notic e th at the pa ramete r in the funct
ion heade r is wr itten ByVa1 ages ( J
As I ntege r , not By Va1 ages As Integ er , and
the functi o n call is wri tten Maxim um(ag es ) ,
not Maxim um (ages () ) .
grades . T he n umber
~ Example 1 T he fo llowin g program calc ulates the average of eve ral
r via inp ut d ialog boxes . The Function
of grades a d the grades themse lves are input by the use
s.
proced ure G etG rades return s an array con tainin g the grade
btnG et . Click
Priva te Sub btnG et Click ( . .. ) Hand les
Cint (Inpu tBox( "Num ber of grade s: " "Grad es" ) )
Dim n umGr ades As Integ er =
s) .Aver age)
t xtAv e r age.T ext = CStr (GetG rades (num Grade
End Sub
Integ er ) As Doub le ()
Func tion Ge tGrad es( ByVa l numGr ades As
Dim g r a des (numG rades - 1 ) As Doub le
For i As I n t eger = 1 To n umG rades
& i & " : " "Get Grade " ))
gra d e s (i - 1 ) = CDbl (Inpu tBox( "Grad e #"
Next
Retur n g r ades
End Func t ion
grade s 80, 85, and 90.]
[Run, enter 3 as the numb er of grades, and then enter the
Average : 85
De l awa r e
Pen n syl v a ni a
Ne w J e r sey
Georg i a
then tells the order in which it jo ined
The fo llowin g progra m requ ests the name of a state and
the union:
Dim s t a t es() As Strin g I O. File .Read AllLi nes( "Sta tes.t xt" )
7.1 C reating and Access ing Arrays • 269
[Run, type a state into the top tex t box, and click on the button .]
a~ U.S. Sta es l = I @) L Sl . .I
Determine Order
If a va lue might occur more than once in an array, an ex tension of the method above will
loca te subsequent occurrences. A tatement of the form
numVar = Array . IndexOf ( arrayName, value , startindex)
where startlndex is an intege r literal or ex pression , looks on ly at elements hav ing index
startlndex or greater, and ass igns to numVar the index of the first occurrence of the req uested
va lue. If the value is not found, then - 1 is ass igned to numVar.
Copying an Array
If arra)'One and arra)'Two have bee n declared with the sa me data type, then the statement
array Two = arrayOne
makes arra)'Two reference the same array as arra)'One. It will have the ame ize and co nta in the
sa me data. This statement must be used with care, however, since after it is executed, arra)'One
and arra)'Two wi ll share the same portion of memory. Therefore, a change in the va lue of an ele-
ment in one of the arrays will affect the other array.
O ne way to make a copy of an array that does not share the same memory locat ion is ill us-
trated by the following code:
'Assume arrayOne and arrayTwo have the same data type and size
For i As Integer = 0 To arrayOne . Count - 1
arrayTwo(i ) = arrayOne ( i)
Next
In ge era!, if strA rray is a string a rray a nd the string va riab le strVar h as been ass ign ed a
string of t he fo rm
"valueO,value l ,value2, ... ,valueN"
the n a sta tement of th e fo rm
strArray = strVar . Split( ","c )
resize strArray to an array with upper bound N having strA nay(O) = valueO , strAnay ( 1) = value
1,
... , strArray (N) = valueN. That is, the first element of the array conta ins the text preceding the
first comma, the second element the text between the first and second commas, ... , and the last ele-
men t the t xt fo llowing the la t comma. The comma character i called the delimiter for the statement
above, and th letter c specifies that d"le comma should have data type C haracter instead of String. Any
character can be u ed as a delimiter. (The two most common delimiters are dl.e comma character and
the space character.) The Split medl.od will play a vital role in Section 7.3.
Examp.le 9 The fo llow ing progra m de te rmines a pe rson 's first a nd last n a mes. The space
ne
ch aracter is used as the de limiter fo r the S plit method. Each e le ment of the a rray conta ins o
part of th pe rson 's full na me.
Comments
1. Using a subscript greater than the upper bound of an array
is not allowed. For instan ce, at
run time the two lines of code in Fig. 7.3 prod uce an excep tion
d ialog box .
l
Make sure data column names are correct.
Get general help for this exceptio~. ----
r~
I
Actions:
V1ew Detail...
Copy exception detail to the clipboard
2. The statem ents Conti nue For and Exit For can be used in
For Each loops in much the sa me
way they are used in For . . . Next loops. A lso, a vari able declar
ed inside a For Each loop has
block- level scope; that is, the var iable ca nnot be referred to
by code outside the loop.
3. After yo u doub le-click on the name of a text fi le and place
it into the text edito r, you can
alter the file's conten ts and save the altered file. To save the
altered file, right-c lick on the
fi le name in the text ed itor's tab and click on "Save bin \ Debug
\fileName."
n is clicked.
3. Dete rmine the outpu t displayed when the butto
les btnD ispla y . Click
Priva t e Sub btnD ispla y_ Click ( . . . ) Hand
Dim numW ords As Integ er
cont ains five word s."
Dim line As Strin g= "This sente nce
"c)
Dim word s() As Strin g= line .Spl it("
numWords = word s.Cou nt
txtOu tput. Text = CStr( numW ords)
End Sub
EXERCISES 7.1
100?
1. Wha t is the size of an array whose uppe r bound is
is 100?
2. Wha t is the uppe r boun d of an array whose size
displayed when the butto n is click ed.
In Exercises 3 throu gh 26, deter mine the outp ut
btnD ispla y.Cl ick
3. Priv a te Sub btnD ispla y_ Click ( ... ) Hand les
Dim n As Integ er = 2
Dim spoo ns(n) As Strin g
spo ons(O ) "soup "
spo ons( l) = "des sert"
spo ons(2 ) = "coff ee"
- 1) & " spoo n."
txt Outp ut.Te xt = "Hav e a " & spoo ns(n
End Sub
btnD ispla y.Cl ick
4. Priv a te Sub btnD ispla y_ Click ( . .. ) Hand les
'I'm look ing over a four leaf clov er.
Dim leave s(3) As Strin g
leave s(O) "sun shine "
leave s(1) 11
rain"
l e aves( 2) "the rose s that bloom in the lane"
l e aves( 3) "som ebody I adore "
Fo r i As Integ er = 0 To 3
1) & ": " & 1eav es(i) )
lstOu tput. Item s.Ad d("L eaf " & (i +
Ne xt
End Sub
les btnD ispla y.Cl ick
5. Priv ate Sub btnD ispla y_ Click ( ... ) Hand
Di m colo rs(l2 0) As Strin g
c o lors( O) = "Atom ic Tang erine "
color s(lOO ) = "Tan"
-1 Then
If color s(O) .Inde x0f(c olors (100 ))
txtO utpu t. Text = "No "
Else
txtO utpu t.Tex t "Ye s 11
End If
End Sub
btnD ispla y.Cl ick
6. Priv ate Sub btnDispla y_ Click ( ... ) Hand les
Dim year s(l) As Integ er
year s (0) 1776
year s(l) = Now. Year 'curr ent year as Integ er
7.1 C reat ing and Access ing Arrays • 273
names(O) II Alii
names (1) 11
Gore"
names(2) "Vidal"
names(3) 11
Sassoon 11
End Sub
In Exercises 19 through 2 2, assume the five lines of th e file Dates.tx t contain the
numbers
1492, 1776, 18 12, 1929, and 1941 and the fil e is in the program 's bin \Debug folder.
19. Private Sub btnDisp lay_ Click( .. . ) Handles btnDisp lay.Clic k
Dim dates() As String= IO . File.Re adAllLi nes("Da tes.txt" )
txtOutp ut . Text = "Pearl Harbor: " & dates(4 )
End Sub
20. Private Sub btnDisp lay_ Click( . .. ) Handles btnDisp lay . Click
Dim dates() As String= IO . File.Re adAllLi nes("Da tes.txt" )
txtOutp ut.Text ="Bice ntennia l Year: " & (Cint(d ates(l)) +
200)
End Sub
21. Pr i vate Sub btnDisp lay_ Click( ... ) Handles btnDisp lay.Clic k
Dim dates() As String= IO.File .ReadA llLines( "Dates. txt")
Dim flag As Boolean = False
For Each yr As String In dates
If (Cint (yr ) >= 1800) And (Cint(yr ) <= 1899) Then
flag = True
End If
Next
If flag Then
txtOutp ut.Text •contain s a 19th-ce ntury date"
Else
txtOutp ut . Text "does not contain a 19th-ce ntury date"
End If
End Sub
22. Private Sub btnDisp lay_ Click( ... ) Handles btnDisp lay.Clic k
Dim dates() As String= IO.File . ReadAll Lines("D ates . txt")
Dim total As Integer = 0
For Each y r As String In dates
If (Cint(yr ) >= 1 9 00) Then
total += 1
End If
Next
txtOutp ut.Tex t = total & " 20th-ce ntury dates"
End Sub
23. Private Sub btnDisp lay_ Click( ... ) Handles btnDisp lay.Clic k
Dim words() As String= {"We", "the", "People ", "of" , "the",
11
United" , 11
States" , "in 11 , "Order" , "to", "form",
"a" , "more", "perfec t", "Union" }
txtOutp ut.Text = BeginWi thVowel (words) & " words begin with
a vowel"
End Sub
276 • Chapte r 7 A rrays
) As Intege r
Functi on BeginW ithVow el(ByVal words( ) As String
Dim total As Intege r = 0
For Each word As String I n words
word = word.T oUppe r
Or
If word.S tartsW ith("A " ) Or word.S tartsW ith("E ")
word. Starts With( "I" ) Or word.S tartsW ith("O ") Or
As Intege r()
Functi on CurveG rades(B yVa l scores () As Intege r)
For i As Intege r = 0 To scores .Coun t - 1
scores (i) = score s(i ) + 7
If scores (i) > 100 Then
scores (i) = 100
End If
Next
Return scores
End Functi on
play . Click
25. Privat e Sub btnDis play_ Click( ... ) Handle s btnDis
Dim nums() As Integ er= {2, 6, 4}
nums = Revers e(nums )
For Each num As Intege r In nums
lstOut put.Ite ms.Ad d (num)
Next
End Sub
r()
Functi on Revers e(ByV al nums() As Intege r) As Intege
Dim n = nums.C ount - 1
Dim temp(n ) As Intege r
For i As Intege r = 0 To n
temp(i ) = nums(n i)
Next
Return temp
End Functi on
Click
26. Privat e Sub btnDis play_ Click( ... ) Handle s btnDi splay.
Dim speech () As String = {"Fou r", "score ", "and",
11
Seven 11 , "years ", 11
ago" }
contains the names of the fi ve G rea t Lakes. Evaluate and interpret each of the follow ing:
(a) lakes. Max (b) lakes . Min
(c) lakes. First (d) lakes.Last
(e) lakes. Count (f) lakes (1)
(g) Array.Inde xOf(lakes, "Erie")
contains the surface areas (in squ are miles ) of the five Grea t Lakes. Evaluate and interpret
each of the following:
(a) lakeAreas . Max (b) lakeAreas.M in
(c) lakeAreas. First (d) lakeAreas. Last
(e) lakeAreas. Count (f) lakeAreas . Sum
(g) lakeAreas . Average (h) lakeAreas ( 2)
(i) Array .IndexOf(l akeAreas, 8000)
contains the populations (in mil lions) of the six N ew England states. Evaluate and inter-
pret each of the following:
(a) statePops.M ax (b) statePops.M in
(c) statePops. First (d) statePops. Last
(e) statePops.C ount (f) statePops (3)
(g) Array.Inde xOf(stateP ops, 1 . 1)
contains the names of the six N ew England states listed in the order in which they beca me
part of the U nited States. Eva luate and interpret each of the following:
(a) statesNE .Max (b) statesNE.M in
(c)statesNE. First (d) statesNE.L ast
(e) statesNE.C ount (f) statesNE(O )
(g) Array. IndexOf (statesNE, "Maine")
278 • Chapter 7 Arrays
the o rde r in
31 . Suppose the array states has been fill ed with the names of the fifty state in
llow ing
which they beca me part of the U nited S tates. Write code to di pl ay each of the fo
states in a list box.
(a) the first state to jo in th e un ion (b) the original th irteen states
(c) the mo t rece n t state to jo in (d) the o rd er numbe r fo r O hio
(e) the second state to jo in the union (f) the twentiet h state to jo in the union
(g) th e last ten states to jo in the union
in the o rd er
32. S uppose the array JJres has bee n filled with the names of the 44 U.S. pres idents
in which they served. Write code to di play each of the fo llowing in a list box.
(a) the first pres id ent (b) the first six pres id ents
(c) the most recent pres id ent (d) the number fo r "James Monroe"
(e) the second pres ident (f) the tenth pres id ent
(g) th e last five pres idents
38,
Assume the array nums contains a list of positive integers. In Exercise s 33 through
write a Function procedur e that calculate s the stated value with a For Each loop.
42. Dim nums () As Integer = IO. File. ReadAll Lines ("Numbe rs. txt")
string
43. Write a single line of code that d isplays the number of words in a se ntence, where th e
variab le line ho lds the sentence.
44. Write a single line of code that d isplays the number of names in the file N ames. txt.
45. The file N umbers. txt conta ins a list of intege rs. Write a program that displays the number
of integers in the fi le and their sum.
e if
46. The fil e SomeS tates.txt contains a list of some U.S . states. Write a program to determin
th e sta tes are in a lphabetica l order.
to find
47. The file N ames2 .txt conta in a list of name in alphabetica l order. Write a program
be repeated ,
and d isp lay those entries that are repea ted in the fil e. When a name is found to
48. S uppose the file Final. txt contains stud ent grades on a final exam. Write a program that dis-
plays the average grade on the exam and the percentage of grades that are above average.
49. The file Oigits.tx t conta ins a list of digits, all betwe n 0 and 9. Write a program that d is-
plays the frequency of each di git.
50. Wri te a Boolean-va lued Function procedure A reSa me to co mpare two intege r arrays and
determine wh ether they h ave the sa me size and hold identi cal values-that is, wh ether
a(i) = b(i) fo r a ll i.
51. Write a Function procedure to calcu late the sum of the entries with odd subscripts in an
intege r array.
52. The file S tates. txt contains the names of the 50 U.S . states. Write a program that creates an
array co nsisting of the states beginning with "New". The program also should display the
names of these states in a list box .
53. Table 7. 2 sh ows the different grades of eggs and the minimum w ight requ ired fo r each clas-
sificatio n. Write a program that proces es the tex t file Eggs.txt conta ining a list of the
we ights of a sample of egg . The program should report the number of eggs in each grade
and th e we ight of the lightest and h avies t egg in the sample. Figure 7.4 sh ows the o utput
of the program. Note: Eggs weighing I ss than 1.5 oun ces cannot be sold in supe rmarkets
and therefo re will no t be counted.
Jum bo 2.5
Extra Large 2.25
Large 2
Medium 1.75
Small 1.5
57 Jumbo eggs
9 5 Ex t ra Large eggs
76 Large eggs
96 Medium eggs
77 Small eggs
Lightest egg: 1 ounces
Heaviest egg: 2.69 ounces
FIGURE 7.4 Output for Exercise 53.
54. The file USPres. txt conta ins the names of the 44 U .S. pres idents in the order in which they
erved . Write a program that places the names in an array and displays all pres idents for a
requested range of numbers. Figure 7.5 on the next page shows one poss ible outcome. (J o hn
Tyler was the tenth pres ident. James Polk was the eleventh president. And so o n.)
Exercises 55 through 58 should use the file Colors.txt that contains the names of the colors
of Crayola® crayons in alphabetical order.
55. Write a program to read the co lo rs into an array and then display th e co lors beginning with
a spec ified letter. O ne pos ible outcome is shown in Fig. 7.6 on t he next page.
56. Write a program that requ ests a colo r as input in a tex t box and then determines whether or
not the colo r is in the tex t file. The program sho uld use the Boolean-va lued Functi on proc -
dure IsCrayo la th at returns the va lue True if the color in the tex t box is a C rayo la color.
57. Redo Ex rc ise 55 with the letter passed to a Functi on procedure th at return a maller array
co nta ining just the colors beginning with the spec ifi ed letter.
280 • Chapter 7 Arrays
::_j
f 10. John Ty!- -;,:- Tickle Me Pink
11 . James Polk
12. Zachary Tay!or
I Timber V\loff
TorchRed
13. Millard Fillmore Tropical Rain Forest
14. Franklin Pierce
15. James Buchanan J ITumbleweed
1 Turquoise Blue
'
FIGURE 7.5 Possible outcome of Exercise 54. FIGURE 7.6 Poss ible outcome of Exercise 55.
58. Write a program that displays the colo rs in reve rse alphabeti ca l order.
59. The file Sonnet.txt contains Shakespeare's So nnet 18. Each entry in the file conta ins a line
of the sonnet. Write a program that reports the ave rage number of words in a line and the
tota l numbe r of words in the sonnet.
60. Statisticians use the concepts of range, mea n, and stand ard dev iat ion to descri be a co llec-
tion of num erica l data. The range is the difference betwee n the largest and small est num-
bers in the collection. The mean is the ave rage of the numbers, and the standard deviation
measures the spread o r di spersal of the numbers abo ut the mean . Fo rma lly, if
x 1, Xz, X3, ... , X 11 is a co llection of num be rs, then
x 1 +x 2 +x 3 + .. . +x 11
mea n = (denote the mea n by m)
n
FIGURE 7.7 Possible outcome of Exercise 61. FIGURE 7.8 Outcome of Exercise 62.
7.2 Us ing U NQ with Arrays
• 28 1
62. The file cores. tx t conta ins scores betwee n 1 and 49. W ri te a program
that uses these scores
to c reate an array frequencies as fo llo ws:
freq uen c ies (O) = ;r of sco res< 10
freque nc ies ( 1) = *of sco res with 10 :::; sco re < 20
freq uen c ies (2 ) =#of scores with 20 :::; sco re < 30
freque n c ies(} ) = 4 of scores with 30 :::; score < 40
frequen cies ( 4) = #of scores with 40 :::; score < 50
The progra m sh o uld th en display th e results in ta bu lar fo rm, as sh o wn
in Fig. 7.8 .
In Exe rcises 63 and 64, execute the statem ent sentenc e = senten
ce. Replac e (", ", "") to
remove all comma s in sentenc e, and th en remove other punctua tion
marks similarl y. After
that, use th e space charact er as a delimit er for the Split method .
63. A se nten ce i ca lled a chain-lin k se nten ce if th e last two lette rs of each
wo rd are the arne as
the first two le tte rs of the n ex t wo rd- fo r instance , "The h ead adminis
trato r o rga nized edu -
ca ti o n o n o nl ine netwo rks. " Write a program th a t accepts a se nte nce
as input a nd de te r-
mines wh e ther it is a ch a in-link ente nce. Test the program with the
sen tence " Broadca st
stat io n , o nce ce rtified , edu cates estimab le legio ns. "
64. A word palindro me is a se nte nce th at reads the sa me, wo rd by wo
rd , backwa rd a nd fo rward
( ign o ring punctua ti o n a nd capita lizatio n) . An exa mple is "Yo u ca n
cage a swa llo w, ca n 't
yo u, but you ca n 't swa llo w a cage, ca n yo u ?" Write a program th a t req
ue ts a senten ce a nd
then determi n es whe th er the se nten ce is a wo rd pa lindrom e. Th e program
sh o ul d place the
wo rds of the sente nce in a n a rray and use a Func tio n procedu re to determi
ne whethe r th e
se nte n ce is a wo rd pa lind rome. (Test th e progra m with the sente nces "Mo
nkey see, mo nkey
do ." a nd "I a m ; therefo re, a m I?" )
liNQ Queries
Video Note
ent) code that describes what you
LINQ A LIN Q query for an array is declar ative (that is, se lf-evid
want to retrieve fro m the array. A state ment of the form
[cond ition on var] Selec t var
Dim queryN ame = From var In arrayN ame Where
of e lemen ts in the array much like
is called a LINQ query. The variable var takes on th e va lu es
declares a va riab le queryN ame and
the loop ing variab le in a For Each loop. The sta temen t
that satisfy the condit ion on var.
ass igns it a equen ce consisting of the eleme nts of the array
on var] ",and " selec t var" are
The phrases " From var In arrayN ame" , "wher e [cond i tion
are ca lled query operat ors, var is
called query clauses. The keywords From, Where , and Select
data . The entire express ion to the
called a range variab le, and arrayName is called the source
right of the eq ual sign is ca lled a query expres sion.
The LINQ query above is usually writte n in th e style
Dim queryN ame = From var In arrayN ame
Where [cond it ion on var]
Selec t var
that you are declar ing a query and
As soon as you type the first line, the Code Editor will know
u at ion. H oweve r, after you type
will treat each pres of the Enter key as signaling a line contin
to tell the Code Editor that the
the last clause of t he query, you can press Ctrl + Shift + Enter
Enter key twice to compl ete entry
query declar at ion is compl ete. (Alter nately , you can press the
of the query.)
in which they
Example 1 The file States .txt contai ns the 50 U.S. states in the order
states with five-le tter names and
joined the union. The following progra m first displays the
express ion return s a sequen ce of
then displays the states beginn ing with "New" . Each query
states that is displayed with a For Each loop.
btnDi splay .Click
Priva te Sub btnDi splay_ Click ( ... ) Handl es
nes( "Stat es.tx t" )
Dim state s() As Strin g = IO. File .Read AllLi
Dim stateQ ueryl = From state In state s
Where state. Leng th = 5
Selec t state
For Each state As Strin g In stateQ ueryl
lstSta tes.It ems.A dd(st ate)
Next
lstSta tes.It ems.A dd( "" )
Dim stateQ uery2 = From state In state s
Where state . Starts Wi th ( "New" )
Selec t state
For Each state As Strin g I n stateQ uery2
lstSta tes.It ems.A dd(st ate)
Next
End Sub
7.2 Us ing LI NQ with A rrays • 283
[ Display States )
Maine
Texas
Idaho
New Jersey
New Hampshire
New York
New Mexico
'---- --
The array methods Count, Max, Min, First, and Last apply to all sequences returned by LINQ
queries, and the array methods Ave rage and Sum apply to nu meric sequences. A lso, the successive
elements in the sequence can be referred to by indices ranging from 0 to queryName.Co unt - 1.
For instance, in Examp le 1, the values of stateQuery1 (O) , stateQuery1 (1) , and
stateQuery1 (2 ) are Maine, Texas, and Idaho.
Example 2 The foll owing program d isplays values associated with numeri c sequences
returned by LINQ queries. Note: The intege r n is eve n if n Mod 2 is 0.
D umbers l = I @J 1-- ~
[ Display Numbers
1
12
s
11
Largest number: 12
Second number: S
Sum of numbers : 31
T h e va ri able in the Se lect clause can be replaced by an express ion involving the variab le.
For instance, if the clause Select nwn in numQuery 1 of Example 2 were replaced by
Select nwn * nwn
th en the first three lines in the list box would be 144, 64, and 121. A lso, bo th Where clause
and Select clauses are optional. W hen th e Where clause is miss ing, all va lues in the source data
are includ ed. A miss ing Select clause produces the same effect as th e clause Select var. In this
textbook we always include a Select clause.
disp lay the name of the teams that have won a S uper Bowl, with each team listed once .
create the array named uniqueWinners containin g the names of the teams th at have won the
S upe r Bowl, with each team appearing just once as an element of the array.
7.2 Using UNQ with Arrays • 285
Example 3 The file US Pres. txt conta ins the names of the 44 U. . presidents. The first
two lines of the fi le are George Washington and John Adams. The follow ing program asks the
user to enter a first name and then displays the names of all the pres idents hav ing that first name:
I Display Presidents }
·-
~;resident James Madison
President James Monroe
President James Polk
President James Buchanan
President James Garfield
President James Carter
For string va lues, the A NS I table is used to evaluate the "less than or eq ual to" cond ition .
Putt ing eleme nts in alphabe tical or numeric order (either ascend ing or de cending) is
referred to as sorting. There are many algorith ms for so rting arrays. The mos t efficient ones use
complex nested loops and are tricky to program. Howeve r, LINQ prov ides the O rder By query
operato r that spa res us fro m hav ing to code co mplicated sort ing algori thms. T he simplest form
of an O rder By clause is
where Direction is one of the keywords Asce nding or Descend ing, and the exp ress ion invo lves
range and/or Let va riables.
Example 4 The following program sorts an array of numbers in ascend ing order. Note: If
the word Ascending is replaced by Descend ing, the array will be so rted in descend ing order.
Sort Numbers
[]
The O rder By operator is quite flex ible and can order arrays in ways other than just alpha-
betical or numeric ord er. Second ary criteria for orde ring can be specified by listing two or more
criteria sepa rated by commas. In general, an O rder By clause of the form
Orde r By expressi onl Direct i on l , expression 2 Direc tion 2, . ..
primarily sorts by expres ionl and Direction! , secondarily by express ion 2 and Direction 2, and
so on. For ins tance, an O rde r By clause such as
Order By l as t Name Ascending , f irstName Ascending
7.2 Using LINQ with Arrays • 287
can be used to alph abetize a seq uence of full na mes. When two peop le have the same last name,
their first n ames will be used to determine wh ose full name comes first .
Example 5 The fo llo wing program uses the file S tates. txt considered in Example 1 and
sorts th e states by th e length of the ir na mes in ascending ord er. S tates with names of the same
length are sorted by the ir names in reve rse alphabe tical order.
( Oisplcrt States )
Utah i-
Ohio
Iowa
Texas ~
Maine
Idaho
Oregon
Nevada
Kansas
Hawaii
Alaska
Wroming ~
Note: In an O rder By clause, the default direction is A scending. For instance, the fo urth line of
Example 5 co uld h ave been written
directly in to a
T he DataSo urce prop rty also can be used to di play the con tents of an array
list box wi th a stateme nt of the form
lstBox. DataSo urce = arrayNa me
a list box, then
Note: If a Se lectedln dexCha nged eve nt proced ure has been defined for
eve nt.
executi on of the DataSo urce property will rr~ise the Se lec tedlnd exChan ged
Binary Search
search. The Binary-
A large array in asce nding ord er i most ffic iently searched with a binary
of the array it lies.
Search method looks for a va lue in the array by first determi ning in wh ich half
half. The process is
The other half is then ignored , and the search is narrowe d to the retained
nt of the fo rm
repeated until the item is found or the entire list has been considered. A stateme
numVar = Array .Binary Search (arrayN ame, value)
me. If the va lue
assigns to numVar the index of an occurre nce of the requested value in arrayNa
is not found , then a nega ti ve num be r is ass igned to numVar.
Comments
Visual Bas ic pro-
1. The Option Infer setting can be made the default se tting for all of your
grams or ca n be made the se tting for a single program .
hown in
(a) If a value for Option Infer is set in the Option defa ult proj ect setting window
programs .
Fig. 3.1 of Section 3.2, th en th at sett ing wi ll be the default setting for all new
nt Option
(b) To override the default se tting for an ind ividual program, enter the stateme
Window . A lternate ly, right-
Infer on or Option Infe r Off at the top of the Code
rties , click on
click on the program name at th e top of Solutio n Explore r, click on Prope
the Comp ile tab, and change the va lue for "Option infer".
sa id to project data.
2. UNQ Where ope rators are sa id to filter data, and Se lect ope rato rs are
form
3. Visual Basic h a a built-in rout ine for so rting arrays. A stateme nt of the
Array .Sort( arrayName)
where the more
sorts the array in ascendi ng orde r. This method is usefu l for simple orting
advanced capa biliti es of LINQ are not needed.
(a) Since the value of query consists of just one name, wh y ca n't the six th
line be replaced
with txtFull Name. Text = query ?
(b) W hat ex pression s, other than query. First , ca n be used for the righ t side
of the sixth
li ne that would yield th e same result ?
EXERCISES 7.2
In Exercises 1 through 18, determi ne the output displayed when the button
is clicked.
1. Private Sub btnDis play_ Click( . . . ) Handle s btnDis play . Click
Di m nums() As In t eger = {5 , 7, 2, 3}
Dim numQue ry = From num In nums
Where num > 4
Select num
For Each num As Intege r In numQue ry
lstOutp ut.Item s.Add( num)
Next
End Sub
4. Priv ate Sub btnDis play _ Click( ... ) Handle s btnDis play. Click
Dim line As String = " 1 492,17 76,181 2,1929 ,1941"
Dim dates() As String = line.S plit(", "c)
Dim dateQu ery = From yr In dates
Where Cint(y r) < 1800
Select yr
lstOutp ut.Data Source = dateQu ery.To List
lstOutp ut.Sele ctedite m = Nothin g
End Sub
5. Priv ate Sub btnDis play _ Click( . . . ) Handle s btnDis play.C lick
Dim line As String = "If,yo u,fail, to,plan ,then,y ou ,
plan,to , fail"
Di m words( ) As Str i ng= line .Split( " , "c )
290 • Chapt er 7 A rrays
) As Boole an
Funct ion IsPali ndrom e(ByV al word As String
reads the same forwa rds and backw ards.
'A palind rome is a word that
Dim n As Integ er word. Lengt h
For i As Integ er 0 To (n - 1) \ 2
tring( i, 1) <> word. Subst ring(n i - l, 1) Then
If word .Subs
Retur n False
End If
Next
Retur n True
End Funct ion
.Click
9. Priva te Sub btnDi splay_ Cl ick( ... ) Handl es btnDi splay
in the numbe rs 2, 6, 7, and 8.
'The first four lines of Numb ers.tx t conta
("Num bers.t xt")
Dim numbe rs() as Strin g= IO.Fi le.Re adAll Lines
Dim query = From num In numbe rs
Selec t Cin t (num)
ls tOutp ut.Ite ms.Ad d(que ry(O) + query (l))
End Sub
btnDi splay .Click
10. Priva te Sub btnDi splay_ click ( ... ) Handl es
'The f irst four lines of Word s.txt conta in scale , top, up, and low.
s("W ords.t xt")
Dim words () As Strin g= IO.Fi le.Rea dAl lLine
7.2 Us ing LIN Q with A rrays • 29 1
15. Private Sub btnDispl ay_ Click( . . . ) Handles btnDispl ay .Cl ick
Dim grades() As Integer = {60, 70, 90, 80}
Dim query = From grade In grades
Order By grade Descendi ng
Select grade
grades = query . ToArray
ReDim Preserve grades(g rades.Co unt- 2) 'drop lowest grade
Dim str As String = "The average after dropping the lowest grade is "
txtOutpu t.Text = str & grades.A verage
End Sub
16. Private Sub btnDispl ay_ Click( ... ) Handles btnDispl ay.Click
Dim golfers(2 ) As String 'top 3 golfers in tourname nt
golfers(O ) "Funk,65 ,69,69,75 " 'total 278
golfers( l) "Ramaro, 67,69,65, 73" 'total 274
golfers(2 ) "McNulty ,68,70,73 ,68" 'total 279
Dim query = From golfer In golfers
Let data golfer.S plit(","c )
Let name data(O)
Let score= Cint(data (1)) + Cint(dat a(2)) +
Cint(data (3)) + Cint(dat a(4))
Let result = score & " " & name
Order By score Ascendin g
Select result
For Each result As String In query
lstOutpu t.Items.A dd(result )
Next
End Sub
17. Private Sub btnDispl ay_ Click( ... ) Handles btnDispl ay.Click
Dim smallPrim es() As Integer= {2, 3, 5, 7, 11, 13, 17, 19, 23,
29, 31, 37, 41, 43, 47, 53, 59,
61, 67, 71, 73, 79, 83, 89, 97}
Dim n As Integer= Cint( I nputBox( "Enter a number less than 100:"))
If Array.Bi narySear ch(smallP rimes, n) < 0 Then
txtOutpu t.Text = n & " is not a prime number"
Else
txtOutpu t. Text n & " is a prime number"
End If
End Sub
(Assume the response is 37. )
18. Private Sub btnDispl ay_ Click( ... ) Handles btnDispl ay.Click
Dim statesNE () As String = {"Conne cticut•, "Maine•, "Massach usetts",
"New Hampshir e", "Rhode Island", "Vermont "}
Dim state As String= InputBox ("Enter a state:")
If Array.Bi narySear ch(states NE, state) < 0 Then
txtOutpu t.Text =state & " is not in New England ."
Else
txtOutpu t.Text state & " is in New England. "
End I f
End Sub
(Assume the response is New York.)
7.2 Using UNQ with Arrays • 293
Use LINQ to carry out the primary tasks of the programs in the remaining exercises of this
section. In Exercises 19 through 24, redo the exercises from Section 7.1 using LINQ queries.
19. Exercise 17 of Section 7. 1 20. Exercise 18 o f Sectio n 7. 1
21. Exercise 21 of Section 7.1 22. Exercise 22 of Section 7.1
23. Exercise 25 of Section 7. 1 24. Exe rci e 26 of Sectio n 7. 1
In Exercises 25 through 28, use the file SBWinners.tx t that lists the winners of the first 44
Super Bowls.
25. Write a program that disp lays the teams ( in alphabetical ord er) who have won a S uper
Bowl. Each team sh ould appear only once.
26. Write a program that displays the teams (in alphabetical o rder) who h ave won a S uper
Bowl and whose name beg in with the letter B. Each tea m should appear only once.
27. Write a program that disp lays in a text box the num.ber of games won by the team specified .
See Fig. 7.9.
FIGURE 7.9 Possible outcome of Exercise 27. FIGURE 7.10 Outcome of Exercise 28.
28. Write a program that disp lay a list of S uper Bowl winners ordered by the number of games
won. See Fig. 7.10.
29. The file Final. txt contains student grades on a fina l exa m. Write a program using LINQ
that disp lays the ave rage grade on the exam and the percentage of grade that are above
average.
30. Write a program that requests fiv e grades as input and then calculates the average after
dropping the two lowest grades.
31. The fi le States.txt conta ins the 50 U.S. states in the order in which they jo ined the un ion.
Write a program to d isp lay the o rigina l 13 states in alphabetical o rd er.
32. An anagram of a word or phrase is another word or phra e that uses the same lette rs with
the same frequency. Punctuation marks, case , and spaces are ignored. W rite a program that
request two words (no punctuation) as input and dete rmines if they are anagrams of each
other. (Test the program with the wo rds Elvis and lives.)
33. The file USPres.txt conta ins the names of the 44 presidents in the o rd er in which they
se rved. The first two lin es conta in the names George W ashington and John Adams. Wr ite
a program that displays the president ordered by their last name.
294 • Chapter 7 Arrays
34. The fi le Words. txt conta ins a list of words. Wr ite a program that d isplays the wo rds in a list
box so rted by the number of diffe rent vowels (A, E, I, 0 and U) in the wo rd. When two
words have the sa me number of different vowe ls, they sho uld be ordered first by the ir
length (desce nding) and then alphabetica lly. The display sho uld show bo th the wo rd and
the number of different vowe ls in the word . See Fig. 7 .11.
( Display Words
I Ma
-
5
--
caulitlower ;.
~dagascar
alawi
5 diSCOIJrage
Malaysia
5 facetious := Maldives
5 dialogue
5 sequoia
- Mali
Ma~a
4 organized
Marshall Islands
4 courage
Mauritania
3 important
Mauritius
3 pulverize
3 educat e
....
35. The file N ations.txt contains the names of the 192 member nations of the Un ited N at ions.
Wr ite a program that initia lly d isplays all the nat ions in a list box. Each time a letter is
VideoN ote typed into a text box , the program should reduce the displayed nations to those beginning
President> with the letters in the text box. Figure 7.12 shows the status after the letters "Ma" are typed
( Homework) into the tex t box. At any time, the use r sho uld be able to cl ick on the name of a nation to
have it appea r in the tex t box.
36. The median of an o rdered set of measuremen ts is a number separating the lower h alf from
the upper ha lf. If the n umber of measuremen ts is odd, the median is the m idd le measure-
ment. If the number of measuremen ts is eve n , the medi an is the ave rage of the two m iddle
measuremen ts. W rite a program that requ ests a number n and a et of n measuremen ts as
input and then displays the median of the measuremen ts.
2. (a) A text box can be filled onl y with a string. The va lue returned by a qu ery is a seqLLence type th at conta ins one
string clemen t. O nly that element, not the seq uence itself ca n be assigned to the text prope rty of the text box.
(b) query(O) , query.Last , query.Max , query.Min
Often we work with s v ral piece of re lated data. For in tance, four re lated piece of data abo ut
a country are name, continent, pofndation, and area. Suppose we are considering this information
fo r th e 192 countries in the United Nat ion . In the ea rly days of programm ing, the way to work
7.3 Arrays of Structu res • 295
with such info rm ation was to put it into four para llel arrays-o ne array of type S t ring fo r names,
a second array of type S tr ing for contin ents, a th ird array of type Do uble fo r populat ions, and a
fo urth array of type Double fo r areas. The modern way of dea ling with such info rmation is to
place it in to a single array of a co mpos ite data ty pe that you define called a structure o r a use r~
defined data type .
Structures
A structure contains variab les of (pos ibly) d ifferent type , wh ich are known as members. A
stru cture is defined in the Declaratio ns section of th e Code Editor by a block of the form
End Structur e
where StructureName is the name of the u se r~d efi ned data type, memberNa mel and
memberName2 are the names of the members of the u se r~d efined type, and MemberT)'/Je l and
MemberTyfJe2 are the correspon ding member data types.
Some examples of structures are
Structur e Nation
Dim name As String
Dim contine nt As String
Dim populatio n As Double 'in millions
Dim area As Double 'in square miles
End Structur e
Structur e Employee
Dim name As String
Dim dateHir ed As Date
Dim hourlyWa ge As Double
End Structur e
Structur e College
Dim name As String
Dim s t ate As String 'state abbrevia tion
Dim yearFoun ded As Integer
End Structur e
Variables hav ing a u se r~ d efined data type are declared with Dim statements just like o rdi ~
nary va riab les. For in tance, the statement
will display the string "As ia" in a text box, and the sta tement
n I countr y . area)
txtOut put . Text = CStr(lO OOOOO * countr y.pop ulatio
wi ll disp lay the popu lat ion de n ity of C hina in a text box.
n of t h e Code Ed itor,
Althou gh structu res are a lways defin ed in th e Declarations sectio
m. Just li ke o rd inary vari-
va ri ab les of use r-defin ed type ca n be decla red an yw h ere in a progra
depend ing o n where t hey are
ab les, they have class- leve l, loca l, o r block- leve l scope
declare d.
to the mem-
Example 1 The fo llow ing program uses the Split method to assign va lues
play a vital ro le when va lu es
bers of a va ri abl e hav ing a user-de fin ed type. This tec hnique will
the pop ulat io n membe r of the
are ass igned fro m text files to an array of stru ctures. Note: S ince
be mult iplied by o ne million
stru cture Nation is give n in terms of m illio ns, the va lue has to
when used in a calcula t ion .
.Load
Privat e Sub frmCo untry_ Load( ... ) Handle s MyBase
'Assig n values to count ry's membe r variab les
Dim line As String = "Chi na,Asi a,l332 .5,369 6100"
Dim data() As String = line.S plit( ","c )
countr y . name = data(O )
count ry.con tinent = data(l )
countr y.pop ulatio n = CDbl (data( 2))
countr y .area = CDbl (data( 3 ) )
End Sub
splay. Click
Privat e Sub btnDis play_ Click( ... ) Handle s btnDi
'Displ ay data in text boxes
txtNam e . Text = countr y . name
txtCon tinent .Text = count ry.con tinent
ulatio n, 0)
txtPop . Text = FormatN umber(l OOOOO O * countr y.pop
" square miles"
txtAre a.Text = Forma tNumb er(cou ntry.ar ea, 0) &
y.area ) &
t x tDens ity.Te xt FormatN umber(l OOOOO O * countr y.popu lation I countr
" people per square mile"
End Sub
7.3 Arrays of Structures
• 297
Display Data
Continent : Asia
Population : 1.332.
Arrays of Structures
S ince a struct ure is a data type, an array ca n be decla
red with a struct ure as its data type. Fo r
instan ce, the statem ent
Dim natio ns(19 1 ) As Natio n
Example 2 The fo llowin g progra m uses the text file UN. txt to fill
an array of st ru ctures
and then uses the array to d isplay the name s of the
count ries in the con ti nen t selec ted by the
use r. T he program uses two list boxes . A ssume the S
tring C o llectio n Ed ito r for lstC o ntin ents
has been filled at des ign t ime with the names of the
seven con t inen ts. The count ries in the
select ed conti nent are el i played in lstCo untrie s.
l=l@) l~ ·J
a .. Display Cou nt ries by Conti nent
-- -- - ;.
Oick on the name Albania
of a continent : Jl.ndorra ~
I
AJ..Jstria
Africa Belarus
Jl.ntarctica Belgium
Asia Bosnia and Herzegovina
AJ..Jstra lia/ Oceania Bulgari a
0 I- Croatia
North America Czech Repub lic ~
So fa r, LINQ Select cl auses h ave conta ined a single ite m. H owe ver, Select cla u es can con -
ta in mu lt iple items. ln th at case t he q uery re turns a seq ue nce of st ruc tu res.
Th e nex t exa mp le uses t he file Co lleges. tx t th at conta ins da ta (na me , sta te, and yea r
fo unded) about co lleges founded before 1800. The first four lines of the file a re
Example 4 T h e fo llowing program displays co lleges alphabe t ica lly ordered (alon g with
the ir year founded ) th at a re in the state spec ified in a masked text box . In this progra m we do
not assume th at th e n umbe r of co lleges in the tex t file is known in advan ce. A lso, th e Se lec t
clause returns a seque nce of values whose da ta type is a st ructure h av ing two me mbers- a na me
me mbe r and a yearFounded mem ber.
Structure College
Dim name As String
Dim state As String 'state abbreviat1 on
Dim yearFounde d As Integer
End Structure
[Run, type a state abbrev iat ion into the masked text box, and cl ick on the button.~
I
a ... Earlies Coll eges l = I @) j-tJ J
State : PA
I Display Colleges )
IDickinson Coll ege 1773
Moravian Coll ege 742
U. of Pennsybtania 1740
U. of Pittsburgh 1787
.1 Wash. & Jefferson 178 1
-
In the progra m above, th e q ue ry returned a sequ en ce of values whose data type is a struc ture
h av ing two me mbers. (The numbe r of me mbe rs was de termin ed by the numbe r of items in the
Select clause. ) The n ew structure type h a no decla red n ame, and thus it is sa id to h ave an
anonymou s type. Local type inferen ce (prov ided by h av ing Option Infe r set to O n ) spa res us
from h av ing to know the n a mes of an on ymous data types.
d isp lays th e va lues re turned by the q uery in th e DataG ridView con tro l dgvOutput. (Note: The
second sta te ment is optio n al. It prevents h av ing a sh aded ce ll in th e table. ) For insta nce, co n -
sider th e progra m in the prev ious example. If the list box is rep laced by the DataG ridView co n -
tro l dgvCo lleges, the state me nt lstCollege s. Items. Cl ear () is de le ted , a nd th e For Each
loop is replaced by the state me nt
I Display Colleges )
name yearFounded
Dickinson College 177.3
- -
Moravian College 117 2
-
U. of Pennsylvania 174.0
lJ . of Pittsburgh 17B7
Wash. & Jefferson 1781
( Display Colleges ]
College Year Founded
Dickinson College 177.3
- ---
Moravian College 17 2
--
U. of Pennsojlvania 17 0
U. of Pittsburgh 1787
Wash. Jefferson 1781
RowHeadersVi ible property is set to False and the fo llow ing two lines of code are added to the
btnOisplay_C lick event procedu re:
dgvColleges .Co lumns( "name" ) .HeaderText = "College"
dgvColleges .Co lumns( "yearFounded" ) .HeaderText = "Year Founded"
Note : The DataGridView contro ls appearing in this textbook have bee n carefu lly sized to
exactly fit the data. Comment 3 exp la ins how this was acco mplished. There is no need for you
to trive fo r such precision when working the exe rcises.
Example 5 The followin g program provides informa t ion about a college se lected from
a
list box by the user. (Note: In this program, the method First can be replaced
by other method s,
such as Last, Max, or Min.)
Struct ure Colleg e
Dim name As String
Dim state As String
Dim y earFoun ded As Intege r
End Struct ure
Dim colleg es () As Colleg e
Privat e Sub frmCol leges Load( ... ) Handle s MyBase .Load
Dim school s() = IO. File .ReadA llLines ( "Colle ges.txt " )
Dim n = school s.Coun t - 1
ReDim college s(n)
Dim line As String 'holds data for a single colleg e
Dim data() As String
For i As Intege r = 0 To n
line= school s(i)
data = line.S plit( ","c )
coll eges (i) . name = data(O)
colleg es(i) .state = data(l)
colleg es(i) .yearFo unded = Cint (da ta(2))
Next
Dim query = From institu tion In college s
Order By institu tion.na me
Select institu tion
For Each institu tion In query
lstColl eges.It ems.A dd(ins titution .name)
Next
End Sub
Privat e Sub lstColl eges_ Selecte dindex Change d( ... ) Handle
s
lstCol leges.S elec tedinde xChang ed
Dim query From institu tion In college s
Where institu tion .name = lstColl eges.T ext
Select institu tion
txtSta te . Text = query. First.s tate
txtYea r.Text = CStr (query .First.y earFou nded)
End Sub
[Run, and click on a college.]
Bowdoin College
Brown U. Stat e : DC
Columbia U.
Dartmouth College Yearfounded : 1789
Dickinson Colleqe I=
18l~-~.~.m-·~·mi!c:::Jl\.-.!
Hampton-Sydney
Hartwick College
Harvard U.
Moravian College
Princeton U.
Rutgers College
304 • Chapter 7 Arrays
to curve
Example 6 The following program uses genera l proced ures to input grades and
the grades.
lculat e .C lick
Privat e Sub btnCa lculat e_ Click( ... ) Handle s btnCa
Dim scores As Grades
Dim semest erAver age As Double
GetGr ades(s cores)
scores = Curve Grade s(scor es)
+ 2 * score s.fina l) I 4
semes terAve rage = (score s.exam l + scores .exam2
er(sem esterA verage , 2)
txtOu tput.T ext = "Seme ster Averag e: " & Forma tNumb
End Sub
Grades
Functi on CurveG rades( ByVal scores As Grades ) As
scores .exam l += 3
scores .exam2 += 4
score s.fina l += 2
Return scores
End Functi on
a Se ester Ave ra ge
Example 7 The follow ing program totals a person's college credits and determines whether
that person has enough cred its for graduation. Notes: The structure variable person is loca l to the
btnGet_Click event procedure. In the fifth line of the procedure, pe r son . name . firstName should
be thought of a (person . name ) . firstName .
Structure FullName
Dim firstName As String
Dim lastName As String
End Structure
Structure Student
Dim name As FullName
Dim c redits() As Integer
End Structure
Else
txtRes ul t .Text person .name. firstNa me & " " &
person . name . l a stName & " needs " &
(120 - total) & "more credits to gradua te."
End I f
End Sub
[Run, click on the bu tton , and respond to requests for input with Miranda
, Smith, 3, 34, 33, 34.]
Comments
involve comput ed
1. When a Select clause conta ins two or mo re items, none of the items ca n
were interest ed in the
va lues. For instance , cons ider the q uery in Example 3 and suppose we
age of each college in 2010. The following query wou ld not be va lid:
Dim co l legeQu ery = From col In college s
Where col.sta te = mtbSta te.Text .ToUpp er
Order By col.nam e Ascend ing
Select col.nam e, 2010 - col.yea rFound ed
EXERCISES 7.3
In Exercises 1 through 10, determine the output displayed when the button is clicked.
1. Structure Rectangle
Dim length As Integer
Dim width As Integer
End Structure
2. Structure College
Dim name As String
Dim state As String
Dim yearFounded As Integer
End Structure
3. Structure College
Dim name As String
Dim state As String
Dim yearFounded As Integer
End Structure
4. Structure College
Dim name As String
Dim state As String
Dim yearFounde d As Integer
End Structure
5. Structure Appearance
Dim height As Double
Dim we i ght As Double
End Structure
6. Structure Employee
Dim name As String
Dim hoursWorke d As Double
Di m hourlyWage As Double
Dim eligibleFor Bonus As Boolean
End Structure
worker.hoursWork ed = 40
worker.hourlyWag e = 25
worker.eligibleFo rBonus True
End Sub
7. Structure TestData
Dim name As String
Dim score As Double
End Structure
(Assume that the three lines of the file Scores.txt contain the fo llowing data: Joe,88;
Moe,90; Roe,95.)
8. Structure Employee
Dim name As String
Dim dateHired As Date
Dim hasDependents As Boolean
End Structure
Structure Citizen
Dim name As String
Di m dayOfBirth As Date
Dim residence As Address
End Structure
Structure Employee
Dim name As String
7.3 A rrays of Structu res
• 311
."
txtO utpu t.Tex t "The secon d game was at leas t as good
End If
End Sub
ReDim cities(n)
Dim line As String 'holds data for a single city
Dim data() As String
For i As Integer = 0 To n
line = cityRecords( i)
data= line.Split{", "c)
cities(i) .name= data(O)
cities(i) .state= data(l)
cities(i) .pop2000 CDbl(data(2) )
cities(i) .pop2010 = CDbl(data(3) )
Next
End Sub
In Exercises 19 through 2 2 use the fil e U SStates.tx t that consists of 5 0 record s and four
fields. Each field gives a piece of info rmation about a state-name, abbreviation, land area
(in sq uare miles), population in the year 2000. The records are ordered by the states' date
of entry into the union. The first fou r lines of the fil e are
Delaware , DE,l95 4 ,759000
Pennsylv ania , PA, 4 4817,1 22 9 60 00
New J e r s e y, NJ,74 17,813500 0
Ge org i a,GA,57 906,76370 00
19. Write a program that accepts a state's abbrev iation as input and displays the state's name
and its area. See Fig. 7.15.
FIGURE 7.15 Possible outcome of Exe rcise 19 . FIGURE 7.16 Outcome of Exe rcise 20.
20. W rite a program that displays the names of the states whose abbrev iat ions are different
than the first two letters of their name. Both the abbreviat ions and the states should be dis-
played. See Fig. 7.1 6.
21. W rite a program that d isplays th e names of the state sorted by their pop ulation densities in
desce nding order. N ext to each name should be the state's pop ul ation density. See Fig. 7.1 7.
Oick on a team.
.
g ...J Baseba ll
Team: Rays
Displcrl Plcr1-ers
PLAYER B D ING
.A.\/ER.A.GE
Jason Bartlett .''2
Pat Burrell 1
-
Carl Crav.ford .3 5
Evan Longoria .281
Dioner Navarro
g
batti ng average and the playe r (or playe rs) havin
25. Writ e a program that displays the highest . ee Fig. 7.21.
display each playe r's team
the highest batting ave rage. The ou tput also hould
11 Baseba ll a~ Base ba ll l = I @) ~~ J
Display Players Display Tearns
(
Angels
Best batting average : 0.365 Astros l]
Athletics
Player Team Blue Jays
Braves
Joe Mauer Twins Brewers
Cardinals
d
txt that disp lays the names of the team s sorte
26. Writ e a program using the fi le Baseball.
alpha bet ica lly. See Fig. 7 .22.
ces. txt that cont ains data abou t the Supr eme
In Exer cises 2 7 throu gh 30 use the file Justi last
d of the fil e cont ains six field s-fir st nam e,
Cou rt justi ces, past and prese nt. Each recor
h they were appointed, year appointed, and
nam e, appointin g president, the state from whic
the last field is set to 0.) The first five lines
the year they left the cour t. (For sittin g judges,
of the file are as follows:
6,0
Sam uel,A lito, Geo rge W. Bush , NJ ,200
30,1 844
Henr y ,Bald win , Andr ew Jack son, PA,l8
,VA ,l836 ,184 1
Phil ip , Barb our,A ndre w Jack son
t , AL,l 937, 1971
Hugo ,Blac k , Fran klin Roos evel
,l970 ,199 4
Harr y,Bl ackm an,R icha rd Nixo n,MN
the
g justices ord ered by the yea r th ey jo ined
27. Writ e a program that d isplays the sittin
Supr eme Cour t.
a president as inpu t from a list and then displays
28. Writ e a program that requests the name of
es should be orde red by the lengt h of time
the justices appo inted by that president. The justic
(Not e: For sitting justi ces, use Now . Year -
they served on the cour t in desce ndin g orde r.
yrAp poin ted as the ir time of serv ice. Othe
rwise, use yrLe ft - yrAp poin ted.) Use the file
file conta ins the names of the presidents in
USP res.tx t to fi ll the presidents list box. That
the ord er they served. See Fig. 7 .23.
a~ Supre me Court
,Appointees
Oick on the name of a president.
Calvin Coolidge William Douglas
Herbert Hoover Hugo Black
Franklin Roosevelt Felix Frankfurter
Hany Truman Stanley Reed
Dwight Bsenhower Robert Jackson
John Kennedy CJ Frank Murphy
Lyndon Johnson Wiley Rutledge
Richard Nixon James Byrnes
29. Write a program that requests a state abbreviation as input and displays th e justices
appo inted from that state. The justices sh ould be ordered by the ir year appo inted. The o ut-
put sho uld also display th e last name of the appointing pres ident and the length of tunc
se rved . (Note: For itting justices , use Now. Year - yrAppointed as the tr t tme of serv tce.
Otherwise, u e yrLeft - yrAppointed. ) A lso, the program sh ould info rm th e user if no
justices have been appointed from the req uested state. ee Fig. 7.24.
a;t S p e rne Co
Display Justices
State abbreviation :
~pointing
Justice
President
Display Justices
William Brennan Dwight Bsenhower
FIGURE 7.24 Possible ou tcome of Exercise 29. FIGURE 7.25 Outcome of Exercise 30.
30. Write a program th at displays the makeup of the Supreme Court at the beg inning of 1980.
The justices sho uld be ord ered by the yea r they were appointed, and the names of the
appo inting pres idents sho uld be d isplayed . See Fig. 7.25.
31. The Twelve Days of Christmas. Each year, PNC Advisors of Pittsburgh publishes a C hristmas
price index. See Table 7.3. Write a program that requests an integer from 1 through 12 and
then lists the gifts fo r that day a long with that day's cost. O n the nth day, the n gift are 1 par-
tridge in a pear tree, 2 turtle doves, ... , n of the nth gift. The program also should give th e
total co t up to and including that day. As an exa mp le, Fig. 7. 26 shows the output in the list
box when the user enters 3. The contents of Table 7.3 , along with the day corresponding to
each gift, are contained in the fi le G ifts.txt. The first three lines of the fi le are as follows:
l,partridge in a pear tree,159.99
2,turtle doves,27 .99
3,French hens , lS
The file Famous.t xt contains the names of some famous American s and their birthdays. U se
this file in Exercises 32 through 35. The first three lines of the fil e are
Paul Allen,l/2 1/1953
Lance Arrnstron g,9/18/19 71
Neil Arrnstron g,S/5/193 0
32. Tuesday's child is full of grace. Display a list of the people in the fil e Famous. txt born on a
Tuesday. (Hint: U se the FormatDa teTime function.) See Fig. 7.27.
33. Display a list of the people in the fil e Famous. txt born during the 1970s. See Fig. 7.28.
34. Display a table showing all the people in the file Famous. txt along with their ages. The peo-
ple should be ordered by their ages in descendin g order.
35. Display a tab le show ing all the people in the file Famous.tx t who are in their forties along
with their ages in days and the days of the week they were born.
A campus club has 10 members. The following program stores informati on about the stu-
dents into an array of structures . Each structure contains the student's name and a list of
the courses h e or she is currently taking. Exercises 36 through 39 request that an additional
event procedure be written for this program.
Structur e Student
Dim name As String
Dim courses() As String
End Structur e
1. The evenr procedu re conta ins two erro rs. First, the defi ni tio n of a struc
wre ca nn ot be inside a procedure; it
must be typed into the Declarati ons section of th e Code Editor. Second,
the state ments Team . school =
"Rice" and Team.m ascot = "Owls" are nor \'a lid. "1i am" should be replaced
by a va riable of type Tea m
th at has prev iously been declared.
2. Structu re Team
Dim school As String
Dim mascot As String
End Structu re
where ROWO consists of the en tries in the top row of the correspo nd ing table delimited
by
commas, ROWl consi ts of the entries in the next row of the correspo nd ing table delimite
d by
commas, and o on .
Example 1 The fo llowing program stores and accesses the data from Table 7 .4.
OBJECT PROPERTY SETIING
a~ Interci Distanc es ~~ G JE§J frm Distances Text Intercity Distances
1. Chicago lblC h Text l. C hicago
2. Los .Angeles lblLA Tex t 2. Los A nge les
Origin :
lblNY Tex t 3. N ew York
3. Ne•.v York
Destination :
lb iPh Text 4. Philade lphia
. Philadelphia lblO rig Tex t O rigin:
mtbOrig Mask 0
Show Mileage Between
Origin and Destination lbiDest Text Dest inat io n :
mtbDes t Mas k 0
Mileage :
brnShow Tex t Sho w M ileage Between
O rigin and Destinat ion
lblM iles Text M ileage:
txtMiles Read O n ly True
Dim rm (,) As Double { { 0' 2054 ' 80 2 ' 738},
{2054, 0, 2 786 , 2706} ,
{802 , 2786, 0, 1 00},
{738 , 2706, 100, 0}}
[Run, type 3 into the O rigin box, type 1 into the Dest ination box, and click on the button
.]
a ... In e rcity Dista nces
1. Chicago
2 . Los Angeles Origin : 3
3. New York
Destinat ion :
. Philadelphia
Mileage : &
322 • Chapter 7 Arrays
The C enter for Sci nee in the Public Interest publi hes
The Nutrition Score-
Example 2
in each of fiv e categ ories are show n in
book, a highly respected rating of foods. The top two foods
n . The following program comp utes
Table 7.6 along with some inform ation on their comp ositio
three array s-a one-dimens ional array
the nutrit ional conte nt of a meal. The table is read into
nutrients for the names of the five
foods for the names of the ten foods, a one-d imensional array
the numb ers from the table. (The value
nutrie nts, and a two-dimens ional array nutTable to hold
kth food.) The arrays foods and nutrients
of nutTable(k, i) is the amou nt of the ith nutrie nt in the
first three lines are as follows:
are filled from the files Foods. txt and Nutri ents.txt, whose
the progra m.
The array nutTable is filled with eleme nts hard- coded into
name d nutFa cts of type NutFact and having fiv e ele-
The progra m uses an array of struct ures
two memb ers; the first mem r h [d-
ment (one fo r each nutrie nt) . The tructur N utF t ha
amou nt of that nutrie nt in the meal.
ing the name of a nutrie nt and the econd holding the total
7.4 Two-D imension a l A rrays
• 323
The program is written in the input-process ing-outp ut format. The input Sub procedur
e
GetAmo unts loops through 10 input dialog boxes that reque t the quant ities of each
food and
places them in to a one-dimensional array named servings . The processing Function
procedure
ProcessData u es the array servings, along with the arrays nutrients and nutTable, to fill the
array of
structures nutFacts. Finally, the output Sub proced ure ShowData uses the array nutFacts
to dis-
play the nutrition al content of the meal into a DataGridView control.
Structu re NutFact
Dim nutrien t As String •name of one of the f1ve nutr1en ts
Dim amount As Double 'amount of the nutrien t in the meal
End Structu re
Private Sub btnDete rmine Click( ... ) Handles btnDete rmine.C lick
Dim serving s(9) As Double
Dim nutFact s(4) As NutFact 'This array of structu res has an
element for each nutrien t.
GetAmo unts(ser vings) 'input
nutFact s = Process Data(se rvings) 'process ing
ShowDa ta(nutFa cts) 'output
End Sub
As NutF act )
Sub Show Data ( ByV al nutF acts ()
plac e the data from the arra y
'Cre ate a quer y and use it to
con trol .
'of ~tructures 1nto a Data Grid View
cts
Dim quer y = From elem ent In n utFa
Let Nut rien t = elem ent. nutr ient
t.am ount )
Let Amo unt = Form atNu mbe r(ele men
Sele ct Nut rien t, Amo unt
ist
dgvO utpu t.Da taSo urce = quer y . ToL
dgvO utpu t.Cu rren tCel l = Noth ing
End Sub
ium sweet
follo wing menu: .5 cups of spin ach, 1 med
[Run, click on th e butto n , and ente r the
a large papaya, and 1 med ium lobst er.]
potato, 2 lice of wh ole whea t bread, .25 of
Nutrient .Amount
calories 45.5
File
Filling a Two-Dimensional Array with a Text
ctu res.
s are simil ar to those used to fill arrays of stru
Text fi les used to fi ll two-dime nsio nal array fo r each row epa-
row of the table, with the entri es
Each line of the text file corresponds to a the text file
ge discussed earli er can be filled with
rated by com mas. Fo r insta nce, the array milea
lines:
Dista nces . txt cons isting of the fo llow ing four
0, 2 054 , 802, 738
2054 ,0,27 86 , 27 06
802 , 2786 ,0,10 0
738, 2706 ,100 , 0
mileage.
The fo llow ing code crea tes and fills the array
Dim mile age( 3 , 3) As Dou ble txt" )
. File . Read AllL ines ( "Di stan ces.
Dim r owOfNums ( ) As Stri ng = IO
Dim line As Stri ng
Dim data () As Stri ng
GetU pper Bou nd(O )
For i As Inte ger = 0 To mile age.
line = rowO fNum s(i)
data = line .Sp lit( ","c )
e.Ge tUpp erBo und( 1)
For j As Inte ger = 0 To mi leag
mile age( i, j) = CDbl (da t a( j) )
Next
Next
7.4 Two-D imensional A rrays • 325
Note: These eleven lines of code, with slight modifica t io n s, a re n eeded in man y of the
exercises. You can store this block of code (o r a ny freque ntl y used fragment of code ) fo r later use
by highlighting it a nd dragg ing it from the Code Edito r in to the Too lbox. To reuse the code ,
just drag it back from the Too lbox to the Code Editor. A copy of the code will rema in in the
Too lbox for further use. Alternate ly, you can cl ic k o n the locat io n in the Code Edi tor whe re
you wan t th e code to be inserted, and then do uble-cl ick o n the code in the Toolbox.
W e reco mme nd tha t yo u place these lines of code in a program, highlight th e m, and drag the m
into th e Too lbox . The n you can drag them o ut when ever you n eed them.
produces a sequence con sisting of the m · n numbers in the array. The me th ods Count , M ax ,
Min , First, Last , A ve rage, and S um app ly to th e q ue ry. A lso, the sequen ce of numbers ca n be
d isp layed in a list box with the DataSource pro pe rty.
Comments
1. W e can define three- (o r high e r-) dimensio na l a rrays much as we do two-d ime nsio n a l
a rrays . A three-dime nsio na l array u es three subscripts, and the a signmen t of va lue
req uires a tr iple -nested loop. A s a n exa mple, a me teoro logist might use a three-dimensio n a l
a rray to record te mperature fo r va rio us da tes, t imes, and e leva tio ns. The a rray might be
decla red with the sta temen t
Dim temps(30, 23, 14) As Double
2. A Re Oim state m n.t canno t ch ange the number of d ime nsio ns of a n a rray. Fo r insta nce, it
cannot c h a nge a o ne-dime nsio na l into a two-dimensio na l a rray.
1. Conside r th e road- mileage progra m in Exa mple 1. H o w can it be modified so the actua l
n a mes of the c ities can be supplied by the use r?
2 . ln wha t types of pro ble ms are two-dime nsio n a l a rrays upe rio r to arrays of struc tures?
EXERCISES 7.4
In Exercises 1 through 16, ass ume the array nums is of type Double and has been fill ed with
the contents of Table 7. 7.
lt,1:1!ft4
7 3 1 0
2 5 9 8
0 6 4 10
326 • Chapter 7 Arrays
6. Di m total As Doub le = 0
For c As Integer = 0 To nums.GetUp perBound(l)
total += nums(2, c)
Next
lstOutput . Items.Add (total)
13. Write code that creates a new array who e entries are twice the en tries of nums.
7.4 Two-D imen iona l Arrays
• 327
14. Write code that uses a For Each loop to find the
average of the numbers in nums.
15. Write code that finds the sum of the even numb
ers in nums two way : first with a For Each
loop and then with a LINQ query.
16. Write code that finds the average of the odd
nun'lb ers in nums two ways: first with a For
Each loop and then with LINQ .
In Exerc ises 17 and 18, deter mine the outp ut of
the code.
17. Dim nums (1, 2) As Doub le
Dim rowO fNum s() As Strin g= IO.F ile.R
ead.A l1Lin es( 11 Digi ts.tx t 11 )
Dim line As Strin g
Dim data () As Strin g
For i As Integ er = 0 To nums .GetU pperB
ound (O)
line = rowO fNum s(i)
data = line .Spl it( 11 , 11 C)
For j As Integ er = 0 To nums .GetU pperB
ound (1)
nums (i, j) = CDb l(dat a(j))
Next
Next
lstOu tput. Item s.Ad d(nu ms(O , 1) + nums
(1, 0))
(Assu me the two lines of the file Digits. txt are
9, 7, 6 and 5, 4, 3.)
18. Dim name s(2, 1) As Strin g
Dim rowO fNam es() As Strin g= IO.F ile.R
ead.A l1Lin es( 11 Peop le.tx t 11 )
Dim line As Strin g
Dim data () As Strin g
For i As Integ er = 0 To name s.Get Uppe
rBou nd(O )
line = rowO fNam es(i)
data = line . Spli t( 11 , 11 C)
For j As Integ er = 0 To name s.Get Uppe
rBou nd(1)
name s(i, j) = data (j)
Next
Next
lst0u tput. Item s.Ad d(na mes( 2, 1) & 11 11
& name s(1, 1))
(Assume the three line of the file Peop le.txt are
Felix , Unga r; Osca r,Ma dison ; and
Henr y, Jame s.)
entr y
the uses of com pute rs in the workplace. Each
20. Tab le 7.8 gives the resul ts of a survey on the
the age catego ry t hat use the com pute r for
shows the perc entage of respo nden t from
indic ated purpose.
. (Use Wo rkers. txt.)
(a) Place the data from the tab le in an array
es in the Sp reads heet s colu mn.
(b) Dete rmin e the ave rage of the perc entag
lled
three campu es. The num ber of stud ent enro
21. A universit y offer 10 cour ses at each of
in each cour e is prese nted in Table 7.9.
llme nts on each camp us.
(a) D isplay the total num ber of course enro
g each cour e.
(b) Disp lay the tota l num ber of stud ents takin
.I
l= I@J I. S'2._
Average
Display Precipitati on for a Nebraska
City Month Precipitation
---
January 0.77
Tota l - ---
February 0.91
Year Precipitation - -- -
for the Year
-- - - March 1.91
1986 36.53 2.94
~ril - --
1987 131 .59 -- ---
- May 4.33
--
1988 28.56
- - June
--
4.08
- - -
1989 31.95
- - July 3.62
-
1990 22.81 - -
August 4.10
- -
1
September 3.45
- -- -
Octo ber 2.09
- - --
November 1.32 ~
December 10.77
G~ ~)
FIGURE 7.30 A magic square.
7.4 Two-D imensional Arrays
• 331
29. A company h as three stores (1 , 2, and 3) , and each store sells fiv e items (1, 2, 3, 4, and
5).
The fo llowing tab les give the number of items sold by each store and category o n a
pa rticu-
lar day, and the cost of each item.
(a) Place the data from the left- hand tab le in a two-dim ensio nal array and the
data from
the righ t- hand tab le in a one-d imensio na l array.
(b) Co mpute and display the tota l dollar amount of sales for each sto re and for
the entire
company.
1. Rep lace the masked text boxes with o rdin ary text boxes to ho ld city names.
The fun ction Fi ndC ityNum can be
useJ to dete rmine the subsc ri pt assoc iated with eac h city. This fun ct ion and the
mod ified eve nt procedure
btn how_Ciick are as follows:
a ~ Analyze a Loan
~0000
.Amount of loan: 250000
Interest rate : 5
[ Qutt
I
- -
FIGURE 7.31 Temp late for the Analyze-a-Loan program.
I= @] ~
u.. Analyze a loan
Interest rate: 5
-
Number of loan years : 30
I OK ]
Show Interest Paid for One Year I
Display Interest Rate Cl'tange Table I
[
Qu~
I
FIGURE 7.32 Mon thly paym ent for a loan.
D Analyze a loan
Interest rate : 5
I51.193.54
Number of loan years : 30 4.125% 51 .211 .63
--
4.250~~
- --
51.229.85
l
4 . 375~~ 51.248.22
Calculate Monthly Payment
-
4.500~~ 51 .266.72
4.625~.
-
51.285.35
4 . 750~~ 51.304.12
Display Amortization Schedule
l 4.875%
-
-
51.323.03
-
-- -
5.000% 51.342.06
- -
l Show Interest Paid for One Year
5. 125 ~~
5.250"1~
-
51.361 .22
---
51 .380.51
- --
IDisplay Interest Rate Olange Table
5.375%
5 . 500~~
5 625~~
- -
T
51.399.93
51.419.48
51.439.15
-
5 . 750~.
- - -
51.458.94
- --
5. 875~~ 51.478.85
! Quit
I 6000%
- -
51.498.88 -....
Analyze a Loan
Assign Assign Specify Assign Assign Request Speficy Assign Assign Specify
values values to query values values to number of query values values to query
from elements & fill from elements beginning & show from elements & fill
text of array DGV text of array month Sum text of array of DGV
boxes of Months boxes of Months boxes EffectOfR ates
l As Dou ble ,
Sub Inpu tDa ta( ByR ef prin cipa
ByR ef num Mon ths As Inte ger )
ByR ef year lyR a te As Dou ble ,
of inte rest , and dur atio n
'Inp ut loan amo unt, yea rly rate
, num Year s As Inte ger
Dim perc enta geR ate As Dou ble
l .Tex t)
prin cip al= CDb l (txt Prin cipa
lyR ate. Tex t)
perc enta geR ate = CDb l (txtY ear mal form
I 100 'Con vert inte rest rate to deci
yea rlyR ate = perc enta geR ate
t)
num Year s = Cin t (txtN umY ears .Tex
Year s * 12 'Du rati on of loan in mon ths
num Mon ths = num
End Sub
As Dou ble ,
a l As Dou ble , ByV al mon thly Rate
Fun ctio n Paym ent( ByV al prin cip Dou ble
ByV al numM ont h s As Dou ble ) As
'Est ima te of mon thly paym ent
Dim esti mat e As Dou ble onth s))
yRa te I (1- (1 + mon thly Rate ) A (-nu mM
esti mat e= prin cip al* mon thl
e are frac tion s of a cen t
'Rou nd the paym ent up if ther
i mat e, 2) Then
If esti mat e = Math .Rou nd(e st
Retu rn esti mat e
Else
0.00 5, 2)
Retu rn Math .Rou nd(e stim ate +
End If
End Fun ctio n
CHAPTER 7 SUMMARY
an array.
are m t effic ientl y proces ed if stored in
1. For prog ramm ing purposes, lists of data al va lues .
t, whic h also can spec ify its size and initi
A n array is decl ared with a Dim state men or ReDim
n be spec ified or chan ged with a ReDim
The size of an alrea dy declared array ca
Progra mming Projects
• 34 1
Preserve statem ent. The metho ds Count, First, Last, Max, and
Min return the size of the
array, first eleme nt, last eleme nt, largest eleme nt, and sma
llest eleme nt, re pectiv e ly. Fo r
numeric arrays, the metho ds Average and Sum retu rn the
average and total of the n umbers
in the array.
2. The lO. File.ReadAllLines metho d return s a string array
conta in ing the conten ts of a fi le.
3. The Split metho d conve rts a line consisting of strings
separa ted by a delim iter (usua ll y a
comm a or a blank space ) to a str ing array. T he join functi on
is its inverse.
4. A For Each loop repeat s a group of statem ents fo r each
eleme nt in an array.
5. U NQ is a powerful M icroso ft techno logy that provid es a stand
ardized way to set criteri a for
info rmatio n retriev a l fro m data o urces, includ ing arrays.
Ope rators such as Fmm, Where,
Distinct, Order By, Let, and Select are used to crea te a query express
ion th at can retriev e a list
of info rmatio n from the data so urce . When each eleme nt
of t he list is a single value, the
ToArray method conve rts the list to an array. UNQ prov ides
an easy way to sort the con -
tents of an array.
displays the sequ ence in a list box. If the se lect clause conta
ins two o r more express ions, a
sta temen t of the fo rm
[ Analyze Grades
I Score
- --
Grade
-
59 D
Number of Exams : - - -
14 :00 D
-
Mean : 71.00 65 c
-
- -- - - -
Standard Deviation : 1 .42 75 Tc
-
~6 D
-- ---
50 B
- ---
66 c
-
47 F
-- ---
9& A
-
:72 c
- --
95 JA
-
71 c
- -
63 D
- - -
77 c
Translate Sentence
FIGURE 7.39 Poss ible outc ome of Prog ramm ing Proje ct
3.
344 • Cha pter 7 Arrays
200 6 in ce rta in
e lo r degrees con ferred in 198 1 and
4. Tab le 7.18 shows the num ber of bach ch ange and a hist ogra m of 2006
les 7. 19 and 7.20 show the percentage
fields of stud y. Tab of these tab les
that allows the user to di p lay any one
leve ls, resp ective ly. Wri te a progra m lly by fi e ld of
on. Tab le 7.18 is ord ered alph abet ica
as an opti o n and to quit as a fo urth opti ered by increas-
ing perc entages, and Tab le 7. 20 is o rd
study, Table 7.19 is orde red by decreas
is a large dot.
ing num be r of degrees. Not e: C hr(l 49)
erred.
IM:JIUQI Percentage change in bachelor degrees conf
%C hange (198 1 - 200 6 )
Field of Stud y
214. 0%
Com pute r and info. sc ienc e
60.7 %
Socia l scien ces and hi to ry 58 .6%
Business 5.3%
Engineer ing -0.8 %
Education
fields.
1t!1:Jifll•l Bachelor degrees conferred in 2006 in certain
Field of Stud y
• • • • • 47,4 80
Com p uter and info. sc ience
• • • • • • • 67,0 45
Engineer ing
• • • • • • • • • • • 107,238
Ed ucat ion
• • • • • • • • • • • • • • • • 161,485
Soci a l sc iences and history ••• ••• • 3 18,042
••• ••• ••• ••• ••• ••• ••• ••• •••
Bu ines
(c) Place the number of gan1es won by each team in the array of structures.
(d) Display a listing of the tea ms giving each tea m's name and number of games won. The
list should be in decreasing ord er by the number of wins.
G. A poker hand can be sto red in a two-dimen sional array. The statement
Dim hand(3, 12) As Integer
declares an array with 52 elements, where th e fir t subscript ranges over the four suits and
the second subscript ranges over the thirteen denomina tions. A poker hand is specified by
plac ing l's in the eleme nts co rre ponding to the cards in the hand. S e Figure 7.40.
A 2 3 4 5 6 7 8 9 10 Q K
Club "- 0 0 0 0 0 0 0 0 1 0 0 0 0
Diamond+ 1 0 0 0 0 0 0 0 0 0 0 0 0
Heart¥ 1 0 0 0 0 0 0 0 0 0 0 1 0
Spade • 0 0 0 0 1 0 0 0 0 0 0 0 0
FIGURE 7.40 Array for the poker hand A 'I A + 5 ill 9 "- Q 'I.
Write a program that requests the five cards as input from the user, creates the related
array, and passes the array to procedures to determine the type of the hand: flush (all ca rds
have the sa me suit) , straight (cards have consec utive denom inations-a ce can co me either
before 2 or after King), traight flu sh , four-of- a- kind , fu ll house (three ca rd of one denom-
ination, two ca rd s of another denom inat ion) , three-of-a- kind , two pairs, one pair, or none
of the above.
7. Airline Reservations. Write a reservation yste m for an airline flight. Assume the airplane
has 10 rows with 4 seats in each row. Use a two-dimen siona l array of strings to maintain a
seating chart. In adJ it ion, create an array to be used as a waiting list in case the plane is fu ll.
The wa it ing list should be "first come, first se rved"; that is, people who are added ea rly to
the list get priori ty over tho e added later. A llow the user the fo llowing three options:
(a) Add a passenger to the flight or waiting list.
1. Request the passenger's name.
2. Di play a chart of the seats in the airplane in tabular form .
3. If sea ts are ava ilab le, let the passenger choose a seat. Add the passenger to the seat-
ing chart.
4. If no sea ts are ava ilab le, place the passe nge r on the wait ing list.
(b) Remove a passenger from the fli ght.
1. Request the passenger's name.
2. Sea rch the seating chart for the passenger's name and delete it.
3. If the wait ing list is empty, update the array so the seat is ava ilable.
4. If the wa iting list is not empty, remove the first person from the list, and give him or
her the newly vacated seat.
(c) Q uit.
346 • Chapter 7 Array
(a) (b)
the following:
Figure 7.41(b) sh ows the status after one generation. Write a program to do
to h old the
1. Declare a two-dim ensiona l array of size n by n, where n is input by the user,
configu ration,
status of each squ are in the current generation. To specify the initial
1's or dashes
h ave the user input each row as a string of length n, and break the row into
with the S ubstring method.
square in the
2. Declare a two-dim ensiona l array of size n by n to hold the status of each
and produce the display in
n ext generat ion. Compu te th e status for each square
cells are used
Figure 7.41(b) . Note: The generat ion changes all at once. Only current
to determi ne which cells will contain individu als in the next gen eration.
as often as
3. Assign the next-ge neration values to the current generat ion and repeat
desired.
the program is
4. Display the individu als in each generation. (Hint: The h ardest part of
cell has. In general , you must ch eck a 3-by-3
determi ning the number of neighbo rs a
be made when the cell is on the
square around the cell in q ues tio n. Excepti ons must
edge of the array. Don't forget that a cell is not a ne ighbo r of itse lf.)
(Test the program with the in itial configurat ion show n in Figure 7 .42. It
is known a the
figure-e ight configurat ion and repeats afte r e ight generat ions.)
Numbe r (ISBN) ,
9. Every book is identifi ed by a ten-ch arac ter Interna tional Stand ard Book
the book. The first nine ch aracte rs are d igits
which is usually printed on the back cove r of
stands for ten). Three exam-
and the last charact er is e ither a digit or the letter X (which
hyphen sepa-
s
ples of ISBNs are 0-13-03 065 7-6, 0-32- 108599-X, and 0-471-5 8719-2. The
single digit and
rate the charact e rs into four blocks. The first block usually consists of a
, etc. ). The second block
identifi e the language (0 for English , 2 for French , 3 for German
Progra mming Projects
• 347
identif ies the publis her (for exa mple, 13 for Prenti ce Hall,
32 fo r Addison -Wes ley-Lo ng-
man , and 471 for Wiley ). The third block is the numb er the
publ ish er has ch ose n fo r the
book. The fourth block, which always consists of a single charac
ter called the check digit, is
used to test for erro rs. Let's refer to the ten
charac ters of the ISBN as
d 1, d 2, d3 , d4 , d5 , d6, d 7, d8 , d9, and d . The check digit is chose
10 n so that the sum
10.0 + 9. 3 + 8 . 2 + 7. 1 + 6 . 0 + 5. 8 + 4. 5
+ 3 ·9 + 2 · 9 + 1·10 = 165
S ince 165/11 is 15, the sum is a multiple of 11. This check ing
scheme will detect eve ry single-
digit and transposition-of-adjacent-digits error. That is, if while
copying an IBSN numbe r you
miscopy a single charac ter or transpose two adj acent charac
ters, then the sum (*) will no
longer be a multip le of 11.
(a) Write a progra m to accept an ISBN type numbe r (inclu ding
the hyphe ns) as input, ca l-
culate the sum (*),an d tell if it is a valid ISBN . (Hint: The
numbe r n is divisible by 11
if n Mod 11 is 0.) Before ca lculati ng the sum, the progra m
should check that each of
the first nine ch aracte rs is a dig it and that the last charac ter
is either a digit o r a n X.
(b) Write a progra m that begins with a va lid ISBN (such a
0-13-0 3065 7-6 ) and then con -
firms that the check ing schem e described above detects eve
ry single- digit and transpo-
sition- of-adj acent- d igits error by testing eve ry poss ible error.
[Hint: If d is a digit to be
replac ed, then the nine poss ibilities for the replac ements are
(d + 1) Mod 10, (d + 2)
Mod 10, (d + 3) Mod 10, ... , (d + 9) Mod 10.]
10. User-Operated Directory Assistance. H ave you ever tried
to ca ll someo ne at a place of busi-
ness and been to ld to type in some letters of their name o n
your teleph one's keypad in o rd er
to ob ta in the ir extens ion ? Write a progra m to simula te this
type of direct ory ass istanc e.
S uppose the names and teleph one ex tensio ns of a ll the empl
oyees of a compa n y are con-
ta ined in the text file Emp loyees. txt. Each se t of three lines
of the file has three pieces of
inform atio n: last name, first and middle name (s), and teleph
one ex tensio n. (We have fill ed
the file with the names of the U.S. presid ents so that the names
will be fam ili ar.) The user
sho uld be asked to press button s fo r the first three letters of
the person 's last name followed
by the first letter of the first name. For insta nce, if the person
's name were Gary Land , the
348 • Chap ter 7 Arrays
[ 1
l[ 2 ABC
l[ l 3 DEF [ Get Instructions l
[ 4 GHI
l[ 5 .JKL
l[ l 6 MNO [ Look Up Another Person l
-
[ 7 PQRS
l[ & TUV
l (9WXYZ ) Willi am Henr y Harr i3cn x2034
ila r ren Gama li el Hard ing x4040
[ * l[ 0
l[ l tf.
349
350 • Chapte r 8 Text Files
Preliminaries
piece of data per line. Fo r
The tex t fil es consid ered in Sectio ns 7.1 and 7.2 h ave a single
of a sta te, a nd each line of the file
instan ce, each line of the fi le States. txt conta ins the n ame
t file, called a C SV format ted
U SPres. txt contai n the n ame of a pres ide nt. Anoth er type of tex
by comm a . (C SV sta nds for
fil e, h as several ite ms of data on each line with the items sepa rated
each line contai ns four
Comma Se parated Values .) An examp le is the fil e USS tates.tx t, where
squ are miles ), and population in the year
items fo r each sta te-na me, abbreviation, land area (in
2000. The first four lines of the file are
c_. States
&17
7~ 9t I=
0
New Jerset/ NJ 1717 813S
Georgia
- --- --
G l 57. fi 7 l7
Connecticut CT "i·B 5 3271
c... States
State State
Abbrevi ation Land .Area Populat ion f
~=r
Delaware DE 1 .S~
PennS'1~van i a P.A. ... a17 1229tfi
New Jerse'f NJ 7 17 &1
Georgia GA 575 6 7517
Connecticut CT 85 l271
WriteAIILines Method
with the Read A llLines meth od. We can
In Chap ter 7 we copied the conte nts of fil es into arrays
The fo llowing line of code creat es a new
reverse the proces with the Write AllLi nes meth od.
Video Note
Manag ing text fil e (or a LINQ query that return s string values)
text file and cop ies the conte nts of a string array
into the file, plac ing one element on each line.
strAr rayO rQue ryNa me)
IO . File . Writ eAll Line s("fi leNa me.t xt",
file by first conv erting the array to a
A simp le nume ric array can be copied into a text
a file using eithe r of the follow ing two sets
string array and then copy ing the string array into
of code:
ount - 1
Dim uppe rBou nd As Integ er = numA rray.C
Dim strAr ray(u pperB ound ) As Strin g
For i As Integ er = 0 To uppe rBou nd
strA rray (i) = CStr (num Array ( i ))
Next
" , strA rray)
IO. File .Wri teAll Line s( "file Nam e.txt
Example 1 The first four lines of the file AgeA tinau g.txt are
[Run, click on the button, and terminate the program. Then cl ick on the Refresh button in the
Solu tion Explorer wi ndow, click on the View A ll Files button, and double-click on the new text
file Sorted .txt in the bin \Debug subfolder. The first four lines of the file are as fo llows.]
Theodore Roosevel t,42
John Kennedy,4 3
Ulysses Grant,46
Bill Clinton,4 6
Example 2 The following var iation of Example 1 displays th e data in the file
A geAtlnaug.txt in a table ord e red by the ages at ina ugurat ion.
I
1
John Kenned}• 3
i
Ulysses Grant "16
1
Bill Ointon 14£- -1 '"
me Co urt justice :
Each line of the file conta ins the fo llowing informa tion a bout a S upre
re a ppo inted , yea r
fir t na me, las t name, appo inting pres ide n t , state from whic h they we
, the las t fi e ld is se t to 0.) The
appo inted, and yea r they left the co urt. (For sitting justices
of a justi ce a nd t he
fo llow ing p rog ram c rea tes a ne w fil e, wh ere each line is the full na me
inted in a ce nding
yea r they we re appo inted. The just ices a re so rted by th e yea r appo
na me in as cendin g
ord er. ] usti ces appo inted during the a me yea r a re so rted by the ir first
o rd e r.
rganize .Click
Private Sub btnReo rganize Cl i ck( ... ) Handle s btnReo
T .e data from a file Sort and restruc ture the data,
'a, d rite t to a new file
es.txt" )
Dim justice s() As String = IO. File .ReadA llLines ( "Justic
Dim query = From line In just ices
Let data= line .Split( ","c )
Let firstNa me = data(O)
Let lastNam e = data(l)
Let yrAppo inted = Cint (data(4 ))
Order By yrAppo i nted, firstNa me
inted
Let newLin e= f ir stName & " " & lastNam e & "," & yrAppo
Select newLin e
IO. File .WriteA llLines ( "NewF i le.txt" , query)
End Sub
button in the
[Run, click on the button , and termina te the program. Then click on the Refresh
the new text file
Solu tion Exp lorer window, click on the View All Files button, and double-click
in the bin \ Debug subfolde r. The first four lines of the file are as follows.]
in
Example 4 The followin g variatio n of Exampl e 3 d isplays th e requested info rmation
a table.
ze. Click
Private Sub btnReo rganize _ Click( ... ) Handle s btnReo rgani
a text file Sort and restruc ture the data,
'Ta :e data from
and display it in a table
es . txt" )
Dim justice s() As String = IO. File .ReadA llLines ( "Justic
Di m query = From line In justice s
Let data= line.S plit( ","c )
Let firstNa me = data(O)
Let lastNam e = data(l)
Let yrAppo inted = Cint (data(4 ))
Let fullNam e = firstNa me & " " & lastNam e
Order By yrAppo inted, firstNa me
Select fullNam e , yrAppo inted
dgvOut put.Dat aSourc e = que ry .ToLis t
dgvOutp ut.Cur rentCe ll = No t hing
End Sub
8.1 Managing Text Files • 355
,.
1
tuiiNarne yrA+Jpointed
---~-- -- I_
Jarnes Wibon 1
--
John Blair 17 9
lJohn Jay 17
--
John Rutledge 17&.9 ....
Set Operations
Often we want to create a new text file from two existing text files. For instance, we might want to
merge the two files (with or without duplications). Or, we might want to update one file by deleting
the items that also appear in the other fi le. Or, we might want the new fi le to contain the items that
appear in both of the existing fi les. The steps we will use to carry out such operations are as follows:
1. U se the ReadAllLines method to fill two arrays with the contents of the two existing text files.
2. A pply a se t operation such as Concat, Union, Intersect, or Except to the arrays or to UNQ
qu eries derived from the arrays.
3. Use the WriteAllLines method to write the resulting array into a new text file .
If array 1 and array2 are string arrays, then
array l.Conca t( array2 ).ToArray is an array containing the elements of array} with array2
append ed, poss ibly with duplications.
array l.Union( array2 ).ToArray is an array containing the elements of array} with array2
append ed, without du plications.
array l.Intersect(array2 ).ToArray is an array containing the elements that are in both
array } and array2 .
array l. Except( array2 ).ToA rray is an array containing the elements of array } with the
elements of array2 removed.
Note: When one of the four operations above is used as the second parameter of a
WriteA llLines method, the ToArray method can be omitted.
These four set operat ions are demonstrated with two simp le fil es in Example 5 and then
with more complex files in Example 6.
A lpha Bravo
Bravo Delta
C harl ie
356 • Chapter 8 Text Files
The following program combines these two files in four ways. Figure 8.3 shows the form for the
program.
[Run, click on each button, and term inate the program. Then click on the Refresh button in the
Solu tion Explorer window, click on the View A ll Files button, and look at the new tex t fi les in
the bin \ Debug subfolder.]
The file Concat.txt contains the five words A lpha, Bravo, C harlie, Bravo, and Delta.
The file Union.txt contains the four words A lpha, Bravo, C harlie, and Delta.
The file lntersect. txt contains the single word Bravo.
The file Except. txt contains the two words A lpha and C harlie.
In the four set operation , one or both of the arrays can be replaced with LINQ queries.
This allows the programmer to ord er, filter, and proj ect the data before co mbining files.
Example 6 The fo llowing program demonstrates the set operations with the two files
Ju tices.txt and USPres.txt. The file U Pr .txt i a ingl -fi ld t xt fil c nt inin th n m
of the 44 presiden ts. The first four lines of US Pres.txt contain the names Geo rge Washingto n,
8.1 M anagin g Tex t Fi les • 357
John Adams, Thomas Jefferson, and James Madison . Note: The file Justi ces.txt shows all
Supreme Court appointm nts as of January 1, 2010 .
Presidents Or Justices
l
Dim justices() As String = IO. File .Read.Al1Lines( 11 Justices.txt 11 )
Dim presidents() As String = IO. File .Read.AllLines( 11 USPres . txt 11 )
[Run, click on each button, and terminate the program. Then click on the Refresh button in the
Solution Explorer window, click on the View All Files button , and look at the new text files in
the bin \Debug subfo lder.]
358 • C hapter 8 Text Files
The file Both .tx t conta ins the single name "William Taft".
The fi le NoAppo intments.tx t contains the names of four presidents.
The file PresOrjustice.txt contai ns 154 names.
Example 7 Each reco rd of the file USStates.txt contains a name field, an abbreviat ion
fie ld, an area field, and a population fi eld. The first two records of the file are
Delaware,DE,l954,759000
Pennsylvania,PA,448 17,1229 6000
The fo llowing program looks up the name of the state whose abbrev iat ion is given . Note:
The method First is required in the line txtName . Text = query . First because query is a
seque nce-namely, a sequ ence of one ite m.
[Run, enter a state abbreviation into the masked text.box, and click on the button.]
State abbreviation : MD
Name: Mar,o!and
• 359
8.1 Ma n agi ng Te xt Files
bu tto n .]
[Run, an d cli ck on th e
l = l @l l. Si. -'
a~ U.S. St a es
.td
Search the File USStates
Population
State Density
Alaska
1.22
Wyoming 5.34
Montana 6.2 6
North Dakota 9.
ntrol
The OpenFileDialog Co same sta nd ard Op en
an d N ote pad, all prov ide th e
suc h as W ord , Ex ce l, en dial g box
W indows app licati on s, yo u wa nt to op en . Figure 8.4 sh ows an Op
spec ify th e fil e th all its
dia log box to he lp yo u a tex t file. Th e sam e Op en dia log box, wi
th N otepad to op en eOialog co ntrol.
th at co uld be used wi sic pro gra ms co urtesy of th e Op enFil
b le to Vi sua l Ba he n yo u do uble-
fun cti on ality, is av a ila th e Di alo gs sec tio n of the Toolbox. W
Th e Op enFi leOialog co
nt rol is in be low th e Fo rm
nt ro l wi ll ap pe ar in th e co mp on en t tray
e To olbox, the co , ince th e
cl ick on th e ico n in th leO ial og l. (W e wi ll no t ch an ge the na me
lt na me Op enFi pe rty we will et for th
e
Designe r wi th th e de fau the co nt ro l' fun cti on. ) The only pro ov e
de c rib es e co mb o box ab
de fau lt na me co mp let ely de ter mi ne s th e tex t tha t appea rs in th
pe rty, wh ich
co n tro l is th e Filter pro
360 • Chapter 8 Text File
Jl Open
u ... I << EXT ORNE (F:) ~ MAJO R_TEXT_FilES "' l"-t j J Sea'dl M/J.JOF_TEX I JILES
Download~ LJ Add e dCo l or~ . txt LJ Famou~ .txt LJ Proverb~ . txt LJ T ow n~ .txt
Recent Plac e~ '--' Gift~. txt Rain.txt LJ UN.txt
LJ AgeAtln aug .txt LJ
Example 9 The followin g program displays the contents of a text file selected by the
user with an O pen dialog box.
OBJECT PROPERTY SETTING
ll
- Display a File ~I 8 llctiJ frmDisp layFi le Text Display a File
btnSelec t Text Select a Text File
Select a Text Rle
l lstOutpu t
OpenFil eDialog 1 Filter Text Docume nts
1st Output
(*.txt) I* .txt
8.1 Manag ing Text Files
• 361
rAdom•
Thomas Jefferson
ames Madison
--,
'-""
ames Monroe
ohn Q . Adams .,...
Comments 8.1
1. In Exam ple 7, the a rray states could h ave been omitted
a nd the first line of t he query
c h anged to
1. Cons ide r Exam ple 7. Suppo se the last line of the que ry we re c hanged to
Selec t name, abbr
EXERCISES 8.1
27. At the beginning of 1990, a complete box of Crayola 1 crayon s had 72 colors (in th e file
Pre 1990.txt). During the 1990s, 8 colo rs were retired (in th e file Retired.txt) and 56 new
colors were added (in the fi le Add ed.txt). Write a program th at creates a text fi le li t ing the
post-1990s set of 120 colors in alphabetica l order.
Exercises 28 throu gh 34 should u se the file Justices.txt discussed at the beginning of this
exercise set.
28. Write a program to create a file in which each record consists of two fie ld - the full name
of a Supreme Court justice, and the just ice's state.
29. Write a program to create a file similar to ] ust ices.txt, but with the state field de leted.
30. Write a program that disp lays the entire contents of the file Just ices. txt in a DataG ridView
control.
31. The fi le USStates.tx t contains information about each of th e 50 states. Each record
conta ins four fie lds-name, abb reviat io n , land area (in sq uare miles), pop ulat ion in t he
year 2000. The record s are o rde red by t he states' date of entry into t he un ion. The first
fo ur lines of the file a re
Delaware,D E,1954,759 000
Pennsylvan ia,PA , 448 17, 1229 6000
New Jersey ,NJ , 7417 , 8135000
Georgia,GA ,5 7906,76370 00
Write a program that creates a file consisting of the states that have not prod uced any
upreme Court justices.
32. The first Supreme Court justice was appo inted in 1789 . Write a program to create a file
that lists the years from 1789 through 2009 in which no S upreme Court justices we re
appo inted . The first fo ur lines of the file will be 179 2, 1794 , 1795, and 1797 .
33. Write a program to create a file that lists the states that have produced Supreme Court jus-
tices, along with the number of justices prod uced. The states shou ld be in alphabetica l order
bythe irabbreviations.Thefir stfour lin softhe filewill be AL,3 ; AZ, 2; CA , 5; co,L
34. Write a program to create a file that lists the pres idents who have appo inted S uprem Court
justices, a long with the numbe r of ju rices appo inted. The pres idents should be in a lphabet-
ical order by the ir fu ll names. The first two lines of the file will be Abraham Lincoln, 5;
Andrew Jackson , 5.
35. Consider the file USStates.tx t described in Exercise 31. Write a program to display the
entire contents of the file in a DataGridView control with the states in alphabetica l order.
1
C rayola is a regi tered trademark of Binney & Sm ith.
366 • Chapter 8 Tex t Files
filen a me
wh e re fi lespec id e ntifies the tex t file to be read. If filesJJec consists o nly of a
p rogra m 's
(th a t i , if n o pa th is give n) , V isual Bas ic will look fo r the fil e in the
bin \ Debug fo ld e r. This sta te me nt , which es ta blish es a commun ica tions link be twee n the
a file for
comp ute r a nd th e disk drive fo r reading da ta fro m the d isk, is sa id to open
varia bles in the
input . Da t a the n can be input fro m the pec ified fi le a nd ass ign ed to
prog ra m .
and 2
Just as with o the r variables, th e declarati on and ass ignmen t state ments in S teps 1
can be comb ined into the single state ment
Each line is
3. Read lines in ord er, on e at a time , from the file with the Readlin e method.
retrieved as a string. A state men t of the form
it to the
causes th e program to look in the file for the next unread line of data and ass ign
variab le strVar.
The OpenTex t method set a po inte r to the first line in the sp cified fil e. Each time
a
is read, a nd the po inter is then moved to
Readlin e method is executed, the line po inted to
the nex t line. Afte r all lines h ave been read from the file, th e va lue of
srVar.C lose()
8.2 Stream Reade rs, StreamWri ters, and Struct ured Exception
H and ling • 367
Example 1 The follow ing progra m uses a Strea mReader to carry out
th e same task as th e
progra m in Exam ple 7 of the prev ious sectio n . That
is, it finds the name of the state who e
abbrev iation is given in a maske d tex t box.
Priva te Sub btn Fin d Click ( ... ) Hand les
btnF ind.C lick
Dim s r As IO. Stre~eader = IO. File .Open
Text( "USS tates .txt" )
Dim a b br As Strin g = mtbA bbr.T ex t . ToUp •mask is LL
per
Dim l i ne As Strin g
Dim found Flag As Boole an = False
Do Until found Flag Or sr.En dOfS tream
line = sr.Re adL i ne
If line. Spli t( ","c ) (1) = abbr Then
txtNa me . Text = line. Spli t( " , "c ) (0)
found Flag = True
End If
Loop
If Not found Flag Then
Dim s tr As Strin g = " is not a valid state
abbre viati on."
Messa geBox .Show (mtbA bbr.T ext . ToUp per &
str, "Erro r" )
mtbAb b r. Cle a r ()
mt bAbb r . Focus ( )
End If
End Sub
Name : Maryland
ess ion
e meth od. If info is a literal, var iable, or expr
3. Place data into the fi le with the WriteLin
of any data type, then the statemen t
swV ar.W riteL ine( info )
file .
writes the infor mation into a new line of the
the fil e, exec ute
4. Afte r all the data have been reco rded in
swV ar. Clos e ()
a
Writ eLin e meth od actu a lly places data into
This state men t is very impo rtant beca use the if you
fers the data to the di sk. The refo re,
temporary buffer, and the C lose meth od trans
migh t be los t. The state men t also brea ks the
om it the state men t swVa r . Clos e (), some data
e its omission migh t prev ent othe r proced ures
com mun icati ons link with the file. The refor
from accessing the file.
Atanasoff
Babbage
Create File Codd
Dijkstra
Eckert
Display File Faggin
Gates
Hollerith
8.2 StrcamR eade rs, Stream Writers, and Stru
ctur ed Exceptio n Han d ling
• 369
lean
ames. txt, a file of names. The Boo
Example 3 The followin g program man ages N e ente red in the
nam
e if the fi le N ame .txt ex ists and the
fun ctio n Isln File retu rns the va lue Tru
text box is in the fi le.
PROPERTY SETTING
OBJECT
tor
Imp orts Sys t em .IO 'Ap pea rs at top of Cod e Edi
Actions :
View Detail
1._Co_Py exception detail to the clipboard
FIGURE 8.5 Excepti on handled by Visual Basic.
an except ion occurred, the code in the Fin ally block is th en execut
ed. The fo llowing code is
illustra tive:
Dim taxCr edit As Double
Privat e Sub btnCom pute_ Click( ... ) Handle s btnCo
mpute .Click
Dim nurnDe penden ts As Intege r , messag e As String
Try
nurnDe penden ts = Cint (Input Box( "How many depen dents?
" ))
Catch
messag e = "You did not answer the questi on with
an " &
"integ er value. We will assume your answer is
zero."
Messag eBox . Show(m essage , "Impro per Respon se" )
nurnDe penden ts = 0
Finall y
taxCr edit = 1000 * nurnDe penden ts
End Try
End Sub
whe re the varia ble exc will be ass ign ed th e n ame of the except
io n . The code in this block will
be execut ed on ly whe n the pecifie d except ion occurs .
The gen e ral fo rm of a Try-Ca tch -Finall y block i
Try
norma l code
Catch excl As Fi rstEx ceptio n
excep tion-h andlin g code for FirstE xcepti on
374 • C hapter 8 Text Files
Argum entOu tOfRa ngeExcept ion A n argu ment to a method is out of range.
str = "Good bye" . Subs tring (l2,3 )
I ndexO u tOfRa ngeEx ceptio n A n array's sub cript is o ut of range .
Dim arr (3) As Integ er
ar r ( 5) = 2
In va IidCast Excep tion A va lue canno t be conve rted to anoth er type .
Dim num As Integ er = Cint ( "one" )
Nu llRefe renceE xception A method is called on a variab le that is et to Noth ing.
Dim str As Strin g, len As Integ er
len = str.L ength
Overflow Excep tion A num be r too big fo r the data type is assign ed.
Dim num As Integ er = 2 00000 0000
num = 2 * num
I0. DirectoryN otFou nd Excep tion A fil e within a miss ing fo lde r is accessed.
Dim sr As IO . Strea mRea der =
)
IO . File.O penT ext(" C: \ BadD ir \ File. txt"
IO.Fil eNotF oundE xception A miss ing file is acces ed.
Di m sr As IO.St reamR eader =
I O. Fil e . Open Text( "Miss ing . txt")
IO .IOEx ceptio n Any file- hand ling excep tion , includ ing those mentioned
e an
above. For instance , an attemp t is made to delete or renam
a closed fi le to an alread y used
open file, to change the name of
ified conta ins nodi k. Note: If
name, or when a disk d ri ve spec
tested with Catch cla uses,
a series of IO excep tio ns is be ing
thi s excep t ion should be th e last one tested.
e)
IO .Fil e. Mov e(fil espe c, Alrea dyEx ist i ngNam
Catch
e xc eptio ns
excep t ion - hand ling code f o r any rema ining
Fina lly
c lean- up code
End Try
ln addition to data validation , a popular use of exception hand ling is to account for errors
when accessing files. Visual Bas ic has th e capab ility to access files sto red on remote se rvers via
the Internet. A n exception is th rown if a desired file is mi sing (IO. FileN otFoundExcept ion ) or
if th e file cannot be read beca use the Internet connection between the computer and the serve r
is broken (IO .IO Exception) .
Example 4 The following program reads the first line fro m a file on a CD. The program
expects the file to res ide in the folder DataFiles of the C D. Note that the clean-up code,
sr. close ( l , in the Finally block is enclosed in a Try-Catch block of its own. This protects the
C lose method fro m any excep tions that might occur.
End Try
End Try
End Sub
[Remove the C D fro m the E: drive, run the program, and then click on the button .]
Erro r
OK
376 • Chapter 8 Text Files
[In ert the CD containing the file USPres. txt (in the folder DataFiles) in to theE: drive and then
click on the button.]
residen
OK
Comments
1. Any variable decla red within a Try-Catch-F inally block has bl ock- level scope. That is, it
will not be ava ilab le after the block terminates.
2. Text fi les are also called sequential files because a SteamReade r reads the records one at a
time in sequence.
1. Give three different ways to display the last record of the file USStates.tx t in a message box.
2. Consider the fo llowing event procedu re.
Pr ivate Sub btnCreate_ Click( ... ) Handle s btnCreate. Click
Dim sw As IO.StreamW riter = IO.File . CreateText ("ABC.txt" )
sw . WriteLine( "abc")
End Sub
In Exercises 1 through 10, determine the output displayed in the text box when the button
is clicked.
1. Private Sub btnDisplay_ Click( .. . ) Handles btnDisplay .C lick
Dim salutati on As String
Dim sw As IO.StreamW r i ter = IO . File.Cr eateText(" Greetings. txt")
sw.WriteLi ne("Hello" )
sw.WriteL ine("Aloha ")
sw.Close()
Dim sr As IO.StreamR eade r IO.File . OpenText( "Greetings .txt")
salutation = sr.ReadLin e
txtOutput. Text = salutat i on
sr.Close ()
End Sub
treamRea ders, Stream Writers, and tructured Exception Handling
8.2
• 377
swo Close ()
Dim sr As IOoStrea mReader IOoFile oOpenT ext("Gr eetingso txt")
salutat ion = sroRead Line
welcome = sroRead Line
txtOutp utoText = welcome
sr oClose ()
End Sub
40 Assume that the contents of the file G ree tings. txt are as shown in Figure 8.6.
Hello
Aloha
Bon Jour
FIGURE 8.6 C ontents of the file Greetingsotxto
Try
num = Cint(t xtBox .Text)
txtOu tput.T ext = "Your numbe r is " & num
Catch
txtOut put . Text "You must enter a numbe r."
End Try
End Sub
splay. Click
6. Privat e Sub btnDis play_ Click( ... ) Handle s btnDi
", "Mexic o"}
Dim nafta( ) As String = {"Cana da", "Unite d States
Try
" & nafta( 3)
txtOu tput.T ext = "The third membe r of NAFTA is
Catch exc As IndexO utOfRa ngeEx ception
txtOu tput.T ext = "Error occurr ed."
End Try
End Sub
7. Privat e Sub btnDis play_ Click( ... ) Handle s btnDi splay. Click
Try
Dim usPop As Intege r = 304000 000 'Appro x popul ation of U.S.
Dim worldP op As Intege r
worldP op = 21 * usPop
txtOu tput.T ext = CStr(w orldPo p)
Catch exc As Argum entOut OfRan geExce ption
txtOu tput.T ext = "Oops"
Catch exc As Overfl owExc eption
txtOu tput.T ext = "Error occurr ed."
End Try
End Sub
8. Privat e Sub btnDis play_ Click( ... ) Handle s btnDi splay. Click
tter As String
Dim flower As String = "Boug ainvil laea", lastLe
Try
lastLe tter = flowe r.Subs tring( l4, 1)
txtOu tput.T ext = lastLe tter
Catch exc As Invali dCastE xcepti on
txtOu tput.T ext = "Oops"
Catch exc As Argum entOut OfRan geExce ption
txtOu tput.T ext = "Error occurr ed."
End Try
End Sub
the folder bin and the fir t
9. Assume that the file Ages. txt is located in the Debug subfold er of
line of the file is "Twent y-one" .
splay. Click
Privat e Sub btnDis play_ Click( ... ) Handle s btnDi
Dim sr As IO.Str eamRe ader
Dim age As Intege r
Try
sr = IO.Fil e .OpenT ext ("Ages .txt") 'FileN otFoun d if fails
age = Cint(s r.Read Line) 'Inval idCas t if fails
txtOu tput.T ext = "Age is " & age
Catch exc As IO.Fil eNotF oundE xcepti on
txtOu tput.T ext = "File Ages. txt not found"
8.2 Strea mReade rs, Strea m Write rs, and Struc tured Excep
t ion H andlin g • 379
12. Ass ume that the file Names. txt conta ins a list
of name in alpha bet ical ord er. Wha t is the
effect of the Myste ry funct ion ?
of the file
any erro rs. Ass ume that the cont ents
In Exe rcises 13 thro ugh 18, iden tify
Gre etin gs.tx t is as show n in Fig. 8.6.
... ) Han dles btnD ispl ay.C lick
13. Priv ate Sub btnD ispl ay_ Clic k( Gre etin gs.t xt)
IO.F ile.A ppe ndT ext(
Dim sw As IO.S trea mW riter =
sw.W riteL ine( "Gu ten Tag" )
sw . Clo se()
End Sub
sw.C lose( )
End Sub
Exerc ises 19 throu gh 25 are related and use the
data in Table 8 .2. The fil e creat ed in Exer-
cise 19 shou ld be used in Exerc ises 20 throu gh
25.
19. Write a program to creat e the text file Cowboy.
txt conta ining the inform at ion in Table 8.2.
1. First: Dim sr As IO. Strea mRea der IO.F ile . Open Text( 11 USS tates .txt 11 )
Dim temp As Strin g = 1111
382 • Cha pter 8 Text Files
8.3 XM l
mandat d
l. However, the expa n ion of the Inte rnet
As we have seen , CSV fi les are quit e usefu Con sort ium reco m-
ting data . The World Wid e Web
a standard text file form at for tran smit
Markup Language ) to be that stan dard.
men ds a format called XML (eXtensible lines
look at a text file cons istin g of the first two
Con side r the CSV file USS tate s. txt. Let's
the new file are
of USS tate s. txt. Tha t is, the two lines of
<sta te >
<name >Pen nsylv ania< /name >
<abb revia tion>PA</ abbr evia tion >
<area >44817 </ area >
<pop ulati on>1229600 </po pula tion>
</ state >
</ us_s tates >
LINQ to XML
LINQ ca n be used with XML fil es in mu ch the
sa me way as wi th CSV fil es-w ith three
diffe ren ces:
Display State s
State Density
State Abbreviation : CA
Name: Califomia
Comments
1. The conte n t of an e lemen t can conta in any
characters excep t for" <" and "&". T hese ch ar-
actersmust be replaced with "< " and "& ", respe
ctive ly. For insta nce, the follow ing
two line migh t appea r in XML files :
Hart•Nic:k College
Harvard U.
FIGURE 8.8 Poss ible o utcom e of Exer cise 21. FIGURE 8.9 Poss ible outco me of Exer cise 22.
IBoy,•doin College
U. of Tenne~;see
I Display Colleges
)
College State ....
Yale U.
Georgeto'l..n U.
U. of Delaware
CT
DC
DE
-
-y
U. of Georg ia GA ..
FIGURE 8.10 P ossible outc ome of Exer cise 23.
FIGURE 8.11 Outc ome of Exer cise 24.
.nam e
txtN ame .Te x t = que ry.F i rs t
Deposits
8.4 A Case Study: Recording Checks and
tion of a qua lity
yo u thro ugh the des ign and imp lem enta
The purpose of this sect ion i to take ok man agem en t
agem ent. Tha t a use r-fri end ly chec kbo
prog ram fo r persona l chec kbo ok man al Bas ic's abi lity to
four pages of cod e clea rly shows Visu
prog ram can be writ ten in less than nce prog ram , sim-
rove the prod ucti vity of prog ram mers. lt is easy to imag ine an enti re fina
imp in on ly a few
prog ram s that hav e gen erat ed mill ions of doll ars of sa les, bein g wr itten
ilar to
weeks by using Visua l Bas ic !
User Interface
Wit h Visu al Bas ic, we can plac e a
replica of a che ck or dep osit slip on
user supp ly the info rma tion as if actu the scre en and let the
ally filling out a che ck or dep osit
the form in its che ck mod e. The Dat slip. Figure 8.13 sho ws
aGr idV iew con trol at the bo ttom of
to display a repo rt deta iling all the the form will be used
tran sact io ns. The purp oses of the four
box abo ve the Dat aGr idV iew con tro butto ns and the text
l are obvious.
g~ Chec
l=J@l l: s.
Date: 4/21/201Oj
Pi3'J' TO
.AmountS
Memo
l = /@J _M
David Schneide r
Date : 5/ 5/2010
AmountS
Source
Memo
.
FIGURE 8.14 Tem plat e for ente ring a dep osit
to be used for
des ign for the che ck and dep os it slip allo ws one set of con tro ls
T he com mo n e, while the tex t of the labe l
llblNa me is set to the use r's nam
bot h items. Th e tex t of the labe
fo rth betw een Pay To and Source.
lblToFrom will cha nge bac k and ause the progra m will
lists the objects and the ir init ial pro perty sett ings. Bec
Tab le 8.3 kCo lor prop-
disp lay ing the nex t che ck, all the tex t for the labe ls and the Bac
always beg in by se ass ign -
ld hav e bee n se t at des ign tim e. We chose inst ead to leave the
erty of the form cou switch from depos it en try to
Set upC hec k met hod, whi ch norma lly is use d to
men ts to the to pre pare the init ial
ry but also can be call ed by the form 's Load eve nt proced ure
che ck ent
fo rm.
mo de (ch eck or deposit) fo r the named lnitiall nfo.tx t and Tra nsa
ctio ns.t xt.
CS V form atte d tex t file
Th e pro gra m uses r co mm a-d elim ited pieces of
e file ln itia llnfo. txt con sist s of a sing le line co nta inin g fou
Th
8.4 A Case Stud y: Reco rdin g C hecks and
Deposit • 391
ltr1:JII:IM Objects and initial prop erty settings for the checkboo
k management program.
Obje ct Prop erty Sett ing
frmA ccou nt
lbl ame
lbl um Tex t
txtN um
lblD ate Text Date:
txt Date
lblTo From
txtToFrom
lblA mou nt Text Am oun t$
txtA mou nt
lblM emo Tex t Mem o
txtM emo
btnR ecor d Text &Re cord This C heck
btnM ode 0 xt &Sw itch to Deposits
btnR eport Text Re& port
btnQ u it Text &Qu it
lblCurBal Text C urre nt Balance
txtB alan ce Read Onl y True
dgv Transacti ons Row Heacle rVisib le False
Record
Transactions
Set up Record
first text file Togg le Display Quit
check or between check
and form transaction
deposit slip and deposit sl ip report
Create
text file
Read Set up Reset
h
Va lidate Reset Set up
I
Set up Reset
text file check input input input check deposit input
fields fields slip fields
FIGURE 8. 16 Hier arch y char t for ch eckb ook ma
n agem ent prog ram.
392 • Cha pter 8 Tex t Files
ure :
Let's exa min e eac h eve nt pro ced
ess the tex t file. Thi s
oun t_L oad first call s the lnit ia lizeDat a Sub pro ced ure to proc
1. frm Acc ist, the pro ced ure
lnit iall nfo .txt ex ists. If it does ex
file
pro ced ure first looks to see if the rmi ne all info rma tion
h pos ibl y the la t entr y of Tra nsa ct ions. txt) to dete
uses it (alo ng wit ure pro mpt s the user for
txt does not ex ist, the S ub pro ced
nee ded to proceed. lf In itia llnfo. nce , and the num bers
e to app ear on the che cks and depos it lips, the star ting bala
t he nam file . The eve nt
ch eck and dep osit slip and the n writes thes e item s to the text
of the first saction type to Che ck
Sub pro ced ure nex t to set the tran
pro ced ure call s the Set upC hec k eve nt pro ced ure the n
bac kgr oun d colo r for a check. The
and sets the app ropriate text and a ub pro ced ure
etln put , whi ch init ializ es all the text boxe . The lnit ia lizeDat
call s Res lid user inpu t.
dlin g to pro tect the cod e from inva
emp loys stru ctur ed exc eption han ent ries. Thi s is
_Cl ick fir t con firm s tha t th e required fi elds con tain va lid
2. btn Rec ord retu rned is Tru e, the n
ncti o n Dat aVa lid . If the valu e
acc omp lish ed by call ing th e fu in app end mode, writes
ren t bala nce , ope n the text file
btn Rec ord _Cl ick upd ates the cur Valid retu rns False,
piec es of dat a to the fi le, and the n closes the file . Wh en Data
e ight is nee ded or
n itse lf pop s up a mes sage box to tell the user whe re info rma tion
th e fun ctio Record but ton again.
info rma tion and th n clic k on the
invalid. The use r must type in the ure tha t the user's inpu t
ctu red exc ep tio n h and ling to ens
The Dat a Val id fun ctio n uses stru a lidC astE xce ptio n is
ber field is not a num ber, the Inv
is va lid. If e ithe r the amo unt or num riat e message ask-
The Cat ch bloc k h and les this exc epti on by displaying an app rop
th row n.
t ion.
ing the use r to reen ter the info rma call s Set upC hec k,
Clic k togg les bac k and fort h from a che ck to a dep osit slip . lt
3. btn Mo de_
n calls Rese tlnp ut.
or its ana log Setu pDe pos it, and the
shown in Fig. 8. 15 .
lete hist ory of all tran sact ions , as
4. btn Rep ort_Click disp lays a co mp
5. btn Qui t_Click end s the program.
nts and var iab les
'cla ss lev el nam ed con sta
Con st INI T_ F I LE As Str ing
= "In itia lin fo. txt "
Con st TRANS_ FIL E As Str ing
= "Tr ans act ion s.tx t"
ent ry
'va ria ble s use d for eac h
Dim isC hec k As Boo lean
and dep osi t slip s
'nam e to app ear on che cks
Dim nam eOn Chk As Str ing
8.4 A Case Study: Record ing C hec
ks and Deposits
• 393
Dim las tCk Nu m As Int num ber of las t che ck
eg er wr itte n
Dim last Dp Nu m As Int num ber of las t dep osi
eg er
Dim cur Ba l As Do ubl e t sli p wr itte n
cu rre nt bal anc e in acc
oun t
Pri va te Sub frrn Ac cou
nt_ Loa d( ... ) Ha ndl es
My Bas e .Lo ad
the c ~o ~e el ar
ab
Ini tia liz eD ata ()
e the >am e nd bal anc
e lab els .
lbl Na me .Te xt = nam eOn
Chk
txt Ba lan ce. Te xt = Fo
rm atC urr enc y(c urB al)
S the dat e ~el to the
c rre nt dat e
txt Da te. Te xt = CS tr (To
day )
Set upC hec k ()
Re set inp ut ()
End Sub
As Bo ole an
Fu nct ion Da taV ali d() dis pla y a me ssa ge if
no t
all da ta are va lid , or
're tur n Tru e if
Str ing =
Dim err orM ess age As orm ati on
two ess en tia l pie ces of inf
'If one of the orM ess age .
its nam e to err
'is mi ssi ng , ass ign
m = "" Th en
If txt To Fro m. Te xt. Tri
If isC hec k Th en
err orM es sag e "Pa y To"
Els e
e"
err orM ess age = "So urc
End If
txt To Fro m. Fo cus ()
xt. Tri m "" The n
El sei f txt Am ou nt. Te
err orM ess age = "Am oun
t"
txt Am oun t.F ocu s()
lds
End If the two nu me ric al fie
the n che ck syn tax of
'if no err ors ye t,
8.4 A Case Stud y: Recordin g C hecks and
Deposits • 395
CHAPTER 8 SUMMARY
tho d c pie an array to a tex t file.
1. The IO.File .WriteA llLines me
ted by com mas , LIN Q
a are stor ed in tex t files wit h the field s of eac h reco rd separa
2. W hen dat the Split me tho d.
to sort , sea rch , and reo rgan ize the dat a wit h a littl e help from
can be used
Prog ram ming Projects
• 397
3. Arr ays and que ries can be com
bined with the set met hod s Con cat,
Exce pt. Union, Inte rsect, and
2
We refer to anyo ne who is neit her
a Rep ublican nor a De moc rat as Inde
pend en t.
39 • Cha pte r 8 Text Files
State: Senators :
Project 2.
FIGURE 8.17 Possible outcome of Programming
t
rde r. Wr ite two programs tha
e file Nam es. txt con tain s a list of names in alp hab etic al o atio n . If it is
3. Th list in its pro pe r loc
and inse rt the nam e into the
request a nam e from the user
hould not be inserted.
a lready in t he list , the nam e t is, use only a Stream -
the firs t pro gra m wit hou t using any arrays or LIN Q; tha
(a) Wr ite
Rea der and a StreamWriter.
usin g arrays and LIN Q.
(b) Wr ite the second program
cre ate and ma inta in te le-
Ma inta in Tele pho ne Directories. W rite a program to
4. Cre ate and in a separa te tex t file. In
ries . Eac h tele pho ne dire cto ry sho uld be con ta ined
pho ne dire cto lep hon e dire cto r ies.
nam ed Dir ecto ries . txt sho u ld hold the nam es of t he te
add itio n, a file a li t box. Aft er
es of all the tele pho ne dire cto ries sho uld be disp layed in
At any t ime, nam directory. Th e fo llow ing but -
tele pho ne dire cto ry is sele cte d, it becomes the current phone
a
ton s sh ould be ava ilab le. ided by an inp ut d ia-
a new tele p hon e di rec to ry. (Th e file nam e sho uld be pro v
(a) Cre ate
log box.)
Prog rammin g Projects
• 399
(b) Add a listi ng (a give n in text
boxes) to the end of the curr ent pho
ne dire ctory.
(c) Delete a name (as give n in a text
box ) from the curr ent pho ne dire ctor
(d) Dis play the nam es and pho n e num y.
bers in the curr ent pho ne dire c to ry.
See Fig. 8.1 8
Phone number:
Name Phon e
Number
Addis ,Ababa 345- 1212
Great Sage 123.-4557
Mand alay 555-57&9
Woodlands 989-·5555
3 · d 1 + d 2 + 3 · d3 + d4 + 3 · d + d
5 6 + 3 · d7 + d8
+ 3 · d9 + diO + 3 · dll + dl 2·
(*)
is a mul tipl e of 10. For inst anc e, for
the UPC in Figure 8. 19,
3 .0 + 7 + 3 .0 + 7 + 3 .3 + 4 +
3 . 0 + 0 + 3 . 9 + 0. 0 + 3 . 3 + 4
= 40.
<? xml ver sio n= ' l.O ' ?> eba lL pla yer s. -->
<!- - ~
lata on ma jor lea gue bas
>
<ma jor_ lea gue _ bas eba ll
<pl aye r >
>
<na me >Aa ron Hil l </n ame
<te am >Bl ue Jay s </ team >
<at Ba ts >68 2 </ atB ats >
<hi ts >l 9 5 </h its >
</p lay er >
ject 6.
FIGURE 8.21 XM L file for Program min g Pro
ll Baseb3 ll
;.
Oick em a tearn . Batting
;.
Pla'J'er Average
V..e·.-in Youkilis .3 5
Vido r Martinez .3 J.
Reds .3 1
Rockies 1:: Jacob>/ BlsbUJy
I
RO'lals
Tigers
Dustin Pedroia .2%
g Pro ject 6.
FIGURE 8.22 Pos s ible out com e of Program min
Additional Controls
and Objects
401
Objects
402 • Cha pter 9 Additiona l Con trols and
and events.
ltr1:J!QM Previously discussed properties, methods,
box.
Method: Inse rt the va lue into th e list
lstBox. Ltems.Add(value) the list box.
Met hod: Remove all items from
lstB ox. Items. Clea r() g.
Property : The se lected item as a strin
lstBox.Text list box.
Property: The number of items in the
lstBox. ltems.Co unt disp laye d in asce nd ing
Property: If set to True, items will be
lstB ox.Sorted
ANS I orde r.
. If no item is selected,
Property: The index of the se lected item
lstBox.Selectecllndex
the va lu e is - 1.
. It must be conv erted to a
Prope rty: The curr entl y se lecte d item
lstBox.Se lectecl i tem or message box.
string before being disp layed in a text
must be conv erted to a
lstBox. ltems(n) Property: The item hav ing index n. lt
or mes age box.
stri ng before being disp layed in a text
ate the list box.
Property: Th e sour ce of data to pop ul
lstBox.Da taSo urce elec ted Index property
Eve nt: Occ urs when the valu e of the
lstBox.Se lected lndexChanged e.
changes. It is the defau lt even t procedur
the li st box.
Eve nt: Occ urs when the user clicks on
lstBox.C ii ck l icks on the list box .
Event: Occ ur whe n the user double-c
lstBox. Dou bleClick
st box
way to cop y the con te nts o f a li
Example 1 The fo llow ing prog ram sh ows two box pop ulat e a n a rray
a text file. Wh en the top but ton is clic ked , th e item s in the list
into clic ked , a St rea m Wri ter
fi le. Wh en the bot tom but ton is
tha t is the n used to c rea te a text file. Not ice tha t the
the list box dire ctly into a text
is used to cop y th e con te nts of to str in gs befo re cop ying
co nve rt the item s in th e list box
Stre am Wri ter doe s not hav e to
them into the fil e.
9.1 List Boxes and ombo Boxes • 403
MSFT~
IBM
MSFT
csco
INTC
I IN TC
J
l MSFT
D DO IV l = I @) 1-·t-3 J
( Remove Duplicates )
MSFT
IBM
csco
INTC
'- - --- ~
FIGURE 9.1 The th ree setti ngs for the D ropD own Style
prop erty.
Nrica
l::J Nrica
....
Antarctica Antarctica
Asia Asia
Australia/ Ocea nia Australia/Ocean ia
Europe Europe
North America North America
South America South America
(a) (b)
FIGURE 9.2 Com bo boxes at run time after their dow
n-arr ows are click ed.
Wit h a S imp le or Dro pDo wn combo box,
the use r ca n fi ll the tex t box eith er by
di rectl y into it or by selec ting an ite m from typi ng
the list. Wit h a Drop DownList style com
user can fill the tex t box only by selec ting bo box, the
an item from the list. (Oro pOo wn is the
ting of a combo box's Dro pOo wnS tyle prop defa ult se t-
erty. ) A list that has drop ped down disa ppea
the user clicks on an item or presses the rs whe n
Ente r key. Wit h any of the three styles,
the va lue of
c b o Box .Tex t
is the cont ent of the text box at the top of
the combo box. Just like list boxes, com bo
popu lated with their String Collectio n Edit boxes can be
or, the ltems.Add meth od, and the DataSour
ce property.
OBJECT PROPERTY
D
~ Lette r Add ress GJ I @) I[][ ] frmA ddress Tex t
SETIING
Lette r Add ress
Trtle Name : lblTitle Tex t Title
cboTitle Item s (sho wn in
Mr. scree n capture)
Display Full Name DropDownStyle Simple
Ms.
Dr. lblN ame Tex t N ame :
The Honorable txtN ame
Her Exce llency btnD isplay Text Display
Fu ll Nam e
txt Display Read O nly True
cts
406 • C hapt er 9 Add ition a l Con tro ls and Obje
click on the
type a name into the Name text box, and
[Ru n , elec t an item fro m the com bo box,
butt on.]
Her Excellency
Mr. Display Full Name
Ms .
Dr.
The Hono rable Her Exce llency Queen Elizabeth
Her Excellen
in Fig. 9.3.
le com bo box prod uces the fo rm show n
T he sa me prog ram with a DropDow n sty .
a DropDow nList style com bo box is used
T he form wi ll look abou t the same whe n
a;} l e te r Address l = I @] ~~ •J
bo box.
FIGURE 9.3 Exam ple 3 with a Drop Dow n style com
N Ne New
Afghanistan ;.. Namibia ... Nepa l ,;. Ne•N Zealand
AJban ia
Algeri a u Nauru
Nepal
Netherlands
Ne•N Zealand
Nicaragua
Niger
kidorra Netherlands Nicaragua Nigeria
Allgol a New Zealand Niger NorNa;'
Alltigua and Barbudc
Argentina
Nicaragua 0 Nigeria 0 Oman 0
Niger Norv.•a>J'
Armenia Pakistan
Nigeri a Oman
AJ..Jstra lia Palau
Norv.•ay Pakistan Panama
(a) (b) (c) (d)
FIGURE 9.4 Success ive comb o box displays .
EXERCISES 9.1
Bach
Beethoven
Cho_Q in
1~1.¥1.
Tc haiko vsky
mm l ]
Dan; ;--- ---1
Goethe
Moli ere
I
Shak espea re
a Converter
;::,
From
l'meter
Lmile
To
George Wash ington
John Adams
Thomas Jefferson
James Madison
James Monroe
John Q . Adams AI;Je at
Length to be Andrew Jackson inauguration :
converted : 5 Martin Van Buren
William Harrison
57
Convert John Tyler
James Polk
Converted Zachary Tay1or
Length : 15.00 Millard Fillmo re
:.___ ____J
FIGURE 9.5 Possible output for Exercise 22. FIGURE 9.6 Possible outp ut for Exercise 23.
23. The file Age sAtl naug uara l.txt gives the
ages at inaugura tion of the first 44 U.S. presi
The first four lines of the file cont ain the dents.
data 57, 61, 57, 57; th e ages of W as hing
Ada ms, Jeffe rson , and Mad iso n a t the ir to n,
inaugura tion . The file USP res.t xt cont ains
na mes of the first 44 Uni t d Sta tes pres iden the
ts in the o rd er they were inaugura ted . Writ
a prog ram that plac es the na mes of the pres e
iden ts into an un so rted list box and the ages
at inaugura tion into an array. Whe n the
user click s on the n ame of a pres iden t, his
inau gura tio n sho uld be displ ayed in a text age at
box. (Hin t: A pres iden t's inde x num be r in
list box will be the sa me a th e inde x num the
ber of his age at inaugura ti o n in the a rray.
See Fig. 9.6. )
24. Writ e a program to ask a pers on whic
h Mon opoly® spac e he or she has land ed on
display the result in a text box. The respo and then
nse shou ld be obta ined with a com bo box
the squares most com mon ly land ed on: Park li ring
Place, Illinois Aven ue, Go, B&O Ra ilroa
and Free Parking. (On e possible outco me d,
to be displayed in the text box is "Yo u
land ed o n Park Plac e.") have
the text
(On e pos ible outc ome to be disp laye d in
screen sizes are 17, 19, 20, and 24 inches.
of memory and a 17 -inc h mon itor.")
box is "You have a Dell com pute r with 2GB
PROPERTY SETIING
OBJECT
ll Stop watc h CEJI B I~ frmStopw atch Text Stop watc h
btnS tart Text Star t
Start lb l econ ds Text Seco nds:
txtSe concl s ReaciOnl y True
btnS top Text Stop
Seconds:
tmrWatch [nter va l 100
Stop
~ r:mrWa 'ch
Start
Seconds : 10.5
Stop
a-;; l otte ry
9 8 4
ls and Obj ect
412 • Cha pter 9 Add itio na l Co ntro
use r might
e the sales tax rate is 5%. Th e
Example 3 In the following progra m, suppos
comes to the re cue.
.05 into the tex t box. A too ltip
not kno w wh eth e r to ent er 5 or
PROPERTY SETTING
OBJECT
Sa les Tax
~~ ... Sales Tax GJ I @) IE§J frm Nam e Tex t
Tex t Sa les tax rate:
lblR ate
Too lTip o n Suc h as 5, 5.25, 5.5
Sale s tax rate : txtR ate
Too ltip l
Price : Tex t Price:
lblP rice
txt Price
Calculate Tota l Cost Tex t Ca lcul ate To tal Cos t
btnC alcu late
Tex t Tot a l cost :
lblT otal Cos t
Rea dOnl y True
Tota l cost : txtT ota lCo st
~ Too iTip l
Ca lcu late .Cl ick
_ Cl ic k( ... ) Han dle s btn
Pri vat e Sub btn Ca l cul ate
= CDb l ( txt Ra te . Tex t ) I
100
Dim tax Rat e As Dou ble t)
CDb l (tx tPr ice . Tex
Dim pri ce As Dou ble = ce
Dou ble = p ric e + tax Rat e * pri
Dim tot alC ost As talC ost )
ma tCu r r enc y (to
txt To talC ost .Te xt = For
End Sub
r the first tex t box.]
[Run, and hov er the mo use ove
Tota l cost :
9.2 Eigh t Add ition al Con trols and Obj
ects • 413
Normally, a con trol placed on a form
does not have a "ToolTt p on Too lTip
property app ears in the Prop erties l " prop erty. Tha t
window only after a Too lTtp con trol
compon ent tray. has bee n add ed to the
In the exa mp le abo ve, we crea ted
a too ltip for on ly one of the text box
could have spec ified a toolt ip for the es. Howeve r, we
oth er con trols.
By default, a tool tip app ears 1/ seco
2 nd afte r the cursor hovers ove r a con
5 seco nds. These two dura tion s can trol and lasts for
be alte red with the Too ltip con trol
Aut oPo pDe lay properties. The num 's A utom atic Oelay and
eric sett ings for these two prop erti
Spe cifically, the Aut oma ticO elay sett es are in millisecond s.
ing dete rmines the leng th of time requ
app ear, and the Aut oPo pDe lay sett ired for a tooltip to
ing dete rm ines the leng th of time the
while the cursor is station ary inside too ltip rem ains visible
a control.
The Clipboard
The Clip boa rd object is used to cop
y or move info rma t ion from one loca
mai ntai ned by Win dows and therefor tion to ano ther. It is
e eve n can be used to tran sfer info rma
dows applica tion to ano ther. It is actu t ion from one Win -
ally a port ion of mem ory that hold s
no properties or eve nts. info rma tion and has
If str is a strin g, then the stat eme nt
w
w
[ Draw Orcle
0
FIGURE 9.9 Pict ure box con tai ning red circ le.
0
FIGURE 9.10 Pict u re box with dese rt scen e.
@J i~ l·
aj Dem o s'l ate f'l> en s l=
Qrder I £;;olor
I ll,s.c ending Ctri+ A
I
Qe5.cend ing Ctri+D
Forml.vb [Design] * X
a .... __F()rml
..C:2Jl 8 I
... ...........................................
'\ }
0
:: - - . - ·····- -- -- -
menu designer
o................... .................,
§] L .l
a:} Demonst rate l
enu s L!:==.J~::J~~~
SL
Orde r Co lor
[5:~:~:~:::::::::::::::::::::::::::::::::::
makes
waste
Bar Controls
• The Horizontal and Vertical Scroll
one of the a rrow but-
scroll bars . W hen the user clicks on
Figure 9.13 show the two types of the user clicks betw een
dist anc e toward that arrow. Wh en
tons, the scro ll box moves a sma ll e dist ance toward that
buttons, the scro ll box moves a larg
the croll box and one of the arro w
t t
Right arrow
[ ~ .._ Bottom arrow
Left arrow
.
FIGURE 9.13 H orizonta l and vert ical scro ll bars
9.2 Eight Add itiona l Controls and Objects
• 419
arrow. The user can also move the scroll box by dragg ing it. The ma in propertie of a scroll bar
control are Minimum, Maximum, Value, S mallC hange, and LargeChange, which are set to
integers. The stand ard prefix for the name of a scro ll bar is hsb or vsb. At any time, hsbBar.Value
is a number between hsbBar.Minimu m and hsbBa r.Max imum determined by the pos ition of the
left side of the scroll box. If the left side of the sc roll box is ha lfway between the two arrows,
then hsbBar.Va lu e is a number ha lfway between hsbBar. Minimum and hsb Bar.Max imum. If
the scroll box is near the left arrow button, then h bBar.Va lu e is an approp riate ly proportion ed
va lue near hsbBar.Minimu m. W h en the user clicks on an arrow button, hsbBar.Value changes
by hsbBar.S ma llC hange and the scroll box moves acco rdingly. When the bar between the
scroll box and one of the arrows is cl icked, h sbBar.Value ch anges by hsbBar.LargeC hange and
the scroll box moves accordingly. When the scroll box is dragged, hsbBar. Va lu e change
acco rdingly. The default va lues of M inimum , Maximum, Va lue, S ma llC h ange, and
LargeCh ange are 0, 100, 0, 1, and 10, respectively. H oweve r, these values are usua lly changed
at design time. The width of the croll box is equal to the va lue of LargeCh ange. S ince
h sbBar.Va lu e is determined by the left sid e of the scro ll box, the greatest va lu e it can assume
is (hsbBar.Max imum - h sbBar.LargeC hange + 1) . Vertica l sc ro ll bars beh ave similarly.
Note : The etting for the Minimum property mu t be less than th e setting fo r the Max imum
prope rty. The Min imum property determines the va lu e for the left and top arrows. The
Maximum property determines the va lues fo r t he right and botto m arrows.
The two controls are refe rred to as HScro llBar and VScrollBar in the Toolbox. The ir
default event, Scroll, is raised whe neve r the user clicks on any part of the cro ll bar.
Example 5 The fo llow ing prog ram uses sc ro ll ba rs to move a miling face aro und
the form. The face is a large Wingd ings c ha rac ter ] insid e a labe l. The va lu es lblFace. Left
and lblFace.Top are the dista nces in pixe ls of the labe l from the left side and top of the
form.
~
~
420 • Chapt er 9 Add itional Controls and Objects
os.Sc roll
Priva te Sub hsbXp os Scrol l( ... ) Handl es hsbXp
lblFa ce.Le ft = hsbXp os.Va lue
End Sub
os.Sc roll
Priva te Sub vsbYp os Scrol l( ... ) Handl es vsbYp
lblFac e.Top = vsbYp os.Va lue
End Sub
a S iling ace
EXERCISES 9.2
47 . Write a program to create a decorat ive digital clock. The clock in the Digita l C
lock form
in Fig. 9. 14 is inse rted in a picture box con tro l co ntaining the Trees.bm p picture.
The
va lue fo r hour, minu te, and seco nd ca n be ob tained as H our( Now), Minute( Now ),
and
Second( N ow).
oA Coin Toss
Outcome : Heads
FIGURE 9. 14 Sample run of Exercise 4 7. FIGURE 9.15 Sample run of Exercise 48.
48. W rite a program using the form in Fig. 9. 15 . Each time the button is pressed, a
Random
object is used to si mul ate a coin toss and the va lues are updated . The figure shows the
sta-
tu s after the button has been pressed 607 time . Note: You can prod uce tosses quickly
by
just holding down the Enter key. Although th e perce ntage of heads initially will flu ctuate
cons iderab ly, it should stay close to 50% after many (say, 1000) tosses.
49. The file Members. txt contains the names of the members of a large club. Write
a program
to random ly se lect people to se rve as Pres ident, Treasure r, and Secretary. Note: A person
cannot hold more than one office.
50. Place the names of the 52 play ing cards in to the array deckOfCards . Then disp lay the
names
of five randomly chosen cards in lstPokerH and.
51. W rite a program that repeated ly rolls a pair of dice and tallies the number of ro lls
and the
number of those ro lls that tota l seven. The program should stop when 1000 sevens
have
been ro lled, and then report the app roximate odds of rolling a seven. (The approxim ate
odds
will be "1 in " followed by the result of div id ing the number of rolls by the number of
ro lls
that came up seven.)
52. Write a program to randoml y select 40 different people from a group of 100 people
whose
names are contained in the text file N ames.txt.
53. The Birthday Problem . G iven a random group of 23 people, how likely is it that two
people
have the same birthday? To answer this question, write a program that creates an array
of
23 elements, randoml y ass ign to each ub cripted variable one of the integer from 1 through
365, and checks to see if any of the subscript ed variables have the same value. (Make the
sim-
plify ing assumpti on that no birthdays occur on February 29.) Now expand the program
to
repeat the process 1000 times and determin e the percentage of th time that there is a match
.
424 • Chapte r 9 Additio na l Contro ls and Objects
32. ...
212 Celsius
Fahrenheit
Sample run of Exercis e 59. FIGURE 9.17 Sample run of Exercis e 60.
FIGURE 9.16
Solutio n Explorer
~ _-_ , ~
a ~
-:::-
..=..J=:..J
];] WincdowsAppl ica~tion l
~ My Project
.:::J
Fo rml.v b
~ Forml .v b
FIGURE 9.18 Solution Explo rer windo w after a secon d for m is added
.
Name : AJ Oark
FIGURE 9.19 Custo mized input dialog box. FIGURE 9.20 C ustom ized message dialog box.
Startup Form
W hen a progra m starts runn ing, only one fo rm (calle
d the startu p for m ) will be loaded. By
defaul t, the first fo rm create d is the sta rtu p form. The
follow ing steps change the startup form.
1. Right -click on the na me of the progra m at the top
of the Solu t ion Exp lorer window and
cl ick on Properties in the drop-down contex t menu .
The progra m's Projec t De igner will
appea r.
2. C lick the App lica tion tab.
426 • Chap ter 9 Additiona l Cont rols and Objects
n list.
3. Selec t a form fro m the Startup form drop -dow
X sy mbo l on its tab.
4. C lose the Proje ct Designer by click ing the
in Form2 .
must be referred to as Form I. total when used
The scope of a class- level cons tant is conv erted to namespace- level by prece ding the key-
era l proce dure and a S truct ure decla ratio n have
word Cons t with the keyword Publ ic. A gen
their h eade r with the keyword Priva te will limit
name space- level scope by default. Prece ding with
ls always h ave name space -leve l scope. Just as
the ir access to the ir decla ratio n form. Cont ro , and cont rol must be
tants , gene ral proce dures
variables, the name s of namespace- leve l cons refer red to in anot her
wed by a perio d) when
prece ded by t heir decla ratio n form's name (follo
fo rm's code.
Modality
d
or mode less form. A moda l fo rm must be close
A fo rm can invok e anot her form as a moda l (Ord inary inpu t and mes-
rest of the program.
before the user can co ntinu e work ing with the
l form s.) With a mode less (or nonm odal) form, the user
sage dialog boxes are examp les of moda l
her form with out havin g to fir t close the initia
can shift the foc us betw een the form and anot
ple of a mode less fo rm.) In this book, new forms
form. (Vi ual Basic's Find dialog box is an exam
will always be invoked as moda l forms.
OBJECT PROPERTY
~I ~ I~
D_. Incom e SETTING
frmln come Text Incom e
Name : lblNa me Text Name :
txtN ame
Total income : lblTo tlnco me Text Total incom e:
txtTo t!nco me
Determine Total Income btnDe termi ne Text Deter mine
Tota l Incom e
= @]
D I nco e
,l l = I@] 1~.-J
D~ So rces of In come
As Stri ng ,
Fun ctio n Con firm ( ByV al userN ame
ByV al pass word As Stri ng ) As Boo lean
)
.Rea dAll Line s( "Ma ster File .txt"
Dim que ry= From line In IO. File
& pass word
Whe re line = userN ame &
Sele ct line
If quer y.Co unt = 1 Then
Retu rn True
Else
Retu rn Fals e
End If
End Fun ctio n
the form .]
[Run , ente r a user na me and password into
Password : vbgll'l 1
:~~.0.~~~~~:
1!:.':... :.. .::.:.
..:!1
9.3 Mult ip le-Form Prog rams
• 43 1
a~ Order Fonn l = I @) ~~ -d
User name : JQ Public
Process Order
Log Out
t even t
eceipt. Note : The code ins ide the btn Prin
8. Add the code show n in Fig. 9.22 to frmR
the prin ter.
proc edure prin ts the cont ents of the form on
,
As Stri ng , ByV al pay As Dou ble
Sub SetP ayro lli nfo( ByV al empName
fica Tax As Dou ble ,
ByV al tota lPay As Dou ble , ByV al
chec k As Dou ble )
ByV al fedT ax As Dou ble , ByV al
txtN ame. Text = empName
cy(p ay)
t x tGro ssPa y.Te xt = Form atCu rren
cy(t otal Pay)
t x tTot alPa y.Te xt = Form atCu rren
cy(f icaT ax)
txtF ic aTax .Tex t = Form atCu rren
fedT ax)
txtF edTa x . Text = Forr natC urre ncy(
chec k)
txt Che ck.T ext = Forr natC urre ncy(
End Sub
with
e, pay, tota lPay , fica Tax ,
frmR ecei pt .S etPa yrol linfo (emp Nam
fedT ax, chec k) 'Tas k 6
~·~~
Practice Problems 9_..~JL~~~
ame.
out using the namespace- leve l varia ble userN
1. Rewrite th e prog ram in Examp le 2 with
EXERCISES 9.3
ed.
outp ut disp layed whe n the butt on is click
In Exer cises 1 thro ugh 4, dete rmin e th e
1. 'For rnl' s code (sta rtup form )
) Han dles btnD ispl ay. Clic k
Pr iva te Sub btnD ispl ay _ Clic k( ...
Forrn 2.Sh owD ialo g()
Form 2.to talC ost)
txtO utpu t.Te xt = Forr natC urre ncy(
End Sub
1
Form2 1 s code
Public Const SALES TAX RATE As Double 0.06
Public totalCo st As Double
1
Form2 1 s code
Private Sub Form2 _ Load( ... ) Handles MyBase. Load
txtName .Text = "John Doe"
txtDate OfBirth . Text = "2/3/198 9"
End Sub
3. Forml 1 s code
1
(startup form)
Private Sub Form1_ Load( ... ) Handles MyBase. Load
Form2.S howDial og()
Dim name As String= Form2.fu l1Name
Dim l astName As String= Form2.G etLastNa me( name)
txtOutp ut.Text = "Your last name begins with " &
lastNam e.Substr ing(O, 1) & " "
End Sub
1
Form2 1 s code
Public fullNam e As String
Me. Close( )
End Sub
6. Con ider the program in Exa mple 9 from Section 7.1 that determines a pe rson 's first and
last names. A lter the program so that the person's full name is typed into the startup form
and a econd fo rm is used to el i play their first and last names.
7. Consider Exa mple 4 of Section 6.1. A lter the program so that a second form showing the
balance after each year appea rs when th e button is clicked on. See Fig. 9.23.
aj Successive Balances
a.J 6% Interes l= §] ~
Year Amount
Amount Deposited: 1 0 0 S100. 0.00
S106. 0.00
[ Calculate Years to Become a Millionaire J 2 S112.360.
In 40 years you will have a million dollars . 3 511 9.101 60
8. Conside r the A nalyze-a-Loa n case stud y from C hapter 7. A lter the program so that the
amortization tab le and the interes t-rate-ch ange table are each displayed in a separate fo rm
when requested. The program sh ould have three forms, and the startup form sho uld not
conta in a DataG ridView control.
9. Consider the Recording C hecks and Depos its case study from C hapter 8. A lter the program
so th at the li t of transactions is di splayed in a second fo rm when requ es ted.
10. Write a program that allows stud ent grades on three exams to be entered one tudent at a time
in frmStudent and then displays each student's average and the class average in frmG rades. Ini-
tially, frmG rades (the startup form) should look like Fig. 9.24 with the text box and DataG rid-
View controls empty. The form frmStudent should initially look like Fig. 9.25 with the four
text boxes empty. The Load event procedure of frmG rades should invoke frmStudent.
Each time a student 's name and grades are reco rd ed, the number in the title bar of frm -
Student sho uld increase by 1. The Terminate button should be clicked o n after a ll students
have been recorded. The da ta for the students sho uld be stored in an array of st ructures
with the structure hav ing four members.
Exam 1: 75
Oass average : 85.8
Exam 2: 88
Name Average
Exam 3: 89
AJ Adams 84
1: ................ ............. .................... ........TI
Brittany Brooks 80 1: Record Student 1
Carol Cole 92
Donald Davis 87 [ Terminate Ent ering Grades
rma t ion. Th e
11. Write a progra m con sisting of three fo rms tha t ga th ers custome r billi ng info
first fo rm (the sta rtup fo rm) sho uld initia ll y look like Fig. 9.26, but with th e tex t box and
list box blank and no radio butto n se lec ted. (The seco nd a nd third fo rms sh o uld initia lly
a n ame,
look like Figs. 9. 27 and 9.29 with a ll tex t boxes blank .) After th e use r prov ides
th e butto n in fr mC ustome r, e ith e r frmCustl nfo o r
selects a billing me thod, a nd clicks o n
frmCard info sh o uld appea r to o bta in the necessa ry info rmat io n.
n is
Le t's first consid er frmC ustlnfo, that appears wh en th e Bill Customer rad io butto
lled a utomatic a lly with the n a me that
se lected . The N ame read -only tex t box sh o uld be fi
se lects
was ente red in frmC ustome r. T h e user e nte rs info rma tio n in to the o the r tex t boxes,
d isplay the
a state fro m the sorted dro p-down -list co mbo box , and cl icks o n th e button to
na mes of
ma iling address in the list box of frmC usto me r as sh o wn in Fig. 9.26. Note: The
th e states can be o bta ined from the fi le S tates. tx t.
in frm -
T h e fo rm frmCard l nfo, which appear wh en th e Bill Credit Card radio butto n
(fo type of
r
C usto mer h as bee n se lected , co nta ins two tex t boxes, o n e simp le combo box
it ia lly auto-
cred it card) and two D ropDown List style com bo boxes. The N ame text box is in
in frmC ustomer. H o wever, th e name can be
ma tica lly filled with the na me that was entered
c sto er l = I @] I""'··~ .J
Name on card : John Q. Public
Name: John Public
txtU serN ame. Text frmL ogin .txtU serN ame. Text
9.4 Graphics
In this secti on, we draw bar charts and pie ch arts
in a pictu re box, and illustrate one meth od for
crea ting anim ation on a form .
Caut ion: S ince the prog rams in this secti on
mi x text and graph ics, what you see on the
moni tor will vary with the moni tor's DPI settin
g. To guara ntee the intend ed outco mes, you
should chec k that your moni to r is set to displ ay
96 DPI (Dot s Per Inch ). For deta ils, see the first
ite m unde r "Configur ing the Wind ows En viron
ment " in Appe ndix B.
Graphics Objects
Yid eoN ote
A tatem en t of the form
Graph ics
Dim gr As Grap hics = picB ox.C reate Grap hics
decla res gr to be a G raphi cs obj ect for the pictu
re box picBox.
cts
438 • Cha pter 9 Addi tiona l Con trols and Obje
big a
met hods is the pixel. To ge t a feel fo r how
The un it of meas urem ent used in grap hics ls thic k. The
ls high , and the bo rder of a fo rm is four pixe
pixe l is, the title bar of a form is 30 pixe . The two
box is two num bers eparated by a co mma
setti ng fo r the S ize property of a pictu re e num be rs to
pictu re box in pixe ls. You can a lter thes
num bers give the widt h and he ight of the rdin ates
ctur e box is identifi ed by a pa ir of coo
spec ify a prec ise size. Each poi nt of a pi
(x, y)
of the pict ure
is its dista nce in pi xe ls from the left side
whe re x (bet wee n 0 and picBox. Wid th) pictu re box.
is its dista nce in pixe ls from the top of the
box, andy (bet ween 0 and picBox. Heig ht)
men t of the fo rm
Tex t is placed in a pictu re box with a state
Bru shes .Co lor, x, y)
gr.D raw Stri ng( stri ng, Me.F ont,
font be u ed to
literal, Me. Font spec ifies that the Fo rm's
whe re string is eith er a strin g varia ble or dina tes (x, y ).
er of the fir t char acte r of the text has coor
el i play the tex t, and the uppe r-left corn abou t 140 poss ible
The colo r of the tex t i dete rmined by Colo
r. Inte lliSe nse will prov ide a list of
example, the state men ts
colo rs after "Bru shes ." is type d. As an
reat eGr aph ics
Dim gr As Gra phic s = picB ox.C
Dim strV ar As Stri ng = "He llo"
t, Bru shes .Blu e, 4, 30)
gr.D raw Stri ng(s trVa r, Me .Fon
t, Bru shes .Red , 35, 50)
gr.D raw Stri ng( "Wo rld" , Me .Fon
Hello
World
(50 ~
(120, 75)
70
[50. 20]
55
data type.
Pie Charts
chart can be used to graph ically display the
Cons ider the three pieces of data in Table 9.3. A pie
ing a pie ch art is to convert the numbe rs to
re lat ive size of these nu mbers. The first step in creat
bill ion , the federal outla y is 33/41 9 ~ .08 or
pe rcents. Since the total expend itu res are $419
49% and 43%. ee Table 9.4. O ur goa l is to
8%. S imila rly, the state and local expen ditures are
pie ch art of Fig. 9.36 .
write a program to d isplay the inform ation in the
•• Feaeral
State
Loca l
Example 1 The follow ing progra m creates the pie chart (see Fig. 9.36)
for the financ ing
of public schoo ls. The program is writte n so that it can
be eas ily con verted to hand le a pie chart
with up to six sectors. A ll that is requ ired is to chang
e the first two Dim statements and the
Me .Tex t statem ent. T he "Dim br() As Brush " line, which
creates an array of brush es, has six
brush es in order to acco mmod ate add itiona l secto rs.
Bar Charts
7. The picture box for the chart has a width
O ur goal here is to prod uce the bar chart of Fig. 9.3
rStyle prope rty is set to Fixed S ingle for
of 210 and heigh t of 150 pixe ls. (Here, the Borde
look bette r with the Borde rStyle prope rty of
instru ction al reaso ns. In general, the bar chart will
the pictu re box left at its defau lt sett ing: N one. )
100
Example 2 The fo llow ing program prod uces the bar ch art of Fig. 9.3 7. Each rectan gle is
20 p ixels w id e, and th e re are 20 pixels be twee n recta ngles.
• Animation
One way to produce animation on a form is to place an image in to a p ictu re box and then move
the p icture by steadi ly ch a ng ing t h e location of the picture box. Figure 9.38 sh ows a ba ll placed
inside a sma ll p icture box .
Example 3 In the fo llowing program , the ba ll in Fig. 9.38 will initia lly move diagon a ll y
in a sou thea t direction and the n bo unce off a n y side of the fo rm it h its. The client area of a for m
is th e gray area within the ti tle bar and borders of th e form. The va lues of M e .C lie ntS ize. H igh t
and Me. lient ize. Wi dth are t he he ight and width of the white area. The v lues of p icB x. Top
and picBox.Left are the distances of the pic ture box from the top and left sid es of the clie nt a rea .
The speed at which the ba ll move is determined by the setting for the Interva l property of
Timerl . At each t ick, the ball will move x pixe ls hori zontally, where x = 1 o r - 1. When x = 1
the ball moves to the righ t, and wh en x = - 1 the ball moves to the left . The va lue of x reve r es
when the ball strikes the right o r left side of the form. The value of y determines the verti cal
motion of the ball in a similar manner,
Dim x As Integer 1
Dim y As Integer 1
Printing Graphics
Graphics can be printed with a PrintDocument control in the sa me way that tex t was printed
in Section 3 .3.
Example 4 The follow ing program produces the same o utput as Exa mple 2. H oweve r,
the output is printed instead of being displayed in a picture box. The changes from Example 2
are as fo llows:
10 The code was moved fro m the btnDisplay _C lick event procedure to the procedure Print-
Docume ntl_PrintP age.
20 The source of the graphics object gr was changed fro m picOutput . C rea teGraphics to
e. G raphics.
30 The Me.Tex t statement wa replaced with a DrawS tring statement .
40 The values of the x-coo rd inates were increased by 300 to approx imate ly center the graph
horizontally, and the va lues of the y-coordina tes were increased by 200 to lower the graph
from the top edge of the page.
9.4 G raphic • 445
Private Sub PrintDocu ment1_ PrintPag e( ... ) Handles PrintDoc umentl.P rintPage
Dim quantity () As Single = {33, 207, 180}
Dim gr As Graphics = e.Graphi cs
gr . DrawLine ( Pens .Black, 340, 310, 510, 310 ) 'x-axis
gr . DrawLine ( Pens .Black, 340, 310, 340, 200) 'y-axis
gr . DrawLine ( Pens .Black, 335, 260, 345, 260) tick marie
gr . DrawStri ng( "$100" , Me .Font, Brushes .B1ack, 305, 255)
gr.DrawS tring( "Financin g for Public Schools ( K - 12)" , Me .Font,
Brushes . B1ack, 300, 175)
For i As Integer = 0 To quantity. Count - 1
gr.Fi11R ectang1e ( Brushes .B1ue, 360 + i * 40,
(310 - quantity (i) I 2), 20, quantity (i) I 2)
Next
gr . DrawStri ng( "Federal State Local" , Me .Font,
Brushes .B1ack, 350, 315)
gr.DrawS tring( "(Expend itures in billions )" , Me .Font,
Brushes . B1ack, 350, 330)
End Sub
Comments
1. A statement of the form
Dim pn As Pen = Pens.Col or
declares pn to be a variab le of type Pen and ass igns it the value Pens. Color.
2. A statement of the form
Dim fnt As Font = New Font(font Narne, size)
declares fnt to be a variable of type Font and ass igns it th specified font and size. For
instance, the statements
446 • Chapter 9 Add itional Controls and Objects
EXERCISES 9.4
in a picture box.
In Exerci ses 1 throug h 4, write a progra m to draw the given figures
1. Draw a circle whose center is loca ted at the center of a picture box.
2. Draw a circle whose leftm ost point is at the center of a picture box.
20.
3. Use the FillEllipse method to crea te an unfilled red circle of radius
4. Draw a triangle with two sides of the same length.
In Exerci ses 5 throug h 18 display the graphic s in a picture box.
design ated countr y. Refer
In Exerci ses 5 throug h 8, write a progra m to create the flag of the
flags, the width is 1.5 times
to Fig. 9.39. Note: The Swiss flag is square . For the other three
the height.
0 2 3 4 5 6 7 8
- - - - - Line1
- - - - - Line2
- - - - - Line3
1 .
2008
Percentage of College Fres men \~lho Smoke
Source: Higher Eaucatio Researc Institute
females
3358
s).
IM:Jip:M Two-year college enrollments {in thousand
1980 1990 2000
1960 1970
2047 2233 2398
Male 283 1375
2479 3007 3358
Female 170 945
t in Fig. 9.44.
15. Wri te a program to crea te the bar char
5. <.•
Fres n a
(% of stu ents con n ·tteu to goal)
17. W rite a program to create the bar chart in Figure 9.46. U se the data in Table 9. 10. Note:
Mand arin and Wu are spoken primarily in C hina.
882
18. Write a program that allows th e use r to display a budget as a pie chart. See Fig. 9.47 on the
next page. After the u er enters numbers into the four tex t boxes and click on the button ,
the pie chart should be displayed.
19. Wri te a program in which an airplane fli es horizo ntally to the right across a form. After it
flies off the form, the airplane should reappear on the left and fly horizontally across the
screen aga in. Note: Use the image Airplane.bmp found in the folder C h09 \Picture .
20. Rewrite the program in Exa mple 1 so that the pie chart is prin ted instead of being di played
in a picture box . Note: You will mos t likely want to replace the variabl e with the pair of
vari ables ex and ey. Then the center of the circle will have coord inates (ex, ey ).
21. Refer to Exe rcise 5. Write a program to print the flag of Italy.
D~ Bud get
• H us ing
• TraBSportati o
. Food
Other
CHAPTER 9 SUMMARY
() holds the items stored in the list box.
1. List boxes provide ea y access to lists of data. Items
lists can be automatically sorted (Sorted
Each item is identified by an index numbe r. The
ltems.RemoveA t, and ltems.Remove
property = True ) and altered (Items.Add ltem,
(Text property), and the numb er of
meth ods), the curre ntly highl ighted item iden tified
items deter mine d (Item s.Cou nt property).
nced text boxes. They allow the user to
2. Simp le and Drop Oown style combo boxes are enha
by typing the item directly into the text
fi ll the text box by se lecting an item from a list or
the comb o box's Text prope rty. A Orop-
box. The conte nts of the text box are ass igned to
that drops dow n instead of being penn a-
DownList style co mbo box is essen tially a list box
nentl y displayed.
a specified time interv al.
3. The timer contro l ra ises an even t repea tedly after
mly selec ted integ e r from a pecified range.
4. An objec t of type Rando m can ge nerat e a rando
guida nce when the mou e hovers over a
5. The ToolTip control allows the program to d isplay
contr ol.
or by pressi ng C trl + C, and its conte nt
6. The Clipboard i filled with the SetText meth od
C trl + V.
are cop ied with the GetTex t meth od or by pressing
Progr ammi ng Projec ts
• 451
list
displ ay the titles of the books in stoc k in a
nonfiction .) A t any time, the prog ram should or just those in one of
layin g eithe r all t itles
box. T he user should have the op tion of disp or alter any
to add a new book , dele te a book,
the two categories. The use r should be able ,
ng and editi ng processes use the econ d form
of the fields of a book in stoc k. The addi lue
user should be able to calculate the to tal va
frmDeta ils. See Fig. 9.49. At any time, the u item File cont ains
in eithe r catego ry. The men
of all books, or the total va lue of the boo ks
the two seco nd -leve l menu items Save and
Exit. The menu items Display and Valu es each
the
s All, Ficti on, and Nonfiction. (Hin t: tore
cont ain the three seco nd -leve l menu item
.)
data abou t the books in an array of struc tures
2.
FIGURE 9.49 The two forms for Prog ramm ing Proje ct
use in
bring a co mpu ter to their annu al mee ting to
3. Voting Mac hine. The members of a club prog ram
program to hand le the elect ion . The
the elect ion of a new president . Writ e a on
he or he is nom inated. Afte r the nom inati
shou ld add each candid ate to a li t box a
able to approach the co mpu ter one at a t ime
process is complete, club members should be on ,
choice. Whe n a Tally Vo tes butt on is clicked
and doub le-click on the ca ndid ate of their shou ld appe ar
s rece ived by each candid ate,
a seco nd list box, ha wing the num ber of vote t num ber
of the candidate (s) with the high e
alongs ide the first list box . A lso, the name(s)
of votes should be disp layed in a list box.
seats
15 rows (num bered 1 thro ugh 15), with six
4. Airplane Seating Chart. An airplane has that keep s track of
Write a mult iform prog ram
(labe led A, B, C, D, E, and F) in each row. nger . The
type of mea l requ ested by each passe
the seats that have been reserved and the
with a line for each row. See Fig. 9.50 (a) .
eating char t should be displ ayed in a list box
row in the list box, the row num ber and the
Whe n the ticke t agen t clicks on the desired
ayed in seve n read -onl y text boxes at the bot-
status of the seats in the row should be displ
one of the text boxes, a seco nd form con ta ining
tom of the form . Whe n the agen t clicks on r.
lar, Low Calorie, and Vege tarian should appea
fou r optio n butto ns labeled Unoccupied, Regu both
n should close the seco nd form and upda te
See Fig. 9.50 (b) . C licki ng on a radio butto ied seats are deno ted with a
list box. Unoccup
the text box and the row for that seat in the . At an y time ,
the first lette r of their mea l type
period , and occupied eat are deno ted with
ber of seats fi lled, the num ber of window seats
the agen t should be able to requ est the num
l ord ered .
vaca nt, and the num bers of each type of mea
Progra mmin g Projec ts
• 453
ABC DE F
R. V R.:.JL
R. R .- .
-'
R. L • : : .,R
C D1splcrj Statistics
RR:Z.,
RV.
VRR
RRR
RRL :Z., .R
Seac a : illed : 62
Kindow s avail : 6 RRR . RR
o . Assign seat SA l = I @) l;....iJ ~~
Regula r ~e al s: 43 •• R •• R
Lo-w·Cal me als: 14 It Unoccupied
' egie me als: S ::::.,R . L . R Regular
R •• • • R
Low Calorie Vegetari an
RRR ::::.,RR
. ::::.,R RRR
RRL .v . (b)
•• R
. LR VRR
A B c D E F
8 R R
(a)
l = I@J I. ~.
a~ e U derde>g and he Worl d Series
WIN NER
2900 29.00~~
Underdog : (
7100 71.00%
Favorite :
2963 29.63%
Six. games : ~
26&6 26.86"4
Seven games:
Day O
a~ Sprea d of a n Epidem ic
Day 3
Susceptible
457
458 • Cha pter 10 Databases
I'U:J!II•II Cities.
pop2 010 pop2 015
nam e coun try
20.1 22.0
Bombay Indi a
13 .1 13.4
Buenos A ires Arge ntin a
15.6 17.0
Calc utta India
17.0 18.7
Delh i Ind ia
14.8 17.0
Dha ka Bangladesh
19.5 20.2
Mex ico C ity Mexico
19.4 20.0
New York USA
19.6 20.1
Sao Pa ulo Braz il
15.8 17. 2
Shan gha i Chin a
36. 1 36.4
Tokyo Japa n
us densely popu lated
an agglome ratio ns" -tha t is, cont iguo
Note : The popu latio n figures are for "urb
urba n areas.
lfi':J!II•IJ Countries.
mon etar y Uni t
nam e pop2 010
41.9 peso
Arge ntin a
152.6 raka
Bangladesh rea l
195 .2
Brazil yuan
Chin a 1379.7
1196.8 rupee
Indi a rupi ah
Indo nesi a
258.5
129.0 yen
Japa n peso
Mex ico 117.4
184.2 rupee
Paki stan dolla r
USA
3 10.1
Non e
click here
I
Add Project Data Source ...
Click the 'Add Project Data Source.. .' li nk t o
conn ect to data .
-- ,
lDotobm
Servi ce
~
Obj ect
sourc e or click
E.nter inform ation to conne ct to the select ed data
ent data sourc e and/ or prov ider.
"Chan ge" to choos e a differ
Data sourc e:
Micro soft Acces. s. Datab ase File (OLE. DB) Chang e ...
Passw ord:
j Save my pas.s.w ord
dv anced ...
OK Cance l
T es.t Conne ction
460
10.1 An Introd ucti on to Databases
• 461
8. If the "Da ta source:" tex t
box doe s not say "M icro soft Acc
clic k on the C hange but ton . A ess Database File (OL E DB) ",
C han ge Dat a Source window will app
Access Database File from the win ear. Sel ect Microsoft
dow's list box and click on the
retu rne d to the Ad d Co nne ctio OK but ton . You will be
n wind ow shown in Fig. 10.3.
9. C lick on the Browse but ton
, nav iga te to and ope n the Dat
Pro gra ms\ C hlO ) , dou ble -cli ck aba ses fo lde r (a sub fo lder of
on Me gac ities .acc db , and clic k
Dat a Source Co nfig ura t ion Wiz on the OK but ton . Th e
ard tha t app ear ed in Step 6 reap
now co nta inin g Megac ities.accdb pea rs wit h the tex t box
.
10. C lick on the Next but ton
. The window in Fig. 10.4 appear
to place a copy of the file Megac s, ask ing wh eth er you wou ld li ke
ities.accdb into the program.
atio n File
to the Ap plic atio n Co nfi gur
Sav e the Co nne ctio n Str ing
i
,/J Yes, save the con nec tion as:
Cancel
<Pr evio us ]I.___N_ext
__>_ __.
p 11.
FIGURE 10.5 W ind ow pro duc ed by Ste
Wizard
Data Sou rce Con figu ratio n
jec ts
Ch oos e Yo ur Da tab ase Ob
----------
you wan t in you r data set ?
-1fl]
Wh ich data base obje cts do
[
~ Tables
@V iews
-- - -
I
..J
DataSet nam e:
MegacitiesDataSet
.____F_in_i_sh__.......J c_a_n_ce_l__~
L[_ _ _
<.P revi ous
p 12.
FIGURE 10.6 Wi ndo w pro duc ed by Ste
462
10.1 A n Intro duct ion to Data bases
• 463
-
pop2010 pop.2.015
nam e coun t ry
20.1 22
~
India
13.1 13.4
I Bu enos Aire!; Arg entina
15.6 17
Ca lcutta Indi a
17 18.7
Delhi Indi a
14.8 17
Dhaka Bangladesh
19.5 20.2
~vl ex ico Ci y Mex ico
19.4 20
New York USA
19.6 20.1
Sao Pau lo Braz il
15.8 17.2
Shanghai China
36 .1 36.4
Toky o Japan
NULL NULL
NULL NULL
* m
I
1 of10
• •I • ..,
and
ities table of th e Megacit ies data base
Example 1 The follo win g prog ram uses the C ed by th e ir 201 0
the nam es of the citie s that are loca ted in Ind ia. The cities are sort
disp lays ulat ion of those cit ies in
prog ram also d isplays the tota l pop
populat ion in dec reas ing orde r. The Q q uery. Not e: In the
erve a the data sour ce for the LIN
a text box. Megacit iesO ataS et.C ities
10.1 An In trod uction to Dat aba es
• 465
O rd er By clause of que ryl , the re
was no need to use the C Dbl fun
was give n to the pop 20 10 field whe ctio n . The data type Doub le
n the dat abase wa crea ted, and the
cit y . pop 201 0 has type Dou refo re LIN Q kno ws tha t
ble.
Total population :
~ Meg ac i ies.DacaSe
~ Ci iesTableAda p er
a~ 1ega ci1ie s
Bombay
Delhi
Calcutta
requ sted by
the Co unt ries tab le for a cou ntry
Example 2 The fo llow ing progra m searches "mo netary Un it" in
tha t the Dat aSo urce met hod d isplays "na me", "pop20 10", and
the user. No tice ", and "co unt ry.m one tary Un it".
u ntry. name", "co unt ry.pop2010
the headers of the tab le, not "co loop ing variab le in a For Each
vari able cou ntry plays a sup porting ro le sim ilar to tha t of a
The
loop.
ase .Lo ad
s_ Loa d ( ... ) Han dle s MyB
Pri vat e Sub f r mC oun trie aMe mbe r was set to Cit ies
ally whe n Dat
'co de gen era ted aut om atic taS et .Co unt rie s)
er.F ill( Me . Me gac itie sDa
Me .Co unt rie sTa ble Ad apt
End Sub
Dis pla y.C l ick
Cli ck( . .. ) Han dle s btn
Pri vat e Sub btn Dis pla y_ sD ata Set .Co unt ries
itie
Dim que ry Fro m cou ntr y In Me gac
e.T ext
Wh ere cou ntry .na me = txtN
am
net ary Un it
ntr y.p op2 010 , cou ntry .mo
Sel ect cou ntr y.n am e, cou
If que ry.C oun t = 1 The
n
dgv Ou tpu t.D ata Sou rce = que ry. ToL ist
dgv Ou tpu t.C urr ent Cel l
= No thin g
Els e " , "No t Fou nd" )
ry is not in the tab le.
Me ssag eBo x . Sho w ( "Co unt
End If
End Sub
t box, and clic k on the but ton.]
[Run, ent er a coun try into the tex
and
tabl e of the Me gac ities dat aba se
Example 3 Th e foll owi ng progra m uses the C ities 1 mi llio n peo ple
-./ by mo re tha n
lays the c ities who se pop ulat ion s are pre dic ted to incr ease bot h the
disp lati o n inc rease, and
ord ered by the ir pro ject ed popu
from 2010 to 20 15 . The citi es are
ea es (in mil lion s) are d isplayed.
city nam e and pop ulation incr
ase .Lo ad
Loa d ( ... ) Han dle s MyB
Pri vat e Sub frm Cit ies _ esD ata Set . Cit ies )
i ll (Me .M ega citi
Me .Ci tie sTa ble Ad apt er.F
End Sub
Dis pla y . Cli ck
Cli ck( ... ) Han dle s btn
Pri vat e Sub btn Dis pla y_
sD ata Set .Ci ties
Dim que ry Fro m cit y In Me gac itie
op 2 015 - city .po p20 10
Let pop inc rea se = cit y.p
1)
mat Num ber (po pin cre ase ,
Let for ma tted inc r = For
Wh ere pop inc rea se > 1
cen din g
Ord er By pop inc rea se Des
tted inc r
Sel ect city .na me , for ma
10.1 An Introduc ti on to Databases • 467
Display Oties
Population
Oty
Increase
Dhaka 2.2
Bombay 1. 9
Delhi 1.7
Calcutta 1.
Shanghai 1..
Example 4 The following program displays the cities fro m the Cities table in a list box
sorted by their population in 2010. When the user clicks on one of the cities,
its coun try, popu la-
tion in 2010, and populat ion in 2015 are displaye d in text boxes. In the second
event procedur , a
query is used to earch for the desired record of the table. In this ca e, the query
returns a sequence
of one value. Since a sequenc e cannot be assigned to a text box, the First method
is used to obtain
the desired value. Note: Notice that the stateme nt lstCiti es . Dataso urce
= query.T oList in
the Load event procedure is not followed by the stateme nt lstCi ties . Selecte
ditem = Nothing .
Had the Selecte dltem stateme nt been added, the ini tial display wou ld show
the data about Tokyo
without revealing the city that the data referred to.
c~ egacities
fo r each city is expan d ed to h o w its count ry's 201 0 popula t io n an d its mo n etary uni t. T his
jo ined table i very h and y if, say, we wa n t to d isplay a c ity's cu rre ncy.
l= l · @l i~J
• Megacit ies
·-
End Sub
10.1 A n Introdu ction to Databa es • 471
Currencies Oties
r-------,
Buenos Aires
Mexico Cit;•
Comments
1. A database resides on a disk, and a DataSe t resides in memory.
A table adapte r serves a a
condui t to allow bid irection al data transfe r betwee n the two. A
bindin g source is used to
simplify attachi ng form con tro ls to data sources .
2. The require ment th at no record may have a n ull entry in a primar
y key an d th at entr ie for
primary keys be un iqu e is called the Rule of Entity Integri ty.
3. The Jo in of two ta bles is a virtu al constru ct. It exists on ly in memor
y.
1. Consid er the qu ery in the Load event proced ure of Exa mple 6. W
hat would happen if the
LINQ operato r Distinc t were omitted ?
2. Consid er the qu ery in Exa mp le 5. W hy ca n 't th e Select clause be
wri tten as follows?
Select city .name, city . countr y, cityPo p2010 , cityPo
p2015 ,
c o untry . name, countr yPop2 010, countr y.mon etaryU
nit
472 • Chapte r 10 Database
EXERCISES 10.1
(b) (c)
(a)
(e) (f)
(d)
ll M egaci ies l = I @) 1- tJ · I
( Displa}' Data
I
Projected
City Country Population
Gro•Nth
Dhaka Bang ladesh
11 . 8b-~
Delhi India 10. %
Bombay India
- -
9 .45~~
Calcutta India 8 . 97~~
Shanghai
- -
China 8.86*4
Mexico City I Mexico
- --
3 . 59~~
New York USA
- -
3. 9 ~~
-- -
Sao Paulo Brazil 2 . 55~~
Buenos Aires -
Argentina 2.2~~
Tokyo Japan 0.8J':~
ions tabl e in a li t
te a prog ram that disp lays the nam es of th e con tine nts from the Nat
17. Wri con tine nt sho u ld be
tine nt's nam e, the cou ntri es in that
box. Wh en the use r clicks o n a con ntri es in desc end ing
ne list box sh ould di play the cou
displayed in two other list boxes. O end ing orde r by
er sho uld disp lay the cou ntri es in desc
orde r by the ir pop ulat ion, and the oth
thei r area. See Fig. 10.13.
the Nat ions tabl e in a list
te a prog ram that disp lays the names of the con tine nts from
18. Wri tine nt sho uld be
Wh en the user clic ks on a con tine nt's nam e, the cou ntri es in that con
box. reco rds sho uld be
g with thei r popu latio n densities. The
displayed (in a Dat aGr idV iew ) alon
ion den sities.
in ascend ing orde r by thei r pop ulat
10.1 A n In trod ucti o n to Databases
• 475
~
AJ..Jstralia/D ceania Argentina
I~
Peru
Europe Peru Colombia
North America Venezuela Bolivia
South lvnerica Chile Venezuela
Ecuador Chile
Bolivia Paraguay
12 Convert
Amount of money to convert :
.Pvnenca j Arnerica
rgentina Arge ntina
ustralia
.AJ.Jstralia
IBrazil I Brazil
Canada
Canada
Chile
Chile
China
China
Colombia Colombia
Czech Rep
Czech Rep
Den mark
Denmark
e 22.
FIGURE 10.15 A possible out put for Exe rcis
ms. Th e fields for the Players
ll.a ccd b has the two tables Pla yer s and Tea
Th e dat aba se Bas eba le are nam e, location,
e, tea m, atB ats , and hits . Th e fields for the Teams tab
table are nam rma tion fro m the
atB ats , and hits . Th e dat abase has been filled wit h info
league, stadium, ue players wit h
for the maj or leag ue. Th e Pla yers table list s all maj or-leag
200 9 baseball season all major-league teams. Us e the
s dur ing the season. Th e Tea ms table lists
at leas t 350 at bat ord s fro m eac h table:
aba se in Exe rcis es 23 thr oug h 38. H ere are thr ee sample rec
Baseball dat
PI ayer s 195
Blu e Jay s 682
Aar on Hi ll 225
Ma rin ers 639
Ich iro Suz uki 212
Yan kee s 634
De rek Jet er
Tea ms 548 6 13 9 8
Na tio nal Wr igle y Fie ld
Cub s Ch ica go 549 3 143 2
Na tio nal Na tio nal Par k
Na tio nal s Wa shi ngt on D.C . 554 3 149 5
Am eric an Fen way Par k
Red Sox Bo sto n
Wh en the user
t sho ws all the team s from the Teams tab le in a list box.
23. Wr ite a program tha a tex t box.
s, the pro gra m sho uld disp lay the team's hom e stad ium in
clicks on one of the team tab le wit h the
m to disp lay in a list box the playe r (or players) in the Player
24. Wr ite a progra
hig hes t bat ting ave rage . Players tab le wit h the
gra m to disp lay in a list box the player (or players) in the
25 . Wr ite a pro
most hit . es of all the teams, the ir
m to disp lay in a Oa taG ridView con trol the nam
26. Wr ite a pro gra sor ted in asc end ing
s, and the team s' bat ting ave rages. Rec ord s sho uld be
hom e stad ium
ord er by the bat ting ave rages. box. Wh en the user
m tha t sho ws all the team s from the Tea ms table in a list
27. Wr ite a pro gra trol the names
team s, the pro gra m sho uld disp lay in a Oat aGr idV iew con
clicks on one of the wit h the ir bat ting ave rages. Th
e
s tab le from tha t team, alo ng
of all the players in the Player rages. See Fig. 10.1 6.
d ing orde r of the ir bat ting ave
players sho uld be listed in. descen .30 0 in a list box. When.
gra m tha t sho ws all the playe rs' bat ting ave rages abo ve
28. Wr ite a pro lay in a Oa taG rid-
on. one of the bat ting ave rages, the pro gra m sho uld disp
the user clic ks t bat ting ave rage,
nam es of all the play ers in the Playe rs tab le wit h tha
View con trol the
10.1 An Introduction to Databases
• 477
~~ ~ aseba ll
~
ihletics
Blue Jays lbert Pujols .3 7
Braves
-
Cubs
.. .
Brewers Skip Schumaker
Yadier Molir a
.3.
3
Diamondbacks Brendan fi.r an
Dodgers
Giants Ryan Ludwi ck &5
of films and
The Acto rs table cont ains som e nam es
first three reco rds of the Line s table. Act ors table.
(b) show s the first three reco rds of the
thei r leading male acto rs. Figu re 10. 1 7 Acto rs table . Use the
ign key to the film field in the
The film field in the Line s table is a fore
44.
Movies data base in Exe rcises 39 thro ugh
film maleLead
famo us Line film
On the Wate rfron t Marl on Brand o
Rose bud. Citizen Kane
Sudd en Impa ct C lin t Eastwood
We'll a lways have Paris. Casa blanc a
Tax i Driver Robe rt OeNi ro
I could a been a conte nder. On the Wate rfron t
(b) Acto rs
(a) Lines
ies datab ase.
FIGURE 10.17 Som e reco rds from the table s in the Mov
rs table?
39. Wh at is the prim ary key in the Acto
table?
40. Wha t is the primary key in the Line s
s table. Whe n
with the nam es of the fi lms in the Line
41. Wri te a program that fills a list box layed in
lead male acto r in that film should be disp
the user clicks on the name of a film , the
a text box. See Fig. 10.18.
Male lead :
Rims :
Marton Branda
Otizen Kane
asablanca
On the Waterfront
.Actor Rim
Famous Une
j Orson 1/1/ells Otizen Kane
Rosebud .
Humphrey Bogart Casablanca
We 'II alwa) ' have Paris .
Marton Brand a On the W aterfront
I coulda been a contender.
Oint Eastw ood Sudden Impac t
Go ahead - make my day.
~mold Schwarzen eger 1 ~e Term
inator
I'll be back .
Jack Nicholson A Fe•N Good Men
You can't handle the truth !
a_. lv1egacities
navigation ~[§D [ID
toolbar - - - - t..~l 0 of {O} • + )< C
name: Cit)• to find :
country :
pop 10:
pop2 1~ :
Total
rT
number
of items
of {O } • •1 ~ X
_1--!-~
~~
FIGURE 10.21 Nav igat ion too lbar.
Ch apt er 10 Databases
480 •
co nte nts of the first record
t aft er the pro gra m is run. The
Figure 10.22 sh ow s the for m jus form. The Move first
es arr ang ed ver t ica lly on the left ide of the
are sho wn in the fo ur tex
t box the first record.
dis abl ed, sin ce the re are no reco rds pre ced ing ve
and Move previous bu tto
ns are s. In gen era l, the fo ur Mo
the Mo ve nex t bu tto n, the sec on d rec ord app ear the tab le is
W he n you cli ck on t rec ord of
iga te to any rec ord of the C ities table. Th e firs fro m 1
bu tto ns all ow you to nav ce a nu mb er
sec on d rec ord pos itio n 2, and so on . If you pla , th e
sa id to have po sit ion 1,
the En ter key
lba r's "C urr en t po sit ion " box and the n press the
tio n too ce, if yo u en ter 7 int o the
"C ur-
thr ough 10 in the nav iga l be displayed. For ins tan
t po siti on nu mb er wil y to ob tai n a
record ha vin g tha no th er wa
inf orm at ion for Ne w York wil l be displayed. A and the n
ren t po sit ion " box, the a c ity int o th e tex t box lab e led "C ity
to find:"
the nam e of
pec ific reco rd is to type
cli ck on the Sea rch for Cit y bu tto n .
l
I. = @] I. .S"2. .I
c::;J 1egacities
1 ofl O ~I + L
Otyto find :
name: Bombay
country : India
pop2010: 20.1
pop2015: 22
l Sea rch
forCrty
J
sta rtu p.
FIGURE 10.22 Tab le- edi tin g pro gra m at
on e o r more of
ren tly dis pla yed rec ord , jus t rep lace the va lu e in
To alte r the dat a in the cur bu tto ns.
cli ck on on e of the Move tto n ( cQa ). Th e tex t boxes
the tex t boxes and the n tab le, cli ck on the Add new bu
ord to the C itie s record, an d cli ck on
To add a new rec you type in the da ta for the new
om e bla nk . Af ter ota l nu mb er of
for the fo ur fields will bec wil l be add ed and the nu mb er in the "T
the new rec ord
on e of the Move bu tto ns,
an ge fro m 10 to 11. on the Delete bu tto n
items" box will ch rec ord from the C it ies table, cl ick
ren tly dis pla yed of items" box wi ll
To rem ov e the cur nu mb er in the "T ota l nu mb er
de let ed and the
( I'. ). Th e rec ord will be
ry is act ua lly
decrease by 1.
ere d in any way , on ly the copy of the tab le in memo
Each time the C ities table
is alt tto n ( ~ ). Note 1:
on the disk, you mu st click on the Update bu
altered. To alter the dat aba
se file e copy is always
tai ns two cop ies of the file Megacities.accdb. On
The So lu tio n Explo rer act
ually con
d copy is located in the
bin \Debug
lut ion Ex p lor er. A sec on
of the So 2: lf the changes you made
displayed near the bo tto m upd ated by the program. Note
d cop y tha t can be o appear in the pri-
folder. It is this secon (ev ery val ue in the foreig n key mu st als
ial Int egr ity updated. Note 3:
vio late the Rule of Referent m wil l cra sh wh en the database file is
le), the pro gra primary key
mary key of the oth er tab Int egr ity (no rec ord may have a null en try in its
le of En tity is
Ch ang es tha t vio late the Ru as soon as a Move bu tto n
ry key s mu st be uni qu e) cause the program to crash 2 and 3.
and ent ries for prima add re sing the issues in No
tes
ssed. Ex ercise s 10 thr ou gh 12 discuss tec hniqu es for op e rat ion of the program.
pre ter acq ua int yo u wi th the
ugh wil l bet
Th e following wa lkt hro
m na med 10- 2- 1.
1. Op en and run the progra eal the thi rd record, the
t bu tto n in the n av iga tio n too lba r tw ice to rev
2. Press the Move nex
on e fo r Ca lcu tta. rch for City bu t-
"C ity to fin d:" tex t box and the n cli ck on the Sea
the
3. Type "N ew York" into
pla y the rec ord for Ne w York.
ton to dis
10.2 Editing and Designing Databases
• 481
1. tart a new program and bind the C ities tab le as was done
in Sectio n 10.1.
2. Add a Bindi ngNa vigato r contro l to the form designer.
(This contr ol can be found in the All
Windows Forms or Data group s of the Toolbox.) After you
doub le-clic k on the contr ol in
the Toolb ox, a contro l named Bindi ngNa v igator l appea
rs in the comp o nent tray at the
botto m of the Form Desig ner. A lso, a nav igatio n too lbar
will appea r ancho red to the top of
the form.
3. Go to the Properties window for Bindi ngNa v igator
1, click on the down-arrow at the right
side of the Bindi ngSou rce property's Settin gs box, and
set the Bindi ngSource prope rty to
Bindi ngSo urce1.
4. Not ice that the too lbar is miss ing the Update
button . The rightm ost item on the too lbar
(see Fig. 10.23) is used to add an updat e butto n to the
nav iga tion too lbar. C lick on the
small down -a rrow on the righ t side of the rightm ost item
and then click on Button in the
drop- down li t that appea rs. A butto n show ing a moun
ta in ( o ) appea rs.
5. Open the Prope rties window for the moun tain butto
n, change its name fro m ToolS tripBu t-
to nl to btnUp d ate, and se t its Tex t property to Upda te.
6. C lick on the ellipses at the right side of the Image
prope rty's Settin gs box, and then click
on th Import butto n in the Se lec t Resource dialog ue
box that appea rs. (An Open dialog
box appea rs.)
7. Browse to locate the fo lder Progr ams\ C h 10, and doub
le-clic k on the file Disk. bmp to place
its pictur e in the Selec t Reso urce window.
8. C lick on the OK butto n to change the image on btnUp
date to a diske tte ( Ji ).
9. C lick on the Data menu in the Visua l Basic Toolb ar,
and then click on Show Data Sources.
A Data ources window show ing the names of the tab
les in the database will appea r in the
location occupied by the Solut ion Explo rer window.
10. Double-cl ick on Cities in the Data Sources windo
w to ob tain the display in Fig. 10.2 4.
482 • Chap ter 10 Databa es
Data Sources
(?1+
J
4 ~ Megaciti esDataSet
abl nam e
abl count ry
abl pop2010
abl pop2015
Coun tries
Comments
1. Since the name fi eld of the C ities tab le is the
prima ry key, each record of the table must
ase does not requir e thatvalues
have a va lue ass igned to its name field. Howeve r, the datab
be assign ed to the other three field s.
on the left side of the form have the
2. In Example 1, the four pairs of labels and text boxes
were dragged from the Data Sourc e
names given to them by Visual Bas ic when the fields
if you like. For instan ce, Coun -
window to the Form Designer. Yo u can change the e names
s of the contr ols Bindi ngSource1
tryTextBox can be changed to txtCountry. Also, the name
ingfu l ones, such as C itiesB inding-
and Bindi ngNa v igato rl can be changed to more mean
Source and C itiesB indingNav igator.
10.2 Editing and Designing Databases
• 485
t as of Ja n -
ra ms \ C h10 \Da tabases fo ld er was c urren
21. The data base ]usti ces.a ccdb in the Prog been appo inted since t h en ,
a nd n ew ju tices have
uary 1, 2010 . If some justi ces h ave retir ed
upda te the da tabase.
CHAPTER 10 SUMMARY
con ta ining
d in a recta ngul a r array, with each row
1. A table is a grou p of d ata item s arran g (co lumn ) is
row is ca lled a record. Each categ ory
the ame categ ories of info rmat io n . Each .
o n e o r mo re tab les tha t are usua lly re lated
ca lled a field. A database is a co llect io n of
a tab le of a d atab ase to a p rog ra m .
2. A BindingSo urce control can be used to bind
iew
r Explorer in Visu a l Stud io ca n be used to v
3. Database Explorer in V B Express and Serve
conn ected to a p rog ra m .
t he table fro m a d atab ase that h as been
ion retri eva l from a ta ble.
4. LINQ can be used to set c rite ri a fo r info rmat
disp layed in a
the exec utio n of a U NQ q uery can be
5. A sequ en ce of reco rds resul t ing fro m
DataGridView control.
Programmin g Projects
• 487
II
Bills for Today's
I Out of Stock
~ems
Bills for Today 's J
Orders .
Out of Stock
~ems
Orde rs .
(b)
(a)
ect 1.
FIGURE 10.25 Ou tpu t of Pro gra mm ing Pro j
first Exam: 8
.AJ Jones B5
George Jackson 93
second oom: Lauren Smith 77
Grace Green &5
final Exam : &5
Fred Adams 9
491
Programming
492 • Cha pte r 11 Object- Ori ent ed
industries has
in the fina nci al, scie ntif ic, eng ineerin g, and softwa re des ign in
Practical exp erie nce tho dologies. As programs grow
ealed som e d iffic ulti es wit h trad itio nal program design me the sam e pro jec t
rev working on
bec om e mo re com ple x, and as the num ber of progra mm ers e inc rea ses
size and thr oughou t the cod
enc ies and inte rrelatio nsh ips
inc reases, the num ber of depend pro gra mmer in one place may hav
e ma ny effects,
ll cha nge mad e by one ripple
expone ntia lly. A sma er plac es. Th e effects of this cha nge may
nde d, in ma ny oth
bot h inte nde d and uni nte l of cod e alo ng the way.
ire pro gra m, req uiri ng the rew riti ng of a grea t dea
thr oug hou t the ent uni t, as mu ch imple-
on to this pro ble m is "da ta hid ing" wh ere, wit hin a
A par tial so luti erlying object-
pos sib le is hid den . Dat a hid ing is an imp ort ant prin cip le und
me nta tion det ail as a and procedures tha t act on
the
nte d pro gra mm ing . An obj ect is an encapsula t ion of dat obj ect can per -
orie tha t the
gra mm er usin g an obj ect is con cerned onl y wit h the tasks ced ure s
data. A pro res and pro
ram ete rs use d by the se task s. Th e det ai ls of the dat a stru ctu
fo rm and the pa
are hid den wit hin the object. us: con tro l obj ect s and code obj
ects. Examples of
Tw o typ es of objects wi ll be of con cern to ls tha t can be cre ate d
,t.fP
tex t box es, list box es, but ton s, and all the oth er con tro
con tro l obj ects are class blo ck beg inn ing
fa r, mo st of our pro grams have con tained a sin gle
from the Too lbo x. So d C lass." A cod e
Vide oNo te
as "Pu blic C lass frm Nam e" and end ing wit h the line "En
a line suc h larl y to a
C las>cs and ohj cc ts wit h
e of a use r-de fine d typ e, call ed a class, wh ich is defined imi
object is a specifi c instanc
s blo ck of the form
structure, but in a separate clas
cutter. The cookie cutter is used to create cookies that you can eat, but you can't eat the cooki e
cutter.
Object-oriente d programs are popu lated with objects that ho ld data, have propertie ,
respond to methods, and raise events. (The generation of eve nts will be discussed in the nex t
section.) Six examples of objects are as follows:
1. In a professor's program to ass ign and display semester grades, a student obj ect might ho ld
a single student's name, social secu rity number, midterm grade, and final exam grade. A
CalcSemGrad e method might calculate the stud ent's se mes ter grad e. Events might be
raised when imprope r data are passed to the object.
2. In a payroll program, an emp loyee object might hold an employee's name, hourly wage, and
hours worked. A CalculatePay method wou ld te ll the object to calculate the wages for the
current pay period.
3. In a checking accou nt program, a check register obj ect might have methods that record
and tota l the checks written during a certain month, a deposit slip object might record and
to tal the depos its made during a ce rtain month, and an account object might keep a run-
ning total of the balance in the account. The account object wou ld raise an event to alert
the bank when the balance got too low.
4. In a bookstore inven tory program, a tex tbook obj ect might hold the name, author, quantity
in stock, and wholesale price of an individual tex tbook. A CalculateRetailPrice method
might instruct the textbook object to calculate the selling price of the tex tbook. An event
co uld be raised when the book went out of stock.
5. In a game program, an airplane object might hold the location of an airplane. At any t ime,
the program could tell the object to display the airplane at its current location or to drop a
bomb. An eve nt could be raised each time a bomb was released so that the program cou ld
determine if anything was hit.
6. In a ca rd ga me program, a card object migh t hold th e denomination and uit of a spe-
cific ca rd . An ldentifyCa rd method might return a string such as "Ace of Spades." A
deck-of-ca rd s objec t might cons ist of an array of card objects and a ShuffleDeck method
that thoroughly shuffl ed the deck. A Shuffl ing event might indicate the progre of the
shuffle.
An importa nt object-o ri ented term is class . A class i a te mplate from whic h objec ts
a re c reated. The class spec ifi es the propert ies and methods that will be co mmon to a ll
objec ts that are insta nces of that class. C lasses a re fo rmulated in class bloc ks. An object ,
whi ch is an insta nce of a clas , can be c rea ted in a program with a pair of state me nts of
the form
The first of these two lines of code declare what type of obj ect the variable wi ll refe r to. The
actual object does not exist until it is crea ted with the New keyword , as done in the second line.
This is known as crea ting an instance of an object and is where an obj ect is actually created
from its class. After this second line of code execute , the object is then ready for use. The first
line can appear either in the Declarat ions section of a program (to declare a class-leve l vari-
able) or inside a procedure (to declare a loca l va riable ). The instantiation line can appear only
in a procedure; however, any object variable can be instantiated when declared (as either class
leve l or local) by using the single line
In a program, properties, methods, and events of the obj ect are accessed with statements of
the form shown in the following tab le:
TASK STATEMENT
The program in Examp le 1 use a class named Student to calculate and d isplay a student's
semeste r grade. The informatio n sto red by an object of the type Student consists of a student's
name, social security number, and grades on two exams (midterm and final). This data is stored
in variables declared with the sta tements
Private m name As String 'Name
Private m s sn As String 'Social security number
Private m midt erm As Double 'Numeric al grade on midterm exam
Private m f i nal As Double 'Numeric al grade on final exam
The word Private guarantee that the variab l s cannot be accessed directly from outside the
object. In object-ori ented programming terminology, these variables are called member vari-
ables (or instance variables). We wi ll fol low the common conventio n of beginning the name
of each member var iable with the prefix "m_". Each of these variables is u ed to hold the value
of a property. However, instead of being accessed directly, each member variab le is accessed
indirectly with a property bloc k. For instance, the fo llow ing property block cons ists of a Get
property procedure to retr ieve (or read ) the va lue of the Name property and a Set property pro-
ced ure to assign (or write) the value of the Name property:
Public Property Name () As String
Get
Return m name
End Get
Set (ByVal v alue As String )
m name = v al u e
End Set
End Property
In a property block, additiona l code can be add ed 'after the Get and Set statements to va li-
date the data befo re they are returned or sto red. T he word Public allows the property to be
acces ed from outside the code for the Student class block. For instance, the Name property can
be accessed by code in the form's class block. On the other hand, since the member va riables
were declared as Private, they cannot be accessed di rec tly from code in the form's block. They
can be accessed on ly through Property procedures that allow values to be checked and perhaps
modified. A lso, a Property procedu re is able to take other steps necess itated by a change in the
value of a member variable.
A property block needn't contain both Get and Set property procedu res. For instance, the
block
Public WriteOnl y Property Mid t erm() As Double
Set (ByVal v al u e As double )
m mi d term = value
End Set
End Property
specifies the Midterm property a "write only." This property could be specified to be "read
only" with the block
11 .1 lasses and Objec ts
• 495
Name:
PROPERTY SETTING
OBJECT
txtFin al
Tex t & En te r Info rmatio n
btnEn rer
Tex t & Display G rade
btnD isplay
Text &Qu it
btnQ uit
dgvG rades Row H ead rsVisible False
Class Stude nt
Priva te m name As Strin g 'Name
Priva te m_ ssn As Strin g 'Soci al secur ity numbe r
Priva te m midte rm As Doubl e 'Nume rical grade on midte rm exam
Priva te m final As Doubl e 'Nume rical grade on final exam
Cas e Els e
Ret urn "F"
End Sel ect
End Fun ctio n
End Cla ss 'Stu den t
, "87"), clic k on the
h as "Ad ams, Al", "123 -45-678 9", "82"
[Ru n, ente r the data for a stud ent (suc Grade button to
to the obj ect, and click on the Display
Enter Information butt on to send the data
rity num ber, and semeste r grad e.]
display the stud ent's name, soci al secu
- -
- - Midterm : Rnal:
SSN : - -
Example 2 The following modifica tion of the program in Example 1 calculates semester
grades for students who have regi tered on a "Pass/Fail" ba is. We create a new class,
named
PFStude nt, with the same member variables and property procedures as the cla s Student.
The
only change need ed in the class block occurs in the CalcSem Grade method. The new
code for
this method is
The only change needed in the form's code is to replace the two occurren ces of Student
with
PFStudent. When the program is run with the sa me input as in Example 1, the output will
be
Adams, Al 123-45-6 789 Pass
Object Constructors
Each class has a special method called a construc tor that is alway invoked when an
object is
instantia ted. The construc tor takes ze ro or more argumen ts, and the code inside the
procedure
block performs any tasks needed for initializing an object. It is often us d to se t default
va lue
for member va riab les and to create other obj ects assoc iated with this object. The first
line of the
constru ctor for a class has the form
The graphica l program in Exa mple 3 illustrates the use of a construc tor to specify the
size
and initial placeme nt of a circle. This task invo lves pixe ls. To ge t a fee l for how big
a pixe l is,
the initial size of the fo rm when you create a new project is 300 pixe ls by 300 pixe ls.
Section
9.4 exp lains how graphic are created inside a picture box with the Graphic obj
ect gr =
picBox.C reateGra phics. In Examp le 3, the statemen t
draws a circle inside a picture box, where Xcoord andY coord are the distances (in pixels)
of th e
circle fro m the left side and top of the picture box.
500 • Chapte r 11 O bj ect-Oriented Program ming
track of
Example 3 The fo llowing program contain s a C ircle object. The obj ect keeps
by two numbe rs, called th e
the locatio n and diamet er of the circle. (The loca tion is specified
box. Distan ces and the
coordin ates, giving the distance from the left side and top of the picture
the circle, and a Move method adds
diamet er are mea ured in pixels.) A Show method d isplays
loca ted at the upper-
20 pixe ls to each coordin ate of the circle. Ini t ially, the (unsee n) circle
is
a button caption ed Move
left corner of the picture box and has a diamet e r of 40. The form has
Ycoord, and Diame ter
and Show Circle that invokes both methods. Not ice that the Xcoord,
s.
properties, rather than the member va ri ab les, appea r in the method
OBJECT PROPERTY SETTING
ck
Privat e Sub btnMov e_ Click( ... ) Handle s btnMo ve.Cli
round . Move(2 0)
round. Show( picCir cle.Cr eateGr aphics )
End Sub
k
Privat e Sub btnQu it_ Click( . . . ) Handle s btnQu it.Clic
Me .Close ()
End Sub
End Class 'frmC ircle
Class Circle
Privat e m x As Intege r 'Dist from left side of pictur e box to circle
Privat e m_ y As Intege r 'Dista nce from top of pictur e box to the circle
Privat e m d As Intege r 'Diame ter of circle
.....__r_~l_ov_e_a_n_d_S_h_o_··•_'a_._rc_le_~) ~
ing
502 • Cha pter 11 Obje ct-O rien ted Programm
es of these argu-
obje ct con tain s argu men ts, the valu
Wh en the line that insta ntiates an 3, the first line typed
procedure. Fo r insta nce, in Exa mpl e
men ts are passed to the o bj ect's New
in the form's code can be cha nged to
0 , 40)
Dim roun d As New Cir cle ( O,
class ca n be cha nged to
and the New proc ed ure for the C ircle
,
Inte ger , ByV al y As Inte ger
Pub lic Sub New (ByV al x As
ByV al d As Inte ger )
h rc:e to x pix els from
'Set the ini tial lo atio n o box .
from the top of the pic ture
'the lef t side and y pix els
els.
'Set the di ~eter to d pix
Xco ord = x
Yco ord = y
Dia met er d
End Sub
Auto-Implemented Properties
ly or Wri teO nly key-
t in that they do not con tain Rea dOn
Som e prope rty bloc ks are very clear-cu blocks can use the
the ir Get or et bloc ks. Suc h property
words and have no addi tion al code in reduce a clea r-cu t
-to-V B20 10 auto -imp lem ente d prop ertie s feature. Thi s feature allows you to
new the property. Visual
omit declaring a member variable for
property block to just its header, and to ber vari able. The
and Set procedur es and a hidd en mem
Basic auto mat ica lly crea tes hidd en Get arac ter. For exam-
erty name preceded by an und erscore ch
nam e of the mem ber variable is the prop ber variab le will be
if you decl are an auto- imp leme nted property named Soc SecN um, th mem
ple, er of this chap ter.
- imp leme nted propertie s in the remaind
named _So cSec N um. We will use auto
EXERCISES 11.1 ·
lstB ox.I tem s.Ad d("P op: " & nati on.P opu lati on & " mil lion ")
End Sub
End Clas s 'frm Cou ntry
ly . Len gth)
txtL eng th.T ext = CSt r(po
ly.P erim eter )
txtP erim ete r.T ext = CSt r(po
End Sub
e lengths betw een 1
ious exe rcise so that all squa res wi ll hav
20. Modify the class Squ are in the prev a squa re of length 1, and
y. Are a = o. s sho uld result in
and 10. For inst anc e, the stateme nt pol ing length 10.
ld result in a square with ach side hav
the stat eme nt pol y.A rea = 200 hou
used to o bta in the
te the cod e for a class ca lled Pair OfD ice. A Ran d o m obje ct sho uld be
21 . Wri bers (suc h as 3, 4,
ing form cod e is exe c uted, three num
va lu e for eac h die. Wh en the follow
boxes.
and 7) sho u ld be eli played in th e text
Dim cub es As Pair OfD ice
... ) Han dles btn Go. Clic k
Pri vat e Sub btnG o_ Cli ck(
cub es =Ne w Pai rOf Dic e()
cub es. Rol l ()
txtO ne.T ext CSt r (cub es .Di el)
txtT wo. Tex t CSt r(cu bes .Di e2)
txtS um. Tex t CSt r(cu bes .Sum OfF ace s)
End Sub
ber of time s that the
. te a prog ram to ro ll a pair of d ice 100 0 t imes, and disp lay the num
22 Wri class Pa irOf Dic e dis-
of the two face s is 7. The prog ram sho uld use an inst ance of the
sum
cussed in the previous exercise.
s Nam e, Num Stud ents ,
l ege. The class should have propertie
23. Wri te the code for a class called Col lty ratio . When the
atio should compute the stud ent- facu
and N umFaculty. The met hod SFR text box:
num ber 12.4 should be disp laye d in the
following fonn cod e is exec uted , the
Dim sch ool As Col lege
.. . ) Han dles btn Go. Clic k
Pri vat e Sub btnG o_ Cli ck(
sch ool = New Col leg e()
of Mar ylan d, Col lege Par k"
scho ol.N ame = "Un ive rsit y
sch ool. Num Stu den ts = 360 41
sch ool. Num Fac ulty = 289 6
ber( sch ool. SFR atio , 1)
txtB ox. Tex t = For mat Num
End Sub
the h ourly wage and
te a prog ram that calc ulat es an employe e's pay for a wee k base d on
24. Wri an inst anc e of the
puta t ions sho uld be perform ed by
the num ber of hou rs wo rked. A ll com
cla s Wa ge.
The prog ram sh ould h ave a
25. W rite a prog ram to implem
ent the cash regi ster in Fig. 11.1.
dep os its and with -
ps trac k of the bala nce and allo ws
cla s call ed Cas hRegiste r that kee
it a negativ e bala nce .
drawals. The class sh ould not perm
Calculate Average
Jl.dd Subtract
Average :
Balance :
Note: S ince a stud ent's social securi ty n umber never changes, there
i no need to have a Set
proper ty proced ure for SocSe cNum .
Example 1 In the follow ing progra m, whi ch uses the same form des ign as
Examp le 1 of the
prev ious section , the user enters four pieces of data about a studen
t into text boxe . W h en the Enter
Information button is clicked on , the data are used to create and initiali
ze an approp ri ate object and
the object i added to an array. W h en the DisJJ/ay Grades button
is clicked on, the name, ocial
security numbe r, and semest er grade for each studen t in the array
are displayed in the grid.
Publi c Class frmGr ades
Dim s t udent s ( SO) As Stude nt
Dim lastSt udent Adde d As Integ er - 1 'Posi tion in array 0f stude nt
most recen tly added
508 • Chap ter 11 Objec t-Orie nted Programming
g
Publ ic Prop erty SocSe cNum () As Strin
As Doub le
Publ ic Write Only Prop erty Midt erm()
Set (ByV al value As Doub le )
m midte rm = value
End Set
End Prop erty
Doub le
Publ ic Write Only Prop erty Fina l() As
Set (ByV al value As Doub le )
m fina l = value
End Set
End Prop erty
11 .2 Work ing with Objects
• 509
D 1 Se ester Grade
Events
In the prev ious section, we drew a para llel
betw een clas es and cont ro ls and showed
defin e properti es and meth ods for cla se . Even how to
ts can be defin ed by the programm er to co mmu
nica te ch anges of prope rties , errors, and the -
progress of lengthy ope rat ions. Such eve nts
called user -defi ned even ts. The state men t are
for ra ising an even t is loca ted in the class bloc
the even t is dealt with in the form's code . k, and
Suppose that the even t is named Use rDefined
and has the parameters par 1, par 2, and so on. Even t
In the class bloc k, the state men t
Pub lic Even t User Defi nedE vent (ByV
al parl As Data Type l,
ByV al par2 As Data Type 2, . . .)
should be placed in the Decl arati ons section
, and the state men t
Rais eEve nt Use rDe fine dEv ent( argl
, arg2 , ... )
ing
510 • Chapter 11 Object-O riented Programm
Clas sNa me
Di m Wi thEv en t s obj ect l As
or the type
Clas s Circ le
Pub lic Even t Posi tion Cha nged ( ByV
al x As Inte ger ,
ByV al y As Inte ger , ByV al d As
'Eve nt is rais ed when the circ Inte ger )
le move s
11 _. •lovin g Circl e
Containment
use of an obje ct
n a mem be r vari ab le of class A makes
We say that class A con tains cla s B whe .
DeckOfCards co ntains the class Ca rd
of type class B. In Example 3, the class
Cla ss Ca rd
Pr iva te m den om ina tio
n As Int eg er 'A num ber fro m 0 thr
Pr iva te m_ su it As Str ou gh 12
ing 'He art s, Clu bs, Dia mo
nds , Sp ade s
Pu bli c Pro pe rty De nom
ina tio n() As Int eg er
Ge t
Re tur n m den om ina tio
n
End Ge t
Se t (By Va l va lue As
Int eg er )
'On ly sto re va lid va
lue s.
If (va lue >= 0) An d
(va lue <= 12) Th en
m den om ina tio n = va
lue
End If
End Se t
End Pro pe rty
m su i t va lue
End If
End Se t
En d Pr op ert y
B of Hearts
17of Diamond~{
Jac:k of Hearts
Queen of Spades
1 of Hearts
EXERCISES 11.2
union. T he firs t
ered by the date of entr y into the
the yea r 200 0. T he reco rds are ord
thre e lines of the file are
4 ,759 000
De l a war e,D E, 1 2/ 7 / 178 7 , 195
2 / 1 2/ 178 7 , 4 4 817 ,122 960 00
Pen nsy lva nia , PA,1
4 1 7, 813 500 0
New Jer sey ,NJ ,l2/ 18 / 178 7,7
a ingle stat e and a
ert ies to hold the info rma tion abo ut
2. C reat e a class Stat e with five prop
(peo ple per sq uare mile) of the state.
met hod that calcu lates the density
displays the state's
tate 's name in an inpu t di alog box and
3. Wri te a prog ram that requ est a ram sho uld use an
entr ance into the unio n. The prog
abb reviation, density, and date of
array of Stat e objects.
s in a Dat aGr idV iew
names of the stat es and their den sitie
4. Wri te a program that displays the
uld use an array of Stat e objects.
ordered by den sity. The program sho
an array of Stat e
from the file one line at a time into
5. Wri te a program that read s the data ten million . Stat es
er the populat ion of a stat e exceeds
objects and raises an eve nt whe nev d in a list box by
their nam es and popu latio ns disp laye
with a large popu latio n sho uld have tate s that con tains
(Hin t: Cre ate a class call ed Uni tedS
the correspo ndin g eve nt procedure. The Add met hod
that add s a new stat e to the array.
the array and defines a met hod A dd
sho uld raise the eve nt.) IllegalN umb er
r the class Squ are from Exe rci e 19 of Sec tion 11.1. Add the eve nt
6. Con side w the new cla s
erties is set to a negat ive num ber. Sho
that is raised whe n any of the prop message.
for the eve nt that d ispla ys an error
block and write an eve nt procedure
.1. Add the eve nt
s in Exe rcise 25 of Sec tion 11
7. Con side r the Cas h Reg iste r clas e mon ey tha n
emp tTo Ove rdra w tha t is rais ed whe n the use r tr ies to sub t ract mor
Att
is in the cash register.
.1. Add the eve nt
ussed in Exercise 21 of Sec tion 11
8. Conside r the class PairOfD ice disc dice. Wri te a pro-
two ones appear dur ing a roll of the
SnakeEyes that is raised whe nev er
gram that uses this eve nt.
Den omi nato r
side r the Frac tion class in Exe rcise 29 of Sec tion 11.1. Add the eve nt Zero
9. Con the eve nt.
r is set to 0. Write a program that uses
that is raise d whe nev er a den ominato
the num erators and
calcu lato r show n in Fig. 11 .3. Aft er
10. Wri te a program for the frac tion ed in the four text
to the left of the equals sign are plac
den omi nato rs of the two frac tion s ears to the righ t
sho uld be clicked on. The re ult app
boxes, one of four operat ions buttons tain s three mem-
the equ als sign . The prog ram sho uld use a Cal cula tor class, whi ch con
of e: In Fig. 11 .3, the
in Exe rci e 28 of Sec tion 11 .1. Not
bers of the type Frac tion d iscussed
frac tion bars are very sho rt list boxes.
ai Game of Dice ~~
lL.==::JI~@)="'~~~
Player 2
a Frac tion Calcu lato r l = I @] II'"'"·EJ I Playe r 1
3
6 5 4
3
=
00 = 4
=
1
Play
~ [±]
8 15 10 Play er 1 wins.
FIGURE 11.4 Sam ple Out put for Exe rcis e 11.
FIGURE 11.3 Sam ple O utpu t for Exe rcise 10.
11.2 Working with Objects
• 5 17
[ Clear l [ Quit l L
Tota l: S11 .55
11
cha rac ter s. Ree nt er the
End Sub
4. T he state men t
11.3 Inheritance
and "inh erit ance." O ne class
classes are "use," "co nta inment ,"
VideoNo te The three rela tion ship s betw een t class A con tain s class B
s obj ects of tha t class. We say tha
use s ano the r class if it manipu late Sec tion 11.2 presen ts
es use of an obje ct of type class B.
Inhe ritan ce
a mem ber vari able of class A mak
whe n
exa mp les of use and con tainmen t. s ) inh erit s the proper-
one class (the chil d or der ived clas
Inh erit anc e is a pro ce by whi ch child has access to all
s, and eve nts of ano the r class (th par ent or base class ). The
ties, met hod pare nt is itse lf a
pro perties, met hod s and eve nts as well as to all of its own. If the
of its pare nt's
11.3 lnh eri ranee
• 519
ch ild , the n it and its chi ldr en
h ave access to all of its par ent
Co ns id er the classes sh ow n 's pro per ties , me tho ds a nd ev
in Fig. 11. 6. All thr ee chi ldr nts.
from the ir par ent . C hild 2 and en inh eri t Pro per ty A and S ub
C hild 3 hav e an add itio nal B
Gr and Ch ild ! ha access to eve nt and a pro perty, res pec
Pro per ty A, Sub B, and Ev tive ly.
tio n E and Sub F. Th e col ent C from its par ent and add
lec tio n of a par ent class a s Fun c-
lo ng wit h its des cen dan ts
hie rar chy . is ca lled a
Parent
Property A
Sub B
I
I
Child1 Child2 Child3
Event C Property D
I
I I
GrandC hild1
GrandChild2
Function E
Event G
Sub F
Sub B ()
'Co de for Sub pro ced
ure B
End Sub
End Cla ss
Cla ss Ch ild 2
Inh eri ts Pa ren t
Ev ent C ()
End Cla ss
Progra mm ing
520 • Ch apt er 11 Ob jec t-O rien ted
Fu nct ion E ()
'Co de for fun cti on E
End Fu nct ion
Sub F ()
'Co de for Sub pro ced ure
F
End Sub
End Cla ss
lat e
Pu bli c Cla ss frm Ca lcu
ma chi nes .
'Cr eat e bo th
New Ad din gM ach ine ()
Dim add er As
lat or ()
Dim cal c As New Ca lcu
( ... ) Ha ndl es
ach ine _ Ch eck edC han ged
Pr iva te Sub rad Ad din gM edC han ged
rad Ad din gM ach ine .Ch eck
div ide fun cti on ali ty.
'Hi de the mu ltip ly and
b tnM ult ipl y.V isi ble
= Fa lse
b tnD ivi de .V isi ble = Fa lse
End Sub
11.3 Inh erit ance
• 521
Pri vat e Sub rad Ca lcu
lat or_ Che cke dCh ang ed( ... ) Ha ndl es
rad Ca lcu lato r.C hec ked Ch
'Sh ow the mu ltip ly and ang ed
div ide fun cti on ali ty.
btn Mu ltip ly . Vi sib le =
Tru e
btn Div ide .Vi sib le = Tru
e
End Sub
e
ond Nu rnb e r () As Do ubl
Pu bli c Pro pe rty Sec
ubl e
Fu nct ion Ad d() As Do
stN urn ber + Sec ond Nu rnb er
Re tur n Fir
End Fu nct ion
As Do ub l e
Fu nct ion Su btr act ()
- Sec ond Nu rnb er
Re tur n Fir stN urn ber
End Fu nct ion
End Cla ss 'Ad din gM ach ine
As Do ubl e
Fu nct ion Mu ltip ly( )
Re tur n Fir stN urn ber * Sec ond Nu rnb er
End Fu nct ion
Do ubl e
Fu nct ion Div ide () As
Re tur n Fir stN urn ber I Se c ond Nu rnb er
End Fu nct ion
End Cla ss 'Ca lcu lat or
the Calculator radio but ton ,
12 and 3, and clic k on the + and - but ton s. C lick on
[Ru n, type in
but ton s.]
and click on the +, - , X , and
~~ ... Ca lcul a ·a ns l= i §J I~ d
Rrst Number: 12
Second Number: 3
Machine
- Add ing
Machine
-
1 1 Calculat or
Resutt : 4
ing
Ca lcS em Gra de( ) As Str
Ov err ide s Fu nct ion est er
for the sem
'Th e stu de nt' s gra de
If My Bas e .Ca lcS em Gra
de = "F" Th en
Re tur n "F ail "
Els e
Re tur n "Pa ss"
End If
End Fu nct ion
End Cla ss 'PF Stu den t
des
Pu bli c Cla ss frm Gra 'St ore s the cla ss
den ts( SO ) As Stu den t to stu de nts ( )
Dim stu 'La st stu de nt add ed
As Int eg er = -1
Dim las tSt ud ent Ad ded
btn En ter . Cl ick
_ Cl ick ( ... ) Ha ndl es
Pr iva te Sub btn En ter
o the arr ay .
'St ore s a stu de nt int
t
Dim pu pil As Stu den n the rad 1o bu tto n.
e the ap pro pri ate ob jec t dep end ing upo
Cr eat
ed The n
If rad Pa s sF ail .Ch eck
pu pil New PF Stu den t ()
Els e
pu pil New Stu den t ()
End If the ob jec t .
the tex t box es int o
'St ore the va lue s in
.Te xt
pu pil . Name = txt Na me
11.3 Inheri tance • 525
Class Studen t
'Membe r variab les to hold the proper ty values
Privat e m midterm As Double
Private m final As Double
Strin g
Over ridab le Func tion CalcS emGr ade() As
h 1.de o he seme ster
Dim grade As Doub le
'T~ rade i~ bas d upc verag e of the midte rm and final exam s.
grade = (m_ midte rm + m_ fina l) I 2
grade = Math .Roun d(gra de) ' ·ound the grade .
Selec t Case grade
Case Is >= 90
Retur n "A"
Case Is >= 80
Retur n "B"
Case Is >= 70
Retur n "C"
Case Is >= 60
Retur n "D"
Case Else
Retur n "F"
End Selec t
End Func tion
End Class Stude nt
g
Over rides Func tion CalcS emGr ade() As Strin
tud nt' rade the ceme ster
If MyBa se . CalcS emGr ade = "F" Then
Retur n "Fail "
Else
Retur n "Pass "
End If
End Func tion
End Class
n for three stude nts. Then click on the
[Ente r the data and click on the Enter Information butto
student.]
Displa y Grades butto n, and fina lly enter the data for anoth er
Grc1ding Option
o Letter Grc1de
Enter lntorrncltion
Brown, Brittc:,ny
c~,le . CamI A
11.3 Inheritance • 527
Example 2 employ inheritanc e and overriding to provide functional ity to one child class.
lf a program contains two or mo re children of a class, however, th e techniqu e of overriding can
lead to confusing programs. Visual Bas ic prov id es a cleaner des ign through the use of abstract
classe .
Example 3 The fo llow ing program calculates the area of several regular two-d imensiona l
sh apes, given the length of one side. (A regular hape is a shape whose sides have identical
length and whose interior angl s are identical.) The abstract parent class hape implemen ts the
Length prope rty and decle1res the N ame and A rea funct ions a MustOver ride. N otice that meth-
od declared with MustO .ride do not have any implemen tation code. Each child class inherits
the property from the parent and implemen ts the two functions. The btnOispla y_C lick event
procedure uses polymorph ism to set the shapes' length and display the shapes' names and areas.
'Display results .
lstOutp ut.Item s.Clear ()
For i As Integer = 0 To 3
l s tOutput .Items.A dd( "The " & shape( i ) . Name & " has area " &
FormatN umber(s hape(i) .Area)) & " "
Next
End Sub
End Class 'frmShap es
Class Square
Inherit s Shape
Class Pentago n
Inherit s Shape
Class Hexagon
Inherits Shape
~
Equilateral Triangle has area 1 .&3.
e Square has area 25. .
e Pentagon has area ~ . 1.
e Hexagon has area 04 .95.
Comments
1. Visual Bas ic uses inheri tance in eve ry Wind ows applica ti on th at is written. Exam inati on
of an y program's code revea ls that the fo rm's class inherits from the .NET framewo rk class
System. Wind ows. Forms. Fo rm.
2. In Example 2, the btnOisplay_ Click event procedure doe not need to know wh ich e le-
ments of the S tudent array are instances of the S tud ent clas and which are instances of the
PFStudent class. In ome situati ons, however, the program may want to know this. Visual
Bas ic provides t he ex press ion TypeOf ... Is to test if an instance was created from a pa rtic-
ular clas (or fro m th e class' parents, grandparent s, etc.) Fo r example, t he follow ing proce-
d ure counts the number of pass/fa il tud ents in th e students array:
Sub CountPass Fail()
Dim query = From student In students
Where TypeOf (student) Is PFStudent
Select student
Dim numPF = que ry.Count
MessageBox .Show( "There are " & numPF & " pass/fail students out of " &
lastStudent Added + 1 & " students in the class." )
End Sub
1. In the class A ddingMachine of Example 1, the Add function could h ave bee n defin ed with
Functio n Add() As Double
Return FirstNur nber + SecondN urnber
End Functio n
Exp lain wh y the Multiply function of the class Ca lculator ca nnot be defined with
Functio n Multipl y() As Double
Return FirstNum ber * SecondN urnber
End Functio n
variab le
2. Conside r th e hierarch y of classes shown below. What valu e is ass igned to the
phrase by th e fo llowing two lines of code?
Dim mammal As New Mammals ( )
Dim phrase As String = mammal. Msg
Class Animals
Overrid able Functio n Msg() As String
Return "Can move"
End Functio n
End Class
Class Vertebr ates
Inherit s Animals
Overrid es Functio n Msg() As String
Return MyBase.M sg & " " & "Has a backbon e"
End Functio n
End Class
Class Mammals
Inherit s Vertebr ates
Overrid es Functio n Msg() As String
Return MyBase.M sg & " " & "Nurtur es young with mother' s milk"
End Functio n
End Class
Class Arthrop ods
Inherit s Animals
Overrid es Functio n Msg() As String
e"
Return MyBase.M sg & " " & "Has jointed limbs and no backbon
End Functio n
End Class
EXERCISES 11.3
two classes:
In Exercises 1 through 4, identify the output of the code that uses the followin g
Class Square
Overrid able Functio n Result(B yVal num As Double) As Double
Return num * num
End Functio n
End Class
11.3 Inh erit ance
• 531
Cla ss Cub e
Inh eri ts Squ are
8. Cla ss He llo
Fun ctio n Hi( ) As Str ing
Re tur n "hi !"
End Fun ctio n
End Cla ss
Progra mming
Ch apt er 11 Ob jec t-O rien ted
532 •
Cla ss Gr eet ing s
Inh eri ts Hi ()
As St rin g
Fu nct ion Go odB ye( )
Re tur n "go odb ye"
End Fu nct ion
End Cla ss
9. Cla ss He llo
ing
Fu nct ion Hi( ) As Str
Re tur n "h i!"
End Fu nct ion
End Cla ss
Cla ss Au ssi e
Inh eri ts He llo
ing
Fu nct ion Hi( ) As Str
Re tur n "G 'da y ma t e!"
Cla ss Wi thi t
Inh eri ts He llo
Hi( ) As Str ing
Ov err ide s Fu nct ion
Re tur n "He y"
End Fu nct ion
End Cla ss
Clas s Euro
Inhe rits Hello
Calc u-
ificC alcu lator that is derived from the class
17. Expa nd Exam p le 1 to use a class Scie nt meti c butto ns.
add ition to the four arith
lator and has an expo nent iatio n butto n in
e and
ent has an abs tract meth od CalcSem Grad
18. Rewrite Exam p le 2 so that the class Stud uden t.
stand s for "Let ter G rade" ) and PFSt
two deriv ed classes ca lled LGS tude nt (LG
ed class
Exe rc ise 25 of Sect ion 11.1. Crea te a deriv
19. Con sid er the class Cash Register fro m cles
at a toll boot h to co llect mon ey from vehi
called FastTrackReg ister that cou ld be used and
processed . Write a progra m using the class
and keep track of th e num ber of ve hicles and two do llar
uld be co llected from each car
havi ng the for m in Fig. 11.7. One dolla r sho
from each truck.
o Car TnJck
Count :
called
26 of Sectio n 11.1. C rea te a deriv ed class
20. Con side r the class tatis tics from Exe rcise nt calle d N ewS p read .
ad func tio n a nd an eve
Com p leteS ta ts t hat a lso prov ides a Spre d iffer ence
sprea d chan ges. (The spread is the
Video Note This even t sh o uld be ra i ed whe neve r the class es to
e . ) Writ e a prog ram that uses the
Stude nt reg istratio n betw een th e high est and the lo we t grad ber
use r. The prog ra m sh o uld d isp lay th e num
(Homework) ana lyze up to 50 exa m grades inpu t by the ulate A verag e butt o n is
t imes . Whe n the Calc
of grad es and the curre nt sp read at all sa mple o utpu t is
th e ave rage of t he grad es. A
click ed on , the prog ram sh ould disp lay
show n in Fig. 11 .8.
trade
book store's inve n tory. The sto re o rders both
21. Writ e a prog ram that keeps track of a Book
prog ram sh ould defin e an abstract class
books and textb ooks from publ ishers. The ,
Price, and the ordin ary prop erties Qua ntity
that cont ains the MustOve rride prop erty deriv ed from the class
eboo k classes sho uld be
Nam e, and Cost. The Text book and Trad up is
by addi ng a markup. (Ass ume that the mark
Book and should override prop erty Price t from the
k.) The prog ram should acce pt inpu
40% for a trade book and 20% fo r a tex tboo ber of
ing stati stics : total num ber of book , num
u er on book o rders and disp lay the fo llow of the
tota l va lue of the inve ntory. (The va lue
textb ooks , tota l cost of the orde rs, and sells all of the book s in
book sto re can mak e if it
inve nto ry is the amo unt of mo ney that the
stock .) A sa mple outp ut is sh own in Fig. 11.9.
salar ied
kly payro ll of a depa rtme nt that hires both
22. Writ e a prog ram that reco rds the wee ber of
ld acce pt use r inpu t and displ ay the num
and hour ly employees. The progra m shou of
s, the total payro ll, and the average num ber
emp loyees, the num ber of salar ied empl oyee (The
sh ould cont a in N ame and Rate prop erties.
hour s worked. The abstr act cla s Emp loyee hour ly
week ly salary for salaried work ers and the
Rate text box hould be fill ed in with the e
H ourly classes sho uld inhe rit the Emp loye
wage fo r hourly work ers. ) T he Sala ried and
S ummary • 535
Type
Rate :
Name: () Salaried
Quantity: Cost :
- 1G 1 Hourly Hours:
[ Order Book
l Record Employee and Hours
FIGURE 11.9 Sample output for Exercise 21. FIGURE 11.10 Sample output for Exercise 22.
class and overrid e the method G rossPay that accepts the n um ber of hours worked as a
paramete r. A sa mple output i hown in Fig. 11 . 10. (Hint: U e an array of a structure that
ho lds the employee object and the numbe r of hours worked during the week.)
1. W hil e rhe derived c lass C a lculato r has access to rhe Propenie and Merhods of rhe base class Add ingMachi ne,
ir does nor have access to irs Pri vare membe r va ri ables.
2. The srr ing "Can move H as a bac kbone Nu rwres young wir h morher's milk"
CHAPTER 11 SUMMARY
1. A n object is an en tity that stores data, has methods that manipulate the data, and can raise
eve nts. A class is a template from wh ich obj ec ts are created. A method spec ifies the way in
which an object' data are manipulated . An event is a message sent by an obj ec t to signal
the occurrence of a condition.
2. Each class is defined in a separate block of code starting with C lass ClassName and ending
with End C lass. Data are stored in member variab le and accessed by procedures ca lled
properties.
3. A prope rty routine contains a G et block to retrieve the value of a member variable or a Set
block to assign a va lue to a member va riable. These procedures can also be used to enforce
constraints and carry out validation.
4. Visual Basic automatically invokes a N ew procedure when an obj ect is created.
5. A n object variable is declared with a statement of the form Dim objectName As ClassName,
and the object is created with a statement of the form obj ectName = New ClassName ( argl,
arg2, ••• ) . These two statements are often combined into the single statement Dim
objectName As New ClassName (argl, arg2, . . . ).
form
7. Events are declared in the Declarations section of a class with a statemen t of the
Pub lic Event UserDef inedEve nt ( argl, arg2, . . . ) and raised w ith a RaiseEv ent
statemen t. The declarati on tatement for the obj ect mu t include the keyword wi thEvent
s
in order for the event coming from the obj ect to be processed . The header of an event-
.. . )
hand ling procedur e has the form Private Sub procedu reName (parl , par2,
Handles objectNa me.User DefinedE vent .
8. The properties, methods, and events of a class are referred to as its interface.
the
9. Inheritance, which i impleme nted with the keyword Inherits, allows a new class (called
(called the base or parent class ) and
derived or child class) to be created from an existing class
to gain its interface .
10. Polymorphism is the fe ature that two cla ses can have methods that are named
the same and
have essentially the same purpose, but different impleme ntations.
classes to
11. The keywords Overridable, Overrides , Mustlnherit, and MustOve rride allow derived
customize inherited properties and methods.
•~ Accounts
New
Date Type of Transaction Amount Balance
c_. BlackJack Ga e
5 of Diamond: ]
3 of Hearts
~k of Diamonds
Ace of ~~bs-
6of 0oh~
-l
Plcf'lerTotal: 18 Deale r Tatal: 17
You win
539
540 • Chapter 12 Web Applica ti ons
Web Developer
Creating a Web Program with Visual
al Bas ic Win d ows
crea ted in muc h the same way as a Visu
As we will soon see, a Web program is u ghs to be pe r-
a Web prog ram here into three walk thro
Video ote
program. We brea k up the crea tion of the steps of the
thro ugh we prese nt a tabl e showing how
Programm ing
form ed in successio n. Afte r each walk
for the Web their Visual Bas ic cou nterpart s.
Web prog ram wa lkth rough diffe r from
prog ram
Firs t wal kthr oug h : Star ting a new Web rosoft Vis ual
click on All Programs, and clic k on Mic
1. C lick on the Win d ows Start butt on, simi lar to the Visual
programs. (A Start page ve ry
Web Deve loper 20 10 Express in the list of
Basic Start page will appea r. ) O ptio ns dialog
se lect Gen eral from the left side of the
2. C lick on Ojni ons in the Tools menu, (Th is step will
o butt on in the Start Pages in section .
box, and clic k on the Design V iew radi "Tab and
rams. ) O ptio nall y, set the va lue for the
not have to be don e for subseque nt prog
on to close the Opt ions wind ow.
inde nt size" to 2. C lick on the OK butt will appea r. Visu al
menu. (A N ew Web Site dialog box
3. C lick on New W eb Site in the File loca tion." If
c hou ld be sele cted as the Inst alled Temp late and File Sys tem as the "We b
Basi
not, cha nge these items. ) tion and name of
The wide com bo box at th e cent er-b otto m of the d ialog box gives the loca
4. the name to
WebS ite I.) We reco mm end cha ngin g
the prog ram . (Th e defa ult name wi ll be e path .
you might wan t to cha nge th
somethi ng like MyW ebProgram. A lso, mod e. See
ble- clic k on ASP .NE T We b Site. The IDE for VW D appea rs in de ign
5. Dou tab "Ma in-
be ente red insid e the red rect ang le with
Fig. 12 .1. The tex t and con trols will regi on.
this regio n as the Mai n Con tent
Con tent (C usto m) ". We will refe r to
star ting a
start ing a prog ram in VW D diffe rs from
Tab le 12. 1 shows three ways in whi ch
program in Visual Bas ic.
Web page
Sec ond wal kthr oug h: Des igni ng the
at ion of the first walk thro ugh.
Not e 1: Thi s walk thro ugh is a con tinu same way as in
a page and form atted in somewh at the
Not e 2: In VW D, text can be type d into
a word processo r.
12.1 Prog ramm ing for the Web, Part l
• 541
Account
App_Data _
Script>
Styles
1> jj] About. a spx
rrr
FIGURE 12.1 The VWD integ rated deve lopm ent envi ronm
ent in design mode.
in the Standard
dou b le-click on the Tex tBox co ntro l
4. Press the space bar twice and then t is, at the
box appears at the inse rtion poin t (tha
group of the Too lbox. N otice that a text
cursor loca tion ).
the Alphabetize
d. In the Prop erties window, clic k on
5. Make sure that the tex t box is se lecte and set the value of
top of the Prope rties wind ow,
butt on, loca te the ID prop erty nea r the Bas ic's Nam e
property is the cou nter part to Visual
the ID property to txtC ost. (VW D's ID
tex t box read s "asp :Tex tBox #txt Cos t".)
prop erty. N otice that the tab above the
cen t tip (suc h
tion the cursor to the righ t of the text box , press the Ente r key, type "Per
6. Posi con trol in
twic e, and double- clic k on the TextBox
as, 15, 18.5 , or 20):", press the space bar
the Too lbar. (An othe r text box appears.)
erce nt.
7. Set the text box's 10 property to txtP k on the But-
text box, press the Ent er key, dou ble-clic
8. Position the cursor to the righ t of the butt on's ID
appe ars at the inse rtion poin t), set the
ton con trol in the Too lbox (a butt on
t property to "Ca lcu late Tip".
property to btnC alcu late, and set its Tex
"Am oun t of tip:",
the butt on, press the Ente r key, type
9. Position the cursor to the righ t of lbox (a text box
k on the Tex tBox con trol in the Too
press the space bar twice, double-clic ip, se t its Rea dOn ly
text box's ID prop erty to txtT
appe ars at the inse rtion poin t), set the scre en now
or to the righ t of the text box. The
prop erty to True, and pos ition the curs
appears as in Fig. 12.2.
Ill
Tip Calculato r
Cost of meal:
[ Ca lcula te Tip
Amount of tip:
ram is run.
FIGURE 12.3 Con tents of the Web brow ser after the prog
tent
Using a Table to Lay Out a Web Page's Con
ing as thos e we
seco nd wa lkth ro ugh is n ot as nice look
The layo ut of the page crea ted in the t boxe would be
In o ur Visua l Bas ic d sign , the thre e tex
h ave been crea ting with Visu a l Bas ic. cont ro l can be
e red h o rizon ta lly in the fo rm. A table
left- a lign ed and the button wo uld be cent
ran ce of the W eb page .
used with VW D to improve the appe a plac ed into
ce lls, whe re text and/ or cont ro ls can be
A table cont ro l is a recta ngul a r array of fo llow ing walk -
re used to align text and cont ro ls. The
each cell. The colu mns of the tab le a
d ve rsion of the previo us prog ra m.
thro ugh uses a table to crea te an imp rove
12.1 Progra mm ing for the Web, Par
t1 • 545
A tab le wa lkt hro ugh : Us ing
a table to imp rov e the design
No te: Th is wa lkth rou gh is a of a Web pro gra m
not a con tin u atio n of the pre
same pro gra m, but wit h a mo vio us wa lkt hro ugh s. It produc
re attr act ive page des ign. es the
1. S tart a new We b program
wit h the name Tip Ca lculator,
Co nte nt reg ion as before . and clear the con ten ts of the
Ma in
2. C lick on Ins ert Tab le fro m
the Table me nu to pro duce the
Fig. 12.4. Inse rt Table di alog box sho wn
in
In se rt Tab le
l1t I~
Size
-- -
...
Row s: I~ ... Colu mns: 12 ...
'";"'
Lay out - ----
Alignment: Default
B [{] Spedfy wid th:
Floa t: Default
EJ! 1100 I n pixels
( In per cen t
Cell padding: 11 ...
... 0 Spe dfy heig ht:
[ l
OK [ Cancel
l
FIGURE 12.4 Th e Insert Table dialog box.
:::::::::::::::::::::::::::::::::::::::::::::::::::::::J l::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::J!......
1l::
..
:::: ..
.... ..
::::: :::
.... ::::: ::::: ::::: ::::: ::::: :::::
...... ::::: ::::: ::::: ::::: :::::
:::: :::: :::: :::: : ::::: ::::!
......
...... ::::::::::::::::::::::::::::::::::::
:!::
..
..
:::: :::: :::: :::::::: :::: :::: :::: :::::::: :::: :::: ::Jl ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::JI......
ll::: :::::::: ..
....
...... ::::: ::::: ::::: ::;;; ;;;:: : :::: :::: :::: :::! :::: :::: :::: :::: ::::
:::: :::: :::: :::: :::: :::: ::::
:::: :::: :::: :::
w ( l) appears; the n
r the top of the firs t col um n unt il a down-arro
6. H over the mouse ove the Properties
but ton . (T he firs t col um n has now bee n selected. ) In
click on the left mo use ent ries in tha t colu mn to be
ign pro per ty to right. Th is will cause the
window , set the Al the righ t colum n, sin ce
No te: Th ere is no nee d to set the A lign property for
right-justified.
its defau lt alignm ent is left. the cu rso r to the second
o the firs t col umn of the second row. Move
7. Type "C ost of me al:" int Toolbox. (A tex t
row and dou ble -di ck on the Tex tBox con tro l in the
col um n of the sec ond st by set tin g its ID
ins erti on poi nt. ) Giv e the tex t box the name txt Co
box appears at the
property to txt Co st. 5, or 20):" int o the left
sim ila r to Ste p 7 to pla ce "Pe rce nt tip (su ch as 15, 18.
8. Use a process t into the right colu mn.
a tex t box named txt Per cen
col um n of the third row and
the left col um n of the fifth
ces s sim ilar to Ste p 7 to place "A mo unt of tip:" into
9. Use a pro colum n.
named txtTip into the righ t
row and a read-on ly tex t box r Modify in
cel ls in the firs t row to select the row. Th en hov er ove
10. Drag the mouse ove r
the reduced from two cells
nu and clic k on Me rge Ce lls. (Th e first row will now be
the Table me
to one celL) "Tip Ca l-
hli ght ed, set its A lign pro pe rty to center, type the words
11. Wi th the first row stil
l hig
cul ato r" int o the row , and make the words boldface.
lcu late and tex t "C al-
ila r to Ste ps 10 and 11, place a but ton named btn Ca
12. In a ma nne r sim
the fou rth row.
cu late Tip" in the cen ter of
eous space. The best way to
col um ns, row s, and tab le to remove extran
13. Resize the tex t box es, column, hover the mo use
cha nge the val ue of its Wi dth property. To resize a
resize a text box is to ble-arrow ( <J=O )
on the righ t side of the column until a horizontal dou
over the double bar the bottom
To resi ze a row , hov er the mo use over the double bar at
appears; the n drag the arro w.
g the arrow. To resize the table,
tica l dou ble-arrow ( ~ ) appears; the n dra
side of the row unt il a ver cross ( ~ ) appears; the n
upp er-left com er of the tab le Lmtil an arrow
hover the mo use ove r the resized by dragging its
u e but ton . Th e tab le wi ll now be selected, and it can be
dic k the left mo sho uld loo k like Fig. 12.6.
nte nt reg ion of the Web page
sizing handles. The Ma in Co
o the btn Ca lcu late eve nt
l ick on the but ton and ent e r the follow ing cod e int
14. Do ub le-c
pro ced u re:
= CD bl (tx tC ost . Te xt)
Dim co st As Do ubl e Te xt) I 100
e = CD bl (tx tPe rce nt.
Dim pe rce nt As Do ubl
urr enc y(p erc ent * co
st)
txt Tip .Te xt = Fo rm atC
12.1 Progra mmin g for the Web, Part I
• 547
Comments
Web program, click on New Web Site, not
New
1. Impo rtant remi nder : Whe n start ing a new on Open Web
exist ing Web prog ram, click
Project, fro m the File menu. Whe n open ing an
12.1 Programming for the Web, Part I • 549
Site, not Open Project, from the File menu. H owever, when clos ing a Web program, click on
Close Project.
2. We have been running Web programs by pressing Ctt·l + FS to run without debugg ing.
H owever, if yo u prefer, you can click on the Start Debugging button in the Toolbar instead.
lf so, you might have to click on an OK button in a dialog box to proceed. A lso, the pro-
gram might still b running after you ex it the browse r. If so, you will h ave to click on Stop
Debugging in the Debug menu to terminate the program.
3. Rena ming a Web program is much ea ier than renaming a Wind ows program. Just close the
program and use Windows Exp lo rer to rename the program's folder.
4. In design mode, the bottom of the Des igner conta ins three buttons labe led Design, SjJlit, and
Source . If you click on the Source button, you will see ASP.NET code co rresponding to the
design of the page. This code can be altered directly to change the page des ign. If you press
the SjJlit button, you will see a split screen showing both the page and its ASP.NET code.
EXERCISES 12.1 . · · - . .
3. 4.
E ter an integer: 4 l 1 po·a o •
Enter an integer: 5 ~
2 po a o ••
Display P oem
/!pa a'a ·I Display Trri angle •••
•••• ~
5. If a bond is purchased for n do llars and sold one yea r later for m do llars, then the discount
rate ism ,~ " and the interest rate is m ~ ", where each is expressed as a percent. Write a Web
program to calcu late the discount rate and interest rate for a bo nd. See Fig. 12.8 .
Bond Rates
Purchase price: 950 Current Dividend Yield
Redemp ion value 1 yr. later: 1000 Most recent ull-year dividend: 1.96
Alaba ma "I
Displa y States Beginning with a Vowel Alaska
Ariz.ona
Displ ay States Beginning with a Conso nant A rka nsas
Idaho
lllin o i ~;
Tip Guideline
Tip Calculator
I
Cost of mea l:
Calculat e Ti p I
T1ppmg He lp
Amo unt of tip: l
FIGURE 12.12 The Default.aspx page.
Validation Controls
inpu t.
fiv e cont rol that can be used to chec k user
The Validation group in the Toolbox cont ains e Valid a tor co ntro l to
lid ato r cont rol and the Rang
In this section we use the RequiredFie ldVa
auth enticate user inpu t. ta in
ed with text boxes to ensure that they con
The RequiredFieldVa lidat or cont rol is u erties
an item has been selec ted. The two key prop
data and is used with list boxes to chec k that you are
Con tralTo Verify and Erro rMessage . Supp ose
of th e Requ iredF ieldValida tor cont rol are txtB ox and a list box
inpu t text box cont ro l nam ed
adding va lid ation for a page conta ining an call the con-
alid ator cont ro ls will be need ed; let's
cont rol named lstBox . Two RequiredFieldV and in
Co ntro iToVerify in rfvTe xt will be txtB ox
trols rfvTe xt and rfvLi st. The setti ng fo r into the
is clicked on befo re data has been ente red
rfvList will be lstBo x. If a butto n on the page the butt on's C lick even t wi ll
has bee n selec ted, then
text box, or befo re an item in the li t box sage prop erty will be
, the setti ng fo r the Erro rMes
not be exec uted. In both of these situa tions
rol.
disp layed in the Requ iredFieldValida to r cont e of
or con t rol chec ks that an entr y in a text box fall with in a set rang
The Range Va lidat rM es-
e Valid ator cont rol are ontr olTo Verify, Erro
va lues. The fi v key propertie of the Rang Type prop erty
Valu e. The poss ible setti ngs for the
sage, Type, Min im um Valu e, and Max imum imum
are String, Integer, Double, Date, and Curr
ency. The se ttings for the Min imum and Max
12.2 Programming for the Web, Part II • 553
properties should be suitab le for the spec ified type, and the se tting for the Minimum property
should be less than or equal to the setting for the Max imum property. Suppose that the se tting
for the ContralTo Verify property is a text box and that data outs ide of the specified range is
typed into the tex t box. Then the error message will be d isplayed in the Range Va lidator contro l
as soon as the tex t box loses focus.
Example 1 The fo llowing program is an extension of the tip-calcu lator program from
Section 12.1. The RequiredFieldValidator contro l is located to the right of the cost tex t box
and the Range Validator control is located to the right of the percent tip tex t box. When the
user clicks on the button, the program checks to see that a cost has been entered and that the
percentage for the tip is reasonable. (The assumption is made that a tip should neve r exceed
100%. ) To be completely protected, an add itional Requ iredFieldValidator control for the
Percent tip text box cou ld have been added. Figure 12.13 shows the contents of the Designer
and Fig. 12.14 shows the settings for the controls. The two red sentences will not appear ini-
t ially in the Web browser when the program is run.
Tip Calculator
Cost of mea l: l You must enter the cost!
Pe rcent t ip (such as 15, 18.5, 20): I Not a valid percentage!
Calcul ate Tip
Amount of t ip : j
I
FIGURE 12 .13 Design for Example 1.
[Run, enter 15 fo r the tip percent, neglect to enter a co t, and click on th Calculate Tip
button.]
T "p Ca cu a tor
Cost o" eal: You must enter the cost!
Postback
the text
Con ider the tip-calculator program. When the use r enters two proper va lues into
in the tex t boxes are se nt back to the server,
boxes and presses the Calculate button, the va lues
se nt to the Web browser.
the tip calculati on is made, and then an updated page is generated and
to have
The page is said to be posted back to the se rve r fo r processing, and a postback is said
occurred.
-no
When a va lidation control is triggered, the matter is h andled entirely by the browser
requests a new page from the
postback occurs. A lso, no postback occurs when the brow er
server.
Class-level Variables
do not
Local var iab les act the same in Web programs as they do in Window s programs. They
ex ist after the procedur e terminat es. C lass-
ex ist until a procedu re is called , and they cease to
wheneve r a page is sent to
level variables in a Web program, on the other hand , cease to ex ist
the next
the Web browser. Therefore, whateve r va lues were ass igned to them will be gone when
postback occurs.
be
There are ways to have a value persist be tween postbacks. For instance, a value can
values involve the
placed in a HiddenField control. Some more advanced methods for reta ining
use of session variab les and cookies.
Programming for the Web, Part II
12.2
• 555
11 Admission F<:>e
/lv;Je
Determine Fee
child ( <6)
minor (6-1 /
Fee : <1 .
o adutt (18-S4)
Visua l Web Develo per does not have a group box contro l capable
of holding a list of radio
button s. The counte rpart is the radio-b utton list contro l. The follow
ing VWD wa lkthrough
creates an enhan ced Web form of the program in Fig. 12.15 . The
Web program has the add i-
tional feature that a warning message is disp layed if a radio button
has not been se lected when
the Determine Fee button is clicked on.
A RadioButtonList Walkthrough
1. Start a VWD program with the name Admi sionFee and delete
the text in the Main Co n-
tent region.
2. Place a table havi ng 3 row , 2 co lumns, and width 275px onto the
page.
3. Use the Tab le menu to merge the three cells in the left column
of the table.
4. Type two spaces followed by the word Age into the left column.
5. Double-click on the word Age and make it boldface by clickin g on
the Bold button on the
Tool bar.
6. Positio n the cu rsor to the right of the word Age and press the Enter
key.
7. Double-click on RadioButtonList in the Standard Group of the Toolbox to
place a radio-b utton
list contro l on the page.
8. Set the control 's ID property to rblAges.
9. C lick on the contro l's Tasks button and then click on Edit Items.
(The Listlte m Collec tion
Editor in Fig. 12.16 on the next page appea rs.)
10. C lick on the Add button and then type "child ( < 6)" into the
setting for the Text property,
as shown in Fig. 12. 17.
11. C lick on the Add button and type in "minor ( 6- 17 )" for the Tex
t property.
12. Repeat Step 11 for "adult (18-64 )" and for "senior (65+ )".
13. C lick on the OK button to indicat e that all of the rad io button s
have been added to the list.
14. Place a button with the name btnDet ermine and Text setting "Deter
mine Fee" into the first
row of the right column .
15. Type the word "Fee:" into the econd row of the right column,
and then to the right of the
word add a text box. Set it ID property to txtFee and its ReadO nly
property to True.
16. Place a RequiredFieldVa lidator (with name rfvAge ) in the third
row of the right column .
556 • Chapter 12 Web A pp licatio ns
+ L•
L-~ '
+
A dd m l___ _
~---o_K_'__-J) [~__c_a_n_ce_l_~
+] .- A! 1.!: -;:
/. .
~ M&
+ Enabled True
Selected False
ch il d ( <6)j
Valu e
trol.
FIGURE 12.17 Listlt em Collec tion Editor fo r a R adioB uttonL ist con
12.2 Programming for the Web, Part ll • 557
17. Set the Contro lToValidate property of rfvAge to rbLAges, set the ErrorMes age property to
"You must select an age!", set the ForeColor to Red, and set the Font Bold property to True.
(See Fig. 12. 18.)
Determine Fee
Age
r child (<6)
Fee:
r minor (6-17)
r adult (18-64)
18. The rad io-button list contro l is simi lar to the Visual Bas ic list box contro l in that the value
of its Tex t property is the selected item represented as a string. Double-cl ick on the button
and enter the fo llowing code:
Protected Sub btnDetermine_ Click{ ... ) Handles btnDetermi ne.Click
Select Case rblAges . Text
Case "child {<6)"
txtFee.Text = FormatCurrency{O)
Case "minor {6-17)"
txtFee . Text = FormatCurrency{S)
Case "adult (18-64)"
txtFee . Text = FormatCurrency{lO)
Case "senior {65+)"
t x tFee . Text = FormatCurrency{7.5 )
End Select
End Sub
raised whenever one of the ch eck boxes is clicked on. That event proced ure updates the total
cost. The difference betwee n the two examp les is that in Exa mple 5 a computation is made
every t ime the use r cl icks on a check box, wherea in Examp le 4 clicking o n a check box does
not ca use a computation.
Both examples can be converted to Web programs with the sa me co ntrols, se ttings, and
code as in Section 4.4 . The Web vers io n of Example 4 wi ll work just fine, but Example 5 wi ll
not work as expected. This happens beca use computations can be made onl y if there is a pos t-
back to the se rver. C licking o n a button trigge rs a pos tback, but clicking on a check box does
not. The situation in the Web ve rsion of Example 5 is eas ily remedied. The check box contro l
has an A utoPostBack property that is se t to False by default. H owever, if it is changed to True,
then clicking on the check box will trigge r a postback and thus will a llow a co mputat ion to be
made. Therefore, all that is requ ired to make the Web version of Example 5 work as intended is
to change the A utoPostBack etting fo r each of the four check boxes.
By defau lt, clicking on a button causes VWD to check for validation. S uch is not the case
with a ch eck box. H owever, if you change a check box's Causes Validation property to True,
clicking on it wi ll invoke a va lid ation check.
Comments
1. As an alternative to using a hyperlink control, a line of code of the form
Response. Redirect ( "WebPageName. aspx" )
A statement such as
cannot be placed in the Declarations section of a Web program as i co mmon ly done in Win -
dows programs.
1. Why did we often avo id plac ing ReadAllLines state ments inside event proced ures in Win-
dows programs?
2. Why is the answe r to Practice Problem 1 not relevant to Web programs?
EXERCISES 12.2
1. Write a program that uses the page des ign in Fig. 12.20. The list box should be populated
with the names of the 50 states in a lphabetical o rd er wh en the page is loaded. (The fi le
States.txt conta ins the names of the U.S. rates in the order in which they joined the
union.) When the user clicks on the button, the selected state should be de leted from the
list box. A va lid ation control should be used to assure that a state h as bee n selected befo re
the button is clicked on . At all times the read-only tex t box should di play th e number of
states remain ing in the list.
12.2 Programming for the W eb, Part II • 559
Un bound
2. Rework Exercise 20 from Section 4.4 (Presidential Eligibility) as a Web program. Add two
va lidat ion controls for the "Date of birth" tex t box. One va lidat ion control should check
that the date entered is 1/21/1978 or ea rlier (to guarantee that the person will be 35 by
inauguration day in 2013) and the other should require that a date has been entered. The
code for the button's C lick event proced ure can be shortened, ince the date would have
already been validated.
3. Rework Exercise 17 of Section 4.4 (Co t of a Computer) as a Web program. U se a
RequiredFieldValidator control to assure that one of the radio buttons is selected. Note 1:
If yo u set the radio-button list's Repea tOirection property to Horizontal, then the radio but-
tons will be d isplayed in a row. Note 2: You must set each check box' CausesValidation
property to True.
4. Rework Exercise 25 of Section 4.4 (Health C lu b Fees ) as a Web program. U se a Required -
FieldValidator contro l to assure that one of the radio button is elected before the fee i
calculated.
5. Rework Example 1 of Section 5.1 (Convert Fahrenheit to Celsius) as a Web program.
Require that the input text box contain a value when the button is clicked on and that the
va lue is in the range from - 459.67 °F (absolute zero ) to 11,000 oF (approx imate tempera-
ture of the urface of the sun).
6. Co nsider the program in the hyperlink wa lkth rough. Replace the h ype rlink co ntro l in the
Help page with a button hav ing the caption "Return to Tip Calcu lator".
7. Rework Exercise 35 of Section 5.2 (Highest Two Grades) as a Web program. Require that
data be entered into each input text box before the button's C lick event i processed and
validate that each grade is between 0 and 100. See Fig. 12.21.
Grades
First grade: j
---
Second grade:jr-- - -
Third grade: I
ine Highest Two Grades
8. Rework Example 3 of Section 5. 1 (Weekly Pay) as a Web program. Requ ire that data be
entered into each input text box before the button's C lick event is processed and va lidate
that the number of hours worked is at most 168 (the number of hours in a week).
9. Rework Exercise 37 of Section 5.2 (Alphabetize Two Words) as a Web program with the
additional provision that both words must begin with lower-case letters. Use a Required-
FieldValidator and a Range Va lidato r control with each text box .
10. Rework Examp le 3 of Section 7.3 (Display Countries by Continent and A rea) as a Web
program without using a structure.
11. Rework Exercise 29 of Section 7.3 (Display Justices from a Spec ified State) as a Web pro-
gram without using a structure.
12. Rework Example 1 of Section 7.4 (Intercity Distances) as a Web program. Use a Requ ired-
FieldValidator and a Range Va lida tor control with each input text box.
1. This was done to avo id read ing a text file from a disk into an array more than once.
2. With a Weh program, any array loses its va lues between postbacks.
3. Place the cursor to the right of the button co ntrol, press the Enter key tw ice, and then
double-click o n the C hart control (in the Data group of the Toolbox ) to place a ch art con -
tro l on the page . The ch art control wi ll di splay a ge neric bar ch art as a placeho lder. (See
Fig. 12.22. )
4. Set the ID property of the ch art control to chtMegacities .
100
,......&-
80
....-'-- r-1-
60 t--
t--
2.0 - r-"'-
r---
0
1 2 3 4 5 6 7 8
FIGURE 12.22 Default.aspx page in Design view.
Add Co nnect io n
Dat a sourc e:
Mi crosoft SQL Server Database Fil e (SqiCii ent) Chang e ...
Log on t o t he server
Pas_·,rvord:
Save my passwor d
[ Advance d ...
,.
Test Conn ection OK [ Cancel
You are attempti ng to add a spec ial fil e type (LlNQ t o SQL Cl asses.) to
an ASP.N ET Web sit e. In general, to us.e this. type of item in your site,
you should pl ace it in th e 'App_Co de' fold er. Do you want to pl ace th e
fil e in t he 'App_C od e' fold er?
Crty Country
The connection you selected uses a local data file that is not in the
current project. ould you like to copy the file to your proj ect and
modify the conn ection?
~--
Ye_,___l [~___N_o __~] [~_H_e_lp__~
k
Protect ed Sub btnDisp lay_ Click( ... ) Handles btnDisp lay.Clic
Dim mcDC As New Megacit iesDataC ontext
Dim query = From city In mcDC.C ities
Order By city.pop 2010 Descend ing
Select city . name, city.pop 2010
chtMeg acities.D ataBind Table(q uery, "name" )
chtMega cities.C hartAre as{O) .AxisX. Interval = 1
chtMega cities.C hartAre as(O) .AxisX. Title "City"
c htMega cities.C hartAre as(O) .AxisY. Title = "2010 Populat ion in Million s "
End Sub
name
Note: The line following the query statemen t binds the chart to the query and uses the
es that all x-values will be displayed .
fie ld to populate the x-values. The next line guarante
6. Run the program and click on the Display button. Figure 12.27 shows the output.
:.f ·;=
...c:
D t:'
..... I;
J .e
../)
:r
Comments
1. The chart control can produce cl uste red bar charts. For instance, if the LINQ clause
Select city . name , c ity . pop2010
and the string "2010 Popu lation in M illions" is changed to "2010 & 2015 Pop ulation in
Millions", then the clustered bar chart in Fig. 12.29 will be produced.
0
~-
<::
-;;;:
~
30 I--
r=
.:::0
..!;!
;:,
20 t - h:-:- .,-;=
0...
li'
l! J
10 -
II n - f-:
f -
~ ~ u
.Q .,f;
3.
1-
~
~ & E
::J
f. Qi
0 ..:
0
,;e
~ z I;
-- ::!
Q;
C1y
FIGURE 12.29 C lustered bar chart.
566 • C hapter 12 Web App licat ion
2. When LINQ is used to prod uce a ba r chart, one of the ite ms in the Select clause must have
type String and the remaining ite ms must h ave a numeric type. H oweve r, when a LINQ
qu ery is used to prod uce a grid, the items in the Se lect clause can have an y data typ s.
1. Wri te a VWD program that use the database Megac it ies.md f to ge nerate a bar chart dis-
play ing the 2010 populat ions of the coun tries whose currency is the peso.
EXERCISES 12.3
In Exercises 1 through 10, write a Web program that uses the database Megacities.mdf to
generate th e bar chart.
1. 2. 25
I:
~ r;
20
c:
s; ~
g
c:
..
:;
""s 15 t---
c:
r-.--- ·- - -
c. ~
;;;
!:.. :;
0 c:.
0 10 1--- 1- r- 1---
0I c...
~
0
0
• 5 t--- 1- r- ~
~
,_ '),
G ~
~
0
," Boo-bay Ca " Delht
CD
Ctt1 m lr a
Ctty
3. 16 4. 25
-= "'~
G
e 1214 2
!;;;
~ 10 -=6 15
3
~ 8
c;
ll.
<.':
..
c
"'
<:
6
4
~
~
0
0 05
"' 2
ll.
0
~
-:3 "' <5
-=c:. ~ -;;
j)
:l"
CD
...~
Ctty
C•l'/
12.3 Using Databases in Web Programs • 567
5. 40 6.
v:
ll c:: 15
c: 30 0
oE oE
~ ~
c:
"' 20 1----.-
!< :- .!;? 10
~ :::1
~
1l.
e-
0 0
c; 10 ----, - '---' - - :- c; 5
0
eXJCO <Ay Sao Paulo Ca leu na !)t,a1.3
Bombily • Yorio: - ory.o Buenoi 1ru Dil 1 Shanghai
City v.1th Above- vera e PopulatJor> City v.1th Popula on ~ 18 1llio
7. 100 8. "' 35
{/"
c:
1200 III Q
~30
e.- I I
-
5 1000 -
e-
ll.
{/"
25
~ lL
c
;:: -~ 20 I-
800
~ ~ ~I
8 :::1
0
600 u 15 I -
0
ci
0 400 ~
[
0
200 - - - - e.- - -
~ ... -
-r
0 0 ~-
~
-
z8 ~
... ....
~
~
~ ..r;
&
..r;
Ol
c;
3
.);l
g f
.... g ~
u
~
8 0 i5
..2
a &"' ~ I 8..r;;;
8
_j
3
..r;
cr
~
0 1- c;
lSc:: 0 ~
en
co J § :z: ~ m ~
c; :z: en
::;;
CD "' ::::
Qj
c. ' c.
0
-e <
I!) e .:; c
c
.&.
fJ)
1'i
9 "
-; ~
8 c
c;)
.E ::> -~
(.J
0
(0
~ ..,Ill ::;;
] &. g l
CD
Country Country
568 • Chapter 12 Web Applica ti ons
In Exercises 11 th rough 16, wri te a Web program that uses the database Megacities.mdf to
generate the grid.
11. 12. City Population Increase
City Population Increase
Dhaka 14.86'3-o Dhaka .2 200 000
Deihl 10.00% Bombay 1900 000
Bombay 9.45 °6 Delhi 1700000
Calcutta 8.97?o Calcutta 1400 000
Shanghai 3.36% Shanghai 1400,000
rl1ex:ico C1t· 359QD t 1E:
1 ICO (It 700,000
r Je 'I fork 3.09'0o ~.Je •r York 600 000
S'lo Paulo 2.55°'0 cao Paulo 500 000
Buenos A1res 2.29% Buenos ~1res 300,000
Tokyo 0.83% Tok·yo :::ooooo
The database Pizza.mdf has a single table Pizzerias that contains data for th e eight leading
pizza chains. The fields for the table are name, sales2007 , sales2008, numStores200 7, and
numStores200 8 . (Sales are given in thousands of dollars.) Two records in the table are
In Exercises 17 through 22, write a Web program that uses the database Pizza.mdf to gener-
ate the bar chart.
18. 3000
00
8 6000
~.
;;
.r
(5
.:;; 4000
0
~ 2000
z"'
.:::
Przzena Przzem;
0
250
])~ 200
50
t ·._
~
"'
.f)
10 I-'
I
;;
00 - -
.,"""
c;
5 f--i
50
14 T-: - .r;
II
-I-
I
_,r!"l I
0~---o- 0
I
50
·100
rl .., ·5
-
'......."' -• -g~
~
'-' ;:!:!:
::: t; g
c. :>
~ 3. u
c ::2 t:: 2. ~
&
Przzen Przzen a
570 • Chapt er 12 Web App licatio ns
f/" 5
4000
"'
en
00
r 5
u;
g
..... 2 0
ol! t 2000 r- r-
......
8
0
rl r•I
w·"'
-"
.J
...c::
N
~
C
- tr
...
N
r~
.3
..,t:! ..
c:
~
!r .I r•
8. ·~
c:;..o::
j ...
1
j
en
~
z
0
r1
_,_~
~~
il :O
:lu .J
I
.:!:
. o/1
·a
T 1rI
§.::~
~ "
::'!...
~
...l
-s -~b
"'
'c:
....,
a
11
3 -;;
::
r
•
~
j
;n
.Ei ~
0
_j
~ u
2. !!: .J £
u &
Pizzena
Pizzena
1. There is no need to ca rry our rhe fo ur stages from the wa lkth ro ugh , since we have already c rea ted an objec t
mode l and LinqDaraSource conr ro l fo r thi s database. The fo llowing steps crea te th e new program, and
Fig. 12.30 shows rhe ba r chart rhar is produ ced :
(a) Starr a new Web progra m with rhe name Pract iceProb and then c lose rhe program.
(b) Use rhe process fo r buil d ing on an ex ist ing Web program d iscussed ar rhe end of Secti on 12. 1 to make
Pract iceProb a c lone of rhe program created in rh e wa lkth ro ugh .
.
20
0
I ~
~·
-
"<:; c
6
c
0.
.::::;. 0 ·- -
"
-I
20 J
r <>ntm e , JC
c -.- Curre r ~ ..
(c) Open PracriceProb in VWD and change rhe q uery to rhe fo ll ow ing:
(d) C hange the string in rhe next to last line of rh c code fro m "City" ro "Country with Peso as C urre ncy".
CHAPTER 12 SUMMARY
1. V isual Web Developer (VWD) is used to crea te programs that res ide on a erver and run in
the W eb browse r of a client co mputer.
2. There are man y imilari t ie betwee n crea ting a Web program with VWD and crea ting a
Visual Basic Windows program. H oweve r, there are so me important d ifference . Fo r o n
thing, tex t can be typed and form atted d irectly into We b pages. A lso, not as man y co ntro ls
are ava ilab le in VWD as in Visual Bas ic, and contro ls that are commo n to both have fewer
properties and eve n ts in VWD than in Visua l Bas ic.
3. The table control is he lpful for aligning tex t and contro l in VWD.
4. Validation controls a llow the brow er to check input befo re it is ent to the se rve r.
5. The hyf)erlinl< control is used to request different pages fro m the se rve r.
572 • Chap ter 12 Web App licatio ns
Answer: I Florid a - FL
Geor gia- GA
Asce'lding
Display Bar Clh a
2C 15 ' Descendir g
~
~ ·r J
..t::
-s
..... '= a:. r
,:
a ~
-=
t::I
~
'
~ ..e
(o';
I
'-
~
./) -;:
i:l:i
I '
1. C lick on New Project in the File menu, or click on the New Project butto
n
( ..::iJ ) on the Too lbar, or press Ctrl + N. Note: If the current progra m
has not been saved, Visual Bas ic wi ll prompt you about sav ing it.
2. Check that Windows Forms App lication is highligh ted.
3. Option ally, type a name for the progra m into the Name box.
4. C lick on the OK button.
1. C lick the Save All button ( ) on the Toolbar, or click on Save All in the
File menu.
2. If the program has not been saved prev iously, give it a na me and then click
on the Save button. Importa nt: If the "Create directo ry for solution
"
check box is checked, then cl ick on the check box to unchec k it. (You
577
578 • Appendix B How To
or
1. Mov e the mouse to the begin ning or end of
the text .
2. H old down the left mouse butto n, move the
mouse to the othe r end of the
text, and release the left mouse butto n.
line.
G. Let a text box disp lay more than one
True . (lf the text box is not wide
1. Set the tex t box's Mul tiline prop erty to
red by the user, the text will wrap
enough to acco mmo date the text ente
tall enough, lines will scro ll out of
down to new lines . lf the text box is not
up or dow n keys. )
view but can be displaye d with the cursor
l to frmElse.
K. C hange the Na me prope rty of Form
ck on the fi le Form 1.vb.
1. ln the Solution Exp lore r wind ow, righ t-cli
that appears.
2. C lick on Rename in the cont ext menu et
3. C hange the name of the file Form
l. vb to frmE lse.vb. (Cau tion : Don 't forg
to reta in the exte nsio n vb.)
Appendix B How To • 581
1. If you suspect that some cells will be too narrow to accommodate their con-
tents, se t the contro l's AutoS izeColumn property to AllCells.
O therwise,
1. Set the first parameter of the control 's S ize property to 100 · [number of
columns] + 3. If there will be a sc roll bar on the right side of the grid, add 17
to the se tting of the parameter.
2. Set the second parameter of the control's S ize property to 22 · [number of
rows] + 1. If an y column head er will occupy more than one line, add 13 to
the pa rameter for each additional line.
1. If the Desc ription pane is not visible, right-click on the Properties wind ow
and then click on Description in the drop-d own contex t menu.
2. Highlight the property in the Properties window. Its purpose will appea r in
the Description pane below.
P. Specify the contro l that will have the focus when the program executes.
1. Set the contro l's Tabindex property to 0.
Setti ng Optio ns
A. Turn off lntelliS ense.
1. C lick on Options in the Tools menu .
it.
2. lf the check box to the left of "Show all settings" is unchec ked, check
3. In the left pane, expand "Text Editor".
4. Expand the subheading "Basic".
5. C lick on the subtopic "Gener al".
headin g
6. Ensure that all the check boxes und er the "Statem ent comple tion"
are unchec ked, then click on OK.
a horizon tal
B. Wrap words to the nex t line in the Code Editor rather than hav ing
scroll bar.
1. Follow reps 1 through 5 of part A above.
wrap".
2. In the righ t pane, place a check mark in the check box labeled "Word
on me nt
Co nfi gu rin g the Wi nd ow s En vir
sett ing for the mon ito r.
A. Det erm ine and /or cha nge the DPl
Windows XP
p to disp lay a con tex t menu.
1. Right-click on the Win dows des kto perties" d i-
menu to brin g up the "Display Pro
2. C lick Properties in the con tex t
alog box .
"Display Properties" dialog box.
3. C lick the Set tings tab on the og box. The
disp lay the mon itor properties dial
4. C lick the Advanced but ton to
in the "DPI sett ing" box.
curr ent DPI sett ing will be sho wn etti ng in
the sett ing, se lect a diff eren t DPI
5. If you wou ld like to cha nge t ures in this boo k
. [Note: The scre en cap
the "DP I se ttin g" dro p -do wn box t sett ing,
rma l Size (96 DPI )." Wi th tha
we re don e with a DPI se ttin g of "No
will appea r like those in the book.]
the form s you see on your scree n er before app ly-
6. If you cha nge d the DPI sett
ing, click on "Restar t the com put
ing the new disp lay sett ings ." not hin g will
did not cha nge the DPI se ttin g,
7. C lick the OK but ton . (If you you
"Display Properties" dialog box, and
hap pen . You wi ll be retu rned to the
to the desktop. )
can press the OK but ton to retu rn d. C lick the
8. If you cha nged the DPI sett
ing, a message box wi ll be displaye
questio n posed, clic k the Clo se but ton
OK but ton twice, answe r "Yes" to the k on the Yes
per ties" dialog box, and clic
at the bot to m of the "Display Pro
allow the cha nges to take effect.
but ton to re tart your com put er and
Win dows Vista
p to disp lay a con tex t menu.
1. Right-c lick on the Win dows deskto e appear-
t menu to disp lay the "Personaliz
2. C lick Personalize on the con tex
anc e and sounds" window. ed for an
fon t size (DPI)". (If you are pro mpt
3. In the left pane, click "Adj ust d or pro vide con -
atio n, type the passwor
ad ministr ato r password or con firm ing will be
firmation by press ing the Continu
e but ton.) The cur ren t DPI sett
indi cated. te: The
oth er DP I etti ng, clic k on it. [No
4. If yo u would like to select the "De faul t scale
don e wit h a DPI se ttin g of
scree n cap tures in this boo k were
Appendix B How To • 585
(96 OPI)". With that setting, the forms you see on your screen will look like
those in the book.]
5. C lick on the OK button. (If you did not change the DPl setting, nothing
will happen. You will be returned to the Personali ze window, and you can
close the window to return to the desktop.)
6. If you changed the DPl setting, restart your computer to allow the changes
to take effect.
Windows 7
1. Right-clic k on the Wind ows desktop to display a context menu .
2. C lick Personalize on the context menu to display the Personalization window.
3. C lick on Display near the bottom of the left pane. Three radio buttons (la-
beled Smaller - 100%, Medium - 125%, and Large r - 150% ) wi ll appear
with the current setting selected. Note: The screen ca ptures in thi book
were made with a setting of"S maller - 100%". With that setting, the forms
you see on your screen wi ll look like those in the book.
4. If yo u do not want to change the setting, clos the window.
5. Othe rwise, select a different setting and click on the A jJply button. (You will
be instructed to log off yo ur computer in order to allow the change to take
effect. Note: You wi ll not have to restart your computer. )
Windows XP
1. C li ck on Folder OjJtions in th Tools menu. (A Fo ld e rs Options dialog
box will appear.)
2. C lick on the View tab in the dia log box.
3. If there is a check mark in the box next to "Hide ex tensions for known file
type ",cl ick on the box to remove the check mark.
4. C lick on the OK button to close the Folders Options dia log box.
Use a Printer
A. Obtain a printout of a program.
1. Invoke the Code Editor.
2. C lick on Print in the File menu. Or, press C trl + P.
3. C lick on the OK button.
586 • Appendix B How To
Pr i n tFo rml.Pr intAc ti on Pri n ting . PrintA ction . PrintT oPri nter
Pr in tFo rml . Prin t()
C. Store frequently used code for easy inclus io n into other programs.
1. Select the code as a block.
the code in
2. Drag the block of code into the Toolbox. (Yo u wi ll now h ave
both the Code Editor and the Toolbox.)
the Code
Note: The block of code will be visible in the Toolbo x wh enever
a copy of the code into the Code
Ed ito r is open. At any time you can drag
Ed itor.
Appendix B How To • 587
W e .use the word disk to refer to either the h ard disk, a diskette, a USB fl
drive, a CD, or a DVD. Each dnve IS td ennfted by a letter. Normally,
hard drive is identifie d by C, the diskette drive by A, and the CD (or DVD)
ash
the
drive by
D or E. Disk manage ment is h andled by Window s.
Disks hold not only programs, but also collections of data stored in file
. The
te rm file refers to either a program fi le, a text fil e, or some other kind of
data file.
Each file has a name consisti ng of a base name fo llowed by an optio na
l extensio n
consisti ng of a period and one or more charact ers. The term filenam e refers
to the
combin ation of the base name, the period, and t he extensio n. A fil ename
ca n co n-
tain up to 215 characte rs, typica lly consisti ng of lette rs, digits, spaces, periods,
and
other assorted characte rs. (The only charact er that cannot be used in filenam
es are
\ , / , : , *, ?, < , > , ", and I.) Extens ions are norma lly used to id entify t he
type of
file. For example, spreads heets created with Exce l have the ex tension
xlsx o r xls
(eXceL Spreads heet), docume nts created with Wo rd have the extensio n
docx or doc
(DOCu ment), and files created with Notepa d have the ex tension txt (TeXT
docu-
ment). Some exampl es of filename are "Annu al Sales.xlsx", "Letter to Mom.do
cx",
and "Phone .txt".
Because a d isk is capable of holding tho usands of fi les, locating a specific file
can
be qu ite time consum ing. Therefore, re lated files are grouped into collecti
o ns ca lled
folders . For instance, one fo ld er might hold all your Visual Basic program
s, and
anothe r the docume nts crea ted with your wo rd processo r.
Think of a d isk as a large fo lder, called the root folder , that contai ns
several
sma ller folders, each with its own name. (The nam ing of fold ers follows
the sa me
rules as the naming of fi les.) Each of these smaller fo lders can conta in
ye t o ther
named folders. Any folder contain ed inside another fold er is said to be a subfold
er of
that fo lder. Each fo lder is identified by listing its name precede d by the names
of the
successively larger fo lders that contain it, with each folder name precede d
by a back-
slash. S uch a sequenc e i called a path . For instance, the path \Sales\
NY08 \ ] uly
iden tifies th e fo lde r] uly, contained in the fo lder NY08, which in turn is
co ntained
in the folder Sales. Think of a file, along with its name, as wr itten on a slip
of pape r
that can be placed into e ither the root fold er or o ne of the smaller folders.
The com-
binatio n of a drive letter fo llowed by a colo n, a path, and a fi lename
is called a
filespec , an abbrev iat ion of "file specific ation." Some exampl es of filespec
s are
C: \ VBOI \ VB.exe and E: \Person a l \ Income09. txt.
Neither Window s nor Vi ual Bas ic distinguishes be tween upperca se and
lowe r-
case letters in fo lder names and filenames. Fo r instance, the names COST
S02.T XT,
Costs02 .T xt, and costs02 .txt are equiva lent.
In many cases fo lders are referred to as directo ries. Many Vi ual Bas ic
o bj ects
and comma nds still refer to fo lders as director ies. The terms "root fo
lder" and
"path" are a referenc e to the "tree" metaph o r co mmonly used to describe
the o rga-
nization of files. In this metaph o r, the large fold er at the lowes t leve l of
the disk is
589
590 • Appendix C Files and Folders
t of as
the roo t folder. The smaller folders contain ed in the root folder can be though
branche ,
branches that emanat e fro m the roo t. Each branch may have smaller
e in one
which in turn may have their own smaller branche s, and o on. Finall y, a fil
leaf on a branch. The leaf is reached by start-
of the e fo lders can be though t of as a
ing at the root and followin g a path through the branche s.
APPE NDIX D
VISUAL BASIC DEBUG GING TOOLS
rrors in progra ms. are called bugs, and the process of finding and correcting them
E is called debuggmg. S nl.Ce Vtsual Baste does not dtscover e rrors due to fau lty
logic, these errors present th e mos t difficulties in debugging. O ne method of discov-
ering a logic error is by desk checking- that is, tracing the va lues of variables on
paper by writing down their expected value afte r "mentally exec uting" each line in
the program. Desk checking is rudimentary and highly impractical except for small
programs.
A nother method of debugging involves plac ing MessageBox . how statements at
strategic points in the program and display ing the va lues of selected variables or
express ions until the error is detected. After correcting the error, you can remove the
MessageBox.Show statements. For older programmin g environmen ts, desk checking
and MessageBox.Show statements we re the only debugging methods ava ilable to the
programmer.
The Visual Bas ic debugger offers an alternative to desk checking and to inserting
MessageBox.Show statements. It allows you to pause during the execution of your
program in order to view and alter va lues of variables. The e values can be accessed
through the Immed iate, Watch, and Loca l windows, known as debugging windows.
Fi le Edit View Project Debug Data Format Tools Win dow Help
Title bar, Menu bar, and Too lbar during run mode.
Title bar, Men u bar, and Too lbar during debug mode.
591
592 • Appendix D Visua l Bas ic Debuggin g Tools
o r "debug," the words "Runnin g" o r "Debugg ing" are displayed (in parenthe es ) in
the Visual Bas ic title bar. The abse nce of these wo rds indica tes that the curren t
mode is "des ign. "
W ith the program in des ign mode, you place contro ls on a form, set their initial
properties, and write code. Run mode is initiated by press ing FS or the Start Debugging
button. Debug mode is invoked automati cally when a run-time error occurs. You can use
Debug options to break the program at specified places. While the program is in debug
mode, you can hover the cursor over an y variable to obta in its current value. Also, you
can usc the debugging windows, such as the Immediate, Watch , and Locals windows, to
examine values of expressio ns. When you enter debug mode, the Too lbar contains a
Continue button. You can click on it to continue with the executio n of the program.
FIGURE 0.1 The Toolbar buttons used to Step Into, Step Over, and Step Out.
As another debugg ing too l, Visual Bas ic allows the program mer to specify ce r-
ta in lines as breakpo ints. Then , when the program is run, ex cution will stop at the
first breakpo int reached . T he programm er can then either step through the program
or continue execut ion to the next breakpoi nt. Also, the program mer ca n place the
curso r o n any line in th e program and have executio n stop at that line with a "Run
to Cu rso r" command . Program executio n norm ally proceeds in ord er th ro ugh the
stateme nts in a procedur e. How ve r, at an y time the program mer can spec ify the
next statemen t to be executed.
T he task discussed prev iously are summari zed next, along with a mean to carry out
each task. The tasks invoked with function k ys also can be produced from the menu
bar, the context menu (produced by clicking the right mouse button) , or the Toolbar.
? expr essio n
FIGURE D.2 Three statem ents execu ted in the Imme diate windo
w.
\ 1\ atch
·~X
Name Valu e Type ....
1 num 100 Integer
1 5 "'num 500 Int.eger f=J
1 num >90 True Boolean
Th e Locals Wi ndo w
ls wind ow from the Debug menu by pos i-
Whi le in brea k mod e, you can open the Loca
ing on Locals. Th is wind ow auto mati -
tioni ng the curso r over Wind ows and then click
of all varia bles in scope. ee Figure 0.4.
ca lly displays th e nam es, va lues, and types
of va riables at any time .
You can use the wind ow to alter the valu es
Loca l;.
Type
Nam e Valu e
:+J 1 l\1e
[+J ; e
Integer
; num 1 3
Integer
1 num2 4
·-4 .. String
; phrase "Hello world.•
-- -- -- --
FIGURE 0.4 A typical Loca ls wind ow.
m: Cha pte r 3
Ste ppi ng thr oug h an Ele men tar y Progra
ral capa biliti es of the debu gge r:
The follo wing walk throu gh demonstrates seve
and a text box (txtBox).
1. C reate a form with a butto n (btn Push )
follo wing even t proc edure:
2. Double-click on the butto n and ente r the
Han dles btnP ush. Clic k
Priv ate Sub btnP ush_ Clic k( ... )
Dim num As Inte ger
ber: "))
num = Cin t(In pu tBox ("En ter a num
num += 1
num += 2
txtB ox.T ext CStr (num )
End Sub
8. Let the mouse hover ove r any occ urrence of the va ria ble num fo r a seco nd
or so. The current va lue of th e variable will be di splayed in a small box . See
Figure 0.5.
9. Press the Stop Debugging button on the Toolbar. (You also can stop debugg ing by
clicking on StoJJ Debugging in th e Debug menu.)
10. Move the cursor to th e line
num += 2
and then press F9. A red dot appea rs on the gray bord er to the left of the line.
This indica tes that the line is a brea kpo int. Press ing F9 is referred to as toggling a
breai<JJoint.
11. Press F5 and click on the button. Respond to the request by entering 5 and click-
ing on OK. The program executes the first three lines inside the procedure and
stops at th e brea kpoint. At this po int, the breakpo int line has not ye t exec uted.
12. Open the Immediate wind ow by press ing C trl + Alt + I. If neces ary, clea r th e
contents of the window by press ing the right mouse button and selecting "Clea r
A ll". Type the statement
? num
into th e Immediate window, and then press Enter to execute the statement. The
appea rance of "6" on the nex t line of the Immediate wind ow co nfirms that the
breakpoint line was not executed.
13. C li ck on the Code Editor.
14. Move the cursor to the line num += 1 , cli ck the right mouse button, and th en
click on "Set next Statement".
15. Press F8 to execute th e se lected line.
16. Return to the Immediate wind ow by clicking on it. Type th e statement" ? num"
and pres Enter to confirm that the va lue of num i now 7. Then return to the
Code Editor.
17. Move the cursor to the brea kpo int line and pres F9 to deselec t the line as a
brea kpoint.
596 • Appe ndix D Visua l Bas ic Debu gging Tools
ctio n
Step pin g thro ugh Programs Con tain ing Sele
Structures: Cha pter 4
If Blo cks
the cond it ion of an If state ment is
The follo wing wa lkthrough demo nstra tes how
n:
evaluated to deter mine whet her to take an actio
1. C rea te a form with a butto n (btnP ush)
, a text box (txtB ox ), and the fo llowi ng
code:
les b t nPus h . Clic k
Priv ate Sub btnP ush_ Clic k( .. . ) Hand
Dim wage As Doub l e
wag e= CDb l(Inp utBo x("W age : "))
If wage < 7 .2 5 Then
txtB ox.T ext "Belo w minim um wage ."
Else
txtB ox. Text "Wag e Ok."
End If
End Sub
Sub", pres the right mouse but-
2. Place the curso r on the line beg inn ing "Private
am will exec ute and the form will
ton, and click on "Run to ursor". The progr
appear.
ye llow arrow poin ts to the state -
3. C lick on the butto n, and then press F8. The
ment cont a ining Inpu tBox .
aining lnpu tBox. Type a wage of
4. Press F8 once to exec ute the state ment cont
is highl ighte d but h as not been
6.25, and press the Ente r key. T he If state ment
exec uted.
has jump ed to the tatem ent
5. Pres F8 once, and notice that the ye llow arrow
. " Beca use the cond ition "wage < 7.25"
txtB ox . Text = "Belo w minim um wage
en .
is true, the actio n assoc iated with Then was chos
. N otice that Else is skipp ed and
6. Press F8 to exec ute the txtBox.Tex t state ment
the ye llow arrow poin ts to End If.
, and the state ment follo wing
7. Press F8 aga in. We are through with the If block
the If block , End Sub, is high ligh ted.
8. Pre s C trl + A lt + Brea k to term inate debu gg ing.
in with 7. 75 ente red as the wage.
9. If des ired, try stepping thro ugh the program aga
false, the Else actio n will be exe-
S ince the cond ition "wage < 7 .25" will be
cuted inste ad of the Then actio n.
2. Place the cursor on the line beginn ing "age =", press the righ t mouse button, and
click on "Run to C ursor". T he program will execute, and the form will appear.
3. C lick on the button. The arrow will point to the statement beginning "age=".
4. Press F8 once to execute the statement begin ning "age=". Type an age of 8, and
press the Enter key. T he arrow points to the Select Ca e statement, but the
statement has not been executed.
5. Press F8 twice, and observe that the arrow points to the act ion as oc iated with
"Case Is < 12".
6. Press F8 once to exec ute the ass ignme n t sta tement. Not ice that the a rrow now
po ints to End Select. Th is demon trates that when more than one Ca e clause is
true, only the first is acted upon.
7. Press C trl + A lt + Break to terminate debugg ing.
8. If des ired , step through the program aga in, entering a different age and predict-
ing which Ca e clause will be acted upon. (Some poss ible ages to try are 12, 14,
18, 33, and 67.)
2. Place the cursor on the line beginning "Private Sub", press the right mouse
button, and click on "Run to C ursor". The program will execute, and the form
wil l appear.
3. C lick on the button. In the Code Editor, a ye llow arrow points to the Private
Sub statement.
4. Press F8 once, and obse rve that the ye llow arrow now po ints to the tatement
p = lOOO . This statement will be executed when F8 is next pressed.
5. Press F8 aga in. The state ment p = 1000 was executed, and the ye llow arrow
now points to the statement calling the Sub procedure GetBalance .
6. Press F8, and obse rve that the ye llow arrow is now po inting to the header of the
Sub procedure.
7. Press F8 three times to execute the ass ignment tatements. The ye llow arrow
now po ints to the End Sub statement. (Notice that the Dim and comment tate-
ments were skipped.)
8. Press F8, and notice that the ye llow arrow has moved back to the btnPush_Cl ick
event procedure and is pointing to the calling statement. By hovering the cu rsor
over the va riab le b, yo u ca n ver ify that the Sub procedure was executed.
9. Press the Sto jJ Debugging button to terminate debugg ing.
+ F8 to ste jJ over the Sub proce-
10. Repeat Steps 2 through 5, and then press Shift
dure GetBalance. The Sub procedure has been executed in it en tirety.
CHAP TER 2
EXERCISES 2.2
1. After a button is clicked, it has a blue bo rd er.
3. C lick on the fo rm to make it the selected object.
C lick on the Prope rties window or Press F4 to act ivate the
Prope rties window.
Select the Text property.
Type "CHE CKIN G ACCO UNT" .
5. Double-click the TextBox icon in the Toolbox.
Act ivate the Properties window.
Select the BackC olor property.
C lick on the down- arrow to the right of the Settin gs box.
C lick on the C ustom tab, and then click on the desired ye llow
in the palette.
C lick on the form to see the empty ye llow text box.
7. Double-click on the Label icon in the Toolbox.
Activ ate the Prope rti es window, and elec t the AutoS ize prope
rty.
Set the AutoS ize property to False.
Select the Text property and type the req uested se ntence.
Select the TextA lign property.
C lick on the down-arrow button to the right of the Settin gs box,
and click on one of the center rectangles.
Resize the label so th at the senten ce occupi es three lines.
9. Double-click on the TextBox icon in the Toolbox.
Act ivate the Properties window.
Set the Name property to txtLanguage.
Select the Text property and type "Visua l Basic 2010".
Select the Font prope rty and cl ick on the ellipsis to the right
of the Settin gs box.
Scroll up the Font list box, and click on Couri er New in the
Font box.
C lick OK.
Widen the text box to acco mmod ate its text.
11. Double-click on the Button icon in the Toolbox.
Act ivate the Properties window, and select the BackC olor proper
ty.
C lick on the down- arrow button to the right of the Settin gs
box.
C lick on the Custo m tab, and then click on the wh ite sq uare
in upper-left corner of the palette .
Se lect the Text proper ty and type "PUSH ".
Select the Font prope rty, and click on the ellipsis.
C lick on Iralic (with XP or Vista) or Oblique (with Windows
7) in the "Font style" li t.
C lick on 24 in the S ize box and click OK.
Res ize the butto n.
601
602 • Answ ers To Se lected O ud -N umbcred Exercises
Place two buttons on the form and pos it ion and resize as shown.
Enter "Batman" as the text of the first button , and enter "Robin" as the text of the second
button.
Increase the font size for both buttons to 14.
27. Begin a new project.
C hange the text in the form's title bar to "Fill the Blank".
Place a labe l, a text box, and another label on the form at appropriat e locations.
C hange the Text setting of the first label to "I'm the king of the" and the Tex t setting of
the second labe l to "A Quote by Leona rd o DiCaprio".
29. Begin a new project.
C hange the text in the form's title bar to "Uncle's Advice".
Place five labe ls and three buttons on the form.
C hange the Text setting of each labe l as indicated.
C hange the settings of the buttons' Tex t prop rti es to "1", "2", and "3 ".
Resize and position the labe ls and buttons.
33. 1 35. Each arrow key moves the text box in the indicated direction.
37. Pressing the right and left arrow keys widens and narrows the text boxes, buttons, and list
boxes in the group of se lected contro ls. The up and down arrow key shorten and lengthen
the buttons and list boxes in the group. The arrow keys have no effect on the labels, and
only the left and right arrow keys affect the text boxes.
39. Drag a labe l and a list box onto the form.
C lick on the label.
Hold down the Ctrl key and click on the list box. (You have now selected a group of two
controls.)
ln th Properties window, cl ick on the plus sign (in XP) or the right-poin ting tri angle
(Vista or W indows 7) to the left of the Font property.
C lick on the Size property, change the se tting to 12, and press the Enter key.
(Alternat ive: Replace the last three lines with th e fo llowing steps. )
In the Properties window, se lect the Font prope rty.
C lick on the ellipsis button to the right of the Settings box.
C lick on 12 in the S ize list and click O K.
41. The labe l is po itioned just to the left of the text box, and the midd les of the two contro ls
are aligned.
43. Center refers to the midpoint horizontally, whereas middle refers to the midpo int vert ica
lly.
45. First blue snap line: tops of the two control are aligned
Purple snap line: middles of the two controls are aligned
Second blue snap line: bottoms of the two controls are aligned
47. The setting is cycl ing through th e d ifferent ava ilab le co lors.
EXERCISES 2.3
1. The word "Hello" 3. The word "Hello" on an orange-co lored background
5. The text box vanishes. 7. The word "Hello" in gree n letters
9. The word "Hello" on a go ld background . 11 . Forml .Text should be Me.Text.
13. Red should be replaced with Color. Red.
604 • An swers To Se lected Odd-N um be red Exercises
CHA PTE R 3
EXER CISES 3.1
X y
29
( ... ) Han dles btn Eva luat e.C lick
Priv ate Sub btnE valu a t e Clic k 0 0
Dim x, y As Dou ble 2 0
X = 2 2 6
y = 3 * X 11 6
X = y + 5 11 6
lstR esu lts. Item s.C lear () 11 6
lstR esu lts. Item s.A dd( x + 4) 11 7
y = y + 1
End Sub
35. 1 37 . 2
31. 6 33. 1
64 15
8
9
EXERCISES 3.2
1. Visual Basic 3. Ernie 5. flute 7. 123 9. Your age is 21.
11. A ROSE I S A ROSE IS A ROSE 13. 5. 5 15. goodbye 17. WALLAWALLA
19. ABC 21. 12 23. 8 ( 0 through 7) 25. True
2 MUNICIPALITY
4 city
55 mph 6
STU
27. The variable phoneNumber should be declared as type String, not Double.
29. End is a keyword and cannot be used as a variable name.
31. The Ind exOf method can not be applied to a number, only a string.
33. Private Sub btnDisplay_ Clic k ( . . . ) Handles btnDisplay.Click
Dim firstName, middleName, lastName As Str ing
Di m y earOfBirth As Integer
firstName = "Thomas"
middleName = "Alv a"
lastName = "Edison"
y earOfBirth = 184 7
txtOutput . Text firstName & " " & middleName & " " & lastName &
", " & yearOfBirth
End Sub
m
37. Dim str As String 'Place in the Decla ration s sectio n of the progra
mpute .Click
39. Privat e Sub btnCom pute_ Click( ... ) Handle s btnCo
Dim distan ce As Doub l e
distan ce= CDbl(t xtNum Sec.Te xt) I 5
distan ce = Math.R ound(d istance , 2)
" & distan ce & "mile s."
txtOu tput.T ext = "The distan ce of the storm is
End Sub
mpute .Click
41. Privat e Sub btnCom pute Click( ... ) Handle s btnCo
Dim cyclin g, runnin g , swimm ing, pounds As Double
cyclin g= CDbl( txtCyc le.Tex t)
runnin g = CDbl(t xtRun . Text)
swimm ing= CDbl(t xtSwim .Text)
pounds = (200 * cyclin g + 475 * runnin g + 275
* swimm ing) I 3500
pounds = Math.R ound(p ounds, 1)
txtWtL oss.Te xt =poun ds & "poun ds were lost . "
End Sub
mpute .Click
43. Privat e Sub btnCom pute_ Click( ... ) Handle s btnCo
Dim revenu e , expens es, income As Double
revenu e = CDbl( txtRev enue.T ext)
expen ses= CDbl( txtExp enses. Text)
income = revenu e - expens es
txtNet incom e.Text = CStr(in come)
End Sub
Expenses: 15
Percentage t ip :
mpute .Click
45. Privat e Sub btnCom pute_ Click( ... ) Handle s btnCo
Dim amoun t, percen tage, tip As Double
amoun t = CDbl(t xtAmo unt.Te xt)
percen tage = CDbl( txtPer centag e.Text )
tip = amoun t * (perce ntage I 100)
txtTip .Text = CStr(M ath . Round (tip, 2))
End Sub
ssMe. Click
Privat e Sub btnPre ssMe Click( ... ) Handle s btnPre
numbe r = numbe r - 1 'decre ase numbe r by 1
txtOu tput.T ext = CStr(n umber )
End Sub
Answ e rs To Se lected Odd-N umbered Exerc ises
• 609
Press Me
100
[ Modify Sentence ]
What you donl owe wonl hurt you . -
Distance skidded : 54
EXERCISES 3.3
5. 0.0 7. -0.6 7 9. 12,3 46.0 00 11. 12
1. 1,23 5 3. 1,23 4.0
15. ($0.2 3) 17. $0.8 0 19. 7.50 % 21. 100.0 0%
13. $12, 346
Month (1 - 12): 2
Year: 2: 11
Number of days : 8
e ind er
Name : Gabriel
OK
Phon e number:
CHAP TER 4
EXERCISES 4.1
1. hi 3. The letter before G is F
[In Exercis es 46 throug h 49, exec ute a s t a t e m e nt o f the fo rm txtout put. Text = Boolea n
expres s ion.]
47 . True 49. Fa lse 51. F a lse 53. T r u e 55. Tru e 57. Fa lse 59. T ru e
EXERCISES 4.2
1. Less than ten. 3. tomorr ow is ano t her day. 5. 10
7. To be, or not to be . 9. Hi 11. You are old enough to vote in 7 days .
13. Syntax e rror. T h ird line sh o uld be If ( (1 < num) And (num < 3)) Then
15. Syntax e rro r. Fo urth line sh o u ld be If ( (major = "Busin ess") Or (major "Comp uter
Scienc e" ) ) Then
17. a = 5
I = I @] L ..i"i. .I
a... 4.2 Exerci_ e 25 l = I @] ~~ •J 11_. 4.2 Exercise 27
Average : &5
Correct .
[I .2 Exercise 29 •2 Exercise 31
Weig ht : li
a ~
4.2 Exercise 33 l = I @) l...tJ "l!J
( Bogart
I[ Raines
l
I came to Casablanca for the waters .
But we're in the middle of the desert .
I was misinformed .
-
d Exe rcises
616 • Ans wers To Selected Odd -Num bere
min e . Clic k
Clic k( ... ) Han dles lblD eter
39. Priv ate Sub btnC omp ute_
Dim day As Stri ng
Dim day l, day2 As Dat e
Dim num Day s As Dou ble
t
day = "1/1 /" & txtY ear. Tex
day l = CDa te(d ay)
day2 = day l.Ad dYe ars( l)
val. Day , day l, day2 )
num Day s = Dat eDi ff(D atei nter
Answ ers To Select ed Odd -N umbered Exerc ises
• 617
EXERCISES 4.3
1. The price is $3.75
3. Meso zoic Era
The price is $3.75 Paleo zoic Era
?
5. The equa tion has no real solut ions.
The equa tion has two solut ions.
The equa tion has exac tly one solut ion.
"
9. Case nom = "Bob" sh o uld be Case "Bob
"PEACH" .
11. Logic e rror: >= "Peac h" sh o uld b e >=
be " ORANGE" To "PEA CH".
Synta x e rro r: " ORANGE TO PEACH" sh o uld
Case Is > 5
txtOu tpu t.Tex t "t wo "
En d Sele ct
Case 2
length= CDbl(InputBox("Input the length of the parallelogram: "))
height= CDbl(InputBox("Input the height of the parallelogram: "))
txtArea.Text = CStr(length * height)
Case 3
length= CDbl(InputBox("Input the length of the kite: "))
width= CDbl(InputBox("Input the width of the kite: "))
txtArea.Text = CStr((length *width) I 2)
Case Else
MessageBox.Show("Your choice is not valid.", "Try Again.")
mtbSelection.Clear()
End Select
mtbSelection.Focus()
End Sub
Display lnfonnation
EXERCISES 4.4
Group Box 1.
1. The word "Income" becomes the caption embedded in the top of
3. The CheckB oxl check box becomes (or remain s) unchecked.
Answers To Se lected O dd-N umbered Exercises • 621
ior.Ch ecked Or
If (radFr osh.Ch ecked Or radSop h.Chec ked Or radJun
radSen ior.Ch ecked) Then
yearS electe d True
Else
yearS electe d False
End If
If major Select ed And yearS electe d Then
Messa geBox .Show ("Infor mation Proces sed")
Elseif Not major Select ed Then
If Not yearS electe d Then
Year." )
Messag eBox.S how("Y ou must select a Major and a
Else
Messag eBox.S how("Y ou must select a Major .")
End If
Else
Messag eBox.S how("Y ou must select a Year." )
End If
End Sub
CHAPTER 5
EXERCISES 5.1
1. 203 3. The population will double in 24 years.
5. 27 is an odd nwnber. 7. Your state income tax is $150 . 00.
9. age before beauty
11. The function header should end with "As String", not "As Integer".
,
Functio n Profit(B yVal popcorn As Double, ByVa l butter As Double
ByVal bucket As Double, ByVal price As Double) As Double
'Calcul ate the profit on a bucket of popcorn
Return price - (popcorn + butter + bucket)
End Functio n
ck
19. Pr ivat e Sub btnComp ute_ Click( ... ) Handles btnCom pute.Cli
Dim weight As Double
weight = CDbl(tx tWeight .Text)
txtOutp ut.Text "The cost of mailing the letter was " &
FormatC urrency( Cost(we ight)) & "·"
End Sub
23. Privat e Sub btnDete rrnine_ Click( ... ) Handle s btnDet errnine .Click
If IsLeap Year(C int(mtb Year.T ext)) Then 'mask is 0000
txtOut put.Te xt mtbYea r.Text & " is a leap ye ar."
Else
txtOut put.Te xt mtbYea r.Text & " is not a leap year."
End If
End Sub
EXERCISES 5.2
1. 88 keys on a piano 3. You look dashing in blue.
5. 1440 minute s in a day 7. Why do clocks run clockw ise?
Becaus e they were invente d in the northe rn
hemisp here where sundia ls go clockw ise.
9. It was the best of times. 11. divorce d 13. 24 blackb i rds
It was the worst of times. behead ed baked in
died a pie.
divorce d
behead ed
survive d
15. The first 6 letters are Visual . 17. cost: $250.00
Shippin g cost: $15.00
Total cost: $265.00
19. You passed with a grade of 92.
21. There is a parame ter in the S ub proced ure, but no argume nt in the stateme
n t ca lling the
Sub proced ure.
23. S ince Handle s is a keyword , it cannot be used as the name of a S ub procedu
re.
25. Privat e Sub btnDis play_ Click( ... ) Handle s btnDis
play.C lick
Dim num As Intege r = 7
Lucky(n um)
End Sub
a • 5.2 Exercise 29
..
gW 5.2 Exercise 33 l = I @) l;._.n_l
( Display Verses of Old McDon ald Had a Farm
)
Old McDonald had a farm . Eyi eyi oh .
Arid on his farm he had a lamb . Eyi eyi oh .
With a baa baa here . and a baa baa there .
Here a baa . there a baa . everywhere a baa baa .
Old McDonald had a farm . Eyi eyi oh .
&
txtO utpu t . Text "The h i ghes t two grad es are " & first
" and " & secon d & " "
End Sub
EXERCISES 5.3
.
1. Gabr iel was born in the year 1980
Forg et Me Not.
3. The state flow er of Alas ka is the
EDU.
5. The first 3 lette rs of EDUCATION are
13. Private Sub btnCalcula te_ Click( ... ) Handles btnCalcula te.Click
Dim annualRat eOfinteres t, monthlyPay ment, begBalance As Double
Dim intForMont h, redOfPrinc ipal, endBalance As Double
InputData( annualRate Ofinterest, monthlyPay ment, begBalance )
Calculate( annualRat eOfinteres t, monthlyPay ment, begBalance ,
intForMont h, redOfPrinc ipal, endBalance )
DisplayDat a(intForMo nth, redOfPrinc ipal, endBalance )
End Sub
CHAPTER 6
EXERCISES 6.1
1. 18 3. 10 5. Maximum number: 7
7. Infinite loop. (To end the program, click on the Stop Debugging button on the Too lbar.)
9. Do and Loop are interchange d 11. While num >= 7 13. Until response< > "Y"
630 • Answers To Se lec ted O dd-N um bered Exercises
15. Until name= "" 17. until (a<= 1) Or (a >= 3) 19. While n 0
k
21. Private Sub btnDisp lay_ Click( ... ) Handles btnDisp lay.Clic
'Reques t and display three names.
Dim name As String, num As Integer = 0
Do While num < 3
name = Inpu tBox ("Enter a name: ")
lstOutpu t.Items. Add(nam e)
num +=1 'Add 1 to value of num.
Loop
End Sub
23. Private Sub btnDisp lay_ Click( ... ) Handles btnDisp lay . Click
Dim celsius As Double = 10
lstOutp ut.Items .Add("C elsius Fahrenh eit")
Do While celsius <= 95
" & celsiu s & " II &
lstOutp ut.Items .Add("
Fahrenh eit(cels ius))
celsius += 5
Loop
End Sub
25. Private Sub btnLoca te_ Click( ... ) Handles btnLoca te.Click
Dim word As String = ""
Dim rPlace, nPlace As Integer
Do
InputWo rd(word)
rPlace word. IndexOf ( "r")
nPlace = word. IndexOf ( "n")
Answers To Selected Odd-N umbered Exercises • 631
r)
Sub Inputin tegers( ByRef mAs Intege r, ByRef n As Intege
m = Cint(tx tM.Tex t)
n = Cint(tx tN . Text)
End Sub
pute.Cl ick
31. Private Sub btnCom pute_ Click( . .. ) Handle s btnCom
Dim age As Intege r = 1
Do While 1980 + age <> age A 2
age += 1
Loop
txtOu tput.Te xt age & " years old"
End Sub
ermine .Click
33. Private Sub btnDet ermine _ Click( ... ) Handle s btnDet
Dim amount As Double 100
Dim yrs As Intege r = 0
Do Until amount < 1
amount = 0.5 * amount
yrs += 28
Loop
txtOut put. Text yrs & " years"
End Sub
ermine .Click
35. Private Sub btnDete rmine_ Click( ... ) Handle s btnDet
Const INTEREST PER MONTH As Double = 0 . 005
Dim loanAm ount As Double = 15000
Dim months As Intege r = 0
Dim balanc e As Doubl e = loanAm ount
Do Until balanc e < loanAm ount I 2
balanc e = (1 + INTEREST_ PER_ MONTH) * balanc e - 290
months += 1
Loop
txtOut put.Te xt months & " months "
End Sub
ermine .Click
37. Private Sub btnDete rmine_ Click( ... ) Handle s btnDet
Dim months As Integer = 0
Dim balanc e As Double = 10000
Do Until balanc e < 600
balanc e = 1.003 * balanc e - 600
An swers To Selec ted O dd -N umbe red Exerc ises
• 633
mont hs += 1
Loop
txtO utpu t . Text mont hs & 11 mont hs; 11
& Form atCu rrenc y(bal ance )
End Sub
( Determine Vll'hen Loan is Ha~ Paid Off ) ( Determine ,,'ll'hen Balanc e Is Less Than ~ 1
nmon ths 17 months ; "-73.91
EXERCISES 6.2
1. Pass #1 3. 2 5. 5 7. ••••• ••••• 9. 4
Pass #2 4 6
Pass #3 6
7
Pass #4 8
Who do we appr eciat e ?
11. The loop is neve r execu ted since 25 is great e r th an 1
and th e step is negat ive.
13. T h e Fo r ... Next loop will not execute since
20 is grea ter than 0. You mu st add step -1 to
the end of the For state ment .
15. Priv ate Sub btnD ispla y_ Click ( ...
) Hand les btnD ispla y.Cl ick
For num As Integ er = 1 To 9 Step
2
lstBo x.Ite ms.A dd(n um)
Next
End Sub
4
f.) lJ 11,} 6.2 Exe rcise 19
8
10 Rnd Average of Rve Numbers
12
14
15 ~
85:'1
l = I §) I. S2 ~J
D~ 6.2 Exercise 23
ck
k( ... ) Han dles btnC alcu late .Cli
23. Priv ate Sub btnC alcu late _ Clic
Dim valu e As Dou ble = 2000 0
For i As Inte ger = 1 To 5
valu e = 0.85 * valu e
lstO utpu t.Ite ms.A dd(i & :
11 11 & Form atCu rren cy(v alue ))
Next
End Sub
k( ... ) Han dles btnC omp ute.C lick
25. Priv ate Sub btnC omp ute_ Clic
0.05
Di m PERCENT RAISE As Dou ble =
As Inte ger, sala ry As Dou ble
Dim name As Stri ng, age
Di m earn ings As Dou ble = 0
name = txtN ame .Tex t
age = Cint (txtA ge.T ext)
sala ry= CDb l(txt Sala ry.T ext)
For i As Inte ger = age To 64
earn ings += sala ry
E * sala ry)
sala ry = sala ry + (PERCENT_ RAIS
Nex t
name & 11 will earn abou t
11 &
txtO utpu t.Te xt
Form atCu rren cy(e arni ngs, 0) & 11 11
End Sub
( Compute E.amings
D 6 2 Exercise 31 l = I @) ~~ J
.Allalyze Radio activ e Decay J
.Cli ck
Clic k( ... ) Han dles btn Dis play
33. Priv ate Sub btnD ispl ay_
ble
Dim pric e, qua ntit y As Dou
lstO utp ut.I tem s.C lear ()
in mil lion s of bus hels
qua ntit y = 80 'cur ren t crop of soy bea ns
" & "PR ICE ")
& " " & "QUANTITY" & "
lstO utpu t.Ite ms. Add ("Y EAR "
For yr As Inte ger = 2010 To
2020
* qua ntit y
pric e = 20 - 0.1 &
tem s.A dd( yr & " " & For mat Num ber( qua ntity )
lstO utp ut.I ))
" & For mat Cur renc y(p rice
qua ntit y 5 * pric e - 10
Nex t
End Sub
btnA naly zeO ptio ns.C lick
Priv ate Sub btnA naly zeO ptio ns Clic k( ... ) Han dles
35.
'Com pare sala ries
Dim opt1 , opt2 As Dou ble
opt1 = Opt ion1 ()
opt 2 = Opt ion2 () t1))
n 1 " & Form atCu rren cy (op
lstO utp ut. Item s. Add ("O ptio Cur renc y(op t2))
n 2 " & For mat
lstO utpu t.Ite ms. Add ("O ptio
If opt1 > opt2 The n
n 1 pay s bet ter. ")
lstO utpu t.Ite ms. Add ("O ptio
E1s eif opt1 = opt2 The n
ns pay the sam e.")
lstO utpu t.Ite ms. Add ("O ptio
Else
2 pay s bet ter. ")
lstO utp ut.I tem s.A dd ( "Op tion
End If
End Sub
a~ 6, Exerci"-e 35
Option 1 = <!1.
Option 2 = S1 .
Option 2 pa>,'S better.
EXERCISES 6.3
or
Private Sub btnCoun t_ Click( ... ) Handles btnDete rmine.C lick
Dim college As String = txtColle ge.Text
Dim i As Integer = 0
Dim found As Boolean = False
Do Until (found = True) Or (i = lstBox.I tems.Co unt)
If CStr(ls tBox.It ems(i)) =colleg e Then
found = True
End If
i += 1
Loop
If found Then
txtOutp ut.Te xt "YES"
Else
txtOutp ut.Text "NO"
End If
End Sub
a 6.3 Exercise 15
1 -
Michigan
W ashington State r, Notre Dame
Oregon
Mare Island
Great Lakes Determine if College has
Harvard Won a Rose Bowl
califomia
1
Califomia YES
usc
W ashington
~ I
I Notre Dame
k
17 . Private Sub b tnRever se_ Click( ... ) Handles btnReve rse.Clic
Dim highest index As Integer = lstBox.I tems.Co unt - 1
For i As Integer = highest index To 0 Step -1
lstBox2 .Items.A dd(1stB ox.Item s(i))
Next
End Sub
Click
19. Private Sub btnAlph abetize_ Click( ... ) Handles btnAlph abetize.
lstBox2 .Sorted =True
Dim highest index As Integer = lstBox.I tems.Co unt - 1
For i As Integer = 0 To highest index
lstBox2 .Items.A dd(lstB ox.Items (i))
Next
End Sub
Answe rs To Selected Odd -N um bered Exercises
• 639
us
Washington State
Oregon
Mare Island
_] usc
usc
u
Great Lakes Texas
Harvard Texas
California usc
California Oklahom a
usc Miami
Washin gton Washin gton
Notre Dame ...... Wiscon sin
Vl/isconsin
( Reverse Ust
1
Michigan ...-
..
a..J 6.3 Exereise 9 l = I@] I~· ~ J
[ Jphabetize States )
Delaware .. Alabama ....
Pennsylvania
New Jersey
Georgia
[l Alaska
Arizona
Arl<ansas
u
Connecticut California
Massachusetts Colorado
M a r1~and Connecticut
South Carolina Delaware
New Hampshire .... Rorida ....
...
C· 6.3 Exercise 23 l= l @) l~ d
Pennsylvania Pennsylvania
New Jersey
Georgia
Connecticut
l_J Georgia
Connecticut
Massachusetts
F! -
Delaware
J [ Display Name of Rrst State )
Delaware ;
Pennsylvani a Pe nnS}~v a ni a
New Jersey New Jersey 0
Georgia 6 Georgia
Connecticut Connecticut Delaware
Massachusetts Massachusetts
Maryland M a r,~ a n d
South Carolina South Carolina
New Hampshire Ne•N Hampshire ...-
31. Pr i vate Sub btnDispl ay_ Click( ... ) Handles btnDispl ay.Click
txtOutpu t.Text = CStr(lstB ox.Items (O))
End Sub
35. Priv ate Sub btnRecor d_ Click( ... ) Handles btnRecor d.Click
lstGrad es .Items.Ad d(txtGrad e . Text)
txtGrade. C lear()
txtGrade . Focus ()
End Sub
Answ ers To Selec ted O dd -Num bered Exerc ises
• 643
. Jas a ,{!.[
I A.n~on a ~,
!Arkansas -
Califomia
Record Grade 71
Colorado
85 Search For
Connecticut
B& State
Calcul ate .l'..verage Delaware
91
Grade and Range Rorida
78
Georg ia
87
A.\l·erage grade : 7 Hawa ii
Idaho ..-
Range : :9 .Arizon a begins with .Ar.
ise
644 • Answ ers To Selected Odd -N umbe red Exerc
Else
txtO u t put. Tex t "No s t ate begi ns with " &
mt bF i rstT woL etter s . Text & "·"
End If
End Sub
CHA PTE R 7
EXERCISES 7.1
5. Yes 7. 1 2
1. 101 3. Hav e a d e sser t spoo n .
25. 4
6
2
orde r)
27. a. Sup erio r (last nam e in alph abet ical
b. Erie (fi rst n ame in alph abe t ica l orde r)
(. Huro n (first na me in th e array)
d. Sup erio r (las t n ame in the array )
e. 5 (num ber of na mes in the array )
f. Ont ario (seco nd na me in t he array )
g. 3 (first array subscript whose elem ent is Erie)
I
-
Ruth
Thomas I
k( ... ) Han dles btnD ispl ay.C lick
49. Priv ate Sub btnD ispl ay_ Clic
ile.R eadA llLi nes( "Dig its.t xt")
Dim strD igit s() As Stri ng= IO.F
Dim freq (9) As Inte ger
.Cou nt - 1
For i As Inte ger = 0 To strD igits
freq (Cin t(str Dig its(i ))) += 1
Next
lstO utpu t.Ite ms.A dd(" Dig it Freq uenc y")
For i As Inte ger = 0 To 9
" & i & " " & freq (i))
lstO utpu t.Ite ms.A dd("
Nex t
End Sub
l = I §J l...t:S·-:"!_,J
ll
- 7. E ercis e 49
4 2
~ 4
6 3
2
3 3
9 3
-
Process Eggs
5 .Jumbo eqg3
9~ ~ xtraLarge e gg3
7E Large e gg3
9E Me dium e ggs
77 Smal l e gg3
Ligh t e st e gg : 1 ounc e 9
Heav i e 3t egg : 2 . E9 ounce 3
648 • Answ ers To Se lected Odd -N umbe red Exe rcises
)
File . Read AllL ines ("Co lors . txt"
55. Dim colo rs () As Stri ng = IO.
) Han dles btnD ispl ay.C lick
Priv ate Sub btnD ispla y_ Clic k( ...
er.T ext.T oUp per
Dim lett er As Stri ng = mtb Lett
lstC olor s.Ite ms. Clea r()
rs
For Each hue As Stri ng In colo
If hue. St arts Wit h(le tter ) Then
lstC ol ors.I tems .Add (hue )
End If
Next
End Sub
ile.R eadA llLi nes( "Co lors .txt" )
57. Dim colo rs() As Stri ng= IO.F
) Han dles btnD ispl ay.C lick
Priv ate Sub btnD ispl ay_ Clic k( ... 'mas k L
Lett er.T ext.T oUp per
Dim lett er As Stri ng = mtb
lstC olor s.Ite ms. Clea r()
llerA rray (lett er)
For Each hue As Stri ng In Sma
lstC olor s. Item s.Ad d(hu e )
Nex t
End Sub
er As Stri ng) As Stri ng()
Fun ctio n Sma llerA rray (ByV al lett
As Stri ng
Dim smA rray( colo rs.C oun t - 1)
Dim coun ter As Inte ger = 0
rs
For Each hue As Stri ng In colo
If hue. S tarts Wit h (l ette r) Then
smA rray (cou nter ) = hue
coun ter += 1
End If
Next
- 1)
ReDi m Pres erve smA rray (cou nter
Retu rn smA rray
End Fun ctio n
EXERCISES 7.2
5. 6 7. 103 9. 8
1. 5 3. goin g
7 offe r
can 't
13. 15
11. 3 stud ents have a grad e of 100 12
st grad e is 80
15. The aver age afte r drop ping the lowe
17. 37 is a prim e num ber
) Han dles btnD ispl ay.C lick
19. Priv ate Sub btnD ispl ay_ Clic k( ... 10, 21}
8,
Dim num s() As Inte ger = { 3, 5,
Dim quer y = From num In nums
Whe re num Mod 2 = 0
Sele ct num
" even num bers "
txtO utpu t.Te xt = quer y.co unt &
End Sub
Displa)' Output
Display Output
a...J
~
7. Exerc i e 25 l= I §l I~ ·:~J
ll ~ 7 2 Exerci se 23 l= l·§l I~ J
( Display Super Bowl ~'inners
]
I Display Output
) 49ers
Bears
;.
lA
6
Bronc os
Buccaneers
u
Chiefs ....
quer y
For Each stat e As Stri ng In
lstO utpu t .Item s.Ad d(st a t e)
Nex t
End Sub
Display States
a 7.2 Exercise 29 l = I @) 1•·..-tJ .J
Connecticut
Delaware
Evaluate Grades Georgia
Maryl and
Average grade : 83.25 Mass achusetts
Ne'N Hampshire
54 . 1 7~~ New Jersey
Percentage abov e average :
lick
k( ... ) Han dles btnD ispl ay.C
33. Priv ate Sub btnD ispl ay_ Clic ines ("U SPr es.t xt")
From pres In IO.F ile.R ead AllL
Dim quer y t
"c) .Las
Let lastN ame = pre s.Sp lit("
Ord er By lastN ame
Sele ct pres
For Each pres As Stri ng I n quer y
lstO utpu t.Ite ms. Add (pre s)
Nex t
Dis tinc t
End Sub
Display Presidents
John Adams
John Q. Adams I]
Chester Arthur
James Buchanan
Martin Van Buren
George H. W . Bush
George IN. Bush
ns.t xt")
IO.F ile.R ead AllL ines ("N atio
35. Dim nati ons () As Stri ng=
. . . ) Han dles MyB ase . Load
Priv ate Sub frmN atio ns _ Load (
ons
lstN ati ons. Dat aSo urce = nati
ons .Sel ecte dite m = Not hing
lstN ati
End Sub
Tex tCha nged
nged ( ... ) Han dles txtN atio n .
Priv ate Sub txtN atio ns_ Tex tCha
Dim quer y From nati on In nati ons
atio n . Tex t)
Whe re nati on.S tart sWi th(t xtN
Sele ct na ti on
lstN ati ons . Data Sou rce = que ry.T oLi st
hing
lstN atio ns. Sele c tedi tem = Not
End Sub
Answers To Selected O dd-N umbered Exercises • 653
EXERCISES 7.3
1. The are a of a football field is 19200 square yards .
3. Duke was founded in NC in 1838. 5. heights are same
170
11. In the event procedure, peace should be prize. peace and yr should be prize. y r .
13. The condition {game1 > game2) is not va lid. Structures can only be compared one field
at a t ime.
15. The cities in Texas, along with their populations. T he cities are ordered by the size of
the ir populations beginn ing with the most popu lous city.
a 7.3 E erci::;e 15
( Display Justices )
John Stevens
Jlvitonin Scalia
Anthony Kenned y
Oarenc e Thoma s
Ruth Ginsbu rg
Stephen Breyer
John Roberts
~muel Alito
nia Sotomayor
For i As Integer = 0 To n
data= group(i) .Split(","c)
people(i) .name = data(O)
people(i) .dateOfBirth = CDate(data(l))
Next
End Sub
IJ ~ 7.3 Exercise 35
Display Table
EXERCISES 7.4
1. 1 3. 3 5. 55 7. 14 9. 2 11. 55
'us e LINQ
Dim query From num In nums .Cast(Of Double)()
Where (num Mod 2 = 0)
Select num
lstOutput .Items . Add(query. Sum)
Display Resu~s I
17. 12
19. Private Sub btnDisplay _ Cli ck ( . .. ) Handles btnDisplay . Click
'Display a company' s inven tory from its two stores
Dim inventory ( , ) As Intege r = {{25, 64, 23}, {30 , 82, 19}}
Dim sales(, ) As Intege r = {{7 , 45, 11}, {4, 24, 8}}
Dim total(2 ) As I n teger
'Adjust the inventory val u es to reflect today's sales
For store As Intege r = 1 To 2
For item As Integer = 1 To 3
inventory (s t ore - 1 , i t em - 1)
An swers To Se lected O dd -N umbere d Exe rc ises
• 66 1
a.,. 7. Exercise 21
30
6
s E.lROL LHENT
l
_ 96
E ·L LU1EH
_g
50
a.. 7.4 E){ercise 19 l= I@) 1- £1 J 05
g
69
Display Inventory per Store and ~ em ... 6
I _3
2 3
IOAL 5
9 49
li_ 26 52 .1 95
5
J
21. Pr ivat e Sub btnDis play_ Click ( .. . ) Handle s btnDi
splay. Click
'Displ ay the course and c ampus enroll ments
'enrol lment array named er
Dim er(,) As Int e ger= {{5, 15, 22 , 21, 12, 25,
16, 11, 17, 23},
{11 , 2 3 , 51, 25, 32, 35, 32, 52, 25, 21},
{2, 12 , 32, 32, 25, 26, 2 9, 12 , 15, 11}}
'Def i ne the a r ray s to accum ulate the inform ation
Dim campu sTotal (2) , course Total( 9) As Intege r
For campus As Intege r = 0 To 2
For course As Intege r = 0 To 9
campu sTotal (c ampus) += er(cam pus, course )
c ourseT otal (cours e) += er(cam pus , course )
Next
Next
'Displ ay the campus enroll ment
l s tOutpu t . Items . Add ("CAMPUS ENROLLMENT")
For campus As Intege r = 0 To 2
lstOut put.Ite ms.Ad d((cam pus + 1) & ": " & campu
sTotal (camp us))
Next
' Displa y the course enroll ment
662 • A nswers To Se lected Odd -Numbered Exercises
Exercise 23
um 1 S))
) & ": " & Form atN umb er(s
lstO utp ut.I tem s.A dd( nam es(i
Nex t
s
' Dis pla y med ian on the exam
I tern s. Add ("Ex am Med ians ")
1 s tOu tpu t.
cou nt I 2)
eve n= (In t(co unt I 2) =
0 To 4
For exam As Inte ger =
+ 1 & ": " &
lstO utp ut.I tem s.A dd( exa m , eve n))
Me dian (sco res, cou nt, exam
Nex t
End Sub
Name : Exam 1:
Exam 2:
Add Student
Exam 3:
Exam :
Display Report
Exam 5:
~
c'"'
ary : 32 . 6
_ _ _ : gs . 6 Displ ay Sales
cot t : S3 . _
xarr. Hed ia.:J s I Sa _ es per sto re
- · g2 1 : &3, 6 _8 . 30
2 : 90
2 : &11 ,2 5 . 9
3: =7 3 : 59, _ 07 . 4
4 : 82 1
:ot a _ sa es : S29 ,u _ . 6J
5 : <>'
C H APTER 8
EXERCISES 8.1
1. Samuel Alito,N J 3. Alito was appoin ted by Bush
Henry Baldwi n,PA Baldwi n was appoin ted by Jackson
7. T he new file contains the full names of the justices whose last name begins
with the letter
Band the years they were appo inted to the court. The justices are ordered
by the year they
were appo inted.
9. The new file is the same as the original file except that the last three fields
have been
de leted from each record.
11. T he new fi le con ta ins the names of the people who subscrib
e to either the New Yo rk
Times or the Wall Street Journal, or both.
13. T he new file conta ins the names of the people who subscribe to the New
York Times but
not the Wall treet Journal.
15. Privat e Sub btnBot h_ Click( ... ) Handle s btnBot h.Click
'Create a file of presid ents who were also vice presid
ents
Dim vicePr es() As String = IO.File .ReadA llLines ("VPre
s.txt")
Dim presid ents() As String = IO . File.Re adAllL ines("U
SPres.t xt")
Dim both() As String = presid ents.In tersect (viceP res)
.ToArra y
IO.File . WriteA llLines ("Both .txt", both)
Messag eBox.S how(bo th . Count & " presid ents", "File Created
")
End Sub
a~ 8. Exe rcise 17
19. Dim countr ies () As String = IO. File . ReadAl lLines ("UN
. txt")
'lstCon tinents was filled at design time
Privat e Sub lstCon tinents Selecte dindex Change d( ... )
Handle s
lstCon tinents .Select edinde xChan ged
Dim selecte dConti nent As String = lstCon tinents . Text
If selecte dConti nent = "Antar ctica" Then
666 • Answe rs To Selecte d Odd-N umbered Exercises
a~ 8.1 Exercise 19
l = I @] 1-fA · J
25.1 24 .000
State
State
r
Percentage of ,..
Abbreviation I ., State
Total Area
AK ALASKA. aska 15.9 i:
Sele ct stat e
ces. txt" , quer yl . Exc ept( quer y2))
I O. F i le.W ri teAl lLin es ( "NoJ usti
End Sub
~========er=e&=e=R=Ie========~~ ~~ =========er=e&=e=R=Ie========~
.txt" )
IO.F ile . Rea dAl lLin es(" Just ices
33. Dim just ices () As Stri ng=
Han dles Crea te . Clic k
Priv ate Sub Crea te_ Cl ick ( . . . )
Dim quer y From line In just ices
Let stat e= l ine. Spl it(" ,"c) ( 3)
Orde r By stat e Asce ndin g
fJus tice s(sta te )
Sele ct stat e & "," & Nwn berO
Dis tinc t
.txt" , quer y)
IO.F i l e . Wr i teAl lLin es(" New File
End Sub
stat e As Stri ng) As Inte ger
Fun ctio n Num berO fJus t i ce s(By Val
Dim que ry = From line In jus t ices
Let plac e= l ine. Spl it(" , "c) (3)
Whe re p lace = stat e
Sele ct plac e
Retu rn quer y . Coun t
End Func t ion
Answe rs To Se lected O dd -Numbered Exercises
• 669
35. Priva te Sub btnDi splay Click ( ... ) Handl es btnDi splay .Click
Dim query From state In IO.Fi le.Re adAll Lines ("USS tates.
txt")
Let data= state .Spli t(","c )
Let name = data(O )
Let abbre v = data( l)
Let area= Forma tNum ber(da ta(2), 0)
Let pop= Forma tNum ber(da ta(3), 0)
Order By name
Selec t name, abbre v, area, pop
dgvSt ates.D ataSo urce = query .ToLi st
dgvS tates. Curre ntCel l = Nothi ng
End Sub
a~ 8. _ ercise 35
.L h .7- c
A 571. 51
z 113.&35
R 5 ..
P.. 15 .~5
___,
Colorado co
EXERCISES 8.2
1. Hello 3 . Bon Jour 5. You must enter a numbe r.
7. Error occur red. 9. File Ages .txt conta ins an inval id age.
11 . The file W elco me.tx t is create d and ha the fo llowin g lines:
Hello
Bon Jour
Create File I ,
I . __(_Add-~en_ to Fi_ile --J
~============~
les btnA dd.Cl ick
21. Priva te Sub btnAd d_ Click ( .. . ) Hand
'Appe nd item to a text fi l e
ndTe xt("C owbo y.txt" )
Dim sw As IO.St ream Write r = IO.F ile . Appe
,20.5 0 " )
sw.W riteL ine(" Winc heste r Rifle
sw.C lose ()
to the file .", "DONE")
Messa geBox .Show ("The item has been added
End Sub
[ Display File ]
item cost
--
Co~ Peacem aker 12.20
sr .Clo se ()
sw . Clos e()
Mes sage Box .Sho w("I tem adde d to
Cow boy2 .txt" )
txtit em. Clea r()
txtP rice .Cle ar ()
End Sub
9.00
EXERCISES 8.3
1. N o 3. N o 5. N o 7. No 9. N o
11. <?xm l vers ion= 'l.O '?> inau gura ted . - ->
ages of the pres iden ts when
< !--T hi s file con tain s the
<Pre side nts>
<pr esi dent >
>
<nam e>Ge orge Was hing ton< / name
on >57 </ag eAt inau gua tion >
<age Atin aug uati
</pr es iden t >
<pr esi dent >
<nam e>Jo hn Adam s</n ame >
ugu atio n>
<age Atin aug uati on >6 1</a geA tina
</pr esid ent>
</ Pres iden ts>
lick
k( . .. ) Han dles btnD ispl ay.C
13. Priv a te Sub btnD ispl ay_ Clic oad( "US Stat es.x ml")
t = XEl eme nt.L
Dim stat eDa ta As XEle men
Dat a . Des cen dan ts(" stat e" )
Dim que ry= From st In s tate > .Val ue)
Let pop = Cin t(st . <po pula tion
Sele ct pop
r(qu ery . Sum, 0)
txtO utpu t.Te xt = Form atNu mbe
End Sub
k
k( ... ) Han dles btnD ispl ay . Clic
15. Priv at e Sub btnD ispl ay_ Clic d("U SSta tes.x ml" )
XEle men t . Loa
Dim s ta teD ata As XEle men t =
Answe rs To Se lected Odd-N um bered Exercises
• 673
Dim query Pop From st In stateD ata.D escen dants ("stat e")
Let pop = Cint( st . <popu lation >.Val ue)
Selec t pop
Dim query Area From st In stateD ata.D escen dants ("stat e")
Let area = Cint( st.<ar ea>.V alue)
Selec t area
txtOu tput.T ext Forma tNumb er(que ryPop .Sum I queryA rea.Su m)
&
" peopl e per squar e mile"
End Sub
a~ 8.3 Exercise 17
~
Alaska Different Vowels
571.951
Texas 261.797 Georgia
Connecticut
Califomia 155.959 South Carolina
Montana Rhode Island
147.046 Louisiana
New Mexico 121 ,598 Minnesota
~
[
Func tion Nurn berO fVow els(B yVal word As Strin g) As Inte ger
word = word .ToU pper
Dim num As Inte ger = 0
If word .Inde xOf( "A") <> -1 Then
num += 1
End If
If word .Inde xOf( "E") <> -1 Then
num += 1
End If
If word . Inde xOf ("I") <> - 1 Then
num += 1
End If
If word . Inde xOf { "0") <> -1 Then
num += 1
End If
If word . Inde xOf ( "U" ) <> - 1 Then
num += 1
End If
Retu rn num
End Func tion
men t.Lo ad(" Coll eges .xml ")
21. Dim coll eges As XEle ment = XEle
) Hand les btnD ispla y.Cl ick
Priv ate Sub btnD isp lay_ Cl ick ( ...
. xml loca ted in the give n stat e
'Dis play the coll eges in Coll eges 'mas k LL
tate. Text .ToU pper
Dim chos enSt ate As Strin g = mtbS ege" )
Desc enda nts ("co ll
Dim quer y= From col I n co l lege s.
Let name = col. cnam e > .Val ue
Let stat e = c ol.c stat e >. Valu e
>. Valu e
Let year Foun ded = col. cyea rFou nded
Wher e stat e = chos enSt ate
Orde r By name Asce ndin g
Sele ct name & " " & year Foun ded
lstC olle ge s.Da taSo urce = quer y.To List
lstC olle ges. Sele cted item = Noth i ng
End Sub
ment .Loa d("C olleg es .xml ")
23. Dim coll eges As XEle ment = XEle
) Hand les MyB ase.L oad
Priv ate Sub frmC olleg es _ Loa d( ...
into the left list box
'Plac e the year s for each colle ge
colle ges. Desc enda nts( "col lege " )
Dim quer y= From col In
.Val ue
Let year Foun ded = col.c year Foun ded>
Orde r By year Foun ded Asce ndin g
Sele ct year Foun ded
Dist inct
For Each yr i n que ry
lstY ears .Item s .Add {yr)
Next
End Sub
hang ed( ... ) Hand les
Priv ate Sub lstYears Sele c tedin dexC
lstY ears . Se lecte dind exCh ange d
ar As Strin g = lstY ears . Text
Dim chos enYe
Desc enda nts(" colle ge")
Dim quer y = From col In colle ges.
Let name = c ol.cn ame> .Val ue
Let year Foun ded = col.c year Foun ded >.Va lue
Wher e year Foun ded = chos enYe ar
Sele ct name
lstC olle ges.D ataS ourc e = quer y.To List
g
lstC olle ges .S elec tedit em = No thin
End Sub
Answ ers To Selec ted Odd -Num bered Exercises
• 675
Oick on a year.
1793 Bowdoin College
U. of Tennessee
25(a).
Priv ate Sub btnS enat e Clic k( ...
) Han dles btnS enat e . Clic k
Dim sr As IO.S tre amR eade r = IO.F
ile.O pen Tex t("S enat elll. txt" )
Dim sw As IO.S trea mW riter = IO.F
ile.C reat eTe xt(" Sen atel ll.xm l")
sw . Wri teLi ne(" <?xm l vers ion= 'l.O
'?>" )
sw. Wri teLi ne ( "< ! - - This file
cont ains data on the lllt h Sena
sw.W riteL ine( "<Se nate lll> ") te -->" )
Dim temp As Stri ng = ""
Do Unt il sr.E ndO fStre am
temp = sr.R eadL ine
sw.W riteL ine( " <sen ator >")
sw . Wri teLi ne(" <nam e>" & tem p.Sp lit(" ,"c) (0)
sw.W riteL ine( " & "</n ame> ")
<s tate >" & temp . Spl it(" ,"c) (1)
& "</s tate >")
sw.W riteL ine( " <par ty> " & tem p.Sp lit(" ,"c) (2)
& "</p arty >")
sw.W riteL ine( " </se nato r>")
Loop
sw.W riteL ine( "< /Sen atel ll > ")
sr . Clos e()
sw. Clos e ()
Mes sage Box .Sho w("F ile Crea ted"
)
End Sub
g 8.3
( Displ- Senators
1~
John McCa in 1\sizona R
25(b).
Priv ate Sub btnD ispl ay_ Clic k( .
.. ) Han dles btnD ispl ay .C lick
Dim sena teDa ta As XEle men t = XEl
eme nt.L oad( "Sen atell l.XM L")
cises
676 • Answ ers To Selected Odd-N umb ered Exer
CHA PTE R 9
EXERCISES 9.1
a. 9.1 Exerci se 17 = @] ~
( Sort Names ]
Abigail
.J.
fl;jdan
Ava Done
Braden
Brianna
Cai~'11
Cait~fll The ordere d fi le ha~ been create d.
Caleb
Chloe
Connor
Emma
B han OK
Isabella
Jacob
Jaden
Kaden
Landon
Madeline
Noah
Olivia
'- -
0
- 9. Exerci s e 25 l = I @] l~.a ~J
EXERCISES 9.2
ds (500 0 mi lliseconds).
1. The Tick eve nt will be trigge red every 5 secon
cur or is hove red over a cont ro L
3. The too ltip will appear one second after the
rderA sc menu item .
5. A chec k mark appears in front of the rnnuO
secon ds.
7. The Tick eve nt wi!l be trigge red every intv ar
is selec ted at rand om and displayed in
9. The name of one of the 44 U .S. presidents
txtB ox.
yed in the list box.
11. Two states are selected at rand om and d ispla
13. The con te nts of the C lipboa rd are delet ed.
is copied into the C lipbo ard.
15. The text curre ntly se lected in txt Box, if any,
17. The cont ents of the C li pboa rd are d isplay
ed in txtB ox.
Secretary Stephanie
Roll Dice
Select Officers
Odds of tossin g 7 are about 1 in
pla y . Cli ck
Cli ck ( . .. ) Han dles btn Dis
57. Pr iva te Sub btn Dis pla y_ fil e
a log box to get the
'Di spla y t he ope n fi l e di
Dim file Sp ec As Str i ng
()
Ope nFi l e Di alog l.Sh owD ial og
= Ope nF i leD i alo gl. File Nam e
f ileS pec
ed in the f i le .
' Dis pla y p i c ture con tain
Fil e( file Spe c )
picB ox. I mag e = Ima ge . From
End Sub
ck
k( .. . ) Han dles tmrM oon . Ti
59. Pr i vat e Sub tmrM oon_ Tic ima ge .
p lay the
'Up date the pha se and dis t i ng is Tru e
s 2 000 ; Tim e r Ena bled set
'Tim er Int erv al set tin g i
pha se += 1
If pha se = 9 The n
pha se = 1
End If se & " . b mp" )
picB ox . Ima ge Ima ge . From Fi l e("M oon " & pha
End Sub
k
ck ( ... ) Han dles tmr Bal l . Tic
61. Priv ate Sub tmr Bal l_ Ti and lab el.
scr oll bar
'Up date the v alu e o f the
er Int erv al set t i ng i s 100 0
'Tim 10
Ball .Ma xim urn
'vsb Bal l. Min i murn = 0 , vsb
cou nt = c oun t - 1
vsb Bal l .Val ue = 10 cou n t
lblB a ll.T ext = CSt r (co u n t)
y the mes sag e and end pro gram .
'If at zer o , dis pla
If cou n t = 0 The n
tmr Bal l. En abl ed = Fal se
YEA R!!! ! " , "NYE" )
Mes sage Box .Sho w (" HAPPY NEW
Me. Clo s e()
End If
End Sub
HAPPY NE hi YEAR!!!!
0
Ans wer s To Selected Odd -Nu mbe red
Exe rcises • 68 1
EXERCISES 9.3
1. $10 6 . 00 3. You r las t nam e beg ins wit h
K.
5. 'Fo rml ' s cod e
Pri vat e Sub btn Dis pla y_ Cli
ck( ... ) Han dles btn Dis pla
For m2. Sho wD ialo g() y.C lick
txtQ uot atio n.T ext = For m2.
quo tati on
End Sub
Rosebud .
Me . Loa d
Act iva ted ( ... ) Han dle s
Pri va te Sub frm Bal anc e_
be r OfY rs) As Yea r
Dim a(fr mM il l i ona ire . num
a(O ) .num = 0 t)
l l i ona i re.t xtA mo unt . Tex
a(O ) .amo unt = CDb l (frmMi 1
a. Cou nt -
Fo r i As Int ege r = 1 To
a(i ) .num = i * a(i - 1) . amo unt
.am oun t = (1 + frmM il lio nai re . INTEREST_ RATE)
a(i )
Ne xt
a
Dim que ry = Fro m yr I n
Let Yea r = yr . n um
cy (y r.am oun t)
Let Amoun t = Forma tCu rren
Sel ect Yea r, Am oun t
= qu ery .To L i st
d gvB ala nce . Dat aSo u r c e
= Not hin g
dgv Bal anc e.C urr ent Ce l l
End Sub
s Me .Fo rmC losi ng
For mCl osi ng( ... ) Han dle
Pri vat e Sub f rmB alan ce
. Cle ar( )
frm Mi l lio nai re.t xtA mo unt
ona ire . txtW hen .C l e ar ()
f rmM illi
t .Fo cus ()
frm Mi l lio na ire . tx tAm oun
En d Sub
EXERCISES 9.4
1. Privat e Sub btnDra w_ Click( ... ) Handle s btnDra w.Clic k
Dim gr As Graph ics = picBo x.Crea teGrap hics
Dim x As Double picBox .Width I 2
Dim y As Double = picBo x.Heig ht I 2
Dim r As Double = x I 2
If r > y I 2 Then
r = y I 2
End If
gr.Fil lEllip se(Br ushes .Black , CSng (x- r), CSng
(y- r),
CSng(2 * r), CSng(2 * r))
End Sub
11 9. Ex:erci e 3 l = l:@l I~ l
Dra•t • Orcle Draw Orcle
'left borde r
gr.Dr awLi ne(Pe ns.Bl ack , 0, 0, 0, 98)
'botto m borde r
gr.Dr awLi ne(Pe ns.Bl ack , 0, 98, 148, 98)
'righ t borde r
gr.Dr awLi ne(Pe ns.Bl ack, 148, 0, 148, 98)
End Sub
les btnC reate .Clic k
7. Priva te Sub btnC reate _ Click ( ... ) Hand
Dim gr As Grap hics = picFl ag.Cr eateG raphi cs
Dim br() As Brush = {Brus hes.O range , Brush es.W hite, Brush es.Gr een}
Dim r As Integ er = 12 'radi us of circl e
99
'p ic Flag. Widt h = 149; picFl ag.H eight =
For i As Integ er = 0 To 2
149, 33)
gr . FillR ectan gle(b r(i), 0, 0 + i * 33,
Next
r, 2 * r, 2 * r, 0, 360)
gr.Fi llPie (Bru shes. Oran ge, 75 - r, 49
, 0, 0, 148, 0) 'top borde r
gr . Draw Line( Pens. Black
Pens. Black , 0, 0, 0, 98) 'left borde r
gr . Draw Line(
'botto m borde r
gr . Draw Line( Pens. Black , 0, 98, 148, 98)
0, 148, 98) 'righ t borde r
gr . DrawL i ne(Pe ns.Bl ack, 148,
End Sub
lick
9. Priva te Sub btnDr aw_ Click ( . . . ) Hand les btnD raw.C
Dim numb ers As Strin g =
1111
l = -1 @) j, _a ...J
g_ 9. Exercise 9
4 5 6 B 9 10 12 13 15 16
0 2 3
CH APT ER 10
EXERCISES 10.1
1. (e ) 3. (d) 5. (b )
se.Lo ad
7. Priva te Sub frmC ities Load( ... ) Hand les MyBa
Data Set.C ities)
itiesT ableA dapte r.Fill (Me. Mega cities
Me.C
End Sub
Answ ers To elected O dd -N um bered Exerc ises
• 685
39. film
d( . .. ) Han dles MyB ase. Loa d
41. Priv ate Sub frmM ovie s _ Loa
e.M ovie sDa taSe t.Li nes )
Me. Lin esT able Ada pter .Fil l(M
e.M ovie sDa taSe t.Ac tors )
Me. Act orsT able Ada pter .Fil l(M
iesD ataS et.L ines
Dim que ry = From line I n Mov
Sel ect line .fil m
Dis tinc t
oLi st
lstF ilms . Dat aSo urce = que ry.T
End Sub
Answ ers To Selected Odd-N umbe red Exe rcises
• 687
Priv ate Sub lstF ilms Sele cted inde
xCh ange d( ... ) Han dles
lstF ilms .Sel ecte dind exC hang ed
Dim quer y From line In Mov iesD ataS et.L ines
Join flic k In Mov iesD ataS et.A
ctor s
On line .film Equ als flic k.fi lm
Whe re line .film = lstF ilms .Tex
t
Sele ct flic k . male Lead
txtL ead. Tex t = que ry.F irst
End Sub
EXERCISES 10.2
7. Add a reco rd to the C ities table whose
name fi lei is emp ty or cont a ins the sa me nam
an already ex isting reco rd . e as
9. (Bin ding Sou rcel .Fin d("n ame ", strV ar)
= 0) And (strV ar <>" Bom bay" )
11. C reate a co ntro l named Bind ingSourc
e2 that has the Co untri es tab le as its Da taM
emb er.
Priv ate Sub Cou ntry Text Box_ Leav
e( .. . ) Han dles
Cou ntry Text Box .Lea ve, Bind ingN
avi gato rl .C lick
Bind ingS ourc e2.P osit ion = Bind
ingS ourc e2.F ind( "nam e",
Cou ntry Text Box . Text )
If (Cou ntry Text Box .Tex t <> "")
And
(Bin ding Sou rce2 .Pos ition = 0)
And
(Cou ntry Text Box .Tex t <> "Arg enti
na") Then
Mes sage Box. Show ("No t a vali d coun
try . ", "ERROR")
Cou ntry Text Box .Foc us()
End If
End Sub
Exercises
688 • Ans wers To Se lecte d Odd -Num bered
13 of 23 [ ] ~
Rim : Casablanca
Rul e of
key field of the Act o rs table. Thu s the
17. A poll o 13 does not appe ar in the
.
Refe rent ial Integrit y would be violated
lds name, address,
Rep lace th e tabl e with two tabl es. The first tabl e should con tain the fie
19. ital.
tain the fi elds city, state , and state Cap
and city. The seco nd table shou ld con
CH APT ER 11
EXERCISES 11.1
ll be reco rded
as 0 and any grad e grea ter than 100 wi
1. A ny nega ti ve grad e wi ll be reco rded
as 100.
l y from th e Mid term prop erty bloc
k and add the follow ing
3. Rem ove the keywo rd Wri teOn
Get prop e rty procedure to it:
Get
Ret urn m mid term
End Get
are writ e only.
5. The prope rties Mid term and Fin al
ed to the va lu e 999 -99- 999 9 .
7. The prop erty socS ecN um is init ializ
th ird line of the even t procedu re.
9. The keywo rd New is miss ing from the
lic and refe rred
vali d. m_n ame would need to be Pub
11. The state men t nom = m nam e is not
to by scholar.m_nam e.
= sch olar .Mi dter m and
13. The stat eme nts pup il. Mid term prop erty is writ e
idte rm) are not valid . The Mid term
lstG rad es. Item s .Add (pup il.M
a valu e.
o nly; it can be set, but cann ot retu rn
15. cou ntry : Can ada
Cap ital : Otta wa
Pop : 31 mil lion
Answ ers To Select ed Odd-N umbered Exercises
• 689
~~ '\ )
-----
Rrst die: 3
Go
Second die:
Sum : 7
Sub Roll ()
m diel rand omN um.N ext(l , 7)
m die2 rand omN um.N ext(l , 7)
End Sub
End Clas s 'Pair OfD ice
EXERCISES 11.2
dles btnD ispl ay.C lick
1. Sub btnD ispl ay_ Clic k( ... ) Han
stud ents (las tStu dent Add ed)
ReDi m Pres erve
y = From pup il In stud ents
Dim quer
Let name = pupi l.Na me
Let ssn = pupi l.Soc SecN um
ade
Let semG rade = pupi l.Ca lcSe mGr
Whe re semG rade = "A"
um, pupi l.Ca lcSe mGr ade
Sele ct pupi l.Na me, pupi l.Soc SecN
Answer s To Selected Odd-N umbered Exercise
• 69 1
End If
End Sub
End Class 'Cash Regis te r
dd
l [ Subtract
OK
Balance : S5
EXERCISES 11.3
Cl a ss Ca s hReg ister
Priva te m balan ce As Doubl e
e
Publi c ReadO nly Pr opert y Balan c e() As Doubl
Get
Retur n m balan ce
Answer s To Selected Odd-N umbered
Exe rci es • 693
End Get
End Pro per ty
End Cla ss 'Ca shR egi ster
a~ a st Trac k
Type of Vehicle
Car Truck
Tota l Revenue : 5.
Number of vehicles :
CH AP TER 12
EXERCISES 12.1
1. Pro tec ted Sub btn Fin d_ Cli
ck( ... ) Han dles btn Fin d.C
Dim max As Dou ble = CD bl(t xtF irst Num lick
If CDb l ( txtS eco ndN um. Tex .Te xt)
t) >m ax The n
max = CD bl(t xtS eco ndN um.
Tex t)
End If
If CD bl(t xtT hird Num .Te xt)
> max The n
max = CD bl(t xtT hird Num . Tex
t)
End If
txtL arg estN um. Tex t = CSt
r(m ax)
End Sub
bered Exe rcises
694 • Answers To Selected Odd -N um
Cli ck( ... ) Han dle s btn Dis pla y.C lick
3. Pro t ec ted Sub btn Dis pla y_ t (tx tNu rnb er . Tex t)
Dim nurn As Int ege r= Cin
nurn - 1
For i As Int ege r = 1 To
t.It em s.A dd( i & " pot ato ")
ls t Ou tpu
Nex t
n)
lstO u t p ut . Item s.A dd( nur
End Sub
s btn Ca lcu late .Cl ick
late Cli ck( . . . ) Han dle
5. Pro te ct e d Sub btn Ca lcu t)
= CD bl( txtP urP rice . Tex
Dim p u r c h Pri ce As Dou ble edV alu e.T ext )
= CD bl(t xtR
Dim re dem Val ue As Dou ble pur chP rice ) I red emValu
e)
t Per cen t((r ede mV alu e-
t xtDi s c Rat e.T ext = For rna pur chP ric e ) I pur chP ric e )
P e rce nt( (re dem Va lue -
t xti ntR a t e.T ext = For mat
End Su b
EXERCISES 12.2
. .. ) Han dle s Me . Loa d
1. Pro tec ted Sub Pag e_ Loa d(
I f Not Is Pos tBa c k The n
=
Dim sta tes () As Str ing apP ath ("A pp_ Dat a \ Sta tes
.tx t") )
IO . Fil e . Re adA llL ine s(M
In sta tes
Dim que ry = Fro m s tat e
Ord er By s t ate
Sel ect sta t e
que ry
ls t Sta tes .Da taS our ce =
ls t Sta tes .Da taB ind ()
t)
t r(ls tSt ate s.It em s.C oun
tx tNu rnS tate s.T ext = CS
En d If
End Sub
De lete . Cli ck
_ Cli ck ( ... ) Han dle s btn
Pro tec t e d Sub btn De lete
(lst Sta tes .Te xt)
l s tSt ate s.It em s.R em ove t)
tr(l stS tate s.It em s.C oun
txtNurn Sta tes .Te xt = CS
End Sub
12.2 Exercise 3
~odel
Total cos~:
tie s wer e
Cau ses Va lida tion pro per
3. 'No te: The Au toP ostB ack and
ck box .
'set to Tru e for eac h che _
. . . ) Han dle s
_ Sel ect edi nde xC han ged (
Pro tec t e d Sub rblM ode l o .Ch eck edC han ged ,
Cha nge d, chk Upg rad edV ide
r blM ode l . Sel ect edi nde x cke dCh ang ed
chk Mem ory . Che
c hkMo dem . Che cke dCh ang ed,
Dim c ost As Dou b l e = 0
bas ed upo n sel ect ion s .
'Ad d amo unt s to the co st
lux e" The n
If r b l Mo del . Tex t = "De
c o st += 100 0
Answer s To Se lected Odd-N umbered Exerci es
• 695
Else
cost += 1500
End If
If chkUpg radedV ideo.Ch ecked Then
cost += 200
End If
If chkMod em.Che cked Then
cost += 30
End If
If chkMem ory . Checke d Then
cost += 120
End If
txtOut put.Te xt Format Curren cy(cost )
End Sub
12.2 Exercise 91
F1rst ord:
Se:ond , ord:
Alphabetiz e W ords
11. Protec ted Sub btnDis play_ Click( ... ) Handle s btnDis
play.C lick
Dim justice s ( ) As String =
IO . File.Re adAllL ines(M apPath ("App_ Data\J ustice s.txt")
)
Dim stateAb brev As String = txtStat e.Text. ToUpp er
Dim query = From justice In justice s
Let data justice .Split( ","c )
Let name = data(O) & " " & data(l)
Let pres = data(2)
Let state = data ( 3 )
Let yrsServ ed = YearsS erved(d ata (4) , data(S ))
Where state = stateAb brev
696 • A nswer s To Selected Odd-N um bered Exe rcises
le ,
Funct ion Years Serve d(ByVal enter As Doub
By Val l e ave As Doub le) As Doub le
If leave = 0 Then
Retu r n (Now. Year - ente r)
Els e
Re t u r n (l eave - enter )
End If
En d Func ti on
12.2 Exercise 11
State abiYev1a 10,... MD
EXERCISES 12.3
Hand les btnD ispla y.Cli ck
7. Pro tecte d Sub btnD ispla y _ Click ( ... )
Dim mc DC As New Mega citie s DataC ontex t
Dim query = From city In mcDC . Citie s
coun try Equa ls
Join coun try In mcDC .Coun tries On city.
count ry.na me
Se l ect city.n ame, count ry.po p201 0
")
c h tMega ci ties.D ataBi ndTa ble(q uery, "name
ch tMega ci ties . Char t Areas ( O) .Axis X.Int erval =1
chtMe g a ci ties . Chart Ar eas ( O) .Axis X . Title = "City "
chtM egaci ties . Chart Areas ( O) .Axis Y.Tit le =
" 2 010 Pop. of Coun try in Milli ons "
End Sub
) Hand les btnD isp l ay . Click
17. Prote cted Sub btnD ispla y_ Cl ick ( . ..
Dim pizza DC As New Pizz a DataC ontex t
Dim query = From cha i n I n p iz zaDC .Pizz erias
Order By chai n.sal es200 8 Desce nding
Let amou nt = chain .sales 2008 I 10000 00
Se l ect chain . name, amoun t
chtPi zzaC hains .Da t aBind Table (quer y, "name ")
al = 1
chtP i zzaCh ains. Char tArea s (O) .Axis X. I nterv
X . Title "P i zzeri a"
chtPi zzaC hains .Char tArea s (O) .Axis
as (O ) . AxisY . Title = "2 0 08 Sa l es in Billi ons"
chtPi zzaC hains . Chart Are
End Sub
Answers To Selected Odd-N umbered Exe rci es • 697
12.3 Exercise 25
Display To al Number of S ores
Tota1 rumber o"" s ores 20,945
INDEX
699
700 • Ind ex
dialog box, 46
Directory, 5, 589
file not found, 369
Disk, 4, 589
index out of range, 271
Displaying file exten sions, 5-6, 585
logic, 61
Di tinct query operator, 284, 341
runtim e, 61
Divide and conq uer meth od, 11
syntax, 61
Division opera tion, 54
Error Corre ct ion Options box, 71
Dolo op,21 8, 221,2 5 1
Error List window, 61, 99
flowchart, 218
ErrorMessage property, 552
pass throu gh a, 218
Esc key, 580
posttest form, 221
Event, 37-4 4, 535
prete st form, 218
declare an, 510
stepp ing throu gh a, 599
default, 46
Docu ment window, 22, 586
hand ler, 38
Docu ment ation , 8, 76-77
procedure, 19, 38, 52
Double data type, 56
user-defined, 509, 536
Doub leCli ck event , 244
Events butto n, 25, 42
Double-click with a mouse, 4
Except set opera t ion, 355
Double-subscripted variable, 319
Exception, 61,37 2
DP! settin g for monitor, 437, 584-8 5
Argu ment OutO fRan ge, 374
Drag with a mouse, 4
Catch block, 373-7 4
DrawEllipse meth od, 414
Finally block, 373- 74
DrawLine meth od, 438
lndex OutO fRan ge, 3 74
DrawRectangle meth od, 414
lnvalidCast, 372- 73,37 4
DrawString meth od, 9 1, 438
IO.D i recto ryNo tFoun d , 374
Driver, 205
IO.FileNot Found, 374
Drop Down comb o box, 404-5
10 .10, 374
DropDownList comb o box, 404-5
Nu llRefe rence, 374
DropDownStyle property, 404-5
Overflow, 3 74
Duck typing, 237
Try block, 373- 74
Exists meth od, 369
Exit Do statem e nt, 223
E Exit For state ment , 237, 27 1
e parameter, 44 Exiting Visual Basic, 577
Elem ent in XML, 383 Expo nent, 62
Elem ent of an array, 259 Expo nenti ation opera tion, 54
Else keyword, 112 Expression
Elself clause, 117 num eri c, 57
string, 72
Empty string, 7 5
Enabled property, 33, 410 Extension of a file name, 5, 585, 589
End displaying in 'Wind ows 7', 5, 585
Cia s, 492 displaying in Windows Vista, 5, 585
Func tion, 160, 16 1 displaying in Windows XP, 5-6, 585
If, 112
key, 27 F
Select, 132
F4 key, 24
Struc ture, 295
F5 key, 27, 577,5 92
Sub,3 8, 175
F8 key, 592
tag in XML, 383
F9 key, 592
EndO fStre am property, 366
Field, 297, 350
Ends With meth od, 108
of a database table, 45 8, 486
Enter event , 45
File, 589
Enter key, 580
add data to, 369
Error
closing a, 366, 368
detec tion, 46
Ind ex • 703
DataS o urce prope rty, 287, 341 Memory, 56, 190, 194
fill at des ign time, 143-4 4, 402 Menu bar, 20, 21, 22
fill with an array or query, 402 Menu Strip contr ol, 415- 18
index numb er, 243, 25 1 Message dialog box, 90, 99
print conte nts of, 586 MessageBox . how method, 90
search, 247 Meth od, 54, 495, 535
Se lected lndex property, 243 abstract, 527
Selec ted lndex Chan ged event , 243 Add, 54,98
Se lected ltem property, 287 Appe ndTex t, 369
Sorted prope rty, 244 C lea r, 54, 75, 98, 402
String Co llectio n Ed ito r, 143-4 4 C lose, 368
Text property, 143 , 244 C reateText, 367
Listl tem ollection Edito r, 555, 556 Exi ts, 369
Litera l, 98 icon, 40
nume ric, 54 lndex Of, 73-74 , 98
string, 68 plit, 270
Load event procedure, 26 1 S ubstri ng, 73, 98
Loca l ToLower, 73, 98
const ant, 194 ToString, 79
scope, 77, 194, 214,4 26 ToU pper, 73, 98
type infere nce, 236, 25 1 Trim , 73, 78, 98
variab le, 194, 2 14, 260 Write Line, 368
Loca ls window, 594, 598 Microsoft Access database fil e, 461
Log ic error, 61 Microsoft Sans Se rif font, 30
Logica l ope rator, 104, 106, 154 Min metho d, 263, 283 ,341
Loop Minim ize button , 4
Do, 218, 22 1, 25 1 Minim um prope rty, 419
For Each, 266-6 7 Mod opera tor, 60
For. .. Next, 230-3 7, 25 1 Moda l fo rm , 426
infin ite, 223 Mode, 369
keywo rd, 218 Modular design , 180, 202-5
nested, 235 Modu le, 11, 202
struct ure, 13, 203 Mo use
Loopi ng variab le, 267 cli ck with a, 4
doub le-c li ck with a, 4,
M d rag with a, 4
hove r with a, 4
Mach ine language, 2 right-cl ick with a, 4
Main Cont ent region, 540 Move method, 369
MainMenu contr ol, 451 Mov ing text, 579
Managing progra ms, 577-7 8 Mu ltiLin e property, 580
Mask property, 85-87 Mu lt iple
Mask ed tex t box contro l , 85-87 , 99 contro ls, 32
Math .Roun d funct ion, 58, 62, 99 decla ration s, 60
Math .Sqrt functi on, 58, 99 forms, 425-2 6, 451
Math ematica l notat ion, 54 Web page , 551
Max method, 263, 283,3 41 Multi plica tion opera tion, 54
Maximize butto n, 4 Mustl nherit keyword, 527
Maxim um prope rty, 41 9 MustO ve ride ke yword , 527
Me keywo rd , 43 , 438 MyBase keyword, 523
Me.C lose () statem ent, 45
Megaciti esData et, 46 1
Memb er
N
of a structure, 295 Name prope rty, 30
va ri ab~,494,4 98, 529 N amed const ant, 90-9 1, 99
706 • Index
s
R
Save a program, 27, 47 , 577- 78
Rad io button control, 146, 150 Save A ll button, 27,5 77
C hecked property, 14 7 Sc ientific notation, 62
708 • Index
Instructors, request your exam copies online and get instant access.
Learn more at coursesmart.com
eed e
This textbook is enhanced with VideoNotes-step-by-step tutorials
available whenever you need them! Whether you are studying for an
exam or need help with a difficult topic, VideoNotes give you additional
examples of key concepts and walk you through the entire problem-
solving process, making sure that you understand each step-just
as if you were in your instructor's office. Throughout the book, you'll
see icons placed in the margin that let you know that a VideoNote is
available to expand on a programming example or problem solution .
With the purchase of a new copy of this textbook, you have access
to VideoNotes. Why not use them? To use VideoNotes, just follow the
directions on the access card at the front of the book.
Prentice Hall
m
is an imprint of )>
z
-------
PEARSON
www.pearsonhighered.com