114 86
English Pages 672 [692] Year 1994
QBASIC WITH AN INTRODUCTION TO VISUAL BASIC FOR ENGINEERING, MATHEMATICS, AND THE SCIENCES
Invoking QBasic 1. From DOS, type QBASIC and press the Enter key.
Some Common QBasic Commands (key1+key2 means “Hold down key! while pressing key2.”) (key1/key2 means “Release key1 before pressing key2.”) cursor between View window and Menu bar program from disk into the View window new program in the View window copy of the current program between View window and Output screen
Alt Alt/File/Open Alt/File/New Alt/File/Print/Enter F4
Toggle Place a Start a Print a Toggle
Esc
Remove a menu, dialog box, or help box
Shift+F5 Alt/File/Save As Alt/File/Exit
Run the the current program. Denoted: [run] Save the current program Exit QBasic and return to DOS
Cul+Y Shift+Ins Home End Cul+Home Ctrl+End
Delete Insert Move Move Move Move
Home/Ctrl+N End/Enter
Insert line above current line with cursor on new line Insert line below current line with cursor on new line
Help
Fl Shift+F1 Esc
Get information about word at cursor Get help on “Help” Remove help box
Dialog Box
Tab Esc
Move around in a dialog box Remove a dialog box
Environment
Cursor Moving
line containing cursor and place in clipboard contents of clipboard at cursor to beginning of line containing cursor to end of line containing cursor to beginning of program to end of program
Procedures To open a window for a subprogram, enter the keyword SUB’ followed by anes The name can be followed by parameters, if desired’. ge
SUB Name FUNCTION
Name
of the subprogram.
To open a window for a function, enter the keyword FUNCTION ilove by the name of the function. The name can be followed by parameters, if desired.
Shift+F2
Cycle through the procedures (in alphabetical order) and the main body of the program.
ey
Display a list beginning with the program name and containing the names of the procedures. Use the cursor-moving keys and the Enter key to make a selection.
F2/(Sel)/Tab/Del/Enter
To delete a procedure, press F2, select the procedure to be deleted, and then press Tab/D/Enter.
Obtaining a Printed Copy of the QBasic Program Output 1. Check that the printer is turned on, has paper, and is “on line.” 2. Run the program and then press F4 twice to display the desired output on the Output screen with “Press any key to continue” removed. 3. Press Shift+Print Screen.
Note: If the program uses graphics mode, consult Chapter 10.1 on the use of GRAPHICS.COM.
Obtaining Graphics from QBasic with a Hercules Adapter and Monochrome Monitor 1. Enter MSHERC before invoking QBasic from DOS. 2. Use SCREEN 3 instead of SCREEN 2 in programs.
This book contains a diskette, the use of which is governed by a break-the-seal Microsoft Software License on the last page of the book.
QOBASIC™ With an Introduction to
Visual Basic for Engineering, Mathematics, and the Sciences Second Edition
David I. Schneider roe
University of Maryland
DECLEN an imprint of
MACMILLAN
COLLEGE PUBLISHING COMPANY, New York
MAXWELL MACMILLAN
CANADA, Toronto
MAXWELL MACMILLAN INTERNATIONAL New York Oxford Singapore Sydney
On the Cover: Veazy (1990) is an unusual, round painting by New York artist Gary Lang. It is acrylic on canvas and measures 27 inches in diameter. Lang’s use of vibrant colors and intentional irregularities in the painted surface create a dazzling visual display. Lang received a Master of Fine Arts degree from Yale University in 1975 and has been the focus of numerous one-man exhibitions throughout the United States and Europe. His work is included in the permanent collections of the Whitney Museum of American Arts, New York; the Museum of Contemporary Art, Los Angeles; the Madison Art Center, Wisconsin; and the Menil Collection, Houston, Texas. He is represented by Brian Gross Fine Art, San Francisco, and Michael Klein, Inc., New York City.
Photography:
John Drooyan
Interior Design and Composition:
Rebecca Evans
& Associates
Photo/Illustration Credits: page 311, Courtesy of Hammond Incorporated; Incorporated; page 436, Courtesy of Resorts International Hotel Casino.
page 444, Courtesy of Hammond
© Copyright 1994 by Macmillan College Publishing Company, Inc. Dellen is an imprint of Macmillan College Publishing Company. Printed in the United States of America.
IBM is a registered trademark of International Business Machines Corporation. Hercules is a trademark of Hercules Computer Technology. Microsoft is a registered trademark of Microsoft Corporation.
All rights reserved. No part of this book may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopy, recording, or any information storage and retrieval system, without permission in writing from the Publisher. Macmillan College Publishing Company 866 Third Avenue New York, NY 10022
Macmillan College Publishing Company is part of the Maxwell Communication Group of Companies. Maxwell Macmillan Canada, Inc.
1200 Eglinton Avenue East, Suite 200 Don Mills, Ontario M3C 3N1
Library of Congress Cataloging in Publication Data Schneider, David I.
QBASIC: with an introduction to Visual Basic for engineering, mathematics, and the sciences / David I. Schneider — 2nd ed.
paeem: Rev. ed. of: Microsoft QBASIC. 1991. Includes index. ISBN 0-02-40761 1-2 1. QBasic (Computer program language). 2. Microsoft QuickBASIC. 3. Microsoft Visual BASIC. I. Schneider, David I. II. Title. QA76.73.Q33S37 1994 005.26’2—dc20 94-9640 CIP ISBN 0-02—40761 1-2 Ponting:
2
394556
Year:
984516
Contents Preface vi Acknowledgments
Chapter 1
An Introduction to Computers and QBasic 1.1 1.2 1.3. 1.4
Chapter 2
An Introduction to Computers 2 Getting Started 4 Using Diskettes and DOS 15 Biographical History of Computing
Program Development Cycle Programming Tools 30
Vil 28
Fundamentals of QBasic 3.1 Numbers 40 372) Strings, 33 3.3 DataInput 63 3.4 Numeric Functions 78 3.5. Screen Placement and Formatting Summary 104 Programming Projects 105
Chapter 4
bbe)
92
ial
Decisions
4.1 Relational and Logical Operators 4.2 IFBlocks 117 4.3 SELECT CASE Blocks 132 Summary 147 Programming Projects 147
Chapter 5
22
Problem Solving 2.1 2.2
Chapter 3
ix
112
Repetition 5.1 DOLoops 152 5.2 Processing Lists of Data with DO Loops 5.3. FOR...NEXT Loops 185 Summary 200 Programming Projects 201
Chapter 6
151 167
207
Procedures
6.1 Subprograms, Part] 208 6.2 Subprograms, Part I] 227 6.3 Functions 242 6.4 Modular Design 254 6.5 A Case Study: Numerical Integration Summary 267 Programming Projects 267
259
iii
iv
Contents
Chapter 7
agit
Arrays 7.1 Creating and Accessing Arrays 272 7.2 Using Arrays 287 7.3. Sorting and Searching 305 7.4 Two-Dimensional Arrays 323 7.5 A Case Study: Calculating with a Spreadsheet Summary 345 Programming Projects 346
Chapter 8
337
355
Sequential Files 8.1 Sequential Files 356 8.2 Using Sequential Files 368 8.3 A Case Study: Creating a Receipt 377 Appendix: Displaying the Contents of a File 381 Summary 382 Programming Projects 382
Chapter 9
389
Random-Access Files 9.1 DataTypes 390 9.2 Random-Access Files 399 Summary 405 Programming Projects 405
Chapter 10
Graphics
407
10.1 Introduction to Graphics 408 10.2 Specifying a Coordinate System 409 10.3 Drawing Graphs of Functions 418 Summary 425 Programming Projects 426
Chapter 11
11.1 Generating Random Numbers 11.2 Games of Chance 436 11.3 Monte Carlo Methods 446 Summary 454 Programming Projects 455
Chapter 12
427
Random Numbers
428
Visual Basic
12.1 An Introduction to Visual Basic 458 12.2 Visual Basic Objects 461 12.3 Visual Basic Events 471 12.4 Converting QBasic Programs to Visual Basic 485 12.5 A Case Study: Recording Checks and Deposits 502 Summary 511 Programming Projects 512
457
Contents
Appendixes
v
515 Appendix A. Appendix B. Appendix C. Appendix Appendix Appendix Appendix Appendix Appendix
D. E. F. G. H. I.
Appendix J.
ASCII Values 515 Usinga Mouse 517 QBasic Statements, Functions, Operators, and Metacommands 520 QBasic Debugging Tools 550 A Summary of QBasic Editing Commands 558 The QBasic Environment 560 HOW TO (QBasic) 566 An Introduction to Windows 575 HOW TO (Visual Basic) 584 Visual Basic Statements, Events, Functions, Methods, Properties, Data Types, and Operators 597
Answers to Selected Odd-Numbered Exercises
621
Index
667
Index of Selected Engineering, Mathematics, and Science Applications
673
Preface This text presents the fundamentals of programming in Microsoft® QBasic™ on IBM PC compatible computers and an introduction to Microsoft® Visual Basic™. My objectives when writing this text were as follows: 1. To develop focused chapters. Rather than covering many topics superficially, I concentrate on important subjects and cover them thoroughly. 2. To use examples and exercises with which students can relate, appreciate, and feel comfortable. I frequently use real data. Examples do not have so many embellishments that students are distracted from the programming techniques illustrated. 3. To produce compactly written text that students will find both readable and informative. The main points of each topic are discussed first and then the peripheral details are presented as comments.
4. To teach good programming practices that are in step with modern programming methodology. Problem solving techniques and structured programming are discussed early and used throughout the book. 5. To provide insights into the major applications of computers, with special emphasis on engineering, mathematics, and the sciences.
Unique and Distinguishing Features Exercises for Most Sections. Each section that teaches programming has an exercise set. The exercises both reinforce the understanding of the key ideas of the section and challenge the student to explore applications. Most of the exercise sets require the student to trace programs, find errors, and write programs. The answers to most of the odd-numbered exercises in Chapters 2 through 8 and selected odd-numbered exercises from Chapters 9 through 12 are given at the end of the text.
Practice Problems. Practice problems are carefully selected exercises located at the end of a section, just before the exercise set. Complete solutions are given following the exercise set. The practice problems often focus on points that are potentially confusing or are best appreciated after the student has worked on them. The reader should seriously attempt the practice problems and study their solutions before moving on to the exercises. Programming Projects. Beginning with Chapter 3, every chapter contains programming projects. The programming projects not only reflect the variety of ways that computers are used in the business and engineering communities, but also present some games and general interest topics. The large number and range of difficulty of the programming projects provide the flexibility to adapt the course to the interests and abilities of the students. Some programming projects in Chapters 7 through 12 can be assigned as end-of-the-semester projects.
vi
Preface
Comments.
vii
Extensions and fine points of new topics are reserved for the
“Comments” portion at the end of each section so that they will not interfere with the flow of the presentation. Case Studies.
Each of the four case studies focuses on an important program-
ming application. The problems are analyzed and the programs are developed with top-down charts and pseudocode. The programs can be found in the EXAMPLES directory of the enclosed diskette. Chapter Summaries. In Chapters 3 through 12, the key results are stated and the important terms are highlighted. Strings Used Throughout Text. The introduction of strings in Chapter 3 and their regular use from then on prepare the student for substantial string-handling
programs. Procedures.
Procedures
are introduced
after decision structures and
loops.
However, Section 6.1 and most of Section 6.2 can be covered after Chapter 3
for those instructors who prefer an early introduction to procedures. Arrays. Arrays are introduced gently in two sections. The first section presents the basic definitions and avoids procedures. The second section presents the techniques for manipulating arrays and shows how to pass arrays to procedures. Appendix on Debugging. The placement of the discussion of QBasic’s sophisticated debugger in an appendix allows the instructor flexibility in deciding when to cover this topic. Reference Appendices. Appendices serve as a compact reference manual for the environments and statements of both QBasic and Visual Basic.
Instructors Solution Diskette. A diskette containing the solution to every exercise and programming project is available for the instructor. Examples,
Case Studies, and Visual Basic Diskette.
Each book contains a
diskette holding all the examples and case studies from this text and also a copy of the Primer Edition of Visual Basic 2.0.
What’s New in the Second Edition
1. Suggestions from students and reviewers of the book have been incorporated as much as possible.
2. The real-life data in the examples and exercises have been updated and revised. 3. The chapter on graphics has been modernized to apply to VGA monitors. 4. The functions VAL and STR$ have been added to the section on built-in functions.
5. The section on DOS has been revised with the assumption that the computer has a hard disk.
6. A discussion of QBasic’s operators has been added to Appendix C.
Viii
Preface
7. The main change is adding an introduction to Visual Basic for Windows— the state of the art in Basic programming. Since Visual Basic uses essentially the same programming constructs as QBasic, students can leverage their knowledge of QBasic and make themselves much more marketable for the 90’s. (Knowledge of Visual Basic makes someone more marketable because its extraordinary combination of power and ease of use has made Visual Basic the tool of choice for developing user-friendly applications in the business world. In addition, Microsoft has made Visual Basic the language used to take full control of its best selling Windows applications such as Microsoft Word or Microsoft Excel.)
There’s one more point that shouldn’t be underestimated—Visual Basic is fun! Learning Visual Basic was very exciting to me—most students have similar reactions when they see how easy it is to build powerful visual interfaces using it. The chapter on Visual Basic can be used in several ways. (a) The chapter can be covered in detail. (b) The instructor can give a survey of the language in one or two lectures. (c) The chapter can be assigned as an optional enrichment topic.
Whether or not the chapter is covered in class, I encourage all students to learn about Visual Basic, the language Microsoft chairman Bill Gates describes as “the programming language for the 90’s.”
Acknowledgments Many talented instructors, students, and programmers provided helpful com-
ments and thoughtful suggestions at each stage in the preparation of this text. | extend my gratitude for their contributions to the quality of the book to Shakil
Akhtar, Central Michigan University; William A. Bailey, Jr., University of North Carolina at Charlotte; Abdel Fatah Bashir, Moorhead State University;
Curtis Bring, Moorhead
State University; John Caldwell, College of Lake
County; Gene B. Chase, Messiah College; Curtis Childress, Rancho Santiago College; Michael Cooper, University of California at Berkeley; Noel Dahlen,
Rancho Santiago College; Louise Darcy, Texas A&M
University; Mark Ellis,
MIT; Richard Fedder, Grand Valley State University; Ronald D. Ferguson, San
Antonio
College; W. Fred Fry, Rancho
Santiago College; Kevin Gorman,
University of North Carolina at Charlotte; Samuel Graff, John Jay College of Criminal Justice; Bill Higgins, Messiah College; Bill Hoffman, Cogswell Polytech College; Milo Johnson, College of the Redwoods; Monte Johnson,
St. Cloud State University; Dee Joseph, San Antonio College; James P. Kelsh, Central Michigan University; Suban Krishnamoorthy, Framingham State College; Shelly Langman; Norman Lindquist, W. Washington University; Jackie Lou, Montgomery College; Lewis D. Miller, Canada College; Calvin Mittman, St. Johns University; Barry Parris, University of South Carolina at Spartanburg; Juanita J. Peterson, College of Alameda; James T. Ramey, Jr., Francis Marion College; John Repede,
University of North Carolina at Charlotte;
Peter Rosenbaum,
Framingham State College; R. Waldo Roth, Tulsa Research Center; Barbara Saxton, Lehigh County Community College; Sandra M. Schleiffers, Colorado State University; Y. Sitaraman, Kentucky Wesleyan College; Phil Steitz, Beloit College; Brooke Stephens, University of Maryland; Bill Strausbaugh, Messiah College; Brian Turnquist, University of Maryland; Michael Willis, Montgomery College; Charles M. Williams, Georgia State University; Sheryl Barricklow,
Grand Valley State University; Joseph Farrelly, Palomar College; Raymond Fadous, University of Michigan at Flint; Francis A. Greene, Essex Community College; Patricia A. Joseph, Slippery Rock University of Pennsylvania; Andy Lau,
Pennsylvania
State at Harrisburg;
Glen
Lobo,
Ferris State University;
Robert Spear, Prince George’s Community College; William A. Moy, University of Wisconsin-Parkside; Andrew McConnell, Napa Valley College; Rita Mudd, Inver Hills Community College; Ernst Rilki, Harper College; Ronald W. Surprenant, Suffolk County Community College; Thomas P. Wiggen, University of North Dakota John Drooyan contributed creative photographs and artwork, Rebecca Evans & Associates used state-of-the-art technology to compose the text. I extend an extra special thanks to Don Dellen, president of Dellen Publish-
ing Company, for his help in planning and executing this text. His partnership and friendship have added a warm personal dimension to the writing process. Last, but not least,
| am grateful to the Microsoft Corporation for their
commitment to producing outstanding programming languages and for their permission to include a copy of the Primer Edition of Visual Basic with each book.
1S gh
a
ad
eer
Si
Bh
a
|
te ee vena
7
on
An Introduction to Computers and QBasic ATAVVES,
ee
OLY
uf
CM=I ee
ae
see
PN
reese ynendomcenlarer teers armed acramiae e eS She 5, Piet
Ricsehent a sre
¢
claus Matas ,
2 Oi: B= Aa
ie
AT
Its Oe
ie Ss Sl Soe
tA
1t5
CIS)
9 CJ ESD
ye
appears and the C drive is the default drive. To change the default drive to B, enter B:. The prompt will change to B>. Files and Directories
Disks hold not only programs but also collections of data stored in data files. The term file refers to either a program or a data file. In Section 1.2 we created a program file. Chapters 8 and 9 are devoted to data files. Each file has a name consisting of a base name of at most eight characters followed by an optional extension consisting of a period and at most three characters. Letters, digits, and a few other assorted characters (see Comment
1) can be used in either the base
name or the extension. Blank spaces are not allowed. Some examples of file names are INCOME.94, CUSTOMER.DAT,
and FORT500.
Since a disk is capable of storing thousands of files, locating a specific file can be quite time consuming. Therefore, DOS allows related files to be grouped into directories. Think of a disk as a large envelope, called the root envelope, which contains several smaller envelopes, each with its own name. (The naming of envelopes follows the same rule as the naming of files.) Each of these smaller envelopes can contain yet other named envelopes. Each envelope is identified by listing it preceded by the successively larger envelopes that contain it, with each envelope name preceded by a backslash. Such a sequence is called a path. For instance, the path \SALES\NY.90\JULY identifies the envelope JULY, contained in the envelope NY.90, which in turn is contained in the envelope SALES. Think of a file name as written on a slip of paper that can be placed into either the root envelope or any of the smaller envelopes. At any time, we can select one of the envelopes. The selected envelope is called the current envelope. All commands to place a slip of paper into an envelope or list the contents of an envelope refer to the current envelope unless a path leading to another envelope is specified. In the language of directories, the root envelope is the root directory, the other envelopes are subdirectories, and the current envelope is the current directory. When DOS is first invoked, the root directory of the current drive is the current directory. The command CD pathName
18
An Introduction to Computers and QBasic
tells DOS to change the current directory to the directory at the end of the named path. The command CD \
makes the root directory the current directory. The command MD directoryName
tells DOS to create a new subdirectory with the specified name in the current directory of the current drive. The command RD directoryName
tells DOS to remove the specified subdirectory from the current directory of the current drive. A subdirectory can be removed only if it has no files or subdirectories. The current directory cannot be removed. The combination of a drive letter followed by a colon, a path, anda file name is called a filespec, an abbreviation of “file specification.” Some examples of filespecs are C:\ DOS\QBASIC.EXE and A:\PERSONAL \ INCOME94.DAT. If the drive (along with the colon) or the path is omitted, then the file is assumed to reside in the current drive or the current directory, respectively. Other DOS Commands Some other commands that can be executed in DOS are FORMAT, DIR, COPY, ERASE, and RENAME.
FORMAT The first time a blank diskette is used, it must be formatted for the computer. The formatting process is analogous to preparing graph paper by drawing grid lines. Let’s assume the unformatted diskette is in the A drive, and the current drive is C. To format the diskette, enter FORMAT
A:
and then follow the directions displayed on the screen. While the formatting is taking place, the light on the A drive will be on, the blank diskette will spin, and the percentage of the diskette formatted will be displayed. After about one minute, the message “Format complete” will appear on the screen, and you will be prompted for a volume label. A volume label is a name (consisting of 1 to 11 characters) for your diskette. You can decline to specify a volume label by pressing the Enter key. You will be informed of the amount of space on the diskette, and the statement “Format another (Y/N)?” will be displayed. Answer
the question by pressing either the Y or N key and then the Enter key. If the answer is N, the DOS prompt will appear and await your next command. If the answer is Y, the steps above will be repeated.
1.3
USING DISKETTES AND DOS
19
Caution: Formatting any disk destroys all its existing files. The hard disk is formatted when the computer is first readied for use, so never enter FORMAT C:.
DIR The command DIR
displays the names of the files and subdirectories in the current directory. (Periods are omitted and the base names are separated from the extensions.)
If the disk has more than a screenful of files, enter the command
DIR /P which makes the computer display just a screenful of files at a time. The command DIR
*.BAS
displays only files with the extension BAS. To generalize, the command DIR
*.ext
displays only files with the specified extension and the command DIR
baseName .*
displays only files with the specified base name.
COPY The command COPY is used to make a second copy of a file. The command COPY filespec
A:
copies the specified file to the current directory of the diskette in drive A. In general, the command COPY filespec
driveLetter:
copies the specified file to the current directory of the disk in drive driveLetter.
ERASE The command ERASE filespec
removes the specified file from the disk. For instance, the command ERASE B:\ ACCOUNTS.BAS deletes the file ACCOUNTS.BAS from the root direc-
tory of the diskette in drive B.
20
An Introduction to Computers and QBasic
RENAME The command filenamel
RENAME
filename2
changes the name of the file identified as filename! to the new name filename2. The new name must be different from the name of any file in the current directory. Comments:
i File names can consist of digits, letters of the alphabet, and the characters &!_ @’‘~(){}-#% $. Spaces are not allowed in file names.
. Neither DOS nor QBasic distinguishes between upper and lowercase letters in file names. For instance, the names COSTS89.BAS,
Costs89.Bas, and
costs89.bas are equivalent. DOS always displays file names with uppercase characters. . The asterisk used with the DIR command is called a wildcard character. It
also can be used with COPY or ERASE to apply the command to many files at once. For instance, COPY *.BAS A: copies files with extension .BAS to the A drive, ERASE TEMP.* erases files with base name TEMP, and COPY
* * B: copies all files in the current directory of the current drive to drive B. . The QBasic command NAME can be used in a program to change the file name of any file on any disk. The statement NAME
"filenamel"
AS
"filename2"
has the same effect as the corresponding DOS command RENAME. Note that with the NAME command, filename! and filename2 must each be surrounded by quotation marks. . The QBasic command KI
filespec™
can be used in a program and has the same effect as the DOS command ERASE. Note that with the KILL command, filespec must be surrounded by quotation marks. . If the name of a QBasic program is not given an extension when saved, QBasic automatically gives it the extension .BAS. This extension can be omitted when opening the program with Alt/F/O, but must be used when deleting or renaming the program.
. The QBasic environment provides a list of the programs on a disk at appropriate times. For instance, pressing Alt/F/O to open a program produces a dialog box similar to the one in Figure 1.9. The file to be retrieved from the disk can either be typed into the narrow rectangle at the top or selected from the list of QBasic programs in the lower rectangle. To make a selection from the listed programs, press Tab to move to the lower rectangle, use the cursor-moving keys to highlight the desired program, and then press the Enter key. With a mouse, you can select a program by double-clicking on it.
21
USING DISKETTES*AND DOS”
1.3
Open
File Nane:
|
Fe-sas
C:NQBASIC Dirs/Dr ives
Files
CASTLE. BAS CATAPULT.BAS EVALUATE.BAS GRAPH. BAS HUNTER. BAS MONEY. BAS NIBBLES. BAS ONE. BAS
PHONE . BAS RENLINE.BAS REVERSI .BAS SORTDEMO .BAS SUBS_EX. BAS
< Cancel
Figure 1.9
>
Dialog Box for Opening a File
PRACTICE PROBLEMS
1.3
1. The commands KILL “OPUS.1” and ERASE OPUS.1 both remove the file named OPUS.1 from a disk. What is the criterion for deciding when a file name must be enclosed by quotes?
Ze Suppose you have saved a QBasic program with the name MYPROG on drive B and you now want to erase the program from the disk. You execute the command KILL “B:MYPROG?” from a QBasic program and receive the error message “File not found.” What happened?
EXERCISES
1.3
In Exercises 1 through 9, give the DOS command that accomplishes the stated task. L Reproduce a file on another disk.
. Change the name of a file.
. Prepare a new diskette for use. . List the files in the current directory.
. Change the current disk drive to drive B.
toe)
. Create a new subdirectory of the current directory. . Change the current directory.
Noy
Sow
SS
. Delete a file from a disk.
. Remove a subdirectory of the current directory.
22
An Introduction to Computers and QBasic
In Exercises stated task.
10 and 11, give the QBasic command
that accomplishes the
10. Delete a program from a disk. 11. Change the name of a program.
the use you d coul How e. driv ette disk one just has er put com your e pos Sup 12. commands discussed in this section to copy all the files in the root directory of a diskette onto another diskette? SOLUTIONS TO PRACTICE PROBLEMS
1.3
1. The criterion is the “environment” that the user is in. File names used in QBasic programs must always be enclosed in quotes. File names used in DOS are never enclosed in quotes.
2. Since an extension was not specified when the program was saved, QBasic added the extension BAS. The proper command to erase the program is KILL “B:MYPROG.BAS”.
1
4 BIOGRAPHICAL HISTORY OF COMPUTING The following people made important contributions to the evolution of the computer and the principles of programming.
1800s George Boole: a self-taught British mathematician; devised an algebra of logic that later became a key tool in computer design. The logical operators presented in Section 4.1 are also known as Boolean operators. Charles Babbage: a British mathematician and engineer; regarded as the father of the computer. Although the mechanical “analytical engine” that he conceived was never built, it influenced the design of modern computers. It had units for input, output, memory, arithmetic, logic, and control. Algorithms were
intended to be communicated to the computer via punched cards, and numbers were to be stored on toothed wheels. Augusta Ada Byron: a mathematician and colleague of Charles Babbage; regarded as the first computer programmer. She encouraged Babbage to modify the design based on programming considerations. Together they developed the concepts of decision structures, loops, and a library of procedures. Decision structures, loops, and procedures are presented in Chapters 4, 5, and 6 of this text respectively.
Herman Hollerith: the founder of a company that was later to become IBM; at the age of 20 he devised a computer that made it possible to process the data for the U.S. Census of 1890 in one-third the time required for the 1880 census. His electromagnetic “tabulating machine” passed metal pins through holes in punched cards and into mercury-filled cups to complete an electronic circuit. Each location of a hole corresponded to a characteristic of the population.
1.4
BIOGRAPHICAL HISTORY OF COMPUTING = 23
1930s Alan Turing: a gifted and far-sighted British mathematician; made fundamental contributions to the theory of computer science, assisted in the construction of some of the early large computers, and proposed a test for detecting intelligence
within a machine. His theoretical “Turing machine” laid the foundation for the development of general purpose programmable computers. He changed the course of the second world war by breaking the German “Enigma” code, thereby making secret German messages comprehensible to the Allies.
John V. Atanasoff: a mathematician and physicist at lowa State University; declared by a federal court in Minnesota to be the inventor of the first electronic digital special-purpose computer. Designed with the assistance of his graduate assistant, Clifford Berry, this computer used vacuum tubes (instead of the less
efficient relays) for storage and arithmetic functions. 1940s
Howard Aiken: a professor at Harvard University; built the Mark I, a large- scale digital computer functionally similar to the “analytical engine” proposed by Babbage. This computer, which took five years to build and used relays for storage and computations, was technologically obsolete before it was completed. Grace M. Hopper: retired in 1986 at the age of 79 as a rear admiral in the United States Navy; wrote the first major subroutine (a procedure used to calculate sin x on the Mark I computer) and one of the first assembly languages. In 1945 she found that a moth fused into a wire of the Mark I was causing the computer to malfunction, thus the origin of the term “debugging” for finding errors. As an administrator at Remington Rand in the 1950s, Dr. Hopper pioneered the development and use of COBOL, a programming language for the business community written in English-like notation. John Mauchley and J. Presper Eckert: electrical engineers working at the University of Pennsylvania; built the first large-scale electronic digital generalpurpose computer to be put into full operation. The ENIAC used 18,000 vacuum tubes for storage and arithmetic computations, weighed 30 tons, and occupied 1500 square feet. It could perform 300 multiplications of 2 10-digit numbers per second, whereas the Mark I required 3 seconds to perform a single multiplication. Later they designed and developed the UNIVAC I, the first commercial electronic computer.
John von Neumann: a mathematical genius and member of the Institute of Advanced Studies in Princeton, New Jersey; developed the stored program
concept used in all modern computers. Prior to this development, instructions were programmed into computers by manually rewiring connections. Along with Hermann H. Goldstein, he wrote the first paper on the use of flowcharts. Stanislaw Ulam: Americar research mathematician and educator; pioneered the application of random numbers and computers to the solution of problems in mathematics and physics. His techniques, known as Monte Carlo methods or computer simulation, are used in Chapter 11 to determine the likelihoods of various outcomes of games of chance and to analyze business operations.
24
An Introduction to Computers and QBasic
Maurice V. Wilkes: an electrical engineer at Cambridge University in England the use to er put com first the AC, EDS the t buil n; man Neu von of ent stud and stored program concept. Along with D.J. Wheeler, and S. Gill, he wrote the first
computer programming text, The Preparation of Programs for an Electronic Digital and use the with th dep in t deal ch whi ), 1951 , ley Wes ondis (Ad er put Com construction of a versatile subroutine library. John Bardeen, Walter Brattain, and William Shockley: physicists at Bell Labs; developed the transistor, a miniature device that replaced the vacuum tube and revolutionized computer design. It was smaller, lighter, more reliable, and cooler than the vacuum tube. 1950s
John Backus: a programmer for IBM; in 1953 headed a small group of programmers who wrote the most extensively used early interpretive computer system, the IBM 701 Speedcoding System. An interpreter translates a high-level lan-
guage program into machine language one statement at a time as the program is executed. In 1957, Backus and his team produced the compiled language Fortran, which soon became the primary academic and scientific language. A compiler translates an entire program into efficient machine language before the program is executed. QBasic combines the best of both worlds. It has the power and speed of a compiled language and the ease of use of an interpreted language. Donald L. Shell in 1959, the year that he received his Ph.D. in mathematics from the University of Cincinnati, published an efficient algorithm for ordering (or sorting) lists of data. Sorting has been estimated to consume nearly one-quarter of the running time of computers. The Shell sort is presented in Chapter 7 of this text.
1960s John G. Kemeny and Thomas E. Kurtz: professors of mathematics at Dartmouth College and the inventors of BASIC; led Dartmouth to national leadership in the educational uses of computing. Kemeny’s distinguished career included serving as an assistant to both John von Neumann and Albert Einstein, serving as president of Dartmouth College, and chairing the commission to investigate the Three Mile Island accident. In recent years, Kemeny and Kurtz have devoted considerable energy to the promotion of structured BASIC. Corrado Bohm and Guiseppe Jacopini: two European mathematicians; proved that any program can be written with the three structures discussed in Section 2.2: sequences, decisions, and loops. This result led to the systematic methods of modern program design known as structured programming.
Edsger W. Dijkstra: professor of computer science at the Technological University at Eindhoven, The Netherlands; stimulated the move to structured programming with the publication of a widely read article, “Go To Statement Considered Harmful.” In that article he proposes that GOTO statements be abolished from all high-level languages such as BASIC. The modern programming structures available in QBasic do away with the need for GOTO statements.
1.4
Harlan B. Mills: IBM
BIOGRAPHICAL HISTORY OF COMPUTING
Fellow and Professor of Computer
25
Science at the
University of Maryland; has long advocated the use of structured programming.
In 1969, Mills was asked to write a program creating an information database for the New York Times, a project that was estimated to require thirty man- years with traditional programming techniques. Using structured programming techniques, Mills single-handedly completed the project in six months. The methods of structured programming are used throughout this text.
Donald E. Knuth: Professor of Computer Science at Stanford University; is generally regarded as the preeminent scholar of computer science in the world. He is best known for his monumental series of books, The Art of Computer Programming, the definitive work on algorithms. The algorithm presented in Exercise 27 of Section 11.1 of this text is an example of the programming gems appearing in Knuth’s books. Ted Hoff, Stan Mazer, Robert Noyce, and Federico Faggin: engineers Intel Corporation; developed the first microprocessor chip. Such chips, serve as the central processing units for microcomputers, are responsible extraordinary reduction in the size of computers. A computer with greater than the ENIAC can now be held in the palm of the hand.
at the which for the power
1970s Paul Allen and Bill Gates: co-founders of Microsoft Corporation; developed languages and the operating system for the IBM PC. The operating system, known as MS-DOS, is a collection of programs that manage the operation of the computer. In 1974, Gates dropped out of Harvard after one year, and Allen left a programming job with Honeywell to write software together. Their initial project was a version of BASIC for the Altair, the first microcomputer. Microsoft is one of the most highly respected software companies in the United States and a leader in the development of programming languages. Stephen Wozniak and Stephen Jobs: co-founders of Apple Computer Inc.; started the microcomputer revolution. The two had met as teenagers while working summers at Hewlett-Packard. Another summer, Jobs worked in an orchard, a job that inspired the names of their computers. Wozniak designed the Apple computer in Jobs’ parents’ garage and Jobs promoted it so successfully that the company was worth hundreds of millions of dollars when it went public. Both men resigned from the company in 1985. Dan Bricklin and Dan Fylstra: co-founders of Software Arts; wrote VisiCalc, the first electronic spreadsheet program. An electronic spreadsheet is a worksheet divided into rows and columns, which analysts use to construct budgets
and estimate costs. A change made in one number results in the updating of all numbers derived from it. For instance, changing a person’s housing expenses will immediately produce a change in his total expenses. Bricklin got the idea for an electronic spreadsheet after watching one of his professors at the Harvard Business School struggle while updating a spreadsheet at the blackboard. VisiCalc became so popular that many people bought personal computers just so they could run the program. A simplified spreadsheet is developed as a case study in Section 7.5 of this text.
26
An Introduction to Computers and QBasic
Robert Barnaby: a dedicated programmer; best known for writing WordStar, one of the most popular word processors. Word processing programs account for thirty percent of all software sold in the United States. The QBasic editor uses WordStar-like commands.
1980s William L. Sydnes: manager of the IBM Entry Systems Boca engineering group; headed the design team for the IBM Personal Computer. Shortly after its introduction in 1981, the IBM PC dominated the microcomputer field. QBasic runs on all IBM Personal Computers and compatibles.
Mitchell D. Kapor: co-founder of Lotus Corporation; wrote the business software program 1-2-3, the most successful piece of software for personal computers. Lotus 1-2-3 is an integrated program consisting of a spreadsheet, a database manager, and a graphics package. Databases are studied in Chapters 8 and 9 of this text and graphics in Chapter 10. Tom Button: group product manager for applications programmability at Microsoft; headed the team that developed QuickBasic, QBasic, and Visual Basic.
These modern, yet easy to use languages, have greatly increased the productivity of programmers. Alan Cooper: director of applications software for Coactive Computing Corporation; is considered the father of Visual Basic. In 1987 he wrote a program called “Ruby” that delivered visual programming to the average user. A few years later, Ruby was combined with QuickBasic to produce Visual Basic, the remarkably successful language that allows Windows programs to be written from within Windows easily and efficiently.
Problem Solving
rd
dy
int
4
TEER
LAY ft
ip
f
ln
het
Piused
he
oes
LIL
i
TET
EL
oo RT VE L Pai
Le
it
Seeed 4
41
14
j
$
f
7 £
/
Pekast
Gf,
LtLf
{
EPL
/
if
/
4
t
i
toda
I
re
Leas
jhe
f
fF
§
j
/
pal
j
‘
rt
28
o
Problem Solving
i PROGRAM DEVELOPMENT
CYCLE
We learned in the first chapter that hardware refers to the machinery in a computer system (such as the monitor, keyboard, and CPU) and software refers to a collection of instructions, called a program, that directs the hardware. Programs are written to solve problems or perform tasks on a computer. Programmers translate the solutions or tasks into a language the computer can understand. As we write programs, we must keep in mind that the computer will only do what we instruct it to do. Because of this, we must be very careful and thorough with our instructions.
Designing
a Computer Program
The first step in designing a program is to determine what the output of the program should be, that is, exactly what the program should produce. The second step is to identify the data, or input, necessary to obtain the output. The last step is to determine 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 same as that used to solve word problems in an algebra class. For example, consider the following algebra problem:
How fast is a car traveling if it goes 50 miles in 2 hours?
The first step is to determine the type of answer requested. The answer should be a number giving the rate of speed in miles per hour (the output). The information needed to obtain the answer is the distance and time the car has traveled (the input). The formula rate = distance / time
is used to process the distance traveled and the time elapsed in order to determine the rate of speed. That is, rate
50 miles/2 hours 25 miles/hour
A pictorial representation of this problem solving process is
Processing
We determine what we want as output, get the needed input, and process the input to produce the desired output. In the following chapters, we discuss how to write programs to carry out the above operations. But first, we look at the general process of writing programs.
2.1
PROGRAM
DEVELOPMENT CYCLE
29
Program Planning A recipe provides a good example of a plan. The ingredients and the amounts are determined by what is to be baked. That is, the output determines the input and the processing. The recipe, or plan, reduces the number of mistakes you might
make if you tried to bake with no plan at all. While it’s difficult to imagine an architect building a bridge or a factory without a detailed plan, many programmers (particularly students in their first programming course) frequently try to write programs without first making a careful plan. The more complicated the problem, the more complex the plan must be. You will spend much less time working on a program if you devise a carefully thought out step-by-step plan and test it before actually writing the program. Many programmers plan their programs using a sequence of steps, referred to as the program development cycle. The following step-by-step process will enable you to use your time efficiently and help you design error-free programs that produce the desired output.
1. Analysis: Define the problem. Be sure you understand what the program should do, that is, what the output should be. Have a clear idea of what data (or input) are given and the relationship between the input and the desired output.
2. Design: Plan the solution to the problem. Find a logical sequence of precise steps that solve the problem. Such a sequence of steps is called an algorithm. Every detail, including obvious steps, should appear in the algorithm. In the next section, we discuss three popular methods used to develop the logic plan: flowcharts, pseudocode, and top-down charts. These tools help the programmer break a problem into a sequence of small tasks the computer can perform to solve the problem. Planning also involves using representative data to test the logic of the algorithm by hand to ensure that it is correct. 3. Coding: Translate the algorithm into a programming language. Coding is the technical word for writing the program. During this stage, the program is written in QBasic and entered into the computer. The programmer uses the algorithm devised in step 2 along with a knowledge of QBasic. 4. Testing and debugging: Locate and remove any errors in the program.
Testing is the process of finding errors in a program and debugging is the process of correcting errors found during the testing process. (An error in a program is called a bug.) As the program is typed into the View window, QBasic’s smart editor points out certain types of program errors. Other types of errors will be detected by QBasic when the program is executed; however, many errors due to typing mistakes, flaws in the algorithm, or incorrect usages of the QBasic language rules can only be uncovered and corrected by
careful detective work. An example of such an error would be using addition when multiplication was the proper operation.
30
Problem Solving
5. Completing the documentation: Organize all the material that describes the program. Documentation is intended to allow another person, or the programmer at a later date, to understand the program. Internal documentation consists of statements in the program that are not executed, but point out the purposes of various parts of the program. Documentation might also consist of a detailed description of what the program does and how to use the program (for instance, what type of input is expected). For commercial programs, documentation includes an instruction manual. Other types of documentation are the flowchart, pseudocode, and top-down chart that were used to construct the program. Although documentation is listed as the last step in the program development cycle, it should take place as the program is being coded.
p
y. PROGRAMMING
TOOLS
This section discusses some specific algorithms and develops three tools used to convert algorithms into computer programs: flowcharts, pseudocode, and top-down charts. You use algorithms every day to make decisions and perform tasks. For instance, whenever you mail a letter, you must decide how much postage to put on the envelope. One rule of thumb is to use one stamp for every five sheets of paper or fraction thereof. Suppose a friend asks you to determine the number of stamps to place on an envelope. The following algorithm will accomplish the task. 1. Request the number of sheets of paper, call it Sheets.
(input)
2. Divide Sheets by 5.
(processing)
3. Round the quotient up to the next highest whole number,
(processing)
call it Stamps.
4. Reply with the number Stamps.
(output)
The algorithm above takes the number of sheets (Sheets) as input, processes the data, and produces the number of stamps needed (Stamps) as output. We can test the algorithm for a letter with 16 sheets of paper. 1. Request the number of sheets of paper, Sheets = 16. 2. Dividing 5 into 16 gives 3.2. 3. Rounding 3.2 up to 4 gives Stamps = 4. 4. Reply with the answer, 4 stamps.
2.2
PROGRAMMING
TOOLS
31
This problem-solving example can be pictured by
Processing (formulas)
Of the program design tools available, the three most popular are the following:
Flowcharts: Graphically depict the logical steps of the program and show how the steps relate to each other.
Pseudocode: program.
Uses English-like phrases with some QBasic terms to outline the
Top-down charts:
Show how the different parts of a program relate to each other.
Flowcharts
A flowchart consists of special geometric symbols connected by arrows. Within each symbol is a phrase presenting the activity at that step. The shape of the symbol indicates the type of operation that is to take place. For instance, the parallelogram denotes input or output. The arrows connecting the symbols, called flowlines, show the progression in which the steps take place. Flowcharts should “flow” from the top of the page to the bottom. Although the symbols used in flowcharts
are standardized,
no standards exist for the amount
of detail
required within each symbol. Below is a table of the flowchart symbols adopted by the American National Standards Institute (ANSI). Figure 2.1 contains the flowchart for the Postage
Stamp problem. Symbol
Name
Meaning
——
Flowline
Used to connect symbols and indicate the flow of logic.
Terminal
Used to represent the beginning (Start) or the end (End) of a program.
Input/Output
Used for input and output operations, such as reading and printing. The data to be read or printed are described inside.
Processing
Used for arithmetic and data-manipulation operations. The instructions are listed inside the symbol.
Decision
Used for any logic or comparison operations. Unlike the input/output and processing symbols, which have one entry
os
and one exit flowline, the decision symbol
has one entry and two exit paths. The path chosen depends on whether the answer to a question is “yes” or “no.”
32
Problem Solving
Connector
Used to join different flowlines.
Offpage Connector
Used to indicate that the flowchart continues to a second page.
Predefined Process
Used to represent a group of statements that perform one processing task.
Annotation
Used to provide additional information about another flowchart symbol.
Read
Set Stamps/5 S Bhaets
Round Stamps up to next whole number
Figure 2.1
|
ae
yor
+
processing
|
processing
|
output
Flowchart for the Postage Stamp Problem
The main advantage of using a flowchart to plan a program is that it provides a pictorial representation of the program, which makes the program logic easier to follow. We can clearly see every step of the program and how each step is connected to the next. The major disadvantage with flowcharts is that when a program is very large, the flowcharts may continue for many pages, making them hard to follow and modify.
2.2
PROGRAMMING TOOLS
33
Pseudocode Pseudocode is an abbreviated version of actual computer code (hence, pseudo-
code). The geometric symbols used in flowcharts are replaced by English-like statements that outline the program. As a result, pseudocode looks more like a program than does a flowchart. Pseudocode allows the programmer to focus on the steps required to solve a problem rather than on how to use the computer language. The programmer can describe the algorithm in QBasic-like form without being restricted by the rules of QBasic. When the pseudocode is completed, it can be easily translated into the QBasic language. The following is pseudocode for the Postage Stamp problem: Program: Determine the proper number of stamps for a letter Read Sheets Set the number of stamps to sheets/5 Round the number of stamps up to the next whole number Display the number of stamps
(input) (processing) (processing) (output)
Pseudocode has several advantages. It is compact and probably will not extend for many pages as flowcharts commonly do. Also, the plan looks like the code to be written and so is preferred by many programmers.
Top-Down Chart The last programming tool we'll discuss is the top-down chart, which shows the overall program structure. Top-down charts are also called hierarchy charts, HIPO (Hierarchy plus Input-Process-Output) charts, structure charts, or WTOC (Visual Table of Contents) charts. All these names refer to planning diagrams that are similar to a company’s organization chart. Top-down charts depict the organization of a program but omit the specific processing logic. They describe what each part, or module, of the program does and they show how the modules relate to each other. The details on how the modules work, however, are omitted.
The chart is read from top to bottom and from left to right. Each module may be subdivided into a succession of submodules that branch out under it. Typically, after the activities in the succession of submodules are carried out, the module
to the right of the original module is considered. A quick glance at the top-down chart reveals each task performed in the program and where it is performed. Figure 2.2 contains a top-down chart for the Postage Stamp problem.
Postage Stamp Program
Read Sheets
Calculate Stamps
| Set Stamps = Sheets/5
Bei la
Display Stamps
an Round Stamps up to next whole number
Figure 2.2. Top-Down Chart for the Postage Stamp Problem
34
Problem Solving
The main benefit of top-down charts is in the initial planning of a program. We break down the major parts of a program so we can see what must be done in general. From this point, we can then refine each module into more detailed plans using flowcharts or pseudocode. This process is called the divide and conquer method. The Postage Stamp problem was solved by a series of instructions to read data, perform calculations, and display results. Each step was in a sequence; that
is, we moved from one line to the next without skipping over any lines. This kind
of structure
is called a sequence
structure.
Many
problems,
however,
require a decision to determine whether a series of instructions should be executed. If the answer to a question is “Yes,” then one group of instructions is executed. If the answer is “No,” then another is executed. This structure is called a decision structure. Figure 2.3 contains the pseudocode and flowchart for a decision structure.
IF condition is true THEN P 1 rocess step(s) ELSE
No
Is
ee Condition fee
Yes
Process step(s) 2 END IF Process step(s) 2
Figure 2.3
Process
step(s) 1
Pseudocode and Flowchart for a Decision Structure
The sequence and decision structures are both used to solve the following problem.
Direction of Numbered New York Streets Algorithm Problem:
Given a street number of a one-way street in New York City, decide
the direction of the street, either eastbound or westbound.
Discussion: There is a simple rule to tell the direction of a one-way street in New York City: Even numbered streets run eastbound. Input: Street number
Processing: Decide if street number is divisible by 2. Output: “Eastbound” or “Westbound”
fe
Figures 2.4 through 2.6 contain the flowchart, pseudocode, and top-down “hart for the New York City Numbered Streets problem.
2.2
Figure 2.4
PROGRAMMING TOOLS
Display
Display
Westbound
Eastbound
Flowchart for the New York City Numbered Streets Problem.
Program: Determine the direction of a numbered NYC street Get Street IF Street is even THEN Display Eastbound ELSE Display Westbound END IF Figure 2.5
Pseudocode for the New York City Numbered Streets Problem
Street Direction
Program
Get
Decide if
Display
Street Number
Eastbound or Westbound
Direction
Figure 2.6 Top-Down Chart for the New York City Numbered Streets Problem
35
36
Problem Solving
The solution to the next problem requires the repetition of a series of instructions.
A programming structure that executes instructions many times is
called a loop structure. We need a test (or decision) to tell when the loop should end. Without 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) is to check a condition before each pass through the loop and continue executing the loop so long as the condition is true.
Is condition true?
DO WHILE condition is true Process step(s)
No
LOOP Process
step(s)
Figure 2.7
Pseudocode and Flowchart for a Loop
Class Average Algorithm Problem:
Calculate and report the grade-point average for a class.
Discussion: The average grade equals the sum of all grades divided by the number of students. We need a loop to read and then add (accumulate) the grades for each student in the class. Inside the loop we also need to total (count) the
number of students in the class. See Figures 2.8 through 2.10. Input: Student grades
Processing: Find the sum of the grades; count the number of students; calculate average grade = sum of grades / number of students. Output: Average grade
2.2
Initialize Counter and Sum to 0
PROGRAMMING TOOLS
Counter and
Sum start at 0
--
|
pei
read
Are there more
data?
Increment
Counter
Add Grade to Sum
Set Average to SunVCounter
Display Average
Program: Determine the average grade of a class Initialize Counter and Sum to 0 Get the first Grade DO WHILE there are more data Add the Grade to the Sum Increment the Counter Get the next Grade LOOP
Compute Average = Sum / Counter Display Average
Figure 2.8 Flowchart for the Class Average Problem
Figure 2.9 Pseudocode for the Class Average Problem
37
38
Problem Solving
Class Average Program
Get Grade
Figure 2.10
Calculate Average
Compute Sum
Display Average
Top-Down Chart for the Class Average Problem
Comments:
is Tracing a flowchart is like playing a board game. We begin at the Start symbol and proceed from symbol to symbol until we reach the End symbol. At any time we will be at just one symbol. In a board game, the path taken depends on the result of spinning a spinner or rolling a pair of dice. The path taken through a flowchart depends on the input.
The algorithm should be tested into a program. Different data checked. This process is known include nonstandard data as well
at the flowchart stage before being coded should be used as input and the output as desk-checking. The test data should as typical data.
Flowcharts, pseudocode, and top-down charts are universal problem-solving tools. They can be used to construct programs in any computer language, not just QBasic. Flowcharts are used throughout this text to provide a visualization of the flow of certain programming tasks and QBasic control structures. Major examples of pseudocode and top-down charts appear in the case studies. There are four primary logical programming constructs: sequence, decision,
loop, and unconditional branch. Unconditional branch, which appears in some languages as GOTO statements, involves jumping from one place in a program to another. Structured programming uses the first three constructs, but forbids the fourth. One advantage of pseudocode over flowcharts is that pseudocode has no provision for unconditional branching and thus forces the programmer to write structured programs.
Flowcharts are time consuming to write and update. For this reason, professional programmers are more likely to favor pseudocode and top-down charts. Since flowcharts so clearly illustrate the logical flow of programming techniques, however, they are a valuable tool in the education of programmers.
There are many styles of pseudocode. form, whereas others use a form that language. The pseudocode appearing in on the primary tasks to be performed by routine details to be completed during
Some programmers use an outline looks almost like a programming the case studies of this text focuses the program and leaves many of the the coding process. Several QBasic
keywords, such as READ, PRINT, IK DO, and WHILE, are used extensively
in the pseudocode appearing in this text.
Many people draw rectangles around each item in a top-down chart. In this text, rectangles are omitted to encourage the use of top-down charts by making them easier to draw.
Fundamentals of QBasic
40
3
Fundamentals of QBasic
1 NUMBERS Much of the data processed by computers consist of numbers. In “computerese,” numbers are often called numeric
constants. This section discusses the
operations that are performed with numbers and the ways numbers are displayed.
Arithmetic Operations The five arithmetic operations are addition, subtraction, multiplication, division, and exponentiation. (Since exponentiation is not as familiar as the others, it is reviewed in detail in Comment 12.) Addition, subtraction, and division are denoted in QBasic by the standard symbols +, —, and /. However, the notations
for multiplication and exponentiation differ from the customary mathematical notations. Mathematical Notation
a-b
or axb a’
QBasic Notation
a*b ar
(The asterisk [*] is the upper character of the 8 key on the top row of the keyboard. The caret [“] is the upper character of the 6 key at the top of the keyboard.) Note: In this book, the proportional font used for text differs from the monospaced font used for programs. In the program font, the asterisk appears as *. If n is any number, then the statement PRINT
n
displays the number n on the screen. If the PRINT statement is followed by a combination of numbers and arithmetic operations, it carries out the operations and displays the result.
EXAMPLE
1
The following program applies each of the five arithmetic operations to the numbers 3 and 2. Notice that 3 / 2 is displayed in decimal form. QBasic never displays numbers as common fractions. Note 1: The star in the fourth and seventh lines is the computer font version of the asterisk. Note 2: The notation [run] indicates that Shift+F5 is pressed to execute the program. CIES PRIN
SiectaerZ
PRINT
3
- 2
PRINTS
ee
PRINT 3 / 2 PRINTS
3a
PRINT
2
END
[run] 5 1
6 Wes 9
a2 *
(3
+
4)
3.1
NUMBERS
41
Scientific Notation
Let us review powers of 10 and scientific notation. Our method of decimal notation is based on a systematic use of exponents.
10! = 10 10° = 100 10? = 1000
107! = 1/10 =.1 10 = .01 107 = .001
10"=1000...0
10° = .000...01
n zeros
n digits
Scientific notation provides a convenient way of writing numbers by using powers of 10 to stand for zeros. Numbers are written in the form b-10", where b isanumber from | up to (but not including) 10, andr is an integer. For example, it is much more convenient to write the diameter of the sun (1,400,000,000 meters) in scientific notation: 1.4-10? meters. Similarly, rather than write
.0000003 meters for the diameter of a bacterium, it is simpler to write 3-107 meters. Any acceptable number can be entered into the computer in either standard or scientific notation. The form in which QBasic displays a number depends on many factors, with size being an important consideration. In QBasic, b-10" is usually written as bEr. (The letter E is an abbreviation for exponent.) The following forms of the numbers mentioned above are equivalent. 143 1049. J
AOD—7
1 4E +09 SI 4 Eos oo SE-OF
3E-7
1 4Ro
1400000000
0000003
The computer displays r as a two-digit number, preceded by a plus sign if r is positive and a minus sign if 7 is negative.
EXAMPLE 2
The following program illustrates scientific notation. The computer’s decision of whether to display a number in scientific or standard form depends on the magnitude of the number. CLS PRENT PRUNES PROCN PRINT PRINT END
GL cenlOne 33.4 Zea LOROSS ileal Olas 10 “~ -20 10 * -2
[run] 1.2E+34 1.2E+08
1200 1E-20 lO
42
Fundamentals of QBasic
Numeric Variables
In applied mathematics problems, quantities are referred to by names. For instance, consider the following high school algebra problem. “If a car travels at 50 miles per hour, how far will it travel in 14 hours? Also, how many hours are required to travel 410 miles?” The solution to this problem uses the well-known formula distance = rate X time
Here’s how this problem would be solved with a computer program. GIES LET
rate
= 50
LET
time
=
LET
distance
PRINT LET
14 = rate
* time
distance distance
LET time PRINT
= 410
= distance
/ rate
time
END
[run] 700 2
The second line sets the rate to 50 and the third line sets the time to fourth line multiplies the value for rate by the value for time and sets to this product. The next line displays the answer to the first question. three lines before the END statement answer the second question in manner.
14. The distance The last a similar
The names rate, time, and distance, which hold numbers, are referred to as
variables. Consider the variable time. In the third line its value was set to 14. In the seventh line its value was changed as the result of a computation. On the other hand, the variable rate had the same value, 50, throughout the program. In general, a variable is a name that is used to refer to an item of data. The value assigned to the variable may change during the execution of the program. In QBasic, variable names can be up to forty characters long, must begin with a letter, and can consist only of letters, digits, and periods. (The shortest variable names consist of a single letter.) QBasic does not distinguish between upper and lowercase letters used in variable names. Some examples of variable names are total, numberOfCars,
taxRate.1994,
and n. As a convention,
we will keep
variable names in lowercase letters except for the first letters of additional words (as in numberOfCars). LET statements are used to assign values to variables and PRINT statements are used to display the values of variables. If var is a numeric variable and num is a numeric constant, then the statement LET
var
= num
3.1
NUMBERS
43
assigns the number num to the variable var. Actually, the computer sets aside a location in memory with the name var, and places the number num in it. The statement PRINT
var
looks into this memory location for the value of the variable and displays the value on the screen. A combination of constants, variables, and arithmetic operations that can be evaluated to yield a number is called a numeric expression. Expressions are evaluated by replacing each variable by its value and carrying out the arithmetic. Some examples of expressions are 2 * time + 7,n + 1, and (a + b) / 3.
(2 + b)
+
CLS LET LET b PRINT a END
Pm
The following program displays the value of an expression.
u
EXAMPLE 3
[run] 30
If var is a variable, then the statement LET
var
= expression
first evaluates the expression on the right and then assigns its value to the variable. For instance, the program in Example 3 can be written as CLS LETial=—5 LET
LET
b
= 4
c =a
*
(2 + b)
PRINTc END
The expression a * (2 + b) is evaluated to 30 and then this value is assigned to the variable c.
Since the expression in a LET statement is evaluated before an assignment is made, a statement such as DEM
te=
tet al
is meaningful. It first evaluates the expression on the right (that is, it adds 1 to the original value of the variable t), and then assigns this sum to the variable t.
The effect is to increase the value of the variable t by 1. In terms of memory locations, the statement retrieves the value of t from t’s memory location, uses
it to compute t + 1, and then places the sum in t’s memory location.
44
Fundamentals of QBasic
PRINT
Statement
Consider the following program. CLS PRINT PRINT END
3 -3
[run] 3 -3
Notice that the negative number —3 begins directly at the left margin, whereas the positive number 3 begins one space to the right. The PRINT statement always displays nonnegative numbers with a leading space. The PRINT statement also displays a trailing space after every number. Although the trailing spaces are not apparent here, we will soon see evidence of their presence.
leading space
i
trailing space
The PRINT statements considered so far only display one number per line. After displaying a number, the cursor moves to the leftmost position and down a line for the next display. Borrowing some typewriter terminology, we say that the computer performs a carriage return and a line feed after each number is displayed. The carriage return and line feed, however, can be suppressed by placing a semicolon at the end of the PRINT statement.
EXAMPLE 4
The following program illustrates the use of semicolons in PRINT statements. The output reveals the presence of the space trailing each number. For instance, the space trailing —3 combines with the leading space of 99 to produce two spaces between the numbers. CLS PRINT
3;
PRINT
-33
PRINT
99;
PRINT
100
END
[run] 31-3)
995100
Semicolons can be used to display several numbers with one PRINT statement. If m, n, and r are numbers, a statement of the form PRINT
ms:
ins)
35
PRINT
m3
n3
r
or
3.1
NUMBERS
45
displays the three numbers, one after another, separated only by their leading and trailing spaces. For instance, the PRINT statements in Example 4 above can
be replaced by the single line PRINT
3;
-3;
99;
100
Comments:
1. Numbers must not contain commas, dollar signs, or percent signs. Also, mixed numbers, such as 84, are not allowed.
Ze In this text we use lowercase letters for variable names. For names such as interestRate, however, we capitalize the first letter of the second word to
improve readability. QBasic allows any type of capitalization you like and helps you to be consistent with the use of uppercase letters in a variable name. For instance, if you use the variable name interestRate in a program and later enter a line using InterestRate, the appearance of the first variable name will automatically be changed to InterestRate by QBasic.
Some people think of the equals sign (=) in a LET statement as an arrow pointing to the left. This stresses the fact that the value on the right is assigned to the variable on the left. Parentheses should be used when necessary to clarify the meaning of an expression. When there are no parentheses, the arithmetic operations are performed in the following order: (1) exponentiations; (2) multiplications and divisions; (3) additions and subtractions. leftmost operation is carried out first.
In the event of ties, the
Level of Precedence for Arithmetic Operations ( ) A
Inner to outer, left to right Left to right in expression
* / + —
Left to right in expression Left to right in expression
QBasic statements and certain other words that have a specific meaning in the QBasic language cannot be used as names of variables. For instance, the statements LET print = 99 and LET end = 99 are not valid. These words are called keywords (or reserved words). Some keywords that are most likely to be used inadvertently are COLOR, ERROR, INT, KEY, POS, SELECT, VAL, and WIDTH. To view the list of keywords, press Alt/H/I and then use
the PgDn and PgUp keys to scroll through the list. Every capitalized word in the listing is a keyword. Grammatical errors, such as misspellings or incorrect punctuations, are called syntax errors. Certain types of syntax errors are spotted by the smart editor when they are entered, whereas others are not detected until the program is executed. When QBasic spots an error, it displays a dialog box. Some incorrect statements and their errors are given below. Statement
Reason for Error
PRIMT 3 PRINT 24 LET 9W =5
Misspelling of keyword No number follows the plus sign 9W is not a valid variable name
46
Fundamentals of QBasic
7. Numeric variables that have not been assigned values by LET statements have the value 0. We say that the default value is 0. GIES Hel @ = & PRINT a9 b3))b END
[run] 0)
8. When a variable is first assigned a value, we say that the variable is initialized. The failure to initialize variables can cause some programs to malfunction. Uninitialized numeric variables have the value 0. 9. The statement LPRINT produces an output on the printer identical to the display on the screen produced by PRINT.
10. The omission of the asterisk to denote multiplication is a common error. For instance, the expression a(b + c) is not valid. It should read a * (b + c).
11. The largest represent is the message usually have
number the numeric variables considered in this text can 3.402823E+38. Attempting to generate larger values produces “Overflow.” The numbers generated by the programs in this text a maximum of seven digits.
12. A Review of Exponents. The expression 2? means 2 - 2 - 2, the product of three 2’s. The number 3 is called the exponent, and the number 2 is called the base. In general, ifr is a positive integer and a is a number, then a’ is defined as follows:
r factors
The process of calculating a’ is called raising a to the rth power. Some other types of exponents are:
Ae
ee
gli2 _
ain = Vq
N positive integer
16!/4 = 2
qmin . (Va)™
m, N positive integers
82/3 = (V8) =4
a* = fat
a#0
10% = 01
13. More than one statement can be placed on a single line of a program provided the statements are separated by colons. For instance, the program in Example 3 can be written as CLS END
eLET =a 2 5:
LE]
bowed
PRINT
al*
(2.45)
In general, though, programs are much easier to follow if just one statement appears on each line. In this text we almost always use single-statement lines.
3.1
NUMBERS
47
PRACTICE PROBLEMS 3.1 1. Evaluate 2 + 3 * 4.
2. Complete the table by filling in the value of each variable after each line of the program is executed.
Pos,
CEMal=—3
4
PRINT a - b WEI |e) Solo)
Ip
EXERCISES 3.1 In Exercises 1 through 10, evaluate the numeric expression.
Loa
2eL ter
3. LPNS
4.34+4%*5
5. (5-3) *4
6.3
(OI
Oe
Dalek 1)
(-2)5
3 =
B.A D3 84
#22 )5
LOS O165 Oe)
In Exercises 11 through 14, write the number in scientific notation as it might
be displayed by the computer. 11. 3 billion
12.123300,000
13.4/10%8
14,32
10420
In Exercises 15 through 20, determine whether or not the name is a valid variable name.
15. temperature
16. Roads&pavements
17. force.1ONewtons
18. 100Volts
19. Viscosity?
20. INTEL80386
48
Fundamentals of QBasic
In Exercises 21 through 28, evaluate the numeric
expression where a = 2,
b =3,and=c4. (bee)
Zeng
ae
22a
Daler
Oe
24.a%c a) b 26-(c=
25nd Osea) aloe
2c
b
a form “bp a 28
In Exercises 29 through 38, write a QBasic program to calculate the value of the expression.
29785
201 (le 2-9)
31. 5.5% of 20
Bae
3317.6 + 102)
34. 44=3°4
35.1
yo ome
io
ue
1
eerie 63, 37. ee
33)
3
a
314 va 11 3 19% pe
1.6
1
In Exercises 39 and 40, complete the table by filling in the value of each variable after each line of the program is executed. 39.
ey Gere eee [ec el |) Oa Reiachs rai al, ss es
3.1
NUMBERS
In Exercises 41 through 50, determine the output of the program. 41. LET amount PRINT
= 10
amount
42. LET a = 4
- 4
PETS
END
Da=95)
PRINT END
LET
4
3;
a+b;
b-a
44. LET number = 5
43. PRINT 1; 2; PRINT
2a
PRINT 5 + 6 END
number
= 2 * number
PRINT number END
45. LET x = 3 PRINT x ~ x3; x +3 END
46. LET n = 2 PRIN3 T* n LETn =n+n
* x
n +n
PRINT
END
47. LET massl1 = 4 acceleration
LET
= 5
* acceleration
massl
LET forcel = LET mass2 = LET force2 = PRINT forcel
10 * acceleration
mass2
+ force2;
force2
- forcel
END
48. LET electronCharge LET
voltage
LET
electronVolt
PRINT END
=
= 1.6E-19
1 = electronCharge
* voltage
electronVolt
49. LET current = 200 LET
current
PRINT
= 25
+ current
current
END
50. LET density LET
volume
LET
mass
= 1 = 4
= density
PRINT mass LET volume = 5 LET mass = mass PRINT mass END
* volume
+ density
* volume
In Exercises 51 through 54, identify the errors. S51. UE
az
(2
52. LET
YE ys WE @) ae 1) Se PRINT c
LET balance = 800 PRINT interest * balance END
END
53. LET balance LET deposit PRINT
END
balance
.05 = interest
= 1,234 = $100 + deposit
49
50
Fundamentals of QBasic
54. LET neutronNumber
= 1
LET electronNumber = protonNumber = 1 PRINT neutronNumber + protonNumber END
In Exercises 55 and 56, rewrite the program with fewer statements. 55. PRINT 1; PRINT PRINT END
2; 1 + 2
56. LET speed = 55 time = 2 distance = speed PRINT distance END LET LET
* time
In Exercises 57 through 64, write a program beginning with a CLS statement, ending with an END statement, and having one line for each step. 57. The following steps calculate a company’s profit. (a) Assign the value 98456 to the variable revenue. (b) Assign the value 45000 to the variable costs.
(c) Assign to the variable profit, the difference between the variables revenue and costs. (d) Display the value of the variable profit. 58. The following steps calculate the amount of work done by a force moving a body a certain distance in the direction of the force. (a) Assign the value 160 to the variable force. (b) Assign the value 14 to the variable distance. (c) Assign the product of force and distance to the variable work. (d) Display the value of the variable work.
59. The following steps calculate the price of an item after a 30% reduction.
(a) Assign the value 19.95 to the variable price. (b) Assign the value 30 to the variable discountPercent.
(c) Assign the value of discountPercent divided by 100 times price to the variable markDown. (d) Decrease price by markDown. (e) Display the value of price.
60. The following steps calculate the kinetic energy of a body in motion. (a) Assign the value 2000 to the variable mass. (b) Assign the value 20 to the variable velocity.
(c) Assign the value 1/2 times the value of mass times the square of the value of velocity to the variable kineticEnergy. (d) Display the value of the variable kineticEnergy.
61. The following steps calculate the balance after three years when $100 is deposited at the beginning of each year in a savings account at 5% interest compounded annually. (a) Assign the value 100 to the variable balance. (b) Increase the variable balance by 5% of its value and add 100.
3.1
NUMBERS
51
(c) Increase the variable balance by 5% of its value and add 100. (d) Increase the variable balance by 5% of its value and add 100. (e) Display the value of the variable balance.
62. Beginning with 10 grams of radioactive cobalt, the following steps calculate the amount remaining after three years. (a) (b) (c) (d)
Assign the value 10 to the variable radioCobalkt. Decrease the variable radioCobalt by 12% of its value. Decrease the variable radioCobalt by 12% of its value. Decrease the variable radioCobalt by 12% of its value.
(e) Display the value of the variable radioCobalkt. 63. The following steps calculate the balance after ten years when $100 is deposited in a savings account at 5% interest compounded annually. (a) Assign the value 100 to the variable balance. (b) Multiply the variable balance by 1.05 raised to the 10th power. (c) Display the value of the variable balance.
64. The following steps calculate the percentage reduction in area of a material resulting from a compressive force. This value is a measure of the ductility of the material, the ability of being easily molded or shaped.
(a) Assign the value .6 to the variable originalArea. (b) Assign the value .501 to the variable finalArea. (c) Assign to the variable ductility, one hundred times the value of the
difference between originalArea and finalArea divided by originalArea. (d) Display the value of the variable ductility. In Exercises 65 through 74, write a program to solve the problem. The program should use variables for each of the quantities. 65. Suppose each acre of farmland produces 18 tons of corn. How many tons of corn can be produced on a 30-acre farm?
66. Suppose a ball is thrown straight up in the air with an initial velocity of 50 feet per second and an initial height of 5 feet. How high will the ball be after 3 seconds? (Note: The height after t seconds is given by the expression —16t? + uot + ho, where vp is the initial velocity and hg is the initial height.) . Ifa car left Washington, D.C. at two o’clock and arrived in New York at seven o'clock, what was its average speed? (Note: New York is 233 miles from Washington.) . A motorist wants to determine her gas mileage. At 23,340 miles (on the odometer), the tank is filled. At 23,695 miles, the tank is filled with 14.1
gallons. How many miles per gallon did the car average between the two fillings?
.A US. geological survey showed that Americans use an average of 1600 gallons of water per person per day, including industrial use. How many gallons of water are used each year in the United States? (Note: The current population of the U.S. is about 260 million people.)
52
Fundamentals of QBasic
70. One mole of a chemical element or compound is the quantity whose weight in grams is numerically equivalent to its atomic or molecular weight in atomic mass units. For example, a mole of oxygen (atomic weight 16) is 16 grams, a mole of carbon (atomic weight 12) is 12 grams, and a mole of carbon
dioxide
(CO,
of carbon
one atom
two of oxygen)
and
is 44 grams
(12 + 16 + 16). Table 3.1 gives selected atomic weights. What
are the
weights in grams of a mole of each of the following elements and compounds? (a) He (helium) (b) O2 (molecular oxygen) (c) H2O (water)
(d) H,SO, (sulfuric acid) (e) NaCl (salt) (f) NaOH (caustic soda)
Element
Atomic weight
Element
Atomic weight
H
1
Na
23
He
4
S
52
O
16
Cl
B5
Table 3.1
Elements and their Atomic Weights
71. According to FHA specifications, each room in a house should have a window area equal to at least 10 percent of the floor area of the room. What is the minimum window area for a 14-foot by 16-foot room? 72. If a light-year is 5,878,000,000,000 miles and the distance of the star Sirius
from Earth is 9 light-years, how many miles is Sirius from Earth? 73. Ifa barrel holds 5.8 cubic feet and the dimensions of a rectangular container of oil are 2 ft. x 3 ft x 4 ft., how many barrels of oil does the container hold?
74. If a baseball is pitched at 90 feet per second and home plate is 60.5 feet from the pitcher’s mound, how long will it take for the ball to reach the batter? SOLUTIONS TO PRACTICE PROBLEMS 3.1 1. 14. Multiplications are performed before additions. If the intent is for the addition to be performed first, the expression should be written (2 + 3) * 4.
PRINT
a - b
Each time a LET statement is executed, only one variable has its value changed (the variable
to the left of the equals sign).
DLO
LRINGS
753
3 : WD STRINGS There are two types of data that can be processed by QBasic: numbers and strings. Sentences, phrases, words, letters of the alphabet, names, phone numbers, addresses, and dates are all examples of strings. Formally, a string constant
is a sequence of characters that is treated as a single item. Strings can be assigned names with LET statements, can be displayed with PRINT statements, and there is an operation called concatenation (denoted by +) for combining strings.
String Variables A string variable is a name used to refer to a string. The allowable names of string variables are identical to those of numeric variables with one modification: each string variable name must be followed by a dollar sign ($). The value of a string variable is assigned or altered with LET statements and displayed with PRINT statements just like the value of a numeric variable.
EXAMPLE
1
The following program shows how LET and PRINT statements are used with strings. The string variable today$ is assigned a value by the third line and this value is displayed by the fourth line. The quotation marks surrounding each string constant are not part of the constant and are not displayed by the PRINT statements. CLS PRINT
"hello"
LET today$ = "9/17/94" PRINT
today$
END
[run] hello
9/17/94 If
x,y,
...,
BEDeVorg.=
yare characters and var$ is a string variable, then the statement "XY oraz
assigns the string constant xy...z to the variable, and the statement DRUND Mex
area Zi
or
PRINT
var$
displays the string xy...z on the screen. If var2$ is another string variable, then the statement LET
var2$
= var$
assigns the value of the variable var$ to the variable var2$. (The value of var$ will remain the same.) String constants used in LET or PRINT statements must
54
Fundamentals of QBasic
by d nde rou sur r neve are s able vari ng stri but s, mark ion tat quo by d nde rou sur be quotation marks. As with numbers, semicolons can be used with strings in PRINT statements to suppress carriage returns and line feeds. However, PRINT statements do not display leading or trailing spaces along with strings.
EXAMPLE 2
The following program illustrates the use of the LET and PRINT statements. GES
LET phrase$ PRINT "It's PRINT "It's
= "win or lose that counts." not whether you "; phrase$ whether I "; phrase$
END
[run] It's
not
whether
It's
whether
you
I win
or
win
or
lose
lose that
that
counts.
counts.
Concatenation
Two strings can be combined to form a new string consisting of the strings joined together. The joining operation is called concatenation and is represented by a plus sign (+). For instance, “good” + “bye” is “goodbye”. A combination of strings and plus signs that can be evaluated to form a string is called a string expression. The LET and PRINT statements evaluate expressions before assigning them to variables or displaying them.
EXAMPLE 3
The following program illustrates concatenation. GES
LET quotel$ LET quote2$ LET quote$ = PRINT quote$
= "The ballgame isn't = "until it's over." quotel$ + quote2$ + " Yogi Berra"
over,
"
END
[run] The ballgame
EXAMPLE 4
isn't
over,
until
it's
over.
Yogi
Berra
The following program has strings and numbers occurring together in a PRINT statement.
GES LET
interestRate
=
.0655
LET principal = 100 PRINT "The balance after END
[run] The balance
after
a year
a year
is
is";
106.55
(1 + interestRate)
* principal
STRINGS.
SO
155
ASCII Table Each of the 47 keys in the center typewriter portion of the keyboard can produce two characters, for a total of 94 characters. Adding | for the space character produced by the space bar makes 95 characters. Many more characters can be displayed. Appendix A shows the complete table of characters, numbered 0 to 255, that the computer recognizes. (The number assigned to each character is called its ASCII value.) The keyboard characters appear with numbers 32 to 126. Figures 3.1 to 3.4 show some different types of characters. The box-drawing characters in Figure 3.3 have been grouped to show how they fit together. The characters in these figures are referred to by their ASCII values. Ifn is a number between 0 and 255, then CHR$(n)
Poo
oe
4S
_
1:
=
~
=
ee oy fie ee ec,
=
ze
-§-
—»
[rod
ma cis oY met Met
fo
(RS Al) eas
2 oe
bad
pies
ae
lie a
tk +4
ag]
de
ft
#4
J
oS
Box-Drawing Characters (179 to 218)
PU Pt Figure 3.4
i~
i
oes
Cee pe (eR
Figure 3.3.
=
Foreign Language Characters (128 to 168)
od
Figure 3.1
=e
We ake We ett
=i
is the string consisting of the single character with ASCII value n. For instance, CHR$(227) is the string consisting of the Greek letter pi.
Bik Pia Sees, ocd intel *lentsRat fo) > eb 20000 THEN
END END
END IF
PRINT PRINT IF
in
a bar
by
a force.
"A stress of 20,000 to 26,000 " an elongation of 1.4 mm"
causes";
31.1F j = 7 THEN LETED ="1 ELSE IF j 7 THEN LET b= 2 END IF END IF
32. IF a < b THEN LE bec PRINT
END 33.
INPUT
IF
END IF "Is
THEN b;
"is
between";
a;
"and";
c
IF
Alaska
bigger
than
LEFT$(answer$, 1) = "Y" LET answer$ = "YES" END IF IF LEFT$(answer$, 1) = “y" LET answer$ = "YES" END IF IF answer$ = "YES" THEN PRINT "Correct" ELSE PRINT "Wrong" END IF END
Texas
THEN
THEN
and
California
combined";
answer$
IF BLOCKS:
4.2
34. INPUT "How tall
(in THEN
ft.)
is
IF feet 141 THEN IF feet < 161 THEN PRINT "Close" ELSE PRINT "Nope" END IF END IF PRINT "The Statue of Liberty END
the
Statue
of
Liberty";
feet
is
151.08
ft
from
to
base
129
torch."
Ser Write a program to determine how much to tip the bartender in a fine restaurant. The tip should be 15 percent of the check with a minimum of $1. 36. Write a quiz program to ask “What is the unit of power?” The program should display “Correct” if the answer is “Watt” or should display “No, a Watt.” otherwise. 3%. A computer store sells diskettes at $1 each for small orders or at 70 cents apiece for orders of 25 diskettes or more. Write a program that requests the number of diskettes ordered and displays the total cost. (Test the program for purchases of 5, 25, and 35 diskettes.)
38. A particle, originally at rest, is subjected to a force F whose direction is constant but whose magnitude varies with time according to the relation
Pare
Din)
for t between 0 and T (Fy and T are constants). For t > T, F = Fy and for t< 0, F = 0. Write a program that requests the value of Fo, T, and t as input and displays the value of F. Test the program with the responses Fo = 5 newtons, T = 100 seconds, and t = 89 seconds.
39. A copying center charges 5 cents per copy for the first 100 copies and 3 cents per copy for each additional copy. Write a program that requests the number of copies as input and displays the total cost. (Test the program with the quantities 25 and 125.)
40. Write a program that requests the names of three chemical elements and their proton and neutron numbers as input, and calculates their mass numbers. (Mass number = proton number + neutron number.) The program then should display the elements and their mass numbers in order from the highest to the lowest mass number. (Test the program with the responses Hydrogen, 1, 1; Sodium, 11, 12; and Oxygen, 8, 8.)
. Write a program to handle a savings account withdrawal. should request the current balance and the amount of the input and then display the new balance. If the withdrawal the original balance, the program should display “Withdrawal
The program withdrawal as is greater than denied.” If the
new balance is less than $150, the message “Balance below $150” should be
displayed.
130
Decisions
e rag ave the ys pla dis and ut inp as es scor e thre ts ues req that m gra pro a te Wri 42. of the two highest scores.
the ests requ that m gra pro a te Wri ts. digi e thre es duc pro g win dra ery lott A 43. three digits as input and then displays “Lucky seven” if two or more of the digits are 7.
44,
Federal law requires hourly employees be paid “time-and-a-half” for work in excess of 40 hours in a week. For example, if a person’s hourly wage is $8 and he works 60 hours in a week, his gross pay should be
(40-8) + (1.5 -8- (60 —40)) = $560. Write a program that requests as input the number of hours a person works in a given week and his hourly wage, and then displays his gross pay.
45. Write a program that requests a word (with lowercase letters) as input and translates the word into pig latin. The rules for translating a word into pig latin are: (a) If the word begins with a consonant, move the first letter to the end of
the word and add ay. For instance, chip becomes hipcay. (b) If the word begins with a vowel, add way to the end of the word. For instance, else becomes elseway. 46. The work done by a force F in changing the elongation of a spring, of stiffness K, from X, to X, is
W = K(X) =X) where X, and X; are the initial and final lengths of the spring respectively. The work done by a load P to elongate a bar by an amount delta is
W = EA - delta? / (2L) where E
is the elasticity,
A is the
area of a cross section,
delta
is the
elongation, and L is the length of the bar. Write a program that requests the body type (Spring or Bar) as input. If the body is a spring, the program should request the values of K, X,, and X,; if it is a bar, the program should request the values of E, A, delta, and L. Then the program should calculate the work
and display the result. (Try the program with the responses Spring, K = 8 Joules/meter’, X, = .1 meters, X, = .115 meters, and the responses Bar, E = 2 - 10!! Joules/meter’, L = 2.0 meters, A = 12 - 10 meters’, delta = 1.4 - 10° meters. )
47. The current calendar, called the Gregorian calendar, was introduced in 1582. Every year divisible by 4 was declared to be a leap year with the exception of the years ending in 00 (that is, those divisible by 100) and not divisible by 400. For instance, the years 1600 and 2000 are leap years, but 1700, 1800, and 1900 are not. Write a program that requests a year as input and states whether or not it is a leap year. (Test the program on the years 1994, 1996, 1900, and 2000.)
48. Write a program that requests the lengths of three line segments as input and tells whether the lines can form a triangle. Note: The lines can form a triangle if the length of the longest line is less than the sum of the lengths of the other two lines.
4.2
IFBLOCKS
131
49. Write a program that requests a number from 1 through 9999 as input and displays the number of digits in the number. A sample run is [run]
Enter The
a number
number
has
from
1 through
9999:
875
3 digits.
50. The flowchart in Figure 4.3 calculates New Jersey state income tax. Write a program corresponding to the flowchart. (Test the program with taxable incomes of $15,000, $30,000, and $60,000.)
Income
0 Oe
cmCRG sme taeecr
3 17 LET price = 5.00 END SELECT PRINT price
SELECT CASE n CASE 5 PRINT "case CASE 5 TO 7 PRINT "case CASE 7 TO 12 PRINT "case END SELECT END
END
Cleo ie2)
1" 2"
3"
(8.55017) 3. INPUT word$ SELECT CASE LEFT$ (word$, 1) CASE ALON eZ PRINT "Begins with an uppercase letter." CASE "a" TO "z" PRINT "Begins with a lowercase letter." CASE ELSE PRINT "Does not begin with a letter." END SELECT END
(apple, Zebra, 49ers) 4. REM List of environmental factors that affect REM limits of a gas or vapor. INPUT n SELECT CASE n CASE 1 PRINT "Temperature:" PRINT "Lower flammability limits decrease PRINT "temperature increases." CASE 2 PRINT "Pressure: " PRINT "Upper flammability limits increase PRINT "pressure increases." CASE 3 PRINT "Oxygen:" PRINT "Upper flammability limits increase PRINT “oxygen concentration increases." END SELECT END
(1, 2, 3)
flammability
as
";
as
";
as
";
140
Decisions
5. INPUT "In what year was the SELECT CASE year CASE 1945 PRINT "Correct" CASE 1943 TO 1947 PRINT "Close, 1945."
CASE IS PRINT CASE IS PRINT END SELECT END
< 1943 "Sorry, 1945. Work > 1947 "No, 1945. By then
ENIAC
on IBM
computer
the had
completed";
began
ENIAC built
in
a stored
June
year
1943."
program
computer."
(1940, 1945, 1950) 6. REM Type of nondegenerate conic INPUT "Enter coefficient of x * INPUT "Enter coefficient of x * INPUT "Enter coefficient of y * ac SEUEGIMCAS Ee Da 204 ete de CASE IS < 0 PRINT "circle or ellipse" CASE 0 PRINT "parabola" CASE ELSE PRINT "hyperbola" END SELECT END
section 2:", a y:", b 2:", c
(2, 0, -1) 7. REM State a quotation LET a = 3 LET a$ = "hello" INPUT b SEUEGTECASENZave De CASE
el
a * a
PRINT
"Less
is more."
CASE IS > LEN(a$) PRINT "Time keeps everything from happening at once." CASE ELSE PRINT "The less things change, the more they remain the END SELECT END
same."
(755.16) 8.
INPUT
"Who
developed
the
stored
program
concept";
name$
SELECT CASE UCASE$(name$) CASE "JOHN VON NEUMANN", "VON NEUMANN" PRINT "Correct" CASE "JOHN MAUCHLY", "MAUCHLY", "J. PRESPER ECKERT", "ECKERT" PRINT "He worked with the developer, von Neumann, on the ENIAC." CASE ELSE PRINT "Nope" END SELECT END
(Grace Hopper, Eckert, John von Neumann)
SELECT CASE BLOCKS
4.3
9.
INPUT
141
whatever
SELECT
CASE
CASE
EESE
PRINT
whatever
"Hi"
SELECT
END END C7
1)
10. The rotation of a body with a constant angular acceleration is described by theta(t) = alpha - t?/2+ wo -t + thetag
where theta(t) is the rotation angle at time t, thetag is the rotation angle at time t = 0, wg is the initial angular velocity, and alpha is the angular acceleration. REM
Determine
the
PRINT
"Enter
PRINT
" alpha,
the
time
given
values
of
wO,
theta,
the
the and
other
variables.
coefficients"; theta0"
INPUT alpha, wO, theta, theta0 SELECT CASE wO * 2 - 2 * alpha * (thetaO - theta) CASESIS#= 2 AND a < 3 THEN PRINT "The process is adiabatic." REM No heat is transferred in or out. END IF IF a = 3 OR (3 < a AND a = 6 THEN PRINT "The process is isobaric." REM Process takes place at a constant END IF
temperature.
pressure.
33. Table 4.3 gives the terms used by the National Weather Service to describe the degree of cloudiness. Write a program that requests the percentage of cloud cover as input and then displays the appropriate descriptor.
Table 4.3
Percentage of Cloud Cover
Descriptor
0-30 31-70 71-99 100
clear partly cloudy cloudy overcast
Cloudiness Descriptors
34. Table 4.4 shows the location of books in the library stacks according to their call numbers. Write a program that requests the call number of a book as input and displays the location of the book.
Table 4.4
Call Numbers
Location
100 to 199 200 to 500 and over 900
basement main floor
501 to 900 except 700 to 750
upper floor
700 to 750
archives
Location of Library Books
35. Write an interactive program that requests a month of the year and then gives the number of days in the month. If the response is February, the user should be asked whether or not the current year is a leap year.
4.3
SELECT CASE BLOCKS
145
36. Figure 4.5 shows some geometric shapes and formulas for their areas. Write a menu-driven program that requests the user to select one of the shapes, requests the appropriate lengths, and then gives the area of the figure.
Omiess en eke
al
es |
Parallelogram lems
Circle Ge. Figure 4.5
Kite (hee ow) fez
Areas of Geometric Shapes
ST. Write an interactive program that requests an exam score and assigns a letter grade with the scale 90-100 (A), 80-89 (B), 70-79 (C), 60-69 (D), 0-59 (F). (Test the program with the grades 84, 100, and 57.)
38. Computerized quiz show. Write a program that asks the contestant to select one of the numbers 1, 2, or 3. and then asks the corresponding question below. The program then should request the answer as input and tell the contestant if the answer is correct. 1. 2. 3.
Who developed the stored program concept? Who discovered the law of universal gravitation? Who first studied the force of attraction and repulsion between two charges?
(Note: The answers are von Neumann, Newton, and Coulomb.)
39. IRS informants are paid cash awards based on the value of the money recovered. If the information was specific enough to lead to a recovery, the informant receives 10 percent of the first $75,000, 5 percent of the next $25,000, and 1 percent of the remainder, up to a maximum award of $50,000.
Write a program that requests the amount of the recovery as input and displays the award. (Test the program on the amounts $10,000, $125,000, and $10,000,000.) Note: The source of this formula is The Book of Inside Information; Boardroom Books, 1993.
40. Write a program that displays the numbers and terms from Table 4.5, requests a number from 1 through 5 as input, and returns the definition of the requested term as output. A sample run of the program is: [run] 1.
algorithm
Enter a number A bug
is
2.
bug
from
a program
3.
input
1 through error.
4.
5: 2
output
5.
software
146
Decisions
ee 6
Term
Definition
1. algorithm
a finite series of steps leading to the solution of a problem
2. bug 3. input
a program error data obtained by a program from a device (such as keyboard or disk) during execution information produced by a program (usually displayed, printed, or recorded on a disk) computer programs
4. output 5. software
Table 4.5 Computer Terms
41. Table 4.6 shows significant inventions made each year from 1962 through 1966. Write a program that requests the year BASIC was invented and responds with either the message “Correct .” a significant invention made that year (if the answer is 1962, 1963, 1965, or 1966), or the message “You
are off by more than 2 years.” In the first two cases, the program should also give the name of the inventor. Year
Invention
Inventor
1962 1963 1964 1965 1966
Minicomputer Cassette tapes BASIC Word processor Noise reduction system
Digital Corporation Phillips Corporation Kemeny and Kurtz IBM Ray M. Dolby
Table 4.6 Significant Inventions
42. Table 4.7 contains information on several states. Write a program that requests a state and category (flower, motto, and nickname) as input and
displays the requested information. If the state or category requested is not in the table, the program should so inform the user. State
Flower
Nickname
California Indiana Mississippi New York
Golden poppy Peony Magnolia Rose
Golden State Hoosier State Magnolia State Empire State
Table 4.7
Motto
Eureka Crossroads of America — By valor and arms Ever upward
State Flowers, Nicknames, and Mottos
SOLUTIONS TO PRACTICE PROBLEMS 4.3 1. (a) Valid. These items are redundant since 1 and 4 are just special cases of IS < 10. However, this makes no difference in QBasic.
(b) Valid. These items are contradictory. However, QBasic looks at them one at a time until it finds an item containing the value of the selector. The action following this CASE clause will always be carried out. (c) Not valid; “2” is a string and the selector has numeric type.
2. Yes. However, the program on the right is clearer and therefore preferable.
Programming Projects
147
Chapter 4 Summary 1. The relational operators are , =, , =.
2. The principal logical operators are AND, OR, and NOT. 3. A condition is an expression involving constants, variables, functions, and
operators (arithmetic, relational, and/or logical) that can be evaluated to either true or false.
4. An IF block decides what action to take depending upon the truth values of one or more conditions. To allow several courses of action, the IF and ELSE
parts of an IF statement can contain other IF statements.
5. A SELECT CASE block selects one of several actions depending on the value of an expression, called the selector. The entries in the value lists must have the same type (string or numeric) as the selector.
Chapter 4 Programming Projects 1. The American Heart Association suggests that at most 30% of the calories in our diet come from fat. Whereas food labels give the number of calories and amount of fat per serving, they often do not give the percentage of calories from fat. This percentage can be calculated by multiplying the number of grams of fat in one serving by 9, dividing that number by the total number of calories per serving, and multiplying the result by 100. Write a program that requests the name, number of calories per serving, and the grams of fat per serving as input, and tells us whether the food meets the American Heart Association recommendation. A sample output is as follows: [run] Enter
name
Enter
number
Enter
grams
Lowfat
milk
contains
Lowfat
milk
exceeds
of
food:
Lowfat
of calories of
fat
per
milk
per serving: serving:
37.5% the
AHA
120
5
calories
from
fat.
recommendation.
2. Write a program to determine the real roots of the quadratic equation ax’ + bx +c = 0 (where a¥ 0) after requesting the values of a, b, and c. Insure that a is nonzero.
Note:
The
equation
has
2,
1, or O solutions
depending upon whether the value of b’ — 4ac is positive, zero, or negative. In the first two cases the solutions are given by the quadratic formula (—b + Vb? — 4ac ) / 2a.
148
Decisions
3. Write a program to find the day of the week for any date after 1582, the year
our current calendar was introduced. The program should: (a) Request the year and the number of the month as input. (b) Determine the number of days in the month. Note: All years divisible
by 4 are leap years, with the exception of those years divisible by 100 and not by 400. For instance, 1600 and 2000 are leap years, but 1700, 1800, and 1900 are not.
(c) Request the number of the day as input. The prompt should list the possible range for the number. (d) Determine the day of the week with the following algorithm. (1) Treat January as the 13th month and February as the 14th month of the previous year. For example 1/23/1986 should be converted to 13/23/1985 and 2/6/1987 should be converted to 14/6/1986. (2)
Denote the number of the day, month, and year by d, m, and y. Compute
w=d+t2m+ INT(.6 * (m+1)) + y + INT(y/4) —INT(y/100) + INT(y/400) + 2
(3)
The remainder when w is divided by 7 is the day of the week of the given date, with Saturday as the zeroth day of the week, Sunday the first day of the week, Monday the second, and so on.
Some sample outputs of the program are: [run] Year (xxxx)?
1776
Month (1 - 12)? 7 Day The
of Month (1 - 31)? 4 day of the week was Thu
[run] Year (xxxx)? 1987 Month (1 - 12)? 2 Day of Month (1 - 28 )? 28 The day of the week was Sat
Test the program with the following memorable dates in the history of the US. space program. On Tuesday, February 20, 1962, John Glenn became the first American to orbit the earth.
On Sunday, July 20, 1969, Neil Armstrong became the first person to set foot on the moon. On Saturday, June 18, 1983, Sally Ride became the first American woman to travel in space. 4. An electric circuit can be:
(a) Resistive (composed of resistors only) with impedance Z given by Z = R, where R is the equivalent resistance. (b) Capacitive (composed of capacitors only) with impedance given by Z = 1/(C- w), where w is the angular frequency and C is the equivalent capacitance.
Programming Projects
(c) Inductive
(composed
only)
of inductors
with
impedance
Z = L- w, where L is the equivalent inductance. (d) R-L series (composed of a resistor and an inductor
149
given by
in series) with
impedance given by Z = VR? + (L-w)’. (e) R-C series (composed of_a resistor and a capacitor in series) with impedance given by Z = VR? + 1/(C-w)’. (f) R-L-C series (consists of a resistor, a capacitor, and an inductor in series) with impedance given by Z = VR? + (L-w—1/(C-w))’. Write a program to calculate the impedance of a circuit. The program should request the type of circuit (from the list above), then the values of the components
of the circuit, calculate
the corresponding
impedance,
and
display the result. Some sample outputs of the program are: [run] Enter the type of circuit: inductive Enter inductance, angular frequency: .02, 100 The impedance Z of the inductive circuit is 2 Ohms. [run] Enter the type of circuit: resistive Enter resistance: 100 The impedance Z of the resistive circuit
is
100
Ohms.
Write a program to request a positive number n and the real and imaginary parts of a complex number as input, and display an nth root of the complex number. The program should convert the complex number to the polar form r(cos 8 + i- sin 8), with O < @ < 2, and then compute r!/™(cos(@/n) + i- sin(@/n)).
the nth root as
FICA taxes have a social security and a medicare component. In 1994, Social security taxes are paid at the rate of 6.2 percent on the first $60,600 of earnings in a year. Medicare taxes are paid at the rate of 1.45 percent on total earnings. Write a program to request this year’s total earnings prior to
the current pay period and the earnings for the current pay period for an employee, and then calculate the FICA tax. . Write a program to solve the system of linear equations ax + by =e cx + dy =f where the values of a, b, c, d, e, and f are stored in DATA statements. The
program should report if there are one, none, or infinitely many solutions, and should display all solutions. Note: The program has a unique solution when ad — bc # 0. Infinitely many solutions can be described as (x, mx + 1) for specific values of m and r.
Genetics. The color of a guinea pig’s coat is determined by a single pair of genes. Two possible coat colors are black and brown. Black is dominant to brown, which means that a guinea pig which inherits a gene for black (B) from one parent and a gene for brown (b) from the other will have a black
coat. The recessive gene will determine the color only if both parents pass on the recessive gene. Hair length is also controlled by a single pair of genes; short hair (S) is dominant to long hair (s). Every guinea pig inherits two
150
Decisions
genes for each trait, but can pass on only one gene for each trait. This gene must be among those received from the parents. For example, a guinea pig with the genetic makeup “Bbss” can pass on either a black or brown coat color, but must pass on long hair. The offspring may or may not have long hair, depending on the hair length gene from the other parent. Write a program that requests the genes from a male and female adult guinea pig in the form of two four-character strings (such as “BbSs” and “bbSs”), requests
the hair color and hair length of a baby guinea pig and determines if the baby could be an offspring of the adults.
Repetition
-333rore
al
point values jage Pymt), $300,1 | Over
this
Hd
name
Print
3
THEN
INT
ELSE
WEND LPRINT
EN
aaa
MDESS$
tt Ga
G
ptal of pr ter fils ile e from a
’ 5 |
i
e(K) ae" > MUPC (K)
WHILE P IF P
i ed items, purchase ii
priceof pi ‘Array numbe-
"To hold ru “UPC numb ‘Price fr’ PC, descri AS #1 MPRI
T2090 LET TO eo LET MUP e O LET MPR d and prin REM -OPEN "“LEDAT” FOR I UPCS,. MDE INPUT
value
bank?,
(K)
: S PCS' ,PU (J) C PUP
: SWAP |
S a= LET K =
3, | point
QO N-1 +1 TO N-1 > PU $(J)
FOR J FOR IF NEXT NEXT J RETURN
INP
es ole ig
Se
CLOSE ARETURN
WAM
a
} i\t )
\\
determine
GE
,
POLE
LE
es
Sonic
oroaram tne
EE
apmold”
HR
SCnrmeLldear «=
M4 ,
if
Mun minim
ALG interactive 1@ AMSHOrS are
PE ashe
CE
cl
4
Xe
PUL TONG i MOUNT MLM
#
oh
title:
REL
,
APE
PSL
iy BOF #
7%
é
D
IE
i
cs
") vou
Do i
iE
Bad2 SRS a é
Ee
quality a
for
a ?
ba; s
.
152
Repetition
5
1 DO LOOPS A loop, one of the most important structures in QBasic, is used to repeat a sequence of statements a number of times. At each repetition, or pass, the statements act upon variables whose values are changing. The DO loop is one of the most important structures in QBasic. It repeats a sequence of statements either as long as or until a certain condition is true. A DO statement precedes the sequence of statements and a LOOP statement follows the sequence of statements. The condition, along with either the word WHILE or UNTIL, follows the word DO or the word LOOP. When QBasic executes a DO loop of the form DO
WHILE
condition
statement (s) LOOP
it first checks the truth value of condition. If condition is false, then the statements
inside the loop are not executed and the program continues with the line after the LOOP statement. If condition is true, then the statements inside the loop are executed. When the statement LOOP is encountered, the entire process is repeated beginning with the testing condition in the DO WHILE statement. In other words, the statements inside the loop are repeatedly executed as long as the condition is true. Figure 5.1 contains the pseudocode and flowchart for this loop.
DO WHILE condition is true Processing step(s) LOOP
Is the condition true?
Execute statements within the loop
Execute statements that follow
the loop
Figure 5.1
Pseudocode and Flowchart for a DO Loop
No
5. Pf (DOLOOPS”
EXAMPLE
1
SOLUTION _
1153
Write a program that displays the numbers from | through 10. The condition in the DO loop is num 1981 PRINT “Earlier than that. The first successful IBM PC clone, " PRINT "the Compaq Portable, appeared in 1983." END SELECT PRINT LOOP UNTIL year = 1981 END
(Assume the first response is 1980 and the second response is 1981.)
"
5:1
6.
REM
Simulate
INSTR,
search
for
a
letter.
INPUT "Enter a word: ", word$ INPUT "Enter a letter: ", letter$ LET counter = 0 LET oldLetter$ = " " DO WHILE (oldlLetter$ letter$) AND counter
LET
= counter
+
DOLOGES
(counter
1) AND (a < 3) 20. UNTIL (state$ = “motion”) AND (acceleration = 5)
21. UNTIL NOT (n = 0)
22. WHILE (a$ = “capacityCharging”) AND (energy < 7) In Exercises 23 and 24, write a simpler and clearer program that performs the same task as the given program. 23. INPUT
num
PRINT
num
INPUT
num
PRINT
num
INPUT
num
PRINT
num
END
53) DO LOOPS,
24. REM
Calculate
REM LET DO
the
number
n of
revolutions
per
165
minute
of a generator loopNum = 0 IF loopNum >= 1 THEN INPUT "Do you want
to continue
(Y/N)";
answer$
ELSE
LET END
IF
answer$
= "Y"
IF
(answer$
= "Y")
OR
(loopNum
= 0)
THEN
INPUT frequency LET n = 60 * frequency LET loopNum = loopNum + 1 PRINT
END
LOOP
n
IF
UNTIL
answer$
"Y"
END
25. Write a program that requests a temperature between 0 and 100 degrees Celsius and converts the temperature to Fahrenheit. If the response is not between 0 and 100, the request should be repeated until a proper response is given. (Note: The formula f = (9/5)c + 32 converts Celsius to Fahrenheit.)
26. According to Newton’s law of motion, the resultant of all of the forces acting on a body of mass m is R=ma
where a is the acceleration of the body. Consider a body of mass m subjected to its weight w = mg (g is the acceleration of gravity) and a frictional force F (due to air resistance) given by F=kyv
where v is the speed of the body and k is a constant depending on the dimensions of the body. The equation of motion is mg — kv = ma
Write a program to solve the above equation (find v) where m, a, g, and k are supplied with INPUT statements. After solving the equation, ask the user if he or she wants another equation solved. 27. Write a program that repeats the question “D’you know the capital of Alaska?” until the correct answer is given. The program should display the statement, “It rhymes with D’you know.” when an incorrect answer is given. 28. Write a program to forecast the weather in Oregon. The program should request input with the prompt “Can you see the mountains (Y/N)?” The program should display “It is going to rain.” or “It is raining.” depending upon whether the first letter of the response is Y (or y) or N (or n), respectively. If the first letter of the response is not Y, y, N, or n, the request should be repeated until a proper response is given.
164
Repetition
Zo A car’s computer can determine the number of gallons of gasoline in the
tank and sense whether the driver’s seatbelt is fastened and the doors are closed. The computer will not allow the car to be shifted out of “Park” if either the driver’s seatbelt is not fastened or any door is open. If the tank contains less than two gallons of gasoline, the message “Get gas.” is displayed. Write a program to simulate the operation of the computer. A sample output 1S:
{run] Is the driver's seatbelt fastened Are all doors closed (Y or N)? Y¥ Please Is
the
fasten
your
driver's
gallons
How
many
You Get
may proceed. gas.
N
N)?
Y
seatbelt.
seatbelt
of
(Y or N)?
gas
fastened
are
in
the
(Y
or
tank?
1
30. Write a program to find the first integer whose cube is greater than 3000. Sls Write a program that asks the user to enter positive numbers into the computer until the product of the numbers exceeds 400. The program should then display the highest number. Sy” There is a legend that King Shirham of India wanted to reward his grand vizier Sissa Ben Dahir for inventing the game of chess. When asked what reward he wanted, Sissa Ben asked for 1 grain of wheat on the first square of the board, 2 on the second, 4 on the third, and so forth, doubling the amount of grains on each successive square. King Shirham quickly found that the amount of wheat in the request would be more than his country could possibly produce. Write a program that uses a loop to calculate on which of
the 64 squares of the chessboard the total number of grains would exceed (a) one million; (b) one billion; (c) one trillion.
a3. Write a program to display all the numbers between | and 100 that are perfect squares.
34. The population of Mexico City is currently 14 million people and growing at the rate of 3 percent each year. Write a program to determine when the population will reach 20 million. 35, Write a program to solve the equation ax + b = c, where the numbers a, b, and c are supplied via INPUT statements. Allow for the case where a is 0. If so, there will either be no solution or every number will be a solution. After solving each equation, ask the user if he or she wants another equation solved. 36. Write a program that requests a word containing the two letters r and n as input and determines which of the two letters appears first. If the word does not contain both of the letters, the program should keep requesting words until one does. (Test the program with the words colonel and merriment.)
521)
DOLOOPS:
— 165
37. The coefficient of restitution of a ball, a number between 0 and 1, specifies
how much energy is conserved when a ball hits a rigid surface. A coefficient of .9, for instance, means a bouncing ball will rise to 90 percent of its initial height after each bounce. Write a program to input a coefficient of restitution and a height in meters and report how many times a ball bounces before it rises to a height of less than ten centimeters. Also report the total distance traveled by the ball before this point. The coefficients of restitution of a tennis ball, basketball, super ball, and softball are .7, .75, .9, and .3, respec-
tively. In Exercises 38 through 43, write a program to solve the stated problem.
38. Savings Account. Fifteen thousand dollars is deposited into a savings account paying 5 percent interest and $1000 is withdrawn from the account at the end of each year. Approximately how many years are required for the savings account to be depleted? 39. Rework Exercise 38 for the case where the amount of money deposited initially is input by the user and the program computes the number of years required to deplete the account. (Note: Be careful to avoid infinite loops.)
40. The simplest semiconductor device is a p—n junction, or diode, made of Germanium or Silicon doped with a particular type of impurity. The current-voltage relationship in an ideal diode is described by
[Sh (ei
1)
I is the current that flows through the diode (in amperes). 1: is the saturation current (in amperes), L. =10°
amperes.
v is the voltage across the diode (in volts). q is the electron charge, q = 1.6 - 107? coulombs k is Boltzmann’s constant, k = 1.38 - 10773 joules / °K T is the temperature of the junction (in °K)
With T = 293°K, calculate and display I as v varies from —.2 volts to 1 volt in steps of .1. 41. One thousand dollars is deposited into a savings account, and an additional $1000 is deposited at the end of each year. If the money earns interest at the rate of 5 percent, how long will it take before the account contains at least
one million dollars? 42. The change, 6, in the dimensions of a block of material of length L is given by
6=a-TL where T is the change in temperature (in degrees Celsius) and o is the coefficient of thermal expansion which is a property of the material. For a block of aluminum of length 3.0 and a = 23 - 10° / °C, calculate 8 for different values of T (T = 10, 15, 20, .. .). Stop when 6 exceeds 4 - 103
meters and display the corresponding temperature. 43. A person born in 1980 can claim “I will be x years old in the year x squared.” Determine the value of x.
166
Repetition
t. ar ch ow fl the to g in nd po es rr co m ra og pr a e it wr 45, d In Exercises 44 an d an ut inp as | an th r ate gre r ege int an ts ues req 5.3 44. The flowchart in Figure y onl its if e im pr is er mb nu A : te No s. er mb nu e im pr factors it into a product of .) 139 d an 0 66 s er mb nu the th wi m ra og pr the st (Te . elf its d an 1 factors are
Get two
Get integer
pos. integers
N>1
M and N
Set F=2
No
Yes
No
Does
Yes
F divide N ?
Increase
F by 1
Set N = N/F
End
Figure 5.3
Prime Factors
Figure 5.4
Greatest Common Divisor
45. The flowchart in Figure 5.4 finds the greatest common divisor of two positive integers input by the user. (The greatest common divisor of two positive integers is the largest integer that divides both of the numbers.) Write a program that corresponds to the flowchart.
5.2
PROCESSING LISTS: OF DATA WITH DOLOOPS
167
46. After the engine of a moving motor boat is turned off, the speed of the boat decreases as it continues to move across the water. If the boat’s speed in miles/hour when
the motor is turned off is initSpeed, then its speed after
moving distance feet is given by speed = initSpeed - Exp(—2 - (distance / 5280)) (a) Write a function that accepts a boat’s initial speed and the distance it
has travelled since the motor was turned off as input, and computes its speed at that distance. (b) Suppose to safely ground a boat on the beach, it should be moving between 2 and 5 miles/hour. Use the function in (a) to write a program
that requests the initial speed of a boat and outputs the distance from the beach the motor should be turned off in order to drift safely to the beach. Hint: Use a loop to increase the distance until the function yields a value in the desired range.
SOLUTIONS TO PRACTICE PROBLEMS 5.1 1. As arule of thumb, the condition is checked at the bottom if the loop should be executed at least once.
2. Either precede the loop with the statement LET continue$ = “Yes” or change the first line to DO and replace the LOOP statement with LOOP UNTIL continue$ “Yes”.
5
vy, PROCESSING LISTS OF DATA WITH DO LOOPS One of the main applications of programming is the processing of lists of data. DO loops are used to display all or selected items from lists, search lists for specific items, and perform calculations on the numerical entries of a list. This
section introduces several devices that facilitate working with lists. Counters calculate the number of elements in lists, accumulators sum numerical values in lists, flags record whether certain events have occurred, and trailer values
indicate the ends of lists. Nested loops add yet another dimension to repetition. Trailer Values
The data to be processed are retrieved by a DO loop either from DATA statements or from the user with INPUT statements. In order for the loop to know when all the data have been read, special data called trailer values or sentinels are added to the end of the list. Commonly used trailer values are —1 and EOD, which stands for “End of Data.” Trailer values should not be possible responses for processing. For instance, if a loop calculates a bowling score, 0 is not a good trailer value since the user might enter O to represent a gutter ball.
168
Repetition
EXAMPLE
1
The s. ion ent inv nt ica nif sig e som of es dat the ys pla dis m gra pro ing low fol The ue val ler trai t firs The s. ent tem sta TA DA in ned tai con are s ion ent inv dates and is , EOD ue, val ler trai ond sec The d. rea is —1 il unt eat rep will is —1. The loop needed to have something
to assign to invention$
on the last execution of
READ. REM
Dates
of
significant
inventions
CES READ dateOfInvention, invention$ DO WHILE dateOfInvention -1 PRINT dateOfInvention, invention$ READ dateOfInvention, invention$ LOOP REM --- Data: date, invention DATA
1100,
rocket
DATA
1410,
wire
DATA
1620,
submarine
DATA
1948,
velcro
DATA DATA END
1964, BASIC -1, EOD
[run] 1100
rocket
1410
wire
1620
submarine
1948
velcro
1964
BASIC
The program in Example 1 illustrates the proper way to process a list of data having a trailer value. The DO loop should be tested at the top. The first item of data should be obtained before the DO statement and used to determine whether the loop should be entered. The loop begins by processing the data and then requests the next piece of data just before the LOOP statement. This method of processing a list guarantees that the trailer value will not be processed. Figure 5.5 contains the pseudocode and flowchart for this technique.
EXAMPLE
SOLUTION
2
Modify the program in Example | to search the list of significant inventions for an invention specified by the user. If the invention does not appear in the list, so notify the user.
For starters, we should begin with an INPUT statement to request the sought invention. We want to keep searching as long as there is no match and we have not reached the end of the list. Therefore, the condition for the DO WHILE statement is a compound logical expression with the operator AND. After the last pass through the loop, we will know whether the invention was found and be able to display the requested information.
5.2
PROCESSING LISTS OF DATA WITH DO LOOPS
Get first item DO WHILE item is not the trailer value Process the item Get the next item
LOOP Is item different from the trailer value?
Process the item
Execute
statements following loop
Figure 5.5 REM CLS
Look
INPUT READ
Pseudocode and Flowchart for Processing a List with Trailer Value for
a specific
"Invention";
inventToFind$
dateOfInvention,
DO WHILE READ
invention
invention$
(inventToFind$ dateOfInvention,
invention$)
invention$
LOOP IF dateOfInvention = -1 THEN PRINT "Invention not found." ELSE PRINT dateOfInvention, invention$ END IF REM
---
Data:
date,
DATA
1100,
rocket
DATA
1410,
wire
DATA
1620,
submarine
DATA DATA DATA END
1948, velcro 1964, BASIC -1, EOD
"Invention
invention
"Date,
AND
to
search
invention
(dateOfInvention ‘Date,
for
invention
-1)
in
list
169
170
Repetition
[run] Invention?
submarine
1620
submarine
[run] Invention? Invention
airplane not
found.
Nested Loops The statements inside of a DO loop can consist of another DO loop. Such a configuration is referred to as a nested loop and is useful in repeating a single data processing routine several times.
EXAMPLE 3
Modify the program in Example 2 to allow the user to look up as many inventions as desired.
SOLUTION
The statements inside the DO WHILE loop will be used to look up inventions as before. At least one pass through the outer DO loop is guaranteed and passes will continue as long as the user responds “Y”. REM Look for specific inventions CLS DO RESTORE INPUT "Invention"; inventToFind$ READ dateOfInvention, invention$
DO WHILE READ
(inventToFind$
dateOfInvention,
invention$)
‘Invention ‘Date,
AND
invention$
to
search
invention
(dateOfInvention ‘Date,
for
-1)
invention
LOOP IF dateOfInvention = -1 THEN PRINT "Invention not found." BESE
PRINT END
dateOfInvention,
invention$
IF
INPUT "Do you want to look up another LOOP UNTIL response$ "Y" REM --- Data: date, invention DATA 1100, rocket DATA
1410,
wire
DATA
1620,
submarine
DATA
1948,
velcro
DATA
1964,
BASIC
DATA
-1,
invention
(Y/N)";
EOD
END
[run] Invention?
velcro
1948
Do you
velcro
want
Invention?
to
up
another
invention
(Y
N)?
Ni
up another
invention
(Y or N)?
N
or
wire
1410
Do you
look
wire
want
to
look
response$
in
list
PROCESSING LISTS OF DATA WITH DOLOOPS
5.2
171
Counters and Accumulators
A counter is a numeric variable that keeps track of the number of items processed. An accumulator is a numeric variable that totals numbers.
EXAMPLE 4
Write a program to count and find the value of coins listed ina DATA statement.
SOLUTION
REM
How much
change
LET
numCoins
= 0
LET
sum
do you
have?
CLS
READ
= 0
num
DO WHILE
num
LET
numCoins
LET
sum
READ
-1 = numCoins
= sum
+
1
+ num
num
LOOP PRINT REM
"The ---
DATAM
value
Data:
wel
of
the";
numCoins;
"coins
is";
sum;
"cents."
coin
5 al Ons
2
Om
END
[run] The
value
of
the
6
coins
is
52
cents.
The value of the counter, numCoins, was initially
0 and changed on each
execution of the loop to 1, 2, 3, 4, 5, and finally 6. The accumulator, sum, initially had the value 0 and increased with each execution of the loop to 1, 2, 7, 17, 27,
and finally 52.
Flags A flag is a variable that keeps track of whether a certain event has occurred. Typically, it is initialized with the value O and then assigned a nonzero value when the event occurs. It is used within a loop to provide information that will be taken into consideration after the loop has terminated. The flag also provides an alternate method of terminating a loop.
EXAMPLE 5
The following program counts the and then reports whether the words of the loop, a word is compared to called orderFlag, is initially assigned words is out of order. The technique 7 when we study sorting. Note: The
number of words in the DATA statements are in alphabetical order. In each execution the next word in the list. The flag variable, the value 0 and is set to 1 ifa pair of adjacent used in this program will be used in Chapter statement in line 5 is a device to get things
started. Each word must first be read into the variable word2$. In fact, wordCounter is incremented only when word2$ gets a non-sentinel value. words.
REM
Count
CLS LET
orderFlag
= 0
Are
they
in
alphabetical
order?
172
Repetition
= 0
LET wordCounter
LET wordl$ = "" READ word2$ DO WHILE word2$ "EOD" LET wordCounter = wordCounter IF word1$ > word2$ THEN LET orderFlag = 1 END IF LET word1$ = word2$ READ word2$ LOOP "The
PRINT
number
IF orderFlag = 0 THEN PRINT "The words are
ELSE PRINT END
words
"The
is";
of words
+ 1
wordCounter
in alphabetical not
are
in
order."
alphabetical
order."
IF
REM --- Data: DATA cambist,
winning words in U.S. National Spelling Bee croissant, deification, hydrophyte, incisor
maculature,
DATA
macerate,
narcolepsy,
shalloon,
EOD
END
[run] The number of words is 9 The words are not in alphabetical
EXAMPLE 6
order.
Write a program to calculate the average of exam grades input by the user. The program also should indicate whether any student received a perfect score.
SOLUTION _ The following program uses the variable numScores as a counter, the variable sum as an accumulator, and the trailer value —1. REM
Calculate
average
score
CLS REM Display instructions PRINT "Enter the scores one at a time. After all of the" PRINT "scores have been reported, enter the number -1." REM Input scores from the user LET numScores = 0 LET sum = 0 LET perfectFlag = 0 INPUT "Enter a Score: ", score DO WHILE score -1 LET numScores = numScores + 1 LET
sum
= sum
+ score
IF score = 100 THEN LET perfectFlag
END IF INPUT "Enter LOOP
a Score:
= 1 ",
score
PROCESSING LISTS OF DATA WITH DO LOOPS
5.2
REM
Compute
and
REM
Announce IF numScores
display
if >=
there
IF
average
are
any
perfect
scores
1 THEN
LET average PRINT
173
= sum / numScores
"The
average
score
is";
average
perfectFlag = 0 THEN PRINT "No perfect score." EESE
PRINT END IF END
"At
least
one
perfect
score."
IF
END
[run] Enter
the
scores
scores
have
one
been
Enter
a score:
80
Enter
a score:
Enter
a score:
90 82
Enter
a score:
Enter
a score:
The
No
average
perfect
at
a time.
reported,
enter
After the
all
of
number
the -1.
88 -l
score
is
85
score.
In Example 6, the value of the counter, numScores, was initially 0 and changed on each execution of the loop to 1, 2, 3, and finally 4. The accumulator,
sum, initially had the value 0 and increased with each execution of the loop to 80, 170, 252, and finally 340. The flag, perfectScore, was initially 0 and never changed. After the loop was terminated, the average was calculated by dividing
340 by 4.
Loops in Mathematics Suppose
the mathematical
function f(x) is defined and continuous on the
interval [a, b], and f(a) has a different sign than f(b). (See Figure 5.7.) Then the equation f(x) = 0 must have a solution between a and b. That is, there must exist a number c between a and b with f(c) = 0. Such a number c is called a zero of the
function. The flowchart in Figure 5.6 describes an algorithm, known as the bisection method, for finding c. At each iteration, the length of the subinterval
containing c is halved. Halving continues until the subinterval reaches a certain tolerance length (such as .00001) or until c is found exactly (an unlikely event). Because single-precision numbers are only accurate to 7 significant figures, the choice of an appropriate tolerance level depends on the magnitude of the zero. For instance, .1 is an appropriate tolerance level if c is near 100,000,000, and 10-3! is appropriate if c is very close to 0. In general, .00001 is a good tolerance level for medium-sized values of c.
174
Repetition
Figure 5.6 Flowchart for the Bisection Method
EXAMPLE
7
Figure 5.7 A Function with a Zero in the Interval [a, 5]
Write a program to find a zero of the function e*— x— 4. This function is graphed in Figure 5.7. REM
REM
The
Bisection Method Approximate a zero of a function
REM values CLS
a and b, where f(a)
f(x)
and f(b)
between
the
have different
user
signs
supplied
PROCESSING LISTS OF DATA WITH DOLOORS
>.2
“175
DEE ENT (x) = EXP(x) = x = 4 INPUT "Enter a tolerance level (such as .00001): ", tolerance REM Guarantee that the tolerance level is not too smal] IF tolerance 0 = total
LET total READ num LOOP PRINT REM
total --- Data:
DATA
5,
2,
+ num
numbers
6,
-1
END
2. REM Display
list of noble gases
READ gas$ DO WHILE gas$ PRINT gas$ READ gas$ LOOP REM
---
DATA
Data:
"EOD"
noble
Helium,
Neon,
gases Argon,
Krypton,
Xenon,
Radon,
EOD
END
3. READ city$, DO
WHILE
IF
pop
pop
city$
>=
"EOD"
7 THEN
PRINT city$ END
IF
READ city$ LOOP REM --- Data: DATA
San
DATA
Boston,
DATA
Chicago,
DATA
New
DATA
EOD,
city,
Francisco,
population
(in millions)
5.6
4 8
York,
17.7
0
END
4. REM READ
Display
some
numeric
constantName$,
DO WHILE READ
value,
constantName$
PRINT
constants.
constantName$;
constantName$,
unit$
"EOD"
" =";
value;
value,
unit$
name,
value,
unit$
LOOP REM
---
Data:
constant
DATA
"Speed
of
DATA
"Planck's
DATA
"Avogadro's
DATA END
EOD,
-1,
light",
2.9979E8,
constant",
EOD
number",
unit
"meters
6.626E-34,
6.022E23,
per
second"
"joule-seconds"
"molecules
per
second"
177
178
Repetition
5. READ
sentence$ was
' flag tells if the loop LET flag = 0 DO WHILE LEN(sentence$) < 20 LET flag = 1 LET sentence$ = sentence$ + sentence$
executed
LOOP
IF flag = 1 THEN PRINT sentence$ BESE PRINT "Loop not executed." END IF REM --- Data: sentence DATARS Is thinkel cane. END
6. READ fruit$ DO WHILE fruit$ "EOD" LET firstLetter$ = LEFT$(fruit$, 1) PRINT TAB(3); firstLetter$ DO WHILE LEFT$(fruit$, 1) = firstLetter$ PRINT fruit$ READ fruit$ LOOP PRINT LOOP REM --- Data: fruits DATA
Apple,
Apricot,
DATA
Blueberry,
Avocado,
Grape,
Lemon,
Banana Lime,
EOD
END
7. REM Display READ DO
list of numbers
num
WHILE READ
num
-1
num
PRINT
num
LOOP REM --DAMAW25 END
Data: numbers 35) S555) 0-2
8. INPUT "Animal"; animal$ READ creature$, groupName$ DO WHILE (creature$ animal$) READ creature$, groupName$
AND
(creature$
"EQD")
LOOP
IF groupName$ PRINT
= "*"
"Animal
THEN not
found."
BESE
PRINT END
IF
REM
---
DATA
"A group
Data:
lion,
of
animal,
pride,
duck,
";
animal$;
name
"s
is
called
a ";
of group
brace,
END
(Assume the response is duck.)
bee,
swarm,
EOD,
*
groupName$
PROCESSING LISTS OF DATA WITH DOLOOPS_
5.2
9. READ word$ DO WHILE IF
word$
"EOD"
LEFT$(word$,
1)
LET cWord$ END IF READ word$ LOOP PRINT cWord$ REM
---
Data:
=
“c”
THEN
= word$
saying
DATA
time,
is,
a,
DATA
Heraclitus,
child,
idly,
moving,
counters,
in,
a,
game
EOD
END
10. REM Determine
the maximum
REM
representing
REM
of
certain
of a set of values
experimental liquids
at
20
values degrees
of
surface
tension
Celsius.
LET
max = 0 READ value DO WHILE value -1 LET rowMax = 0 LET value = 0 DO WHILE value -2 IF value > rowMax THEN LET rowMax = value END IF READ value LOOP PRINT
IF
rowMax
rowMax
> max
LET
=
max
THEN rowMax
END IF READ value LOOP PRINT
max
REM
---
REM
tetrachloride,
Benzene,
REM
soap
and
Data:
surface
solution,
DATAG2275.4 26205, 25-97 DATA 63.1, 465, 32, -2 DATA 25,°72-9,.-c, —1 END
In Exercises 11 through 11. READ DO
num
WHILE PRINT
READ REM
DATA END
---
num
-1
num
num Data:
numbers
5505.05,
15-2
tension water.
of
Ethyl
Alcohol,
Carbon
Glycerine,
Mercury,
olive
-2
and
-1
are
-2
14, identify the errors.
trailers
oil, values
179
180
Repetition
12. LET flag = 0 DO WHILE flag 1 INPUT "Enter radius: ", radius IF radius * radius < 0 THEN LET flag = 1 END IF LOOP END
of some U.S.
names
13. REM Display
Presidents
DO
READ name$ PRINT name$ LOOP UNTIL name$ --- Data: DATA Lincoln, REM
= "EOD" presidents Washington,
Kennedy,
Reagan,
EOD
END
14. READ num DO WHILE 1 < num < 5 PRINT "The period of
pendulum
is";
num;
"seconds."
num
READ
LOOP DATA
the
3,
2,
4,
7,
2
END
15. Write an interactive program to find the largest of a collection of positive numbers. The user should be prompted to provide numbers until the response —1 is given, at which time, the largest number should be displayed. (Test the program with the collection of numbers 89, 77, 95, and 86.)
16. Table 5.1 contains some SI derived quantities and their units and symbols. Write a program that requests a symbol and gives the corresponding quantity and its unit. The user should be informed if the unit is not in the table.
Table 5.1
Quantity
Unit
Symbol
frequency force pressure power inductance energy capacitance
hertz newton pascal watt henry joule farad
Hz N Pa W H J E
SI units
17. Write an interactive program that asks the user to INPUT a distance in miles and converts it to kilometers. The process should be repeated until the user signs off by entering —1. Note: 1 mile is approximately 1.6 kilometers. (Test the program with the values 3 and .625.)
PROCESSING LISTS OF DATA WITH DOLOOPS
5.2
181
18. Write a program that allows the user 10 tries to answer the question “Which USS. President was born on July 4?” After three incorrect guesses the program
should give the hint “He once said, ‘If you don’t say anything, you won’t be called upon to repeat it.”” After seven incorrect guesses the program should give the hint “His nickname was ‘Silent Cal.’” Note: Calvin Coolidge was born on July 4, 1872. 19: Table 5.2 shows the different grades of eggs and the minimum weight required for each classification. Write an interactive program in which the user repeatedly inputs the weight of an egg and obtains the appropriate grade. The user should enter a negative number to terminate the process. (Note: Eggs weighing less than 1.5 ounces cannot be sold in supermarkets.) Figure 5.8 shows a typical output of the program.
Grade
Weight
(in ounces)
Weight The
Jumbo Extra Large Large Medium Small
Table 5.2
BS Dio 2 ei i
Grades of Eggs
of egg
grade
is
in ounces? Extra
2.3
Large.
Weight of egg in ounces? Send it to the bakery.
1.4
Weight
-1
Figure 5.8
of egg
in ounces?
Output for Exercise 19
20. When n capacitors C,, C), ..., C,, are connected in parallel in a circuit, the equivalent capacitance is defined as
Coie Cl
Ort
ae Ge
Consider a circuit with capacitors in parallel. Write a program to request the capacitances as input and display the values of C.,, Cray and C,,i, where
C
max
= C,,(1 + precision)
and
CG min ~ eat — precision)
The precision and the values of the capacitances C,, C), ..., C,, should be entered as input one at a time. The following is a typical output of the program. [run] Enter
-1
Enter Enter Enter Enter Enter
the precision: a capacitance: a capacitance: a capacitance: a capacitance:
Ceq
10.5
=
when
all
capacitances
have
been
entered.
.01 1 3.5 6 -1
microfarad
Cmax = 10.605 microfarad Cmin = 10.395 microfarad
le Table 5.3 contains the meanings of some abbreviations doctors often use for prescriptions. Write a program that requests an abbreviation and gives its meaning. The user should be informed if the meaning is not in the table.
182
Repetition
Meaning
Abbreviation
before meals needed as ly free twice daily a drop at bedtime four times a day
ac ad lib bid gtt hs qid Physicians’ Abbreviations
Table 5.3
Naps. Consider the list of the three radioactive elements Plutonium, Radon, and Uranium. The following program asks the user for an additional radioactive element and then displays the four elements in alphabetical order. REM
Merge
a new
radioactive
element
into
an
ordered
list
CES INPUT
“Enter
a new
radioactive
element:
READ element$ DO WHILE (element$ = "A") AND (letter$ max then k2 = max (e) Increment n by 2 and repeat from step (b) if possible. Be sure to make provisions for handling the last array element if there are an even
number of array indices.
7.2,
USING ARRAYS
301
32. A branch point (or a node) in an electric network is a point where three or more conductors are joined. Kirchoff’s first rule states that the algebraic sum of the currents flowing towards any branch point is zero. The currents (given in Table 7.7) at a node are stored in the array current(). Write a program to calculate and display the sum of the entries with odd subscripts in the array.
Current
Table 7.7
1 See 0 Sie 2-09
Oi
1205
ie
0
ea
Currents at a Branch Point
33. Write a program to dimension an array with the statement DIM state$(1 TO 50) and maintain a list of certain states. The list of states should always
be in alphabetical order and occupy consecutive elements of the array. The options for this menu-driven program should be as follows: (a) Request a state as input and insert it into its proper position in the array. (If the state is already in the array, so report.) (b) Request a state as input and delete it from the array. (If the state is not in the array, so report.)
(c) Display the states in the array. (d) Quit.
34. Write a program that requests a sentence one word at a time from the user and then checks whether the sentence is a word palindrome. A word palindrome sentence reads the same, word by word, backward and forward (ignoring punctuation and capitalization). An example is “You can cage a swallow, can’t you, but you can’t swallow a cage, can you?” The program should hold the words of the sentence in an array and use procedures to obtain the input, analyze the sentence, and declare whether the sentence is a word palindrome. (Test the program with the sentences, “Monkey see, monkey do.” and “I am; therefore, am I?”)
3D. Write a program to find the number of students scoring above the average grade on an exam, where the grades are input one at a time with the grade of —1 as trailer value. (Assume the class contains at most 100 students.) Use a procedure to input the grades and a function to calculate the number. Note: The procedure must have two parameters, an array parameter for the grades and a numeric parameter for the number of elements of the array that have been assigned values.
36. Table 7.8 displays the approximate speed (in feet per second) of sound waves in various substances (at room temperature). Write a program to READ the information into parallel arrays and print it out with the units converted to miles per hour (1 ft/sec = 0.682 mph). The program should still work if more data is added to the DATA statements.
302
Arrays
Substance
Speed (ft/sec)
Air
1,126
Hydrogen Carbon dioxide
4,315 877 4,820 16,800 11,500 12,960
Water Steel Brass Granite
Table 7.8 Speed of Sound in Various Substances
OTE Suppose an array of 1000 names is in ascending order. Write a procedure or portion of a program to search for a name input by the user. If the first letter of the name is N through Z, then the search should begin with the 1000th element of the array and proceed backwards. 38. Table 7.9 shows two lists of minerals and their hardnesses based on Moh’s hardness scale. Write a program to input each list into an array (the number of items in each list is unknown) and then create a third array by merging the lists, in order of hardness.
Hardness 1 j} 3 4 5 6 7 8 9 10 Table 7.9
Mineral Talc Gypsum Calcite Fluorite Apatite Orthoclase Quartz Topaz Corundum Diamond
Hardness LS 2.) 3 ie) oy) 6.5 7 [ibe 8 9
Mineral Graphite Halite Mica Malachite Turquoise Pyrite Garnet Tourmaline Emerald Sapphire
Moh’s Hardness Scale for Two Sets Of Minerals
39. The array a() has been dimensioned to have range | to 4, and values have been assigned to a(1) through a(4). Write code to reverse the order of these values in the array.
40. Modify Exercise 39 to reverse an array of arbitrary length. 41. Write a program that requests a sequence of numbers from the user and then reports whether the numbers are in increasing order, decreasing order, or neither. 42. Write a program to accept ten words to be input in alphabetical order and store them in an array. Then accept an eleventh word as input and store it in the array in its correct alphabetical position.
USING
7.2
ARRAYS
303
43. We define the scalar product, or inner product, of two vectors (in this case, arrays) p() and q() of dimension n as the sum of the products of correspond-
ing array elements, that is scalar product = p(1)q(1) + p(2)q(2) +... + p(n)q(n) Write a function to compute the inner product when p(), q() and nare passed as arguments.
44,
The center of mass of a system of n particles of mass m,, m),..., mM, is specified by its coordinates x and y in the plane: m= (myer
mpx9-4+ ... tom, x) | Gin, tm
+... oP My)
y = (myyy + myy2 +... + myy,) / (my + m2 +... + My) where x; and y, are the coordinates of the particle of mass m,. Write a program to:
(a) INPUT the masses and the x- and y-coordinates into parallel arrays m(), x(), and y().
(b) Calculate the sum m, + m) +... +m, and store it in the variable sum. (c) Calculate the scalar products m- x andm- y (d) Calculate the coordinates x and y of the center of mass. The value of n should be entered with an INPUT statement. Test the program with n = 3, m, = 20 g, m, = 50 g, m; = 60 g, (x, y,;)=(0,0),
(xX), ¥2)=(20,0), and (x3, y3)=(3,15). 45. Table 7.10 gives the boiling points of certain substances at normal atmospheric pressure. The program below displays the substances with a boiling point higher than that of water. Modify this program to display only the substance with the highest boiling point. REM
Display
boiling
points
CLS DIM substance$(1 TO 8) DIM boilingPoint(1 TO 8) CALL Display(substance$(), boilingPoint()) REM --- Data: substance, boiling point DATA Copper, 1187, Ethyl Alcohol, 78, Gold, DATA
Lead,
DATA
Silver,
1756,
Mercury,
2193,
Water,
356,
Oxygen,
2660
-182.97
100
END
SUB Display (substance$(), boilingPoint()) REM Read substances and boiling points. FOR
index
=
1 TO
8
READ substance$(index), boilingPoint (index) IF boilingPoint(index) > 100 THEN PRINT substance$(index), boilingPoint (index) END
NEXT END
SUB
IF
index
304
Arrays
Table 7.10
Substance
Boiling point (°C)
Substance
Boiling point (°C)
Copper Ethyl alcohol Gold Lead
1187 78 2660 1756
Mercury Oxygen Silver Water
35 -183 2193 100
Boiling Points
46. Write a program that inputs names and associated telephone numbers from the user and inserts them into parallel arrays. The insertion should maintain the arrays in ascending order by name. In cases where two or more names are identical, the telephone numbers for the names should be in ascending order. Hint: Treat the telephone numbers as strings. 47. Modify the program in Exercise 46 so that names can be deleted from the list. In cases where there are two or more matches, request a telephone number to uniquely identify the name to delete. Do not assume the user will input valid names or numbers. 48. Given the elements in Table 7.11, write a program to load the information into four arrays of range 1 to 6, element$(), symbol$(), atomicNum(), and massNum(), and ask the user for an element. Have the computer find the element and display its symbol, atomic number, and mass number. Account
for the case in which the user requests an element that is not in the table.
Table 7.11
Element
Symbol
Atomic #
Mass #
Hydrogen Helium
H He
i 2
1 +
Lithium
Li
3
7
Carbon Sodium Oxygen
(e Na O
6 el 8
IZ 23 16
Atomic Data
49. Suppose letter grades are assigned as follows: 97 and above 94-96 90-93 87-89 84-86 80-83 77-79
Write letter. always
A+ ji) AB+ B BC+
74-76 70-73 67-69 64-66 60-63 0-59
C CD+ D DF
a program that accepts a grade as input and displays the corresponding (Hint: This problem shows that when you search an array, you don’t look for equality. Set up an array range() containing the values 97,
94, 90, 87, 84,..., 59 and the parallel array letter$() containing A, A-, B+, ...,F Next, perform a sequential search to find the first i such that range(i) is less than or equal to the input grade.)
7.3.
ING G RCH N SEA AND I SORT
= 305
SOLUTIONS TO PRACTICE PROBLEMS 7.2 1. Yes, provided each element of the array has the same value.
2. The third CASE tests for duplicates and only assigns one array element to the third matrix if duplicates are found in the two arrays. Thus, we remove the third CASE and change the first CASE so it will process any duplicates. A situation where you would want to merge two lists
while retaining duplications is the task of merging two ordered arrays of test scores. SELECT
CASE
first$(m)
CASE IS second$(n)
LET
third$(r)
LET
n=n+1
= second$(n)
SELECT
SORTING AND SEARCHING A sort is an algorithm for ordering an array. Of the many different techniques for sorting an array, we discuss two, the bubble sort and the Shell sort. Both sorts use the QBasic statement SWAP. If varl and var2 are variables of the same type (that is, both numeric or both string), then the statement SWAP
varl,
var2
assigns varl’s value to var2, and var2’s value to varl.
EXAMPLE SOLUTION
1
Write a program to alphabetize two words supplied by INPUT statements. REM Alphabetize two words CLS INPUT "First word"; first$ INPUT "Second word"; second$ IF first$ > second$ THEN SWAP first$, second$ END
IF
PRINT
first$;
" before
";
second$
END
[run] First
word?
Second age
beauty
word?
before
age beauty
Bubble Sort The bubble sort is an algorithm that compares adjacent items and swaps those that are out of order. If this process is repeated enough times, the list will be
306
Arrays
ordered. Let’s carry out this process on the list Pebbles, Barney, Wilma, Fred,
Dino. The steps for each pass through the list are as follows: 1. Compare the first and second items. If they are out of order, swap them. 2. Compare the second and third items. If they are out of order, swap them.
3. Repeat this pattern for all remaining pairs. The final comparison possible swap is between the second-to-last and last elements.
and
The first time through the list, this process is repeated to the end of the list. This is called the first pass. After the first pass, the last item (Wilma) will be in
its proper position. Therefore, the second pass does not have to consider it and so requires one less comparison. At the end of the second pass, the last two items will be in their proper position. (The items that must have reached their proper position have been underlined.) Each successive pass requires one less comparison. After four passes, the last four items will be in their proper positions and, hence, the first will be also. Pebbles . _ Barney
Barney
Barney
Barney
First
Barney
Pebbles —»Pebbles
| Pebbles
— Pebbles
Pass
Wilma
Wilma —»> Wilma
Fred
Fred
Fred
Fred
Fred
epee
Dino
Dino
Dino
Dino
Dino
Wilma
Barney —» Barney
Barney
Barney
Second
Pebbles —» Pebbles
Fred
Fred
Pass
Fred
foe
Pebb les
Dino
Dino
Dino
be
Wilma
Wilma
Wilma
Barney —» Barney
Barney
Third
Fred ——+ Fred
Dino
Pass
Dino
Dino
Fred
Pebbles
Pebbles
Musee
Wilma
Wilma
Wilma
ow Pebbles Wilma
Barney —> Barney Fourth
Dino ——» Dino Pebbles
Pebbles
Wilma
Wilma
EXAMPLE 2
Write a program to alphabetize the names Pebbles, Barney, Wilma, Fred, Dino.
SOLUTION _
Sorting the list requires a pair of nested loops. The inner loop performs a single pass and the outer loop controls the number of passes.
7.3.
REM
Alphabetize
a list
CLS DIM name$(1 TO REM Read names FOR i = 170 5 READ name$(i) NEXT i REM Bubble sort FOR passNum = 1 FOR i = 1 TO
of
five
307
names
5)
names TO 4 ‘Number 5 - passNum
IF name$(i) > name$(i + 1) SWAP name$(i), name$(i END
SORTING AND SEARCHING
of
passes is 1 less than number of items ‘Each pass needs 1 less comparison
THEN + 1)
IF
NEXT
NEXT
REM
passNum
Display
alphabetized
list
FAR 7 2 il yO s PRINT name$(i), NEXT 7 REM
---
DATA
Data:
Pebbles,
name
Barney,
Wilma,
Fred,
Dino
END [run] Barney
EXAMPLE 3.
Dino
Fred
Pebbles
Wilma
Table 7.12 contains facts about the ten most populous metropolitan areas with listings in ascending order by city name. Sort the table in descending order by population.
Metro Area
Population in Millions
Median Income % Native | per Household __ to State
% Advanced Degree
Boston Chicago Dallas Detroit
4.2 8.1 3.9 4.7
$40,666 $35,918 $32,825 $34,729
73 is 64 76
12 8 8 i
Houston
3G
$31,488
67
8
Los Angeles
14.5
$36,711
59
8
New York Philadelphia San Francisco Washington
18.1 5.9 6.3 3.9
$38,445 $35,797 $41,459 $47,254
73 70 60 a)
it 8 11 17
Note: Column 4 gives the percentage of residents who were born in their current state of residence. Column 5 gives the percentage of residents age 25 or older with a graduate or professional degree.
Table 7.12
The Ten Most Populous Metropolitan Areas
Source: The 1990 Census
308
Arrays
SOLUTION
After the data are written into parallel arrays, the collection of parallel arrays is sorted based on the array pop(). Each time two items are SWAPed in the array pop(), the corresponding items are SWAPed
in each of the other arrays. This
way, for each city, the items of information remain linked by REM
Sort
table
of metropolitan
areas
by
population
CLS DIM city$(1 TO 10), pop(1 TO 10), income(1 TO 10) DIM natives(1 TO 10), advDeg(1 TO 10) CALL ReadData(city$(), pop(), income(), natives(), CALL SortData(city$(), pop(), income(), natives(), CALL ShowData(city$(), pop(), income(), natives(), REM
---
Data:
city,
pop.,
med.
income,
DATA
Boston,
DATA
Chicago,
DATA
Dallas,
DATA
Detroit,
4.7,
34729,
76,
7
DATA
Houston,
3.7,
31488,
67,
8
DATA
Los
Angeles,
DATA
New
York,
DATA
Philadelphia,
DATA
San
DATA
Washington,
4.2,
40666,
8.1,
73,
35918,
3.9,
14.5,
18.1,
64,
5.9,
Francisco,
8
59,
73,
35797,
6.3,
3.9,
8
36711,
38445,
8
11
70,
41459,
47254,
% native,
advDeg()) advDeg()) advDeg()) % advanced degree
12
73,
32825,
acommon subscript.
32,
8
60,
11
17
END
SUB ReadData (city$(), REM Read city, pop., FOR
i
=
READ
10
city$(i),
pop(i),
income(i),
natives(i),
advDeg(i)
7
NEXT END
1 TO
pop(), income(), natives(), advDeg()) med. income, % native, % advanced degree
SUB
SUB ShowData (city$(), pop(), income(), natives(), advDeg()) REM Display ordered table PRINT , "Pop. in", "Med. income", "% Native", "% Advanced" PRINT “Metro Area", "millions", "per hsd", "to State", "Degree" PRINT FOR i = 1 TO 10 PRINT city$(i), pop(i), income(i), natives(i), advDeg(i) NEXT END SUB
SUB SortData (city$(), pop(), income(), natives(), advDeg()) REM Bubble sort table in descending order by population FOR passNum = 1 TO 9 FOR index = 1 TO 10 - passNum IF pop(index) < pop(index + 1) THEN CALL SwapData(city$(),pop(),income() ,natives() ,advDeg() , index) END
NEXT
IF
index
NEXT passNum END SUB
ING G SEARCH ANDIN 7.3. SORT
SUB SwapData REM
Swap
SWAP SWAP SWAP SWAP SWAP END SUB
(city$(),
pop(),
income(),
natives(),
advDeg(),
309
index)
entries
city$(index), city$(index + 1) pop(index), pop(index + 1) income(index), income(index + 1) natives(index), natives(index + 1) advDeg(index), advDeg(index + 1)
[run] Metro
Area
New York Los Angeles Chicago San Francisco Philadelphia Detroit Boston Dallas Washington Houston
Pop. in millions
18.1 14.5 8.1 6.3 5.9 4.7 4.2 oN) 329 Bail
Med. income per hsd
38445 36711 35918 41459 35797 34729 40666 32825 47254 31488
% Native to State
73 59 73 60 70 76 73 64 32 67
% Advanced Degree
ila 8 8 11 8 i 12 8 17 8
Shell Sort The bubble sort is easy to understand and program. However, it is too slow for really long lists. The Shell sort, named for its inventor, Donald L. Shell, is much more efficient in such cases. It compares distant items first and works its way down to nearby items. The interval separating the compared items is called the gap. The gap begins at one-half the length of the list and is successively halved until eventually each item is compared with its neighbor as in the bubble sort. The algorithm for a list of n items is as follows.
1. Begin with a gap of g = INT(n/ 2). 2. Compare items | and 1 + g, 2 and2 + g,...,n—gandn. Swap any pairs that are out of order.
3. Repeat step 2 until no swaps are made for gap g.
4. Halve the value of g. 5. Repeat steps 2, 3, and 4 until the value of g is 0. The Shell sort is illustrated below. Crossing arrows indicate that a swap occurred. Initial Gap = INT([Number of Items] / 2) = INT(5 / 2) = 2
310
Arrays
Pebbles
Pebbles
Barney —> Barney
Barney
Pebbles —» Pebbles First
Barney
Pass
Wilma
—> Wilma
Wilma
Dino
Fred
Fred ——»
Fred ve
Fred
Dino
Dino
Dino
Wilma
Since there was a swap, use the same gap for the second pass. Dino
Dino
Pebbles
Dino
Second
Bamey X
Barney —> Barney
Pass
Dino
Pebbles
Fred
Fred ——»
Fred
Wilma
Wilma
Wilma—» Wilma
Barney
§ Pebbles—» Pebbles Fred
Again, there was a swap, so keep the current gap. Dino
Dino
Dine 2.
Dino
Third
Barney
Barney —> Barney
Pass
Pebbles—» Pebbles
Barney
| Pebbles —» Pebbles
Fred
Fred ——»
Fred
Wilma
Wilma
Wilma
Fred —»> Wilma
There were no swaps for the current gap of 2 so, Next Gap = INT([Previous Gap] / 2) = INT(2 / 2) = 1 Dino
Barney
Barney
Fourth
Barney
Dino ——» Dino
Pass
Pebbles
= Pebbles—» ae
Barney
Barney
Dino
Dino
Fred
Fred
Fred
Fred
Fred
Pebbles —» Pebbles
Wilma
Wilma
Wilma
Wilma —» Wilma
Since there was a swap (actually two swaps), keep the same gap. Barney _» Barney
Barney
Barney
Barney
Fifth
Dino ——~ Dino ——»
Dino
Dino
Dino
Pass
Fred
Fred ——»
Fred ——»
Fred
Fred
Pebbles
Pebbles
Pebbles —-» Pebbles >
Wilma
Wilma
Wilma
Pebbles
Wilma—» Wilma
Since there were no swaps for the current gap, then Next Gap = INT([Previous Gap] / 2) = INT(1 /2) =0
and the Shell sort is complete.
7.3.
SORTING AND SEARCHING
311
Notice that the Shell sort required 14 comparisons to sort the list whereas the bubble sort required only 10 comparisons for the same list. This illustrates the fact that for very short lists, the bubble sort is preferable; however, for lists
of 30 items or more, the Shell sort will consistently outperform the bubble sort. Table 7.13 shows the average number of comparisons required to sort arrays of varying sizes.
Array Elements
Table 7.13
EXAMPLE
Bubble Sort Comparisons
Shell Sort Comparisons
5
10
1)
10
45
oy
15 20 25
105 190 300
| 19) 302
30 50 100 500 1000
435 1225 4950 124,750 499,500
364 926 2638 Ldvokl 58,460
Efficiency of Bubble and Shell Sorts
4 _ Use the Shell sort to alphabetize the parts of a running shoe (see Figure 7.6).
tongue eyelets
heel patch/ Achilles’ tendon pad
binding padding
eye stay
toe box
trim
ry
/
stud
f.
uppers
outsole
sole
midsole wedge
manufacturer s ornament
Figure 7.6
Running Shoe
foxiNg
heel counter
312
Arrays
SOLUTION
In the following program, the data are read into part of an array. In subprogram ReadData, the variable numParts both provides the subscripts the array and serves as a counter. The final value of numParts is passed to other subprograms. The subprogram SortData uses a flag to indicate if a swap been made during a pass. REM
Sort
and
display
parts
of
running
GES DIM part$(1 TO 50) CALL ReadData(part$(),
numParts)
CALL SortData(part$(),
numParts)
CALL ShowData(part$(),
numParts)
shoe
REM --- Data: part of running shoe DATA toe box, vamp, laces, eye stay, eyelets, tongue DATA binding, padding, heel patch, heel counter, foxing DATA midsle wdge, mfg's ornmt, sole DATA
uppers,
trim,
stud,
outsole,
EOD
END
SUB ReadData
(part$(),
numParts)
REM Read part names LET numParts = 0 READ item$ DO
WHILE
LET
item$
numParts
"Number "EOD"
= numParts
LET part$(numParts) READ item$ LOOP END SUB
SUB ShowData
(part$(),
+
1
= item$
numParts)
REM Display sorted list FOR i = 1 TO numParts PRINT part$(i), NEXT i END SUB
SUB SortData
of parts
(part$(),
of parts
numParts)
REM Shell sort shoe parts LET gap = INT(numParts / 2) DO WHILE gap >= 1 DO LET doneFlag = 1 FOR index = 1 TO numParts
- gap
IF part$(index) > part$(index + gap) THEN SWAP part$(index), part$(index + gap) LET END
doneFlag
IF
NEXT index LOOP UNTIL doneFlag
LET gap = INT(gap LOOP END
SUB
= 0
= 1
/ 2)
‘Halve
the length
of the gap
the for the has
7.3.
[run] binding
eye
heel
laces
mfg's
padding
sole
stud
trim
uppers
vamp
patch
stay
eyelets
SORTING AND SEARCHING
foxing ornmt
midsle toe
heel wdge
box
313
counter
outsole tongue
Searching Suppose we had an array of 1000 names in alphabetical order and wanted to locate a specific person in the list. One approach would be to start with the first name and consider each name until a match was found. This process is called a sequential search. We would find a person whose name begins with “A” rather quickly, but 1000 comparisons might be necessary to find a person whose name begins with “Z.” For much longer lists, searching could be a time-consuming matter. However, when the list has already been sorted into either ascending or descending order, there is a method, called a binary search, that shortens the
task considerably. Let us refer to the sought item as quarry. The binary search looks for quarry by determining in which half of the list it lies. The other half is then discarded and the retained half is temporarily regarded as the entire list. The process is repeated until the item is found. The algorithm for a binary search of an ascending list is as follows (Figure 7.7 contains the flowchart for a binary search): 1. At each stage, denote the subscript of the first item in the retained list by first and the subscript of the last item in the retained list by last. Initially, the value of first is 1 and the value of last is the number of items in the list.
2. Look at the middle item of the current list, the item having the subscript middle = INT ((first + last) / 2).
3. If the middle item is quarry, then the search is over. 4. If the middle item is greater than quarry, then quarry should be in the first half of the list. So the subscript of quarry must lie between first and middle — 1. That is, the new value of last is middle — 1.
5. If the middle item is less than quarry, then quarry should be in the second half of the list of possible items. So the subscript of quarry must lie between middle + 1 and last. That is, the new value of first is middle + 1.
6. Repeat steps 2 through 5 until quarry is found or until the halving process uses up the entire list. (When the entire list has been used up, first > last.) In the second case, quarry was not in the original list.
314
Arrays
Get quarry Set first, last Set flag = 0
Is first < last AND flag = 0 0)
Calculate middle
middle item = quarry
2
middle item > quarry
2
Set first = middle + 1
Figure 7.7
Flowchart for a Binary Search
EXAMPLE 5
Assume the array firm$() contains the alphabetized names of 100 corporations. Write a program that requests the name of a corporation as input and uses a binary search to determine whether or not the corporation is in the array.
SOLUTION —
REM array firm$()
already ordered alphabetically
CLS INPUT
"Enter
the
name
of
a corporation:
REM Binary search of firm$() LET foundFlag = 0 BET
Shiiesite
LET
last
= =
100
",
corp$
for corp$ ‘1 indicates
corp$
found
7.3.
DO WHILE (first corp$ LET last = middle - 1 CASE IS < corp$ LET first = middle + 1 SELECT
END LOOP
1 THEN
=
foundFlag
IF
" found."
PRINT corp$; BESE
PRINT END
" not found."
corp$;
IF
END
Suppose the corporation input in Example 5 is in the second half of the array. On the first pass, middle would be assigned INT((1 + 100)/2) = INT(50.5) = 50
and then first would be altered to 50 + 1 = 51. On the second pass, middle would be assigned INT((51 + 100))/2 = INT(75.5) = 75. If the corporation is not the
array element with subscript 75, then either last would be assigned 74 or first would be assigned 76 depending upon whether the corporation appears before or after the 75th element. Each pass through the loop halves the range of subscripts containing the corporation until the corporation is located. In Example 5, the binary search merely reported whether or not an array contained a certain item. After finding the item, its array subscript was not needed. However, if related data are stored in parallel arrays (as in Table 7.4),
the subscript of the found item can be used to retrieve the related information in the other arrays. This process, called a table lookup, is used in the following example.
EXAMPLE 6
Suppose the cities in Example 3 have been ordered alphabetically. Use a binary search procedure to locate the data for a city requested by an INPUT statement.
SOLUTION
In the following program, the DATA statements have been ordered by the name of the city. REM
Search
for
city
in
the
metropolitan
areas
table
GIES DIM city$(1 TO 10), pop(1 TO 10), income(1 TO 10) DIM natives(1 TO 10), advDeg(1 TO 10) CALL ReadData(city$(), pop(), income(), natives(), advDeg()) CALL GetCityName(searchCity$) CALL FindCity(city$(),pop(),income(),natives(),advDeg(),searchCity$) REM
---
Data:
city,
4.2,
pop.,
Boston,
DATA
Chicago,
DATA
Dallas,
DATA
Detroit,
4.7,
34729,
76,
7
DATA
Houston,
3.7,
31488,
67,
8
3.9,
35918,
32825,
73,
income,
DATA
8.1,
40666,
med.
12
73,
64,
8
8
% native,
% advanced
degree
316
Arrays
36711,
14.5,
Angeles,
8
59,
DATA
Los
DATA DATA DATA DATA END
New York, 18.1, 38445, 73, 11 Philadelphia, 5.9, 35797, 70, 8 San Francisco, 6.3, 41459, 60, 11 Washington, 3.9, 47254, 32, 17
,natives(),advDeg() ,searchCity$)
(city$(),pop(),income()
FindCity
SUB
Binary
LET
foundFlag
HET
qhnieSie
LET
last
city
for
table
search
REM
name
'l
= 0
= city
found
Sal
=
10
DO WHILE (first searchCity$
CASE
1
-
= middle
last
LET
CASE IS < searchCity$ LET first = middle + 1 SELECT
END
LOOP
END
file"
in
not
"City
PRINT END
= 0 THEN
foundFlag
IF
IF
SUB
SUB GetCityName (searchCity$) REM Request name of city as INPUT "City"; searchCity$ END
SUB
SUB ReadData (city$(), REM Read city, pop., FOR
1
=
READ NEXT
END
input
2 10
pop(), income(), natives(), advDeg()) med. income, % native, % advanced degree
10
city$(i),
pop(i),
income(i),
natives(i),
3
SUB
SUB ShowData REM
(city$(),
Display
PRINT
,
PRINT
"Metro
city
"Pop.
pop(),
and
in",
income(),
associated "Med.
natives(),
income",
"%
Native",
"millions",
"per
PRINT
city$(index),
pop(index),
income(index),
PRINT
natives(index),
hsd",
"to
PRINT
SUB
[run] City? Baltimore City not in file
advDeg(),
index)
information
Area",
END
advDeg(i)
advDeg(index)
"%
Advanced"
State",
"Degree"
7.3.
SORTING AND SEARCHING
317
Comments:
1. Suppose our bubble sort algorithm is applied to an ordered list. The algorithm will still make n — 1 passes through the list. The process could be
shortened for some lists by flagging the presence of out-of-order items as in the Shell sort. It may be preferable not to use a flag since for greatly disordered lists, the flag would slow down an already sluggish algorithm. - In Example 3, parallel arrays already ordered by one field were sorted by another field. Usually, parallel arrays are sorted by the field to be searched when accessing the file. This field is called the key field.
. Suppose an array of 2000 items is searched sequentially; that is, one item after another, in order to locate a specific item. The number of comparisons
would vary from 1 to 2000, with an average of 1000. With a binary search, the number of comparisons would be at most 11, since 2!! > 2000.
. The built-in function UCASE$ converts all the characters in a string to uppercase. UCASE$ is useful in sorting and searching arrays when the alphabetic case (upper or lower) is unimportant. For instance, in Example 5, if UCASE$
were included in the SELECT CASE comparisons, then the
binary search would locate “Mobil” in the array even if the user entered “MOBIL”. . The SWAP statement cannot be used to switch all the values of two arrays at once. For instance, if a() and b() are arrays, then the statement SWAP a, b or SWAP a(), b() will not do the job. Instead, a loop must be set up to
interchange each of the corresponding elements separately.
. The QBasic function TIMER can be used to determine the speed of a sort. Precede the sort with the statement LET t = TIMER.
After the sort has
executed, the statement PRINT TIMER - t will display the duration of the sort in seconds.
PRACTICE PROBLEMS
7.3
1. The pseudocode for a bubble sort of an array of n items is given below. Why is the terminating value of the outer loop n — 1 and the terminating value of the inner loop n — j? FORA = 1O n= 1 FOR k= 1 TOn=j IF [kth and (k+1)st items are out of order] THEN SWAP them NEXT k NEXT j
2. Complete the table by filling in the values of each variable after successive passes of a binary search of a list of 20 items, where the sought item is in the 13th position. First
1 11
Last
20 20
Middle
10
318
Arrays
7.3
EXERCISES
m. gra pro the of put out the ine erm det 4, h oug thr 1 ses rci Exe In 2. DIM gag$(1
1. LET p = 100
TO 2)
LET q = 200 SWAP p, q PRINT p; q
READ gag$(1), gag$(2) IF gag$(2) < gag$(1) THEN SWAP gag$(2), gag$(1)
END
END
IF
PRINT gag$(1),
gag$(2)
REM --- Data: comedians DATA Stan, Oliver END
4. DIM a(1 TO 3)
3. INPUT x, y
SWAP x, Y LET swappedFlag
= 1
IF swappedFlag = 1 THEN PRINT "Numbers interchanged."
> a(k
a(k)
a(k),
SWAP IF
END
1)
THEN
a(k
+ 1)
+
k
NEXT
IF
1043-93
ke=" IF
8X32 is
eO0mZ
aa
FOR
PRINT
END
j
NEXT FOR
IF
END
a(j)
READ
y > x THEN
IF
aaaleOns
FORSd
= 0
swappedFlag
LET
j
END
NEXT
and 11 as input.) 7 s (Use the number
sikh NEXT
j
REM
---
an numbers
Data:
DAWAt/
seo
4
END
In Exercises 5 and 6, identify the errors. 6. DIM a(1 TO 3), b(1 TO 3)
5. DIM c(1 TO 4), d$(1 TO 4) FOR
EORSim
4
NEXT
7
DYN
Data:
---
Wh, 25
da
REM
numbers
Hy
leaOes b(i)
a(i), 7
SWAP a(i), b(i)
SWAP c(4), d$(4) REM
=e
READ
d$(i)
c(i),
READ NEXT
1 10
i =
Gy
75
Gy
---
DATARS
&
numbers
Data:
SSee 575095,
Ul
END
END
7. Which type of search would be best for the array shown below? 1
2
3
4
5
SORTING AND SEARCHING
7.3.
319
8. Which type of search would be best for the array shown below? 1
d,
a
4
5
- Consider the items Tin Man, Dorothy, Scarecrow, and Lion, in that order.
After how many swaps in a bubble sort will the list be in alphabetical order? - How many comparisons will be made in a bubble sort of 6 items? - How many comparisons will be made in a bubble sort of n items? - Modify the program in Example 2 so that it will keep track of the number of swaps and comparisons and display these numbers before ending.
- Rework Exercise 9 using the Shell sort.
. How many comparisons would be made in a Shell sort of 6 items if the items were originally in descending order and were sorted in ascending order? 15. If a list of 6 items is already in the proper order, how many comparisons will be made by a Shell sort? 16. The following subprogram fills an array of 200 integers with values between
0 and 63 that are badly in need of sorting. Write a program that uses the subprogram and sorts the array nums() with a bubble sort. Run the program and time the execution. Do the same for the Shell sort. SUB
FillArray
REM
Generate
(nums()) numbers
from
LET nums(1) = 5 FOR i = 2 TO 200 LET nums(i) = (9 * nums(i NEXT i END SUB
0 to
63
- 1)
and
+ 7)
place
MOD
in
array
64
liz: Suppose a list of 5000 numbers is to be sorted, but the numbers consist of only 1, 2, 3, and 4. Describe a method of sorting the list that would be much faster than either the bubble or Shell sort. 1S: The bubble sort gets its name from the fact that in an ascending sort successive passes cause “lighter” items to rise to the top like bubbles in water. How did the Shell sort § get its name? 19. What is the maximum number of comparisons required to find an item in a
sequential search of 16 items? What is the average number of comparisons? What is the maximum number of comparisons required to find an item in a binary search of 16 items?
20. Redo Exercise 19 with 2N items, where N is any positive integer.
320
Arrays
d. tan ers und to y eas is and a dat of s set ll sma on ent ici eff is t sor 21. The insertion g yin pla of d han a er ord ple peo t mos t tha er nn ma e sam the It is carried out in cards:
(1) Read the first item of data and place it in an array. tive rela ced pla be uld sho it re whe ide dec and data of m ite t nex the d Rea (2)
a dat ng sti exi e mov , ary ess nec If y. arra the in red sto y ead alr a dat to the in m ite new the Put m. ite new the for ce spa e mak to ay arr the in down its appropriate location. the in er ord in ced pla and d rea n bee has a dat all il unt 2 p ste eat Rep (3) array.
Suppose up to 100 items are stored in DATA statements. Use the insertion sort to place the items into an ascending ordered array.
JV An ascending selection sort of an array is carried out with the following steps:
(1) Search the array for the element with the smallest value and exchange it with the first element. (2) Search the remaining second through last elements for the smallest value and exchange it with the second element. (3) Continue this process for each element of the array in succession. Write a procedure to accept an array as input and order it with a selection sort. In Exercises 23 through 30, write a short program (or partial program) to complete the stated task. 23. Without using the SWAP ables x and y.
statement, interchange the values of the vari-
24. Display the names of the seven dwarfs in alphabetical order. As the DATA statement use: DATA
Doc,
Grumpy,
Sleepy,
Happy,
Bashful,
Sneezy,
Dopey
25. Table 7.14 lists the top 10 most attended exhibits in the history of the National Gallery of Art. Read the data into a pair of parallel arrays and display a similar table with the exhibit names in alphabetical order. 26. Table 7.15 contains data for the nine planets of our solar system (rounded to whole numbers). Write a program to read the data into parallel arrays, and then output a list of the planets sorted according to size, period of rotation, or period of revolution, as specified by the user. Note: The periods given in terms of days must be converted to hours or years.
27. The median of a set of n measurements is a number such that half the n measurements fall below the median and half fall above. If the number of measurements n is odd, the median is the middle number when the meas-
urements are arranged in ascending or descending order. measurements n is even, the median is the average of measurements when the measurements are arranged in scending order. Write a program that requests a number measurements as input and then displays the median.
If the number of the two middle ascending or den and a set of n
7.3.
SORTING AND SEARCHING
Attendance (in thousands)
Exhibit
1053 999 836
Rodin Rediscovered Treasure Houses of Britain Treasures of Tutankhamen
Table 7.14
Chinese Archaeology
684
Ansel Adams Splendor of Dresden Wyeth’s Helga Pictures Post-Impressionism Matisse in Nice John Hay Whitney Collection
652 617 558 558 537 513
National Gallery of Art’s Greatest Hits
Planet
Diameter (km)
Period of Rotation
Period of Revolution
Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune Pluto
4,880 125122 12,742 6,800 143,000 121,000 52,000 50,000 2,290
59 43 24 24 10 10 17 16 6
88 225 365 687 12 30 84 165 248
Table 7.15
321
days days hours hours hours hours hours hours days
days days days days years years years years years
Planet Data
28. An airline has a list of 200 flight numbers in an ascending sorted array. Accept a number as input and do a binary search of the list to determine if the flight number is valid. 29. Modify the program in Exercise 16 to compute and display the number of times each of the numbers from 0 through 63 appears. 30. Allow a number n to be input by the user. Then accept as input a list of n numbers. Place the numbers into an array and apply a bubble sort. 31. Write a program that accepts an American word as input and performs a binary search to translate it into its British equivalent. Use the following list of words for data and account for the case when the word requested is not in the list. American
British
American
British
attic business suit elevator flashlight french fries gasoline
loft lounge suit lift torch chips petrol
ice cream megaphone radio sneakers truck zeTO
ice loud hailer wireless plimsolls lorry nought
322,
“Artays
The s. mal ani in nd fou ts men ele al mic che mon com the ws sho 7.16 32. Table te Wri . ght wei y bod an hum of t cen per of er ord g sin rea dec in m the table lists a menu-driven program to display the table in: (a) the order given
(b) increasing order according to atomic weight (c) increasing order according to atomic number Use calls to a single Shell Sort subprogram to accomplish tasks (b) and (c) above.
Symbol
Element
Oxygen Carbon Hydrogen Nitrogen Calcium Phosphorus Chlorine Sulfur Potassium Sodium Magnesium lodine Iron Table 7.16
Approximate Atomic Weight
O O Et N Ca le Cl S K
16 12 It 14 40 31 oe: 32 39
Na Mg
MS 24
I Fe
Ley 56
Atomic Number
Chemical Elements Found in Animals
33. Write a program that accepts a student’s name and seven test scores as input and calculates the average score after dropping the two lowest grades. 34. Table 7.17 shows the boiling points of selected metals. Write a program to READ the information into parallel arrays and display it in increasing order of boiling point temperature.
Metal
Aluminum Barium Calcium Cesium Lithium
Table 7.17
Boiling Point (°C) 2330 1640 1487 690 1367
Boiling Metal Manganese Potassium Rubidium Sodium Strontium
Point (°C)
1126 119 679 892 1384
Boiling Points of Metals
35. Given the flight schedule in Table 7.18, write a program to load the information into four arrays of range | to 5, flightNum(), orig$(), dest$(), and deptTime$(), and ask the user to request a flight number. Have the computer find the flight number using a binary search and display the information corresponding to that flight. Account for the case where the user requests a nonexistent flight.
TWO-DIMENSIONAL ARRAYS
7.4
Table 7.18
Flight #
Origin
Destination
Departure Time
iby 209) 298 326 445
Tucson LEN Albany Houston New York
Dallas Boston Reno New York Tampa
8:45 10:15 1:35 2:40 4:20
323
a.m. a.m. p.m: p.m. p.m.
Flight Schedule
SOLUTIONS TO PRACTICE PROBLEMS 7.3 1. The outer loop controls the number of passes, one less than the number of items in the list. The inner loop performs a single pass, and the jth pass consists of n — j comparisons. 2.
First
Last
Middle
l
20 20 14 14
10 15 Le 13
Il 11 1S
7 ;4
TWO-DIMENSIONAL
ARRAYS
Each array discussed so far held a single list of items. Such called single-subscripted variables. An array can also hold table with several rows and columns. Such arrays are called arrays or double-subscripted variables. Two tables are shown gives the road mileage between certain cities. It has four rows Table 7.20 shows the leading universities in three disciplines. and five columns.
Chicago Los Angeles New York Philadelphia
array variables are the contents of a two-dimensional below. Table 7.19 and four columns. It has three rows
Chicago
Los Angeles
New York
Philadelphia
0 2054 802 738
2054 0 2786 2706
802 2786 0 100
738 2706 100 0
Table 7.19 Road Mileage Between Selected U.S. Cities
1
2
3
4
5
Business
UofPA
MIT
U of IN
U of MI
UC Berk
Comp Sc.
MIT
Cng-Mellon
UC Berk
Cornell
U of IL
Engr/Gen.
UCLA
U of IL
Uof MD
U of OK
Stevens I.T.
Table 7.20
University Rankings
Source: A Rating of Undergraduate Programs in American and International Universities, Dr. Jack Gourman, 1993
324
Arrays
Two-dimensional array variables store the contents of tables. They have the same types of names as other array variables. The only difference is that they have two subscripts, each with its own range. The range of the first subscript is determined by the number of rows in the table and the range of the second subscript is determined by the number of columns. The statement DIM arrayName(m1
TO nl,
first be
m2
if
TO x
Kor
last row
last column
first column
dimensions an array corresponding to a table with rows labeled from m1 TO nl] and columns labeled from m2 TO n2. The entry in the jth row, kth column is arrayName(j,k). For instance, the data in Table 7.19 can be stored in an array named rm(). The statement DIM
rm(1
TO 4,
1 TO 4)
will dimension the array. Each element of the array has the form rm(row, column). The entries of the array are rm(1,1)=0 toa(241 )=2054 rm(3,1)=802
rm(1,2)=2054 Tim ee) =O rmi(3,2)=2786
rm(4,1)=738
rm(4,2)=2706
= rm(1,3)=802 mi(2,3)=2786 m(3,3)=0
rm(4,3)=100
rm(1,4)=738 m(2,4)=2706 rm(3,4)=100
rm(4,4)=0
The data in Table 7.20 can be stored in a two-dimensional string array named univ$(). The statement DIM
univ$(1
TO 3,
1 TO 5)
will dimension the array. Some of the entries of the array are univ$(1,1) ="U of PA" unive(7.3) ="UG Berk" univ$(3,5) = "Stevens I.T."
EXAMPLE SOLUTION
1
Write a program to store and access the data from Table 7.19. Data are read into a two-dimensional array using a pair of nested loops. The outer loop controls the rows and the inner loop controls the columns. REM
Determine
road
mileage
between
OES DIM
rm(1
TO
4,
1 TO
4)
CALL
ReadMileages(rm())
CALL
ShowCities
CALL InputCities(row, col) CALL ShowMileage(rm(), row, REM --- Data: distances DATA 0, 2054, 802, 738 DATA 2054, 0, 2786, 2706
col)
cities
TWO-DIMENSIONAL ARRAYS
7.4.
DATA 802, DATA 738, END
2786, 2706,
0, 100 100, 0
SUB InputCities (row, col) REM Input origin and destination INPUT "Origin"; row INPUT "Destination"; col END SUB
SUB ReadMileages (rm()) REM Read mileages into FOR row = 1 TO 4 FOR col = 1 TO 4 READ rm(row, col) NEXT col NEXT
END
325
cities
a two-dimensional
array
row
SUB
SUB ShowCities REM Show possible cities PRINT "1. Chicago" PRINT "2. Los Angeles" PRINT "3. New York" PRINT "4. Philadelphia" PRINT END SUB
SUB ShowMileage (rm(), row, col) REM Display mileage between cities PRINT "The road mileage is"; rm(row, END
SUB
1.
Chicago
2.
Los
Angeles
3.
New
York
4.
Philadelphia
Origin? 3 Destination? The
col)
road
1
mileage
is 802
So far, two-dimensional arrays have only been used to store data for convenient lookup. In the next example, an array is used to make a valuable computation. EXAMPLE
2.
The Center for Science in the Public Interest publishes The Nutrition Scorebook, a highly respected rating of foods. The top two foods in each of five categories
are shown in Table 7.21 along with some information on their composition. Write a program to compute the nutritional content of a meal. The table should be read into an array and then the program should request the quantities of each food item that is part of the meal. The program should then compute the amounts of each nutritional component consumed by summing each column with each entry weighted by the quantity of the food item.
326
Arrays
Calories
Protein (grams)
23 160 230 85 65 178 110 156 5D 405
3 2 10 8 3 3.8 Z 24 126.8 28.8
spinach(1 cup) sweet potato (1 med.) yogurt(8 oz.) skim milk (1 cup) wh. wheat bread (1 slice) brown rice (1 cup) watermelon (1 wedge)
papaya (1 lg. tuna in water (1 |b.) lobster (1 med.)
Table 7.21
SOLUTION
REM
Fat (grams)
0.3 1 3
the
nutritional
content
of
73 190
table
DIM quantity(1 TO 10) CALL ReadData(comp()) CALL InputAmounts (quantity ()) CALL ShowData(comp(), quantity()) REM
---
Data:
component
data
DMV 235 35 sole SHI Ss) DATA 160, 2, 1, 9230, 46 DATA230," 10,3, 120), 343 DATA 85, 8, 0, 500, 302 DATA 65, 3, 1, 0, 24 DYNAN AUS} Slaten aSl5 Wy IKs! DATA ITO Zou lee Zool 30 DATA 156, 2.4, .4, 7000, 80 DAY SMa IOs, SeO Oy 7/5) DATA 405, 28.8, 26.6, 984, 190 REM --- Data: top-rated foods
DATA DATA DATA
spinach (1 cup), sweet potato (1 med), yogurt (8 oz) skim milk (1 cup), wh. wheat bread (1 slice) brown rice (1 cup), watermelon (1 wedge), papaya (1 1g)
DATA tuna in water (1 1b), lobster (1 med) REM --- Data: component names DATA calories, protein (grams), fat (grams) DATA vitamin A (IU), calcium (mg) END
SUB
InputAmounts
REM
Request
OR
tS
READ
END
quantities
Ih NO) food$;
TNRUT
Sees
SUB
7
of
We
food$
PRINT NEXT
(quantity())
Guan tya(in)
foods
consumed
46 343
18 30 80
a meal
‘Composition
93
24
GES
DIM comp(1 TO 10, 1 TO 5)
(mg)
302
Composition of Ten Top-Rated Foods
Determine
Calcium
7.4
SUB
ReadData
REM
Record
FOR
row
=
FORScol
END
327
(comp()) composition
1 10 =
of
foods
in
array
10
17 10%5
READ comp(row, NEXT col NEXT
TWO-DIMENSIONAL ARRAYS
col)
row
SUB
SUB ShowData (comp(), quantity()) REM Display amount of each component PRINT PRINT "This meal contains the following PRINT "of these nutritional components: FOR col = 1 710 5 LET amount = 0 READ compName$ FOR row = 1 TO 10 LET amount = amount + quantity(row) NEXT
"
* comp(row,
col)
row
PRINT compName$ NEXT col END SUB
+ ":
"3; amount
[run] spinach (1 cup): 1 sweet potato (1 med): 1 yogurt (8 oz): 1 skim milk (1 cup): 2 wh. wheat bread (1 slice): brown rice (1 cup): 0 watermelon (1 wedge): 1 papaya (1 1g): 0 tuna in water (1 1b): .5 lobster (1 med): 0
3
This meal contains the following of these nutritional components: callonies: ~11/5.5
protein
quantities"
(grams):
quantities
105.4
fat (grams): 10.1 vitamin A (IU): 20960 1224.5 calcium (mg):
Vectors and Matrices
Vectors and matrices are represented as one- and two-dimensional respectively. The statements DIM DIM
vec(1 mat(1
TO n) TO m,
1 TO
arrays,
n)
declare a vector having n entries and an m X n matrix, that is, a matrix of m rows and n columns.
328
Arrays
Programs involving matrices commonly use procedures to carry out matrix
operations. The UBOUND function can be used to obtain the size of a matrix. The values of UROUND(mat,
1) and UBOUND(mat, 2) are the number of rows
and columns of the matrix, respectively.
EXAMPLE 3
The following program multiplies a column vector on the left by a 3 x 5 matrix and displays the entries of the product. The sizes of the vector and the product are determined by the UBOUND function from the dimensions of the matrix. The program can be modified for a matrix of a different size by changing just the third line and the DATA statements. REM
Multiply
a vector
by
a matrix
CLS DIMEMatrix(Cis i0es.m
1s 1015)
DIM vector(1 TO UBOUND(matrix, 2)) DIM product(1 TO UBOUND(matrix, 1)) CALL FillEntries(matrix(), vector()) CALL Multiply(matrix(), vector(), product()) CALL ShowEntries (product ()) REM
---
Data:
DATAR/
e255
matrix
Oncc
DATARSRcas
DATA REM
6,
seca
8,
4,
1,
6
---
Data:
vector
7,
235.
2,
DATA,
9
END
SUB FillEntries (matrix(), vector()) FOR row = 1 TO UBOUND(matrix, 1) FOR
col
READ
=
1 TO
UBOUND(matrix,
matrix(row,
col)
col
NEXT
row
NEXT
FOR row = 1 TO UBOUND(matrix, READ vector(row)
2)
row
NEXT END
2)
SUB
SUB Multiply (matrix(), vector(), product()) FOR row = 1 TO UBOUND(matrix, 1) LET product(row) = 0 FOR
col
LET NEXT NEXT END
=
1 TO
UBOUND(matrix,
product(row)
= product(row)
col row
SUB
SUB ShowEntries (product ()) FOR row = 1 TO UBOUND(product) PRINT product (row) NEXT END
SUB
row
2)
+ matrix(row,
col)
* vector(col)
7.4.
ARRAYS
TWO-DIMENSIONAL
= 329
[run] 154 141 134
Comments:
1. A two-dimensional array variable can hold either numeric data or string data, but not both. 2. Three- (or higher) dimensional arrays can also be defined in a similar way
as two-dimensional arrays. For instance, a three-dimensional array uses 3 subscripts, and the assignment of values requires a triple-nested loop. As an example,
a weatherman
might
use a three-dimensional
array to record
temperatures for various dates, times, and elevations.
PRACTICE PROBLEMS
7.4
1. Consider the road mileage program in Example 1. How can the program be modified so the actual names of the cities can be supplied by the user? 2. In what types of problems are two-dimensional arrays superior to parallel arrays?
EXERCISES 7.4 In Exercises 1 through 10, determine the output of the program. Ls DIM LET
a(1 70 20; 1 10 30) fa(3..5)) =6 22 ea(3 5.5)
2. Heat capacity of a material is defined as the ratio of the heat Q supplied to the corresponding temperature rise: Heat Capacity = Q/(T7-T}) DIM
heatCapacity(1
TO
100,
1 TO
50)
BETSOF="50
LET LET
PRINT
tempRise = 20 heatCapacity(Q,
tempRise) heatCapacity(50, 20)
= 2.5
END
3. DIM year(1
TO 100,
1 TO 50)
WEI ye 7 UE Y = 8 LET year(x, y) = 1937 PRINT year(7, 8) + 50 END
4. DIM metal$(1
TO 5, 1 TO 5)
LET b$ = "Aluminum" LET metal$(2, 3) = b$ PRINT metal$(2, 3) END
330.
Arrays
«DIM actors(1 10s5.) 10=5) LET b$ = "Bogart" SWAP actor$(2, 3), b$ PRINT actor$(2, 3) PRINT actor$(3, 2) END
gq
p,
6. READ
NEXT k PRINT NEXT j REM --- Data: DATARZ aoe END DIM a(1 TO 4, 1 TO FOR j = 1 T0 4 FORKS = SI TORS
q)
DIM a{1 TO p, P10 FOR j = 1 TO p FOR) k=) 10ng READ a(j, k) PRINT a(j, k)s;
numbers
tae
mc
sO
Om
5)
. The magnetic energy stored in an inductor is e = Li’/2. L is the inductance and i is the electric current in the inductor. DIM e(1 TO 4, 1 TO FOR i = 1 T0 4 FORRES sleiOn5
Petve (sue PRINT NEXT L PRINT NEXT 7
OR
ay Sil
5)
sul
e(i,
nies i202
L),
10. READ x, y DIM power(1
1@) 3
FOR k = 1 T0 3 READ s(j, k) NEXT k NEXT
ARNT NEXT
j
REM
---
hs
ale 10x k= 1 toy
NEXT aye
- j
- k;
k
PRINT
Data:
numbers
a5
le
Se
1 TO y)
READ power(j, k) PRINT power(j, k)
Ons SiGis
go=
FOR
j
FORM i=l
DEAN END
FOR
TO x,
Ses
bia ae
NEXT
j
REM
---
Data:
xX,
y,
power
DWN
Zeiss
Assan
Say
iyi
DATA
43.2,
48.0,
51.8,
60.0
END
TWO-DIMENSIONAL ARRAYS
7.4.
331
In Exercises 11 and 12, identify the errors. 11. REM Fill Di)
ah
FORSe
an array 10
=
35
th ye) a)
1 10,4
AO
Ie = ih yO s READ a(j, k) NEXT k NEXT 3 REM
DMN
---
th,
Data:
numbers
25
Gs,
34
"S6
@,
da,
Os
@,
i,
2
END
12. REM REM
The of
voltage time
across
during
3 capacitors
---
Data:
recorded
as
a function
charging
DIM voltage(1 TO 3, 1 TO 3) AO aj 2 i TOs READ capacitorNumber FOR = TWO & READ voltage(k, j) NEXT k NEXT j INPUT "Capacitor number (1, 2 or 3)"; INPUT "Time (1, 2 or 3)"; time PRINT voltage(capacitorNumber, time) REM
is
capacitor
number,
capacitorNumber
voltages
at
3 different
times
ONDA iL, si, 2, 28 DAMN 25 Soba Boeig 59) DAW Ag Sue lis Sitio uae 5 END
In Exercises 13 through 23, write a procedure or program segment to perform the stated task. 13. Given an array dimensioned with the statement DIM a(1 TO 10, 1 TO 10),
set the entries in the jth column to j (forj = 1,..., 10).
14. Consider a system of ten bodies where each body is acted on by ten forces in the same direction. The values of the forces acting on the n‘® body are the entries of the n' row of the array force(1 TO
10, 1 TO
10). Compute
the sum of the forces acting on the 10" body. 15. Given an array dimensioned with the statement DIM a(1 TO 10, 1 TO 10), and values assigned to each entry, interchange the values in the second and third rows.
16. The period of a pendulum of length L is given by
T (seconds) = 2nVL/g where g = 9.8 m/s? is the acceleration of gravity. The values of T are measured for different values of L and stored in the array period(1 TO 3, 1 TO 4). Find the greatest value and the location(s) at which it occurs.
332
~=Arrays
45), TO 1 3, TO a(1 DIM ent tem sta the h wit ed ion ens dim y arra an en 17. Giv
and values assigned to each entry, find the greatest value and the locations (possibly more than one) at which it occurs.
18. Assume the matrices matA(), matB(), and matC() have been dimensioned with the statements DIM matA(1 TO m, 1 TO n), DIM matB(1 TO n, | TO r), and DIM matC(1 TO m, 1 TO r). Assign to matC() the product of matA() and matB().
19. Display the entries of matA(). Note: Use PRINT USING and assume the numbers of rows and columns are not too large. 20. Assume the square matrices matA() and matB() have the same size. Given a positive integer n, assign to matB() the nth power of the matrix matA(). 21. Assume the matrices matA(), matB(), and matC() Assign to matC() the sum of matA() and matB().
have the same size.
22. Assume the matrices matA() and matB() have been dimensioned with the statements DIM matA(1 TO m, 1 TO n) and DIM matB(1 TO n, 1 TO m). Assign to matB() the transpose of matA(). 23. Assume the matrices matA() and matB() number c, assign c times matA() to matB().
have the same
size. Given
a
In Exercises 24 through 31, write a program to perform the stated task. 24. A company has two stores (1 and 2), and each store sells three items (1, 2,
and 3). Table 7.22 and Table 7.23 give the inventory at the beginning of the day and the amount of each item sold during that day. Item
Item
1 St
ne
Table 7.22
Dor
wOAU
eee
E23
Beginning Inventory
S
Uet4or
cuen2a'
Table 7.23
2
e
24
3 11
18
Sales for Day
(a) Record the values of each table in an array. (b) Adjust the values in the first array to hold the inventories at the end of
the day and display these new inventories. (c) Calculate and display the total number of items in the store at the end of the day.
25. Table 7.24 gives the composition of 100 grams of a chemical substance and the amount (in grams) of its constituents. (a) Place the data from the table in an array.
(b) Determine the total amount of Hydrogen used.
TWO-DIMENSIONAL ARRAYS
7.4
= 333
Hydrogen
Oxygen
Sodium
Chlorine
Substance
(H)
(O)
(Na)
(Cl)
Water (H,O) Salt (NaCl) Hydrogen Chloride (HCl) Caustic Soda (NaOH)
Lhd 0.0 2.74 BS
88.89 0.0 0.0 40.0
0.0 39.35 0.0 7D
0.0 60.65 97.26 0.0
Table 7.24
Chemical Composition of a Substance
26. A university offers 10 courses at each of three campuses. The number of students enrolled in each is presented in Table 7.25. (a) Find the total number of course enrollments on each campus. (b) Find the total number of students taking each course.
Course
Li
Campus
Table 7.25
1 a 3
De PLY be
2
3
4
le 823) OAL
iZZaee 031 320
2 23, SG2e
5
6
ts
2 25 32 7 35, h25e 426)
Oe 32 229
8
9
10
ee 8 er Ieee
ee ae
Number of Students Enrolled in Courses
27. A state highway department is interested in the variation of two-lane highways. By measuring the width of all two-lane concrete roads, the data containing in Table 7.26 were collected. The first array represents the data and the second one represents the frequency of each measurement. Note that the frequency of each number in a row of array 1 is entered in the corresponding column in array 2. Place the measurements and the frequencies in two arrays and compute the mean value of the width of a two-lane highway. Measurements (meters)
eh. Oh) Bete th es Aeyh 64) 109766 95 67, OS eed OO iV ie 12
Table 7.26
Frequency
6s) 268 ei3
2 1 l 3
5 4 2 4 6
4 l 2D 1 1
Width of Two-Lane State Highways
28. Table 7.27 gives the number of stores for 1991 and 1992 for the five leading retail franchises
(a) Place the data into an array. (b) Calculate the total change companies.
in the number
of stores for these five
334
= Arrays
1. 7-Eleven 2. True Value 3. Ace Hardware 4. ServiStar 5. Radio Shack
Table 7.27
1991
1992
6500 7000 52001" 4500 6746
6395 6800 85200 4500 6756
Number of stores for Leading Retail Franchises
Source: Stores, May 1993
29. The scores for the top three golfers at the 1992 PGA Championship are shown in Table 7.28. (a) Place the data into an array.
(b) Compute the total score for each player. (c) Compute the average score for each round.
Round 1
Nick Price Jim Gallagher, Jr. John Cook Table 7.28
Z
3
4
10 safe T2663 Lie ee
68" 72 eed
70 10 Gare
1992 PGA Championship Leaders
30. Table 7.29 contains part of the pay schedule for federal employees. Table 7.30 gives the number of employees of each classification in a certain division. Place the data from each table into an array and compute the amount of money this division pays for salaries during the year.
Step
GS-1 GS-2 GS-3 GS—4 GS-5 GS-6 GS-7 Table 7.29
1
Z
3
4
11,903 13,382 14,603 16,393 18,340 20,443 PRIA:
£2300 13,701 15,090 16,939 18,951 21,124 23,474
12,695 14,145 15577 17,485 19,562 21,805 24,231
13,090 14,521 15,064 18,031 20,173 22,486 24,988
1993 Pay Schedule for Federal White-Collar Workers
Table 7.30
NH
at
OP
WR
ke Ware
ODOANDN W
Gare) — Coot) Or
ce UN CoG
aS
GS-1 GS-2 GS-3 GS-4 GS-5 GS-6 GS-7
= 335
fh
TWO-DIMENSIONAL ARRAYS
7.4.
Number of Employees in Each Category
31. Consider Table 7.20, the rankings of program that places the data into an be input, and gives the categories in might appear more than once or not
three university departments. Write a array, allows the name of a college to which it appears. Of course, a college at all.
32. A company has three stores (1, 2, and 3), and each store sells five items (1, 2, 3,4, and 5). Table 7.31 and Table 7.32 give the number of items sold by each
store and category on a particular day, and the cost of each item. (a) Place the data from the left-hand table in a two-dimensional array and the data from the right-hand table in a one-dimensional array. (b) Compute and display the total dollar amount of sales for each store and for the entire company. Item
1 Le 25) 2) 1 34s
Store
Table 7.31
2 3 4 O4ee 23 ao C2 el Sen O4uaN 122 A 48s
Item Cost
5 Oo 85
Number of Items Sold During Day
1 Z 3 ~
$12.00 $17.95 $95.00 $86.50
5
$78.00
Table 7.32
Cost per Item
33. Suppose a course has 15 students enrolled and five exams were given during the semester. Write a program that accepts each student’s name and grades as input and places the names in a one-dimensional array and the grades in a two-dimensional array. The program should then display each student’s name and semester average. Also, the program should display the median for each exam. (For an odd number of grades, the median is the middle grade. For an even number of grades it is the average of the two middle grades.) 34. An n-by-n array is called a magic square if the sums column, and each diagonal are equal. Write a program array is a magic square and use it to determine if either is a magic square. Hint: If at any time one of the sums others, the search is complete. (a)
fat 12 6 SaeeOe 13 3
ti 7 ll 2
4 Y 5 16
(by
of each row, each to determine if an of the arrays below is not equal to the
ero Ad) ESiniel2 6 25-0 TS LAO §) Bie he
EER 5 24 7 i a4 8 isis is
336
Arrays
ng duri city aska Nebr cal typi a for n atio ipit prec hly mont the gives 7.33 e Tabl . 35 a five-year period. Write a program that reads the table from DATA statements into an array and then produces the output shown below. [run] precipitation
Total
1986 1987 1988 1989 1990
year
each
for
36.53 31.59 28.56 31.96 22.81
Average precipitation for each May Apr Mar Feb Jan
0.77
1.91
(0-91.
52:94..4.33
Jan. Feb. Mar. 0.88 1.11 2.01 0.76 0.94 2.09 0.67 O80 1.75 0.82.40/80 | 1199 10.7 2 60.00 ie
1986 1987 1988 1989.” 199012 Table 7.33
Apr. 3.64 3.29 2:70 3.05 O02
month Jun
Jul
Aug
Sep
Oct
Nov
4.08"
3.62
4:10
3.50,
2.09")
14 32500.77
May June July 6.44 5.58 4.23 4.68 3.52 3.52 4.01 3:88 3-72 4.19'°4.44°13.98 31233 M2987 65)e
Aug. Sept. 4.34 4.00 4.82 3.72 3:78 .3:.55 457° 3.43 7 998255
Oct. 2.05 2.21 VSS 232 299
Nov. 1.48 1.24 PZ) 1.62 S055
Dec
Dec. 0.77 0.80 O61 0.75 0.92
Monthly Precipitation (in inches) for a Typical Nebraska City
36 . The coordinates of the vertices of an n-sided polygon can be stored in an array dimensioned
with
DIM
vertices(1
TO
n,
1 TO
2). The
x- and
y-coordinates of a starting vertex are assigned to the first row of the array, the coordinates of the vertex to the left of the starting vertex are assigned to the next row of the array, and so on. Write a function that accepts an array of vertices as input and returns the value of the perimeter of the polygon. a4 The Euclidian norm of a matrix is the square root of the sum of the squares of elements of the matrix. Write a function that returns the Euclidian norm of a matrix. SOLU TO TI PRACTICEON PROBLEMS S 7.4 1. The subprogram FindCityNum can be used to determine the subscript associated with each city. This subprogram and the modified subprogram InputCities are as follows: SUB
FindCityNum
SELECT
CASE LET
CASE LET
CASE LET
CASE LET
END
CASE num
"LOS num
"NEW num
=
1
ANGELES" = 2
YORK" = 3
"PHILADELPHIA" num
num)
UCASE$(city$)
"CHICAGO"
SELECT
END SUB
(city$,
= 4
7.5
SUB
A CASE STUDY: CALCULATING WITH A SPREADSHEET
InputCities
(row, col) REM Input origin and destination INPUT "Origin"; city$ CALL FindCityNum(city$, row) INPUT "Destination"; city$
CALL END
337
FindCityNum(city$,
cities
col)
SUB
2. Both parallel arrays and two-dimensional arrays are used to hold related data. If some of the data are numeric and some are string, then parallel arrays must be used since all entries of an array must be of the same type. Parallel arrays should also be used if the data will be sorted. Two-dimensional arrays are best suited to tabular data.
i
*—
A CASE STUDY: CALCULATING SPREADSHEET
WITH A
Spreadsheets are the most popular type of software used on personal computers. A spreadsheet is a financial planning tool in which data are analyzed in a table of rows and columns. Some of the items are entered by the user and other items, often totals and balances, are calculated using the entered data. The outstanding feature of electronic spreadsheets is their ability to recalculate an entire table after changes are made in some of the entered data, thereby allowing the user to determine the financial implications of various alternatives. This is called “What if?” analysis. Figure 7.8 contains an example of a spreadsheet used to analyze a student’s financial projections for the four quarters of a year. Column 5 holds the sum of the entries in the other four columns, rows 4 and 10 hold sums of the entries in rows | through 3 and 5 through 9 respectively, and row 11 holds the differences
of the entries in rows 4 and 10. Since the total balance is negative, some of the amounts in the spreadsheet must be changed and the totals and balances recalculated. This case study develops a menu-driven program to produce a spreadsheet with the five columns of numbers shown in Figure 7.8, three user-specified categories of income, and five user-specified categories of expenses. The following three tasks are to be selected from a menu:
1. Enter data. The user is prompted for three income categories and five expense categories, and for the amounts in each category for each quarter of the year. Then the program should calculate the amounts for totals and balances, display the complete spreadsheet, and display the menu below it horizontally. 2. Alter data. The user specifies each entry to be altered by giving its row, column, and new amount. After each change is entered, the amounts for the totals and balances should be recalculated and the total spreadsheet and menu displayed. The user is then prompted for further changes until he responds to the request for row, column, and new amount with 0, 0, 0. 3. Quit.
338
Arrays
5
Total
1 Fall
2 Winter
3 Spring
4Summer
1 Job 2 Parents 3 Scholarship 4 Total Expenses
1000 200 150 1350
1300 200 150 1650
1000 200 150 1350
2000 0) 0 2000
5300 600 450 6350
Tuition Food Rent Books Misc Total
400 650 600 110 230 1990
0 650 600 0 210 1460
400 650 600 120 300 2070
0 650 400 0 120 1170
800 2600 2200 230 860 6690
11 Balance
—640
190
-720
830
—340
Income
5 6 7 8 9 10
Figure 7.8 Spreadsheet for Student’s Financial Projections
The 55 locations in the spreadsheet that hold amounts are called cells. Each cell is identified by its row and column numbers. For instance, the cell 10, 2 contains the amount 1460.
Designing the Spreadsheet Program In keeping with the top-down approach to problem solving, we break the problem into a small number of basic tasks, each of which will then be broken down further. The first task is the setting up of the fixed labels. After that, a menu is presented with the following three options.
1. Create spreadsheet
2. Revise spreadsheet 3. Quit
The first two menu items are broken down into specific subtasks.
1. Create spreadsheet. To form the spreadsheet, we must request the income and expense categories and amounts from the user, calculate the totals and balances, and then display the resulting spreadsheet; that is, task 1 is divided
into the following subtasks. 1.1 Input income and expense categories 1.2 Input income and expense amounts
1.3 Calculate totals and balances 1.4 Display spreadsheet
2. Revise spreadsheet. The user may request a change in just one of the cells by providing its row and column and the new amount. Then the program will recalculate all the totals and balances and display the revised spreadsheet. That is, task 2 is divided into the following subtasks. 2.1 Input cell (row, column) and new amount 2.2 Calculate totals and balances
2.3 Display spreadsheet
(oe. CASE STUDY: CALCULATING WITHA SPREADSHEET
%339
Notice that tasks 2.2 and 2.3 are the same as tasks 1.3 and 1.4. Since the subprogram that performs tasks 1.3 and 1.4 can also be used for tasks 2.2 and 2.3, respectively, considerable work is saved. Whenever possible, generalpurpose subprograms such as these should be incorporated in the design of a program.
The next step in designing the program is to examine each of the subtasks identified above and decide which, if any, should be divided further into smaller tasks. The input tasks, 1.1, 1.2 and 2.1, are basic, so we won’t divide them any
further; but the calculate and display tasks, 1.3 and 1.4, are more involved. These subtasks can be broken down as follows. 1.3 Calculate totals and balances. This subtask requires computing income and expense totals for each of the time periods, computing balances for the time periods, and a “row total” corresponding to each income and expense category of the spreadsheet. 1.3.1
Calculate income totals
1.3.2 Calculate expense totals 1.3.3 1.3.4
Calculate balance Calculate row totals
1.4 Display spreadsheet. To display the spreadsheet, we need to produce the table in Figure 7.8 that contains labels for the income and expense categories and time periods, and has its data arranged in rows and columns. 1.4.1 Display labels 1.4.2 Display data The top-down chart in Figure 7.9 shows the stepwise refinement of the problem. The items in the main part of the chart that are contained in rectangles have continuations below.
Manage a Spreadsheet
Set Up Labels
Present Menu &
Create Spreadsheet
Revise Spreadsheet
Quit
Calculate Totals and Balances
Display
Get Choice
Input Income and Expense Categories
Input Income and Expense Data
Calculate Totals and Balances
Display Spreadsheet
Input New Income and Expense Data
Calculate Totals and
Display Spreadsheet
Balances
Calculate Income Totals
Figure 7.9
Calculate Expense Totals
Calculate Balances
Spreadsheet
Calculate Totals for Rows
Top-Down Chart for Spreadsheet Case Study
Display Labels
Display Data
340
Arrays
Pseudocode for the Spreadsheet Program The workhorse of the top-down chart is the third row. The following pseudocode shows how these tasks are carried out. INPUT INCOME Clear the screen FOR row counter Prompt user for NEXT Display one blank FOR row counter Prompt user for NEXT INPUT INCOME Display two blank FOR row counter Prompt user for NEXT Display one blank FOR row counter Prompt user for NEXT
AND EXPENSE CATEGORIES
(Subprogram InputCategories)
from 1 to 3 income label corresponding to row counter line from 5 to 9 expense label corresponding to row counter AND EXPENSE DATA (Subprogram InputData) lines from | to 3 income data corresponding to row counter line from 5 to 9 expense data corresponding to row counter
CALCULATE TOTALS (Subprogram CalculateSpreadsheet) Calculate Calculate Calculate Calculate
income totals expense totals balances row totals
DISPLAY SPREADSHEET (Subprogram DisplaySpreadsheet) Display column labels FOR row counter from | to 11 IF row counter is 1 THEN
Display income label END IF IF row counter is 5 THEN Display expenses label END IF IF row counter is 11 THEN Display blank line END IF
Display row data NEXT INPUT NEW DATA (Subprogram InputNewData) DO Input new data for spreadsheet LOOP UNTIL data okay
Writing the Spreadsheet Program Three arrays suffice to hold the spreadsheet. (See Table 7.34.) Three of the elements of the array rowLabel, the fourth (Total), 10th (Total), and 11th
7.5
A CASE STUDY: CALCULATING WITH A SPREADSHEET
341
(Balance), are fixed. The other elements of that array are the categories to be
determined by the user. The column labels are all fixed. The data for all rows except 4, 10, and 11 must be entered by the user.
Arrays
Range
Information Held
rowLabel$() colLabel$() userData()
LTOT! LOS PO
Job, Parents, ..., Balance Fall, Winter, . . . , Total Amounts in the 55 cells
Table 7.34
tal bes
The Arrays That Hold the Spreadsheet
When values have been assigned to the three arrays, the totals are easily calculated with loops containing accumulators. Then the balances are calculated by performing subtractions. After the user has entered the spreadsheet, he or she is presented with a menu of three options. The user can enter a completely new spreadsheet (with possibly different categories), revise selected data in the current spreadsheet, or quit. The first task is identical to the formation of the original spreadsheet and the last task is trivial. After selecting the update option, the user is asked for a data entry to alter. The entry is specified by giving the location of the entry, namely its row and column, and the value of the entry. After the three responses are obtained, the program recalculates all the totals and balances. The user can continue to revise the spreadsheet to his heart’s content. The user indicates that he or she is finished with the update by responding with 0, 0, 0. Table 7.35 shows each task discussed above and the subprogram that carries out the task. The program follows.
1.
2.
Bx
InputSpreadsheet 1.1 Input income and expense categories 1.2 Input income and expense data 1.3 Calculate totals and balances 1.3.1 Calculate income totals 1.3.2 Calculate expense totals 1.3.3 Calculate balances 1.3.4 Calculate row totals 1.4 Display spreadsheet 1.4.1 Display labels 1.4.2 Display data Revise spreadsheet 2.1 Input new data 2.2 Calculate totals and balances 2.3 Display spreadsheet Out
Table 7.35
Tasks and Their Procedures
InputSpreadsheet InputCategories InputData Calculate CalculateIncomeTotals CalculateExpenseTotals CalculateBalances CalculateRowTotals DisplaySpreadsheet
ReviseSpreadsheet InputNewData Calculate DisplaySpreadsheet
342
~=Arrays
REM
Spreadsheet
Ae
KK
REM
*
REM
*
REM
*
REM REM REM REM
* * * *
REM
*
REM
KKK
IK
KKK
KKK
Program KKK
KKK
KKK
KKK
KKK
KKK
IK
KKK
KKK
KKK
KKK
KKK
KEKEKKKKKKKEK
*
%
Table
Variable
%
User's main menu choice (1, 2, or 3) Column labels (seasons and TOTAL) Numeric data entered by user, totals Row categories entered by user
choice colLabel$() entries() rowLabel$()
* ts * is fe
KK
KEKE
KKK
KKK
KKK
KKK
KKK
KKK
KKK
KKK
KKK
KKK
KKKKKKKKKKKKKKEKE
CLS DIM colLabel$(1 TO 5), rowLabel$(1 TO 11), CALL SetUpLabels(rowLabel$(), colLabel$())
entries(1
TO
11,
1 TO
DO
CALL GetChoice(choice) SELECT CASE choice CASE 1
CALL
InputSpreadsheet (rowLabel$(),
colLabel$(),
CASE 2 CALL ReviseSpreadsheet (rowLabel$(), CAS
LOOP REM
entries())
"Have
a nice
day."
SELECT
UNTIL ---
DATA
colLabel$(),
ERS
PRINT END
entries())
choice
Data:
1 Fall,
= 3
column
labels
2 Winter,
3 Spring,
4 Summer,
5 Total
END
SUB Calculate (entries()) REM Calculate totals and balances for spreadsheet CALL CalculateIncomeTotals(entries()) CALL CalculateExpenseTotals(entries()) CALL CalculateBalances(entries()) CALL CalculateRowTotals(entries()) END
SUB
SUB CalculateBalances (entries()) REM Calculate balances FOR col = 1 TO 4 LET entries(11, col) = entries(4, col
NEXT END
SUB
SUB CalculateExpenseTotals (entries()) REM Calculate total expenses FORSCOM = sles Ona, LET total = 0 FOR row = 5 T0 9 LET total = total + entries(row, row
NEXT
LET NEXT END
col)
SUB
entries(10, col
col)
= total
col)
- entries(10,
col)
5)
A CASE STUDY: CALCULATING WITH ASSPREADSHEED
i
SUB
CalculateIncomeTotals (entries()) REM Calculate total income FOR
col
=
1 T0
LET
total
FOR
row
LET LET
= 0 =
1 TO
total
NEXT
4
3
= total
2col)i=
total
col
END
SUB
SUB
CalculateRowTotals
REM
Calculate
FOR
row
LET
=
total
(entries())
totals
1 TO
for
rows
11
110.4
LET total = total NEXT col LET entries(row, 5) NEXT
all
= 0
FORSCOl=s
END
col)
row
entries (4.
NEXT
+ entries(row,
+ entries(row,
col)
= total
row
SUB
SUB DisplaySpreadsheet (rowLabel$(), colLabel$(), REM Display all spreadsheet information
entries())
GIES
VET asia"
\
PRINT USING a$; LET a$ = "## \ FOR
row
=
SELECT
1 TO CASE
Nor
\
em
colLabel$(1); colLabel$(2); \ #ttttt #HHttHH
Aa
a
Ne
colLabel$(3); colLabel$(4); ainda #ettet #tbtotH"
11 row
CASES
PRINT
CASE
"
Income"
"
Expenses"
5
PRINT
PRINT
CASES! PRINT CASESEESE END
SELECT
REM
The
following
two
lines
should
be
joined
and
PRINT USING a$; row; rowLabel$(row); entries(row, entries(row, 3); entries(row, 4); entries(row, 5) NEXT
row
END
SUB
SUB
EraseLines
REM
Erase
two
LOCATE 21, 1 PRINT TAB(79); WOCAIIE Zn 1 PRINT TAB(79) ; LOCNM2 Zil, il END SUB
lines
near
bottom
of
screen
entered
1);
as
one
line.
entries(row,
2);
colLabel$(5)
343
344
Arrays
SUB GetChoice (choice) REM Input user option HONE Zik dl PRINT "1. Enter data
for
menu
main
Update
2.
Se
data
OUlts
DO HOGATIE 225.01 INPUT "Number of choice: LOOP UNTIL (choice = 1) OR END SUB
(rowLabel$(),
InputCategories
SUB
OR
(choice
= 3)
colLabel$())
labels
category
Input
REM
", choice (choice = 2)
CLS "Income
PRINT row
FOR
INPUT
=
category"
1 TO
3
rowLabel$(row)
"Label";
row
NEXT
rowLabel$(4)
LET
= "Total"
PRINT
PRINT "Expense category" FOR row = 5 10 9 INPUT "Label"; rowLabel$(row) row
NEXT
rowLabel$(10) rowLabel$(11)
LET LET END
SUB
SUB
InputCategoryData
REM
Input
FOR
col
PRINT INPUT
amounts
= "Total" = "Balance"
(colLabel$(), for
one
entries(),
row)
category
= 1 T0 4
USING " \ \: "3; colLabel$(col); "", entries(row, col)
col
NEXT SUB
END
SUB InputData (rowLabel$(), colLabel$(), entries()) REM Input numeric data for entire spreadsheet PRINT PRINT
FOR
row
=
1 10
3
PRINT "Enter each season's income from "; rowLabel$(row) CALL InputCategoryData(colLabel$(), entries(), row) NEXT
row
PRINT
FOR
row = 5 T0 9 PRINT "Enter each season's expenses CALL InputCategoryData(colLabel$(),
NEXT END
SUB
row
for "; rowLabel$(row) entries(), row)
Programming Projects
SUB
InputNewData
REM
Input
(row,
row,
col,
column,
345
newData)
and
new
amounts
for
spreadsheet
update
DO CALL
EraseLines
PRINT
“Enter
INPUT
"Row,
0,
0 to
Column,
LOOP
UNTIL
CALL
EraseLines
END
0,
(row
>=
0)
terminate"
New
data:
AND
(row
",
=
0)
AND
(col
year(index + 1) THEN CALL SwapData(name$(), year(), index) END IF NEXT index NEXT passNum END SUB
SUB SwapData (name$(), year(), index) REM Swap names and years SWAP name$(index), name$(index + 1) SWAP year(index), year(index + 1) END
SUB
SUB WriteData (name$(), year(), REM Write data back into file OPEN
"YOB.DAT"
FOR
OUTPUT
AS
numPeople) #1
FOR i = 1 TO numPeople WRITE #1, name$(i), year(i) NEXT
CLOSE END
7
#1
SUB
If the program from Example 4 of Section 8.1 is executed after running the program in Example 1, the output will be Name
Age
Johnny Ringo
68 54
Barbra Sylvester
52 48
in
1994
370
Sequential Files
Merging Sequential Files In Section 7.2, we considered an algorithm for merging two arrays. This same algorithm can be applied to merging two ordered files provided each file ends with a trailer value. (Relying on the EOF function instead of trailer values requires contorted code.) Trailer values are easily added after opening the files FOR APPEND. Suppose you have two ordered files (possibly with certain items appearing in both files) ending with the same trailer value, and you want to merge them into a third ordered file (without duplications). The technique for creating the third file is as follows. 1. Add a trailer value to the end of each file.
2. Open the two ordered files FOR INPUT and open a third file FOR OUTPU 3. Get the first item from each file.
4. Repeat steps (a) and (b) below until one of the items retrieved is a trailer value.
(a) If one item precedes the other, write it into the third file and get the next item from its file. (b) If the two items are identical, write one into the third file and get the next item from each of the two ordered files.
5. At this point, the item most recently retrieved from one file may not be the trailer value. In this case, write that item and all remaining items preceding the trailer value to the third file. 6. Close the three files.
EXAMPLE
2
The following program merges two ordered files of numbers into a third file. REM
Merge
CLS INPUT INPUT INPUT
two
"Name "Name "Name
ordered
files
of first file"; filel$ of second file"; file2$ of merged file"; file3$
LET
trailer
= -1
OPEN
filel$
FOR
APPEND
AS
#1
OPEN
file2$
FOR
APPEND
AS
#2
WRITE
#1,
trailer
WRITE
#2,
trailer
CLOSE
#1,
#2
OPEN filel$ FOR INPUT AS #1 OPEN file2$ FOR INPUT AS #2 OPEN file3$ FOR OUTPUT AS #3 INPUT #1, numl INPUT #2, num2
8.2"
DO WHILE
numl
SELECT
CASE
numl
IS
CASE
trailer
num2
371
trailer
< num2
numl
#3,
WRITE
#1, numl > num2
INPUT CASE IS WRITE
#3,
num2
INPUT
#2,
num2
WRITE
#3,
numl
INPUT
#1,
numl
INPUT #2, SELECT
num2
num2
CASE
END
AND
USING SEQUENTIAL FILES
LOOP DO WHILE
numl
WRITE
#3,
numl
INPUT
#1,
numl
LOOP DO WHILE
num2
WRITE
#3,
num2
INPUT
#2,
num2
trailer
trailer
LOOP CLOSE END
#1,
#2,
#3
Control Break Processing Suppose a small real estate company stores its sales data for a year in a sequential file in which each record contains four fields: month of sale (1 through 12), day
of sale (1 through 31), address, price. Typical data for the sales of the first quarter of a year are shown in Figure 8.6. The records are ordered by date of sale.
Figure 8.6
Month
Day
Address
Price
January January January February February March
9 20 25 15 23 15
102 Elm Street 1 Main Street 5 Maple Street 1 Center Street 2 Vista Drive 205 Rodeo Circle
$203,000 $315,200 $123,450 $100,000 $145,320 $389,100
Real Estate Sales for First Quarter of Year
Figure 8.7 shows the output of a program that displays the total sales for the quarter year, with a subtotal for each month.
372
Sequential Files
[run] January January January
for January:
$641,650
1 Center Street 2 Vista Drive
$100,000 $145,320
Subtotal 15 23
February February
for
Subtotal March
15 -
Total
Figure 8.7
for
$203,000 $315,200 $123,450
102 Elm Street 1 Main Street 5 Maple Street
9 20 25
205 Subtotal
First
$245,320
February:
Rodeo
Circle
$389,100
for March:
Quarter:
$389,100
$1,276,070
Output of Example 3
A program to produce the output of Figure 8.7 must calculate a subtotal at the end of each month. The variable holding the month triggers a subtotal whenever its value changes. Such a variable is called a control variable and each change of its value is called a break.
EXAMPLE 3
Write a program to produce the output of Figure 8.7. Assume the data of Figure 8.7 are stored in the sequential file HOMESALE.DAT.
SOLUTION
The following program allows for months with no sales. Since monthly subtotals will be printed, the month-of-sale field is an appropriate control variable. REM Display home sales by month CLS OPEN "HOMESALE.DAT" FOR INPUT AS #1
LET format$ = "\ LET format2$ LET
month
\ ##
= "
‘Adjust
\ Subtotal
NOT
for \
\
EOF(1)
#1,
‘Flag
to
IF
S###, HHH"
indicate
THEN
newMonth$,
day,
addr$,
price
EESE END
necessary
= 0
INPUT LET
as
\ S###, ###"
LET month$ = "" LET done = 0 DO WHILE done = 0 IF
path
done
= 1
Manel
One Wise
end
of
list
8.2
IF
(newMonth$ month$) IF month >= 1 THEN
OR
(done
= 1)
USING SEQUENTIAL FILES
THEN
373
‘Control break processing ‘Don't print on first month
PRINT PRINT
USING
format2$;
month$
+ ":";
monthTotal
PRINT
END IF LET month$
= newMonth$
month
LET
monthTotal
END IF IF done
+
= month
LET
1
= 0
= 0 THEN
PRINT
USING
LET yearTotal
format$;
newMonth$;
= yearTotal
END
IF
LET
monthTotal
monthTotal
#1 USING
for
LOOP CLOSE PRINT END
"Total
First
day;
addr$;
price
+ price + price
Quarter:
$#,###,###";
yearTotal
Comments:
1. DOS has a command called SORT that orders the records of a sequential file. The command SORT
filename2
sorts the records of the first file in ascending order by the first field and places them into a new file called filename2. The DOS command SORT
filename2
/R
produces a descending sort.
PRACTICE PROBLEMS 8.2 1. The program in Example 2 contains three DO loops. Explain why at most one of the last two loops will be executed. Under what circumstances will neither of the last two loops be executed? 2. Modify the program in Example 2 so that duplicate items will be repeated in the merged file.
EXERCISES 8.2 Exercises 1 through 4 are related. They create and maintain the sequential file AVERAGE.DAT to hold batting averages of baseball players. 1. Suppose the season is about to begin. Compose a program to create the sequential file containing the name of each player, his times at bat, and his number of hits. The names should be entered by input statements and the times at bat and number of hits initially should be set to 0.
374
Sequential Files
2. Each day, the statistics from the previous day’s games should be used to update the file. Write a program to read the records one at a time and allow the user to enter the number of times at bat and the number of hits in yesterday’s game for each player in response to INPUT statements. The program should update the file by adding these numbers to the previous figures. . Several players are added to the league. Compose a program to update the file.
. Compose a program to sort the file AVERAGE.DAT with respect to batting averages and display the players with the top ten batting averages. Hint: The file must be read once to determine the number of players and again to load the players into an array. Exercises 5 through 7 are related. They create and maintain the sequential file NUCLEI.DAT
to hold data of radioactive nuclei.
5. The number of radioactive nuclei in any sample of radioactive material decreases continuously as the nuclei disintegrate. The rate at which the number decreases, however, varies widely for different nuclei. If No is the number of nuclei at time t = 0, then the number of nuclei at time t is given by N(t)
= Noe™
where A is the rate of disintegration. The half life T,;) of a radioactive sample is defined as the time required for the number of nuclei to decrease to half the number at t = 0.
Typ = LOG(2)—A. Compose a program to create a sequential file containing radioactive ele-
ments and the values of No and T/7. The data should be entered by INPUT statements. Test the program with the data in Table 8.3.
Element
T 1/2 (days)
No
4475 1920 138
200 175 150
Tritium (H?) Cobalt (Co®°) Polonium (Po?!®) Table 8.3. Activity of Radioactive Elements
6. Each day, the amount of radioactive nuclei decreases. Write a program to calculate the amount of nuclei remaining after 100 days (calculate the value
ofN at t = 100) and update the value of No to N in the sequential file.
7. Several elements (with their corresponding No and T, j2) are to be added to the list. Compose a program to update the file.
82)
USING SEQUENTIAL FILES
375
Exercises 8 and 9 refer to the ordered file BLOCK.DAT containing the names of people on your block and the ordered file TIMES.DAT containing the names of all people who subscribe to the New York Times.
8. Write a program that creates a file consisting of the names of all people on your block who subscribe to the NY Times. . Write a program that creates a file consisting of the names of all NY Times subscribers who do not live on your block. 10. The file DENSITY.DAT contains the names and the densities of five metals in the following order: Brass, 8.6, Gold, 19.3, Mercury, 13.6, Platinum, 21.4, Silver, 10.5. The file DENSITY1.DAT is similar to the file DENSITY.DAT but contains the following metals with their densities: Brass, 8.6, Mercury,
13.6. Write a program to create a file consisting of the information in DENSITY.DAT but with the information contained in DENSITY1.DAT deleted. After the deletions, the new file should have the name DENSITY.DAT. 1
Suppose a file of positive integers is in ascending order. Write a program to determine the maximum number of times any integer is repeated in the file. (For instance, if the entries in the file are 5, 5, 6, 6, 6, and 10, then the output iso)
12; Several kinds of rocket propellants, coded as A, B, C, ... are being tested.
Each record of the file TEST.DAT contains one of the code letters and the burn rate from test firing the rocket. The records are ordered by the code letters. Write a program to display the code letter, number of tests, and average burn rate for each propellant. The program should also display the total number of tests conducted and the average burn rate of all propellants. For instance, if the first four records of the file are BENS) eo “B29 SCE30)
then the first two entries of the output would be [run] Propellant
Number
Average
of Tests
Burn
A
2
33
B
1
29
Rate
Ley, An elementary school holds a raffle to raise funds. Suppose each record of the file RAFFLE.DAT contains a student’s grade (1 through 6), name, and
the number of raffle tickets sold, and that the records are ordered by grade. Write a program using a control break to display the number of tickets sold by each grade and the total number of tickets sold.
376
Sequential Files
AT .D US NS CE file l tia uen seq ted sor the e pos Sup . aks Bre l tro Con 14. Multiple
m for the has ord rec h eac re whe te, sta a of nts ide res all contains names of
h oug thr s pas one in , ine erm det to m gra pro a te Wri ”. “lastName”,“firstName te: (No e. nam full on mm co t mos and me na last on mm co t mos the file, the
ing urr occ t firs the y pla dis uld sho m gra pro the tie, a of nt eve In the unlikely
name.) For instance, the output might be as follows. [run] The
most
common
last
name
is
Brown
The
most
common
full
name
is
John
Smith
and es nam the ns tai con ER ST MA file the e pos sup 16, and 15 ses rci Exe In phone numbers of all members of an organization, where the records are ordered by name. 15. Suppose the ordered file MOVED contains the names and new phone numbers of all members who have changed their phone numbers. Write a program to update the file MASTER.
16. Suppose the ordered file QUIT contains the names of all members who have left the organization. Write a program to update the file MASTER. 17. Suppose a file must be sorted by QBasic, but is too large to fit into an array. How can this be accomplished? 18. What are some advantages of files over arrays?
19. Do the following steps at the computer. (a) Create a sequential file HOMES
containing the five records Huron,
Ontario, Michigan, Erie, and Superior in the given order. (b) Execute the command
Exit from the Files menu. You will now be in
DOS. (c) Enter the command TYPE HOMES to see the Great Lakes displayed in the given order. Their first letters should spell HOMES. (d) Enter the command
SORT
HOMES
to order the great
lakes. (e) Enter TYPE HOMES to see the Great Lakes displayed in alphabetical order. SOLUTIONS TO PRACTICE PROBLEMS 8.2 1. Execution proceeds beyond the first DO loop only after a trailer value is read from one of the input files. Since each of the following DO loops executes only if the trailer value of the associated file was not read, at most one loop can execute. Neither of the loops will be executed if each input file contains only the trailer value or if the last entries of the files are the same.
2. Change the SELECT CASE block to the following: SELECT CASE
numl
IS num2
WRITE
#3,
num2
INPUT
#2,
num2
SELECT
A-GASE STUDY: CREATING AIREGEIPT
oo
8, 3
S77
A CASE STUDY: CREATING A RECEIPT Most supermarkets have automated check-out counters. Scanners read coded information on each item and send the information to a computer that produces an itemized receipt after all the items have been scanned. This case study develops a program to produce an itemized check-out receipt after all the coded information has been entered. The standard code is the Universal Product Code (UPC), which consists of
a sequence of 10 digits appearing below a rectangle of bars. (See Figure 8.8.) The bars have these digits encoded in a form that can be read by an optical scanner. The first five digits encode the manufacturer and the second five digits specify the product and the size of the package. The digits 37000 00430 appear on a jar of peanut butter. The string 37000 is the code for Procter & Gamble and 00430 is Procter @ Gamble’s code for a 22-ounce jar of creamy Jif peanut butter. Of course, the string 00430 will have an entirely different meaning for another
|
Figure 8.8
37000°
00430
Universal Product Code
Suppose a supermarket carries four thousand items and a sequential file called MASTER.DAT holds a record for each item consisting of the following information: the UPC, the name of the item, the price. Let us also assume the file has been sorted by the UPC for each record and that the file ends with a sentinel record whose fictitious UPC is greater than any actual UPC. (Note: The use of a sentinel is a common practice when an entire file will be read sequentially. The advantage of using a sentinel, as opposed to relying solely on EOF, will become apparent when the program is written.) For instance, the file might contain the following data for three food items. "3700000430","22-0z "4119601012","19-0z
Jif Peanut Butter",1.76 Prog Minn Soup",1.19
soz sCSmC inn 53 07m 0 “70/34 "9999999999", "Sentinel",0
ROS@mlea)
1.65
We wish to write a program that will accept as input UPC codes entered from the keyboard and produce as output a printed itemized receipt. One way to proceed would be to take each UPC as it is input into the computer and then search for it in the master file to find the item description and price. We then would have to search sequentially through a long file many times. A better way to proceed is to first store the input UPCs in an array and then sort the array in increasing order, the same order as the master file. Then the information can be located in just one sequential pass through the master file.
378
Sequential Files
The program must be able to handle the special case in which a UPC code entered is not in the master file. Suppose the first array item, after the array of UPCs has been sorted, is not in the master file. Then its UPC will never equal one of the UPCs in the master file. At some point during the sequential pass through the master file, the array UPC will be less than the most recently read UPC from the master file. This indicates that the UPC is not in the master file, and that the user must be informed of this fact. After the array of UPCs has been sorted, the search algorithm is as follows.
1. Begin with the first (lowest) array item. (It is most likely higher than the first UPC in the master file.)
2. Read records from the master file until the record is found whose UPC matches or exceeds the array UPC.
3. If the master file UPC matches the array UPC, then print the corresponding description and price of the item from the master file and add the price to the running total. Otherwise, print a message stating that the item is not in the master file.
4. Repeat steps 2 and 3 for each element of the array.
Designing the Supermarket Check-Out Program The major tasks of the program are as follows:
1. Input UPC codes from the keyboard (and count number of items). Task 1 uses a loop that requests the UPCs of the items purchased. A counter should keep track of the number of items purchased and a sentinel should indicate when all the UPCs have been entered. 2. Sort the array of UPC codes into ascending order. Task 2 can be accomplished with a bubble sort since the array is small. 3. Create an itemized receipt. Task 3 can be divided into smaller subtasks. After the master file is opened, the file is searched sequentially for the triplet holding the first array UPC. If this record is found, the item name and price are printed and the price is added to the total. Then, the second item is looked for in the same manner. This process continues until all possible items and prices have been printed. Of course, any unlocatable item must be reported. Finally, the total price is printed and the master file is closed. That is, task 3 is divided into the following subtasks: 3.1 Open the master file. 3.2 Search for array UPCs in the master file. 3.3 Print an itemized receipt. 3.4 Close the master file.
Figure 8.9 shows the top-down chart for the program.
83
AICASE STUDY: CREATING AREGEIPT
Create Itemized Bill
Reset Master UPC File
Input
Sort
Create
UPC Codes
UPC Codes
Itemized Bill
Search for UPCs in File
Print Bill Entries
Close Master UPC File
Figure 8.9 Top-Down Chart for the Supermarket Check-Out Program
Pseudocode for the Supermarket Check-Out Program INPUT UPC CODES (Subprogram InputCodes) Initialize numItems counter to 0 Prompt user for input DO WHILE there are more items to be entered Read the UPC into the current array element Increment numItems Prompt user for more input LOOP SORT UPC CODES (Subprogram SortCodes) FOR passNum = | TO numltems — 1 FOR i = | TO numltems — passNum IF the ith array UPC is greater than the (i+1)th THEN Switch the ith and (i+1)th array elements
END IF NEXT i NEXT passNum CREATE ITEMIZED RECEIPT (Subprogram MakeReceipt) Open the master file Initialize total to 0 Read first triplet from the master file FOR i = 1 TO numlItems DO WHILE item i’s UPC > the current file UPC Read the next record from the master file LOOP IF item i’s UPC = the file UPC THEN
Print the corresponding item description and price Increase total by price ELSE Print that the UPC is not in the master file END IF NEXT i Print total Close the master file
9379
380
Sequential Files
Writing the Supermarket Check-Out Program Table 8.4 shows each of the tasks discussed above and the procedure used to perform the task.
1. 2. 3. Table 8.4
Task
Procedure
Input UPCs and count number of items Sort the array of UPCs into ascending order Create itemized receipt
InputCodes SortCodes MakeReceipt
Tasks and Their Procedures
The following program loads the purchased items into an array, sorts the array, and then carries out the search algorithm. A sample run is presented. REM
Print
out
an
itemized
KKK
KK
grocery
bill
REM REM
KKKK
KKK
KKK
KKK
KKK
KKK
KKK
KKK
KKK
KKK
KKK
KKK
KKK
KKK
KKK
KKKKKKKEEK
REMips
*
REM * itemUPC$()
Array of UPC's
REM
* numItems
Counts
REM
*
REM
KR
the
for the items
number
of
items
purchased
_
purchased
i te
KK
KKK
KKK
KK
KKK
KKK
KK
KKK
KKK
KK
KKK
KKK
KK
KKK
KKK
KKK
IK
KKK
KK
KKK
KKKEK
REM DIM
itemUPC$(1
TO
100)
CLS CALL InputCodes(itemUPC$(), numItems) CALL SortCodes(itemUPC$(), numItems) CALL MakeReceipt(itemUPC$(), numItems) END
SUB InputCodes REM
Fill
LET
numItems
PRINT
the
"Enter
(itemUPC$(), array
with
numItems) UPC
codes
for
items
purchased
= 0 * when
all
items
have
been
entered."
PRINT
INPUT "Enter UPC code DO WHILE code$ "*" LET
numItems
of
= numItems
item: +
",
code$
1
LET itemUPC$(numItems) = code$ INPUT "Enter UPC code of item: LOOP END SUB
",
code$
SUB MakeReceipt (itemUPC$(), numItems) REM Output store receipt REM total Total cost of all purchases REM code$ UPC at the current file position REM descr$ Description of item at current position REM price Price of current item OPEN "MASTER.DAT" FOR INPUT AS #1 LET total = 0 INPUT
#1,
code$,
descr$,
price
‘Read
first
record
from
master
file
Appendix: Displaying the Contents of a File
FOR
1 =
1 TO
DO WHILE
INPUT
381
numItems
itemUPC$(i)
#1,
code$,
> code$
descr$,
price
LOOP
IF itemUPC$(i)
= code$ THEN
LPRINT descr$; TAB(37); price LET total = total + price BESE UPRINT “**. UPCT si temUPCS (ays. 2@not dusted $$###.##"; CLOSE #1 END SUB
SUB SortCodes
(itemUPC$(),
numItems)
REM
Perform
bubble
sort
FOR
passNum
= 1 TO
numItems
FOR
i
=
1 TO
numItems
total
on
the
-
array
1
- passNum
IF
itemUPC$(i) > itemUPC$(i + 1) SWAP itemUPC$(i), itemUPC$(i END IF NEXT 7 NEXT passNum END SUB
THEN + 1)
[run] Enter
* when
Enter Enter Enter Enter Enter
UPC UPC UPC UPC UPC
code code code code code
22-oz
Jif
Peanut
Butter
e716
22-oz
Jif
Peanut
Butter
ev7i6
all
items
of of of of of
item: item: item: item: item:
have
been
7073405307 3700000430 3700000430 4100034200 *
** UPC 4100034200 not listed **
2.5 Total
oz
CS
Cinn
Rose
entered.
Tea
S=Ssessas2asaetasessssS25552>
yee
ee ee printer
ie65 $5.17
Chapter 8 Appendix: Displaying the Contents of a File The following program reads the first 2000 characters of a file requested by the user, and displays them on a graphics monitor. (To run the program with a monochrome display monitor, change the fourth line to DEF SEG = G@HBO00.) Carriage returns appear as single musical notes and line feeds appear as reverseimage circles. Press any key to clear the screen. (This program uses some statements not covered in the text.)
382
Sequential Files
REM
Display
GS INPUT DEF
"FILE
every
TO
READ";
= &HB800
SEG
character
in
a file
to
&HB000
file$ ‘Change
SGREENBO R= Onm0 OPEN file$ FOR INPUT AS #1 CES LET 1 =20 DO WHILE (i 2000) AND (NOT EOF(1)) ‘Read next LET char$ = INPUT$(1, #1) POKE 2 * i, ASC(char$)
for
monochrome
character
display
from
file
1
REbe tes
LOOP #1
CLOSE
LET
a$
= INPUT$(1)
‘Pause
until
a key
is
pressed
END
Chapter 8 Summary 1. Each file has a filespec that gives the disk drive holding the file and the file name. QBasic programs associate a reference number with any file used in a program and refer to the file by that number. . When sequential files are opened, we must specify whether they will be created and written to, added to, or read from by use of the terms OUTPUT,
APPEND, or INPUT. The file must be closed before the operation is changed. Data are written to the file with WRITE# statements and retrieved with INPUT statements. The EOF function tells if we have read to the end of the file.
. A sequential file can be ordered by placing its data in arrays, sorting the arrays, and then writing the ordered data into a file. This process should precede adding, deleting, or altering items in a master file.
Chapter 8 Programming Projects 1. Suppose the sequential file “ALE” contains the information shown in Table 8.5. Write a program to use the file to produce Table 8.6 in which the baseball teams are in descending order by the percentage of games won.
Programming Projects
Team
Won
Lost
82 78 ic 78 65 83 87
70 73 80 14 88 70 64
Baltimore Boston Cleveland Detroit Milwaukee New York Toronto
Table 8.5
383
American League East Games Won and Lost, 9/23/93
American League East Toronto New York Baltimore Boston Detroit Cleveland Milwaukee Table 8.6
W
L
Pct
87 83 82 78 78 73 65
64 70 70 8) 74 80 88
576 42 eyes. OL ps Add 425
American League East Standings on 9/23/93
2. Write a rudimentary word processing program. The program should (a) Request the name of the sequential file to hold the document as input from the keyboard. (b) Clear the screen and display the symbol > as a prompt at the upper left corner of the screen.
(c) Request the first line of the file as input from the keyboard and write this line to the file when the Enter key is pressed. Note: Blank lines are acceptable input, but lines exceeding 60 characters in length should not be accepted (the user should be prompted to reenter the line). (d) Display a second prompt at the leftmost position of the next line of the screen and carry out (c) for this line. (e) Continue as in (d) with subsequent lines until the user responds with EOD. (EOD should not be written to the file.) (f) Clear the screen and display the complete text file on the screen. [sample Enter
run] the
name
of
the
file
to
[Screen cleared] >The most important feature !ILINE TOO LONG!! >The most important feature >performs correctly. This is >solution to the problem is
>E0D The
most
performs solution
important
feature
create:
MYFILE
of a computer
program
is
that
it
of a computer program is that it most likely to occur when the systematically planned.
of
a computer
program
is
correctly. This is most likely to occur when to the problem is systematically planned.
that
the
it
performs
384
Sequential Files
3. Write a program that counts the number of times a word occurs in the
sequential file created in Programming Project 3. The file name and word should be input from the keyboard. For instance, opening MYFILE and searching for “is” would produce the output: “is” occurs 3 times. A department store has a file containing all sales transacted for a year. Each record contains a customer’s name, zip code, and amount of the sale. The file is ordered first by zip code and then by name. Write a program to display the total sales for each customer, the total sales for each zip code, and the total sales for the store. For instance, if the first seven records of the file are "Adams,
John", 10023,34.50
"Adams,
John",10023,60.00
"Jones,
Bob",10023,62.45
"Green,
Mary", 12345,54.00
"Howard, Sue",12345,79.25 "Smith, George",20001,25.10
then the output will begin with Customer Adams, John Jones,
Total Sales 94.50
Bob
62.45
Total sales Green, Mary
of zip 54.00
code
10023:
156.95
. Write a program that requests a positive integer as input, generates the prime
factors with the algorithm of Exercise 44 in Section 5.1, and writes these primes to the file PRIMES. (For instance, if the user responds with the number 3240, the file PRIMES will contain the primes 2, 2, 2, 3, 3, 3, 3, 5
in that order.) The program should then read the file PRIMES and produce a table showing each prime and its multiplicity. A sample output is as follows. [run] Enter Prime
2 3 5
a positive
integer:
3240
Multiplicity
3 4 1
Light consists of electromagnetic waves having a speed of propagation c = 3- 10° meters per second, but differing in frequency f and wavelength lambda. The general wave relation
c = lambda - f holds for each wave. Table 8.7 shows the wavelengths for colors in the visible spectrum. Write a program to place this data into a sequential file. Then write a second program to use the sequential file to create the output shown in Figure 8.10. Calculate the frequency range of each wave in the spectrum using the formulas fax = ¢/lambda,,i,
fmin = c/lambda,,,.
Programming Projects
385
For instance, for violet,
fee
oR Ou (400. 10 uae fo = 3. 108/(450 - 10-?) Color
Table 8.7
Figure 8.10
lambda,
;,,(nm)
lambda,,,,, (nm)
violet blue green yellow
400 450 500 550
450 500 Spy 600
orange
600
650
red
650
700
Visible Spectrum (nm denotes nanometers)
Wavelengths (nanometers) 400 to 450
Color
Max.
Freq.
Min.
Freq.
violet
750.00E+12
666.67E+12
450
to
500
blue
666.67E+12
600.00E+12
500
to
550
green
600.00E+12
545.45E+12
550 600 650
to to to
600 650 700
yellow orange red
545.45E+12 500.00E+12 461.54E+12
500.00E+12 461.54E+12 428.57E+12
Output for Project 6
7. Create and Maintain an Astronomical Data File. Use the data in Table 8.8 to
write a menu-driven program that performs the following tasks: (a) Create a sequential file consisting of the names, magnitudes, distances, and locations of several stars. The information should be supplied in response to INPUT statements. (b) Display the information in the sequential file. (c) Delete a star and the corresponding magnitude, distance, and location from the sequential file. (d) Add a star and its corresponding magnitude, distance, and location to the sequential file.
386
Sequential Files
Name Sirius Canopus Rigil Arcturus Vega Capella Rigel Procyon Achernar Altair Betelgeuse Aldebaran Spica Antares Pollux Fomalhaut Deneb
Magnitud
Distance (light-years)
Location (constellation)
—1.60 —0.73 —0.20 —0.06 0.04 0.08 0.11 0.50 0.48 Oe 0.80 0.85 0.96 1.00 145 1.16 eas)
9 650 540 36 UG 45 900 11 118 16 520 68 220 520 35 23 1600
Canis Major Carina Centaurus Bootes Lyra Auriga Orion Canis Major Eridanus Aquila Orion Taurus Virgo Scorpio Gemini Piscis Austrinis Cygnus
Table 8.8 Seventeen Brightest Stars Source: New York Public Library Desk Reference
8. Table 8.8 gives information about the 17 brightest stars. (The magnitude of a star is a measure of its brightness. The lower the magnitude, the brighter the star. The sun has a magnitude of —26.7.) Suppose each line of the table has been placed in the sequential file STARS with the statement WRITE
#1,
name$,
magnitude,
distance,
location$
Write a program to read the file into four parallel arrays, sort the arrays by the names of the stars, repeatedly accept the name of a star as input, and use a binary search to locate the star and display the three pieces of information about the star. A sample outcome is as follows: [run] (Enter * to exit the program.) Enter the name of a bright star: Magnitude:
.11
Distance: Location:
900 Orion
Rigel
(Enter * to exit the program. ) Enter the name of a bright star: Ras Algethi Ras Algethi is not one of the 17 brightest stars. (Enter * to exit the program.) Enter the name of a bright star:
*
Programming Projects
387
9. A fuel economy study was carried out for five models of cars. Each car was driven for 100 miles of city driving, then the model of the car and the number of gallons used were placed in the sequential file MILEAGE with the statement WRITE
#1,
model$,
gallons
Table 8.9 shows the first entries of the file. Write a program to display the models and their average miles per gallon in decreasing order with respect to mileage. The program should utilize three parallel arrays of range 1 TO 5. The first array should record the name of each model of car. This array is initially empty; each car model name is added when first encountered in reading the file. The second array should record the number of test vehicles for each model. The third array should record the total number of gallons used by that model. Note: The first array must be searched each time a record is read to determine the appropriate index to use with the other two arrays.
Model
Gal
Model
Gal
Model
Gal
LeBaron Escort Beretta
49 4] 4.3
Cutlass Escort Escort
4.5 3.8 3.9
Cutlass LeBaron Escort
4.6 Sell 3.8
Skylark
4.5
Skylark
46
Cutlass
4.4
Table 8.9 Gallons of Gasoline Used in 100 Miles of City Driving
Random-Access Files (=
9) 6 2060, RETURN S000 -:
options and point values kent or Mortaage Fymt),
oe
1 Over
with
this
Lice
ret
eee
‘To
LET MUPCS = “" ure LET MPRE =O = ~~ ‘Pri 150 REM -- Fian d d n print UPC. d » 2060 OPEN “UPC.DATFO "R INPUT AS INPUT #1. MUPC#. MDES#. MERI
bank? €
Arr
(
LET TOTALPRI = 0
pri
and
name
Print
:
2020
a point value
question, fcount
‘
£700
(==— Sub: RK = 1 LET
arte
y
tt
7
i
Zence
i
ii
&
te
Se
iis 194 1O4 4
j
‘=
z
il
a) aes) a4]
ters
Al
;
HO
af
2
Yi
ee
rigs
=
anal
Bi
a |
| |
|
|
4
|
‘
|
7
=
ms) i!
=
a i
|
|‘|
I
is
i
i |
2%
a
ee:
|
|
|
C
“A
a) i
Subroutines
EP:
Le
S
*
f
K
ve
a
|
|
es
1G? 1CGU
S
a
‘
RIT
|
+
FRG RE TUS
g ibe]
iece
| A
| £2 care ca. Petes Spt fee LE BRR
BAe + Po REESE a £ aKa é ,
FER 1
E
e
Pah bb
¥
vf
A
Ie
5
CPE
:
>
‘
‘ eee
F
t
Ee
‘
58
Ae
There are times when we want to consider the values assigned to variables of different types as being the same, such as city and town$ in Example 3. In this situation, the function RTRIM$ comes to the rescue. If a$ is an ordinary string or a fixed-length string, then the value of RTRIM$ (a$)
is the (variable-length) string consisting of a$ with all right-hand spaces removed. For instance, the value of RTRIM$(“hello
”) is the string “hello”. In
Example 3, if the IF block is changed to (RTRIM$(city) = town$) PRINT "same" BLSe PRINT "different" END IF IF
AND
(RTRIM$(city)
= RTRIM$(municipality))
THEN
then the first line of the output will be “same”. Records
We have worked with four different data types in this text: numbers, strings, arrays, and fixed-length strings. Strings and numbers are built-in data types that can be used without being declared. On the other hand, arrays and fixed-length strings are user-defined data types that must be declared with a DIM statement before being used. A record is a user-defined data type that groups related variables of different types. Figure 9.1 shows an index card that can be used to hold data about colleges. The three pieces of data—name, state, and year founded—are called fields. Each
field functions like a variable in which information can be stored and retrieved. The length of a field is the number of spaces allocated to it. In the case of the index card, we see that there are three fields having
lengths 30, 2, and 4,
respectively. The layout of the index card can be identified by a name, such as collegeData, called a record type.
Dae Ate GPBS:
393
Name:
State: _ Year Founded:
Figure 9.1
An Index Card Having Three Fields
For programming purposes, the layout of the record is declared by the block of statements TYPE
collegeData nom AS STRING * 30 state AS STRING * 2 yearFounded AS SINGLE END TYPE
Each character of a string is stored in a piece of memory known as a byte. Therefore, a field of type STRING * n requires n bytes of memory. However, numbers (that is, the single-precision numbers we use in this text) are stored in
a different manner than strings and always use four bytes of memory. A record variable capable of holding the data for a specific college is declared by a statement such as DIM
college
AS
collegeData
Each field is accessed by giving the name of the record variable and the field, separated by a period. For instance, the three fields of the record variable college are accessed as college.nom, college.state, and college.yearFounded. Figure 9.2 shows a representation of the way the record variable is organized.
college
college.nom college.state
college.yearFounded
Figure 9.2
Record Variable with Values Assigned to the Fields
394
Random-Access Files
In general, a record type is created by a TYPE block of the form TYPE
recordType
fieldNamel fieldname2
END
AS fieldTypel AS fieldType2
TYPE
where recordType is the name of the user-defined data type, fieldName], fieldName2, ... are the names of the fields of the record variable, and fieldType1,
fieldType2, . . . are the corresponding field types, either STRING * n, for some n, or SINGLE. A record variable recordVar is declared to be of the user-defined
type by a statement of the form DIM
EXAMPLE 4.
recordVar
AS
recordType
The following program processes records. REM
Demonstrate
use
of
records
CLS TYPE
collegeData
nom AS STRING * 30 state AS STRING * 2 yearFounded
AS
SINGLE
END TYPE DIM college AS collegeData INPUT "Name"; college.nom INPUT "State"; college.state INPUT "Year Founded"; college. yearFounded LET century = 1 + INT(college.yearFounded / 100) PRINT RTRIM$(college.nom); " was founded in the"; century; PRINT "th century in "; college.state DIM university AS collegeData LET university.nom = "M.I.T." LET university.state = "MA" LET university. yearFounded = 1878 IF college.yearFounded < university.yearFounded THEN LET when$ = "before " EESE LET when$ = "after " END IF PRINT RTRIM$(college.nom); " was founded "; PRINT when$; RTRIM$(university.nom) END
[run] Name? Oberlin State? OH
College
Year Founded? 1837
Oberlin
Oberlin
College College
was was
founded founded
in the before
19 th century M.I.T.
in
OH
ON
(DATASEYPES!
395
TYPE statements can only appear in the main body of a program, never in procedures. However, DIM statements can be used in procedures to declare a local record variable. When
records are passed to and from procedures,
parameter in the SUB or FUNCTION parameter
EXAMPLE
5
AS
the
statement must have the form
recordType
The following program uses procedures to perform the same tasks as the program in Example 4. REM
Demonstrate
use
of
records
with
procedures
CLS TYPE collegeData nom AS STRING * 30 state AS STRING * 2 yearFounded AS SINGLE END TYPE DIM college AS collegeData CALL GetData(col lege) CALL DisplayStatement (college) END SUB
GetData
REM
END
(school
Request
the
INPUT
"Name";
INPUT
"State";
INPUT
"Year
AS name,
collegeData) state,
and
year
founded
school.nom school.state
Founded";
school.yearFounded
SUB
SUB DisplayStatement (school AS collegeData) REM Display the name, century founded, and state LET century = 1 + INT(school.yearFounded/100) PRINT RTRIM$(school.nom); " was founded in the"; PRINT
"th
century
in
";
END
PRINT PRINT END SUB
when$
= “after
century;
school.state
DIM university AS collegeData LET university.nom = "M.I.T." LET university.state = "MA" LET university.yearFounded = 1878 IF school.yearFounded < university.yearFounded LET when$ = "before "
BIESE LET
of a school
THEN
"
IF
RTRIM$(school.nom); " was founded when$; RTRIM$(university.nom)
";
Comments:
1. Record variables are similar to arrays in that they both store and access data items using a common name. However, the elements in an array must be of the same data types, whereas the fields in a record variable can be a mixture
396
Random-Access Files
of different data types. Also, the different elements of an array are identified by their indices whereas the fields of a record are identified by a name following a period. 2. If the record variables recVarl and recVar2 have the same type, then all the field values of recVar2 can be assigned simultaneously to recVarl by the statement
LET
recVarl
=
recVar2
3. Statements of the form PRINT
recVar
and INPUT
recVar
are invalid, where recVar is a record variable. Each field of a record must
appear separately in PRINT, INPUT, and READ statements. Also, comparisons involving records using the relational operators , =, , = are valid only with the record fields, and not with the records themselves. 4. In addition to being declared as numeric or fixed-length string data types, the elements of a user-defined variable type can also be declared as other types of records. However, we do not use such structures in this text. 5. An array of fixed-length strings is declared by a statement of the form DIM arrayName (a TO b) AS STRING
* n
6. When fixed-length strings are passed to and from procedures, the corresponding parameter in the SUB or FUNCTION statement must be a variable-length string. 7. The four different types of numeric variables available in QBasic are shown in Table 9.1. Variables can be specified as one of these types by trailing the name with the proper type-declaration tag or using a DIM statement with the appropriate type identifier.
Numeric Type Integer Long integer Single-precision Double-precision
Table 9.1
Type-Declaration Suffix % Se none or ! =
Identifier Used —_ Bytes of in DIM Statement Storage INTEGER LONG SINGLE DOUBLE
2 4 4 8
The Four Types of Numeric Variables
PRACTICE PROBLEM 9.1 1. In Example 4, why was nom used instead of the more common name for the variable to hold the name of the college?
OU
EXERCISES
DATAGIYPES
9.1
In Exercises 1 through 4, determine the output of the program. 1. DIM ocean AS STRING DIM LET LET
river ocean river
PRINT
* 10
2. DIM colour as STRING * 6
AS STRING * 10 = "Pacific" = "Mississippi"
ocean;
LET colour = "Blue" LET color$ = "Red" PRINT colour; color$;
river
END
END
3. TYPE appearance height AS SINGLE weight AS SINGLE eyeColor AS STRING * 5 END TYPE DIM personl AS appearance DIM person2 AS appearance LET personl.height = 72 LET personl.weight = 170 LET personl.eyeColor = "brown" LET person2.height = 12 * 6 LET person2.weight = personl.weight LET person2.eyeColor = "brownish green" IF personl.height = person2.height THEN PRINT "heights are same" END IF PRINT person2.weight IF personl.eyeColor = person2.eyeColor THEN PRINT “eye colors are same" END IF END
4. TYPE testData nom
AS
score
STRING AS
END
TYPE
DIM
student
* 5
SINGLE AS
testData
FORE letOn3 CALL GetScore(student) CALL PrintScore(student) NEXT i REM
DATA
---
Data:
Joe,
18,
names,
Moe,
scores
20,
Albert,
25
END
SUB
GetScore
READ
student.nom,
END
SUB
SUB
PrintScore
PRINT
END
SUB
(student
AS
student.score
(student
student.nom;
testData)
AS
testData)
student.score
colour
397
398
Random-Access Files
In Exercises 5 through 10, determine the errors. 6. DIM state$ AS STRING * 15
5. TYPE zodiac nom AS STRING * 15 sign AS STRING * 11 END TYPE
state$
LET
= "Maryland"
state$
PRINT END
astrology AS zodiac nom = "Michael" sign = "Sagittarius"
DIM
LET LET
END
name
STRING
AS
streetAddress
*
STRING
AS
friend
AS
*
secondWord
15
END
* 15
AS
var2 END
*
5
TYPE
vitamins
10. TYPE STRING
a AS SINGLE
* 5
b AS
NUMBER
AS
STRING
AS
5
*
address
9; TYPE values label
STRING
AS
firstWord
15
cityState AS STRING zip AS SINGLE DIM
print
8. TYPE
7. TYPE address
TYPE
SINGLE
END
TYPE
DIM
minimum
LET
minimum.b
= 200
LET
minimum.a
= 500
PRINT
vitamins
AS
minimum
END
In Exercises 11 through 14, write a TYPE block to declare a user-defined data type of the given name and types of elements. JEU Name: planet; Elements: planetName, distanceFromSun 12. Name: taxData; Elements: SSN, grossIncome, taxableIncome 13. Name: car; Elements: make, model, year, mileage 14. Name: party; Elements: numberOfGuests, address 15; Write a displays commas hold the
program that requests three words as input from the user and then them on the screen in the first three zones without using any in the PRINT statement. Do this by declaring the variables used to words as fixed-length strings of the appropriate length.
16; Write a program to look up data on notable tall buildings. The program should declare a user-defined data type named “building” with the elements “nom”, “city”, “height”, and “stories”. This interactive program should allow the user to input the name of a building and should search through DATA statements to determine the city, height, and number of stories of the building. If the building is not in the DATA statements, then the program should so report. Use the information in Table 9.2 for the DATA statements. Building
City
Empire State Sears Tower Texas Commerce Tower Transamerica Pyramid
New York Chicago Houston San Francisco
Table 9.2
Tall Buildings
Height (ft)
Stories
1250 1454 1002 853
102 110 75 48
RANDOM-ACCESS
9.2
FILES
399
SOLUTION TO PRACTICE PROBLEM 9.1 1. Reserved words may not be used as names of variables. Although name$ can be used in a LET statement, statements such as DIM name AS STRING or DIM name AS STRING * 30 are not valid since “name” is a reserved word.
Q, D: RANDOM-ACCESS
FILES
A random-access file is like an array of records stored on a disk. The records are numbered 1, 2, 3, and so on, and can be referred to by their numbers. Therefore, a random-access file resembles a box of index cards, each having a
numbered tab. Any card can be selected from the box without first reading every index card preceding it; similarly, any record of a random-access file can be read without having to read every record preceding it. One statement suffices to open a random-access file for all purposes: creating, appending, writing, and reading. Suppose a record type has been defined with a TYPE block and a record variable, called recVar, has been declared with a DIM statement. Then after the statement OPEN
"filespec"
FOR
RANDOM
AS
#n
LEN
= LEN(recVar)
is executed, records may be written, read, added, and changed. The file is referred
to by the number n. Each record will have as many characters as allotted to each value of recVar. Suppose appropriate TYPE, DIM, and OPEN statements have been executed. The two-step procedure for entering a record into the file is as follows. 1. Assign a value to each field of a record variable. 2. Place the data into record r of file #n with the statement PUT
#n,
r,
recVar
where recVar is the record variable from step 1.
EXAMPLE
1
The following program COLLEGES. DAT. REM
Create
the
writes
random-access
CLS TYPE collegeData nom AS STRING * 25 state AS STRING * 2 yrFounded AS SINGLE END TYPE CALL CreateFile END
file
three
records
to the random-access
COLLEGES.DAT
"Name
of
college
‘State
where
'Year
college
college
was
is
located
founded
SUB CreateFile REM Create and write three records into the file COLLEGES.DAT DIM college AS collegeData OPEN "COLLEGES.DAT" FOR RANDOM AS #1°LEN = LEN(college)
file
400
Random-Access Files
= 1 T0
recordNum
FOR
3
INPUT "Name of college"; college.nom INPUT "State located"; college.state INPUT "Year founded"; college.yrFounded PUT #1, recordNum, college NEXT recordNum CLOSE #1 END SUB
[run] Name State Year Name State Year Name State Year
of
College
Comm.
Houston
college?
located? TX founded? 1971 of
located?
Area
Milwaukee
college?
Col.
Tech.
WI
founded? of
1912 college? Virginia
Tech
located? VA founded? 1872
The two-step procedure for reading data from a record is as follows: 1. Execute the statement GEG
eo
necvar
to assign record r of file #n to the record variable recVar. 2. Use the field variables of the record variable to either display values with PRINT or to transfer values to other variables with LET. EXAMPLE
2.
SOLUTION —
Write a program to display the entire contents of the random-access file COLLEGES.DAT. REM Access the random-access CLS TYPE collegeData nom AS STRING * 25 state AS STRING * 2 yrFounded AS SINGLE END TYPE CALL DisplayFile END SUB DisplayFile DIM college AS
file COLLEGES.DAT
"Name
of
college
"State
where
‘Year
college
college
was
is
located
founded
collegeData
OPEN "COLLEGES.DAT" FOR RANDOM AS #1 LEN = LEN(college) PRINT "College", , "State", "Year founded" FOR recordNum = 1 TO 3 GET
#1,
recordNum,
PRINT college.nom, NEXT recordNum CLOSE #1 END SUB
college
college.state,
college.yrFounded
9.2
[run] College Houston
State Comm.
College
Milwaukee Area Virginia Tech
Tech.
Col.
RANDOM-ACCESS FILES
Year
TX
1971
WI VA
1912 1872
401
founded
The total number of characters in the file with reference number n is given by the value of the function OF (n)
The number of the last record in the file can be calculated by dividing this value by the record length. The LOF function, rather than the EOF function, should be used to determine when the end of the file has been reached. For instance,
in Example 2 the FOR statement in the subprogram DisplayFile can be written as FOR
i = 1 TO
LOF(1)
/ LEN(college)
Also, the pair of statements LET
lastRecord
PUT
#1,
= LOF(1)
lastRecord
+
1,
/ LEN(college) college
can be used to add a record to the end of the file. Comments:
1.
Random access files are also known as direct-access or relative files. Since each record has the same number of characters, the computer can calculate where to find a specified record and, therefore, does not have to search for
it sequentially.
2. Unlike sequential files, random-access files needn’t be closed between placing information into them and reading from them. 3. Random-access files do not have to be filled in order. For instance, a file can
be opened and the first PUT statement can be PUT #, 9, recVar. In this case, space is allocated for the preceding eight records. 4. If the record number r is omitted from a PUT or GET statement, then the
record number used will be the one following the number most recently used in a PUT or GET statement. For instance, if the line PUT
#1,
, college
is added to the program in Example 2 just before the CLOSE statement, then the information on Virginia Tech will be duplicated in record 4 of the file COLLEGES.DAT. 5. Users often enter records into a random-access file without keeping track of the record numbers. If file #n is open, then the value of the function LOC (n)
is the number of the record most recently written to or read from file n with a PUT or GET statement.
402
Random-Access Files
6. Each record in a random-access file has the same length. This length can be any number from | to 32767. 7. When the statement OPEN “COLLEGES.DAT” FOR RANDOM AS #1 LEN = LEN (college) is typed, the words “FOR RANDOM” can be omitted. The smart editor will insert them automatically. 8. The decision of whether to store data in a sequential file or in a randomaccess file depends on how the data are to be processed. If processing requires a pass though all the data in the file, then sequential files are probably desirable. If processing involves seeking out one item of data, however, then random-access files are the better choice.
PRACTICE PROBLEM 9.2 1. In Example 2, the first PRINT statement clearly displays “State” in the 3rd print zone. Why will the second PRINT statement also display the value of college.state in the 3rd print zone?
EXERCISES 9.2 In Exercises 1 through 8, determine the output of the program. For each of the programs, assume the file COLLEGES.DAT was just created by Example 1, record type collegeData has been declared with a TYPE block, and the first two lines of each of these programs are DIM
college
OPEN
AS
collegeData
"COLLEGES.DAT"
FOR
RANDOM
AS #1
1. GET #1, 3, college PRINT college.state CLOSE
#1
CLOSE END
3. FOR
i = 1 TO LOF(1)
GET
#1,
i,
/ LEN(college)
college
PRINT college.state NEXT i PRINT LOC(1)
CLOSE END
#1
4. LET college.yrFounded PUT
#1,
GET
#1,
PRINT
CLOSE END
2,
= 1876
college
2, college college.nom; #1
5. LET college.nom LET
= LEN(college)
2. GET #1, 3, college PRINT LOF(1); LOC(1)
END
LET
LEN
college.state
college. yrFounded
= "Harvard"
= "MA" college.yrFounded = 1636
#1
9.2
PUT FOR
RANDOM-ACCESS FILES
403
#1, 4, college i = 3 10 4
GET #1, 1, college PRINT college.nom, NEXT i CLOSE #1 END
6. LET college.nom
college.state,
= "Michigan
LET LET
college.state
PUT
#1,
=
FOR@ip
State"
"MI"
college.yrFounded 1,
college.yrFounded
=
1855
college
= al 083
GET
#1,
i,
PRINT
college
college.nom
NEXT i CLOSE #1 END
7GET
#1,
91s college
GET #1, , college PRINT college.nom,
CLOSE END
8. LET
college.state,
college.yrFounded
#1
lastRec
= LOF(1)
/ LEN(college)
GET #1, lastRec, college PRINT college.nom, college.state,
college. yrFounded
#1
CLOSE END
In Exercises 9 through 12, identify the errors. Assume the given code has been preceded with the statements TYPE
filmCredits
nom film
AS
STRING
AS
END
TYPE
DIM
actor
* 25
STRING AS
* 35
"Name
of
actor
"Name
of
film
#2,
CLOSE END 10.
3,
#2
CLOSE END
LEN
= LEN(filmCredits)
actor
#2
OPEN ACTRESS.DAT FOR RANDOM AS #3 LET actor.nom = "Garland" LET actor.film = "Wizard of 0z" LET lastRec = LOF(3) / LEN(actor) PUT
actress
filmCredits
9. OPEN "ACTORS.DAT" FOR RANDOM AS LET actor.nom = "Bogart" LET actor.film = "Casablanca" PUT
or
#3,
lastRec
#3
+
1,
actor
LEN
= LEN(actor)
404
Random-Access Files
1 i OPEN "ACTORS.DAT" actor.nom
LET
actor.film
PUT
#1,
1,
actor
GET
#1,
1,
actor
CLOSE PRINT
RANDOM
AS
#1
LEN
= LEN(actor)
"Stallone"
=
LET
FOR
=
"Rocky"
#1 actor
END
12. OPEN “ACTRESS.DAT" AUN
CLOSE
fills,
Ih,
FOR
RANDOM
AS
#3
LEN
= LEN(actor)
Geile
#1
END
13: Give an OPEN statement and TYPE block for a random-access file named NUMBERS.DAT in which each record consists of three numbers.
14. Give an OPEN statement and TYPE block for a random-access file named ACCOUNTS.DAT in which each record consists of a person’s name (up to 25 characters) and the balance in their savings account. LS: Consider the sequential file YOB.DAT discussed in Section 8.1 and assume the file contains many names. Write a program to place all the information into a random-access file. 16. Write a program that uses the random-access file created in Exercise 15 and
displays the names of all people born before 1970. 17. Write a program that uses determine a person’s year with an INPUT statement, year of birth or report that
the random-access file created in Exercise 15 to of birth. The program should request the name search for the proper record, and either give the the person is not in the file.
18. Write a program that uses the random-access file created in Exercise 15 and adds the data Joan, 1934 to the end of the file.
Exercises 19 through 22 refer to the file COLLEGES.DAT. colleges have been added to the file in no particular order.
Assume many
19; Write a program to allow additional colleges to be added to the end of the file using data entered by INPUT statements. 20, Modify the program in Exercise 19 to insure that the name of the college input has no more than 25 characters. Vass Write a program to find the two oldest colleges. jap, Write a program to display the data on any college requested in response to an INPUT statement. The college should be identified by name and located
by a sequential search of the records. Note: Remember to take into account the fact that each college name retrieved from the file will contain 25 characters. 23: Extend the program in Exercise 22 in the following way: after the information on a college is displayed, exchange its record with the previous record; unless, of course, the displayed record is the first record. (A familiar rule of
Programming Projects
405
thumb for office filing is: 80% of the action involves 20% of the records. After the program has been used many times, the most frequently requested records will tend to be near the top of the file and the average time required for searches should decrease. )
SOLUTION TO PRACTICE PROBLEM 9.2
1. The value of college.nom will have length 25 for each college. Therefore, it will extend into the second print zone and force the value of college.state into the third print zone.
Chapter 9 Summary 1. A fixed-length string is a variable declared with a statement of the form DIM var AS STRING * n. The value of var is always a string of n characters.
. A record is a composite user-defined data type witn a fixed number of fields that either are of fixed-length string or numeric type. TYPE statements define record types and DIM statements are used to declare a variable to be of that type. . After a record type has been specified, the associated random-access file is an ordered collection of record values numbered
1, 2, 3, and so on. Record
values are placed into the file with PUT statements and read from the file with GET statements. At any time, the value of LOF(n) / LEN(recordVar) is the number of the highest record value in the file and the value of LOC is the number of the record value most recently accessed by a PUT or GET statement.
Chapter 9 Programming Projects 1. Balance a Checkbook. Write an interactive program to request information (payee, check number, amount, and whether or not the check has cleared) for each check written during a month and store this information in a
random file. The program should then request the balance at the beginning of the month and display the current balance and the payee and amount for every check still outstanding. . A teacher maintains a random-access file containing the following information for each student: name, social security number, grades on each of two hourly exams, and the final exam grade. Assume the random-access file
406
Random-Access Files
GRADES has been created with string fields of lengths 25 and 11 and three n bee have s ber num rity secu al soci and es nam the all and ds, fiel c eri num entered. The numeric fields have been initialized with zeros. Write a menu-driven program to allow the teacher to do the following. (a) Enter all the grades for a specific exam.
(b) Change a grade of a specific student with data entered using INPUT statements. (c) Print a list of final grades that can be posted. The list should show the
last four digits of the social security number, the grade on the final exam, and the semester average of each student. The semester average is determined by the formula (exam1
+ exam2 + 2 * finalExam) / 4.
Rational Addition. Write a program to add two rational numbers and display their rational sum. A sample output is as follows. [run] Enter
the
numerator
Enter
the
denominator
Enter
the
numerator
Enter
the
denominator
of
the of
of
the
the
of
first
number:
first
second
the
second
8 15
number: number:
number:
3
10
sum is 5 / 6
The
The program should contain the definition TYPE
Rational
num
AS
LONG
den
AS
LONG
END
TYPE
After each rational number is input, the program should check that the denominator is not zero, and then use the greatest common divisor (see Exercise 45 of Section 5.1) of the numerator and denominator to reduce the
rational number to its simplest form. The least common multiple of the two denominators is their product divided by their greatest common divisor. The sum should be displayed in reduced form. The number should be displayed as an integer if the denominator is | or —1, and otherwise as a fraction with a positive denominator.
Graphics
408
1 O
Graphics
i INTRODUCTION
TO GRAPHICS
QBasic has impressive graphics capabilities. Figure 10.1 shows a graph that can be displayed on the screen and printed by the printer.
be Figure 10.1
Graph of the function f(x) = e*sin(20x)
Most monitors can display graphics (such as points, lines, and circles) if the computer contains the proper monitor adapter card. The most common configurations are a graphics monitor attached to a graphics card or a monochrome display attached to a Hercules card. To determine whether your system can support graphics, execute the following program. If you have graphics capabilities, the program will draw a diagonal line. SCREEN 2 LINE (0, 0)-(639, END
199)
Monochrome displays attached to a Hercules card can produce graphics in QBasic provided the program MSHERC.COM is executed from DOS before QBasic is invoked. MSHERC.COM can be found in the DOS directory. (If your computer has both a Hercules graphics card and a color graphics card, enter MSHERC.COM /H from DOS.) To further check the graphics capabilities on a system equipped with a Hercules card, execute the program above with SCREEN 2 replaced by SCREEN 3. Graphics cards have several different display modes. The modes vary in the width of text characters, the number of points that can be displayed horizontally and vertically, and the number of colors available. The two modes always available are referred to as text mode and high resolution graphics mode.
Text Mode: With an appropriate monitor, text can be displayed in 16 different colors specified with the COLOR statement. Text mode is the default mode. It was used in all programs in Chapters 1 through 9.
10.2
SPECIFYING A COORDINATE SYSTEM
409
High Resolution Graphics Mode: Text and graphics can be displayed in the two standard colors of the monitor that we refer to as black and white. Depending
on the monitor, the second color might be green or amber. Text is displayed in 25 eighty-character rows. High resolution graphics mode is invoked with the statement SCREEN 2 (or the statement SCREEN 3 for a monochrome display attached to a Hercules card).
Most monitors purchased within the last four years are VGA monitors, which are capable of utilizing many screen modes. The most useful graphics mode for VGA monitors is very high resolution graphics mode. Very High Resolution Graphics Mode: Text and graphics can be displayed in many colors. Text is displayed in 30 eighty-character rows. Very high resolution graphics mode is invoked on a VGA monitor with the statement SCREEN 12.
The DOS directory contains a program called allows you to print graphics for certain configurations If you intend to print graphics, you must execute this QBasic. The form of the statement depends on the Some variations are:
GRAPHICS.COM that of monitors and printers. program before invoking type of printer you have.
Printer
Command
Dot-matrix printer HP LaserJet compatible printer HP DeskJet printer
GRAPHICS GRAPHICS PASERJET GRAPHICS DESKJET
(See the DOS manual for other variations.) If you want to print the contents of a QBasic graphics screen, press Shift+PrintScreen. This printout is called a screen dump. Comments:
1. All the programs in this chapter contain the statement SCREEN 2. If you are using a monochrome display with a Hercules card, replace this statement with SCREEN 3. With a VGA monitor, you may use SCREEN 12. 2. The SCREEN statement not only specifies a graphics mode, but also clears the screen.
1 O
M
SPECIFYING A COORDINATE
SYSTEM
Suppose we have a piece of paper, a pencil, and a ruler and we want to graph a line extending from (2, 40) to (5, 60). We would most likely use the following
three-step procedure:
410
Graphics
1. Use the ruler to draw an x-axis and a y-axis. Focus on the first quadrant since both points are in that quadrant. 2. Select scales for the two axes. For instance, we might decide that the numbers on the x-axis range from —1 to 6 and that the numbers on the y-axis range from —10 to 80.
3. Plot the two points and use the ruler to draw the straight line segment joining them.
EXAMPLE
1
(a) Draw a coordinate system with the numbers on the x-axis ranging from —2 to 10, and the numbers on the y-axis ranging from —3 to 18. (b) Draw the straight line from (1, 15) to (8, 6). (c) Draw the straight line from (—2, 0) to (10, 0).
SOLUTION
(a)
18
(b)
-3
(c) The point (—2, 0) is the left-hand end-
point of the x-axis and the point (10, 0) is the right-hand endpoint; therefore, the line joining them is just the portion of the x-axis we have pictured.
We draw paper, pencil, steps 1 and 3. values for the
these graphs on the screen with the same three steps we use with and ruler. The only difference is that we first do step 2, and then The QBasic statement WINDOW is used to specify the range of axes and the statement LINE serves as the ruler.
10.2
SPECIFYING
A COORDINATE SYSTEM
411
The statement WINDOW
(a,
c)-(b,
d)
specifies that numbers on the x-axis range from a to b and that numbers on the y-axis range from c to d. (See Figure 10.2.) The ordered pair (a, c) contains the lowest numbers on the two axes and the ordered pair (b, d) contains the highest numbers.
d
a
b
c Figure 10.2
Result of WINDOW
Statement
Figure 10.3
Result of LINE Statement
The statement LINE
(xl, yl)-(x2,
y2)
draws the line segment from the point with coordinates (x1, yl) to the point with coordinates (x2, y2) (see Figure 10.3). In particular, the statement LINE (a, 0)-(b, 0) draws the x-axis and the statement LINE (0, c)—(0, d) draws the y-axis.
The following program produces the graph of Example 1, part (b): SCREEN
2
WINDOW (-2, -3)-(10, LINE (-2, 0)-(10, 0) LINE (0, -3)-(0, 18) LINE (1, 15)-(8, 6)
‘Go
18)
into
high
resolution
graphics,
clear
screen
'Specify coordinate system ‘Draw x-axis ‘Draw y-axis ‘Draw the straight line
END
Note: With a VGA monitor, you may replace SCREEN 2 by SCREEN 12 in this and future programs to obtain a sharper image.
EXAMPLE
2
Consider Figure 10.4. (a) Give the WINDOW statement that specifies the range for the numbers on the axes. (b) Give the statements that will draw the axes. (c) Give the statement that will draw the line.
412
Graphics
Figure 10.4
-10)-(5,
(-1,
(a) WINDOW
SOLUTION
Graph for Example 2 120)
highest x-value
lowest y-value
(b) x-axis:
(-1, 0)-(5,
LINE
desea c
(1,
0)
120)
(0, -10)-(0,
y-axis: LINE
(c) LINE
highest y-value
bs
lowest x-value a]
si
100)-(4,
i
d
50)
There are two other graphics statements that are just as useful as the LINE statement. The statement PSET
(x, y)
plots the point with coordinates (x, y). The statement CIRCLES
(my)
aur
draws the circle with center (x, y) and radius r.
EXAMPLE
SOLUTION
3.
Write aprogram to plot the point (7, 6) and draw a circle of radius 3 about the point.
— The rightmost point to be drawn will have x-coordinate 10; therefore the numbers on the x-axis must range beyond 10. In the following program we allow the numbers to range from —2 to 12. (See Figure 10.5.) REM
Draw
SCREEN ‘For
circle
with
center
(7,
2 VGA
6)
and
radius
‘Initialize monitor
use
WINDOW (-2, -2)-(12, LINE (-2, 0)-(12, 0) LINE (0, -2)-(0, 12) PSET (7, 6) CIRCEER (7-06) es END
SCREEN
12)
12
in
line
3
screen
above
'Specify coordinate "Draw x-axis ‘Draw y-axis ‘Draw ‘Draw
system
center of circle the circle
SPECIFYING
10.2.
Figure 10.5
A COORDINATE SYSTEM
413
Graph for Example 3
The numbers appearing in WINDOW, LINE, PSET, and CIRCLE statements can be replaced by variables or expressions. For instance, the PSET statement in Example 3 can be replaced by Weise
BSI
= 7
(6%5
36 2710)
At any time, QBasic designates a point as the last point referenced. Initially, it is the point in the center of the screen. After a graphics statement is executed,
the point changes to a point appearing in the statement. After a PSET or CIRCLE statement is executed, the named point becomes the last point referenced. After a line is drawn, the second point named in the LINE statement becomes the last point referenced. A variation of the LINE statement uses the last point referenced. The statement LINE
-(x,
y)
draws a line from the last point referenced to the point (x, y) and makes (x, y)
the new last point referenced. Consider a statement of the form LINE (x1, yl)—(x2, y2) where one or both of the points (x1, yl) and (x2, y2) are off the screen. QBasic locates the points in a fictional coordinate system larger than the screen but containing the two
points. QBasic then "imagines" the line connecting the two points in the large coordinate system and displays only the portion of the line lying on the screen. That is, it clips off any hidden portion of the line. As before, (x2, y2) becomes the last point referenced. The following program produces the output of Figure 10.6. REM
Demonstrate
line
SCREEN 2 ‘For VGA monitor use WINDOW (0, 0)-(4, 2) LINE (0, 0)-(6, 2) LINE -(2, 0) END
clipping SCREEN
‘Last
12
pt.
and
last
point
in
line
above
ref.
referenced
is to right
of the
screen
414
Graphics
Figure 10.6
Line Clipping
Consider the task of drawing the line from (0, 0) to (2, 2). This line has
slope 1 and makes a 45 degree angle with the x-axis. Whether the line drawn by the statement LINE (0, 0)-(2, 2) makes a 45 degree angle with the x-axis depends on the WINDOW statement. Since the physical width and height of the screen are in a 4 to 3 ratio, true slopes are achieved with WINDOW statements for which b — a and d — c have a 4 to 3 ratio. Some
WINDOW
statements of this type are the following: WINDOW WINDOW WINDOW WINDOW
(-4, -3)-(4, 3) (-8, -6)-(8, 6) (-1, -1)-(7, 5) (0, 0)-(64, 48)
Comments:
1. In Examples 1 through 3, the range of numbers on the axes extended from a negative number to a positive number. Actually, any values of a, b, c, and dcan be used ina WINDOW statement. In certain cases, however, you will
not be able to display one or both of the axes on the screen. (For instance, after WINDOW
(1, —1)—(10, 10) has been executed, the y-axis cannot be
displayed.) 2. LOCATE statements are used to place text and therefore are not affected by WINDOW statements. 3. The radius of a circle uses the scale specified for the x-axis.
4. With a color VGA monitor, you can modify the above programs to produce colorful displays in very high resolution graphics mode. The numbers 0 through 15 identify colors as shown in Table 10.1.
O 1 2 3
Black Blue Green Cyan
Table 10.1
4 5 6 7
Red Magenta Yellow White
Values for Colors
8 9 10 11
Gray Light blue Light green Light cyan
12 13 14 15
Light red Light magenta Light Yellow High-intensity white
10.2
SPECIFYING
A COORDINATE SYSTEM
415
Lines, points, and circles can be drawn in colors. To use color c, place “, c” at the end of the corresponding graphics statement. For instance, the
statement LINE
(x1,
yl)-(x2,
y2),
4
draws a red line. 5. Appendix C describes the other QBasic graphics statements. (a) An extension of the CIRCLE statement draws ellipses, arcs, and sectors
of circles and ellipses. (b) The BLOAD statement restores the screen from a file created with BSAVE. (c) The BSAVE statement saves the contents of the graphics screen in a file. (d) The COLOR statement sets the background and drawing colors. (e) The DRAW statement creates sketches.
(f) The graphic GET and PUT statements create animation. (g) The PAINT statement fills in regions with colors or tiled patterns.
(h) The PALETTE and PALETTE USING statements specify a collection of colors to appear on the screen. (i) The PMAP function translates between natural and physical coordinates. (j) The PRESET statement erases points from the screen. (k) The SCREEN statement invokes many different graphics modes for EGA or VGA adapters. (1)
The VIEW statement translates, clips, or restricts graphics.
PRACTICE PROBLEMS
10.2
Suppose you want to write a program to draw the x- and y-axis and the line from (3,10) to (23,20).
1. Select a WINDOW statement so that the x- and y-axis can be drawn, the line fills most of the screen, and the line appears with the proper slope. 2. Write a program to draw the axes, the line, and a small circle around each
end point of the line.
3. Write the statements that draw a tick mark on the y-axis at height 10 and label it with the number 10.
EXERCISES
10.2
1. Determine the WINDOW tem of Figure 10.7.
statement corresponding to the coordinate sys-
416
Graphics
30
Figure 10.7 Exercise 1
Coordinate System for
2. Determine the WINDOW tem of Figure 10.8.
Figure 10.8 Exercise 2
Coordinate System for
statement corresponding to the coordinate sys-
3. Suppose that the statement WINDOW (-1, —8)—(4, 40) has been executed. Write down the statements that draw the x-axis and the y-axis. 4. Suppose that the statement WINDOW
(-3, — .2)—(18, 1) has been exe-
cuted. Write down the statements that draw the x-axis and the y-axis.
In Exercises 5 through 8, write a program to draw a line between the given points. Select an appropriate WINDOW statement, draw the axes, and draw a small circle around each end point of the line.
55 (3;200)5 (105150)
6. (4, 4), (9, 9)
Tipo
8. (30), (6,30)
Gee)
In Exercises 9 through 20, write a program to draw the given figures. Draw the axes only when necessary. 9. Draw a circle whose center is located at the center of the screen.
10. Draw a tick mark on the x-axis at a distance of 5 from the origin. 11. Draw a tick mark on the y-axis at a distance of 70 from the origin. 12. Draw a circle whose leftmost point is at the center of the screen. 13. Draw four points, one in each corner of the screen. 14. Draw a triangle with two sides of the same length. 15. Draw a rectangle. 16. Draw a square. 17. Draw five concentric circles, that is, five circles with the same center.
18. Draw a point in the center of the screen. 19. Draw a circle and a line that is tangent to the circle.
20. Draw two circles that touch at a single point.
10.3.
DRAWING GRAPHS OF FUNCTIONS
417
In Exercises 21 through 24, consider the following program. What would be the effect on the circle if the WINDOW WINDOW statement? SCREEN
statement were replaced by the given
2
WINDOW (-5, -5)-(5, CIRCEEN(O 0) 3
5)
‘Specify coordinate system ‘Draw circle centered at origin
END
21. WINDOW
(-8, —8) — (8,8)
22. WINDOW
23. WINDOW
(-8, —5) — (8, 5)
24. WINDOW (-2, -2) - (2, 2)
(—5, —8) — (5, 8)
25. Write a program to draw the graph of the line y = (1/2)x + 1. 26. Write a program to draw the graph of the line containing the two points (13) and (3,2).
27. Write a program to request the numbers r and s as input and then draw the graph of the straight line through the origin and point (r, s).
28. Write a program to request the values m and b as input and then draw the graph of the straight line y = mx + b.
SOLUTIONS TO PRACTICE PROBLEMS
10.2
1. To include the origin on the screen (and therefore the axes) and all of the line from (3,10) to (23,20), the smallest acceptable ranges for the x and y coordinates are 0 to 23 and 0 to 20. For
the slope to be correct, a 4 to 3 ratio between the overall range of the x and y coordinates is needed. If we let the x coordinates range from —4 to 28 and the y coordinates range from —2 to 22, then the minimum ranges are just met (so the line will fill as much of the screen as possible) and the ratio of the overall ranges is (28 — (-4))/(22 — (-2)) = 32/24 = 4/3. The WINDOW
statement to specify this coordinate system is WINDOW
(-4,
-2)-(28,
22)
2. The radius below for the small circles was chosen by trial and error. REM
draw
axes,
SCREEN
2
WINDOW
(-4,
a
line,
-2)-(28,
LINE LINE
(-10, 0)-(50, 0) (0, -5)-(0, 40)
LINE
(3,
10)-(23,
CIRCLE}
(e10)5.
Cuxcls
(35
20)5
and
endpoints
22)
20) 3 os
END
3. The LINE statement easily draws the tick mark at the precise height on the y-axis. Deciding where to LOCATE the cursor before PRINTing the 10 is a matter of trial and error. LINE
(-.5,
LOCATE 13, PRINT 10
10)-(.5, 6
10)
418
1 O
Graphics
3 DRAWING GRAPHS OF FUNCTIONS This section creates graphs of functions. Initially, the formula for a function is given explicitly. Then the function is given as the solution to a differential equation of the form y’ = g(t, y) with an initial condition.
Functions Given Explicitly EXAMPLE
SOLUTION
1
Write a program to draw the graph of the LOG function. See Figure 10.9.
— Of the many possible choices of a WINDOW statement, the one chosen here meets two criteria: the 4:3 ratio guarantees an accurate scale, and the graph fits nicely on the screen. The subprogram Initialize invokes a graphics mode, specifies the ranges of values for the x-axis and the y-axis, and draws the two axes. The subprogram Graph uses a FOR. ..NEXT loop to draw many points on the graph. The step size is set to 1/720 of the width of the screen since 720 is the largest number of pixels horizontally in any graphics mode. Since the LOG function is defined only for x > 0, plotting begins with a small positive value of x. REM Graph
the function
LOG(x)
DEF
FNf(x)
LET
a = -1:
LET
b = 7
"Extent
of
Wey
@ Sess
May
al ses}
‘Extent
of y-axis
=
LOG(x)
LET s = (b-
a) / 720
CALL Initialize(a, CALL Graph(.01, b, DO: LOOP END
b, s)
‘Step size c,
x = xl
PSET NEXT
(x,
x2
loop
'Supress
interval STEP s
"Press
[xl,
x2]
any
with
key
step
to
continue"
size
s
FNf(x))
x
END
SUB
SUB
Initialize
REM
TO
for FOR/NEXT
d)
SUB Graph (x1, x2, s) REM Draw graph over FOR
x-axis
Set
SCREEN
(a,
graphics
2
b,
c,
mode,
d) coordinate
scales,
draw
axes
"Invoke graphics mode and clear the screen "For VGA monitor use SCREEN 12 in line above WINDOW (a, c)-(b, d) LINE (a, 0)-(b, 0) ‘Draw x-axis LINE (0, c)-(0, d) "Draw y-axis END SUB
10.3.
Figure 10.9
DRAWING GRAPHS OF FUNCTIONS
A Graph of the Function f(x)
419
= LOG(x)
The program in Example | uses variables for the ranges of the x- and y-axes and passes the values of these variables to the subprograms. In practice, the programmer must experiment with different values of a, b, c, and d to obtain a good graph. The design of the program simplifies changing these values; only the third and fourth lines of the program need to be altered. The graph in Figure 10.9 can be improved by graphing with line segments instead of points. The revision of the subprogram below produces the graph shown in Figure 10.10. This figure contains all the points of Figure 10.9, but uses the last point referenced to connect these points with line segments. SUB Graph (xl, x2, s) REM Draw graph over PSET
(xl,
FOR
x = xl
LINE NEXT END
-(x,
interval
[xl,
x2]
with
STEP
s
FNf(x1)) TO
x2
STEP
s
FNf(x))
x
SUB
Figuré 10.10
An Improved Graph of the Function f(x)
= LOG(x)
420
Graphics
Although the “4:3 ratio rule” produces an accurately scaled graph, the rule is not appropriate for certain functions. For instance, a reasonable coordinate system for the graph of f(x) = x’ from x = -10 to x = 10 is specified by the statement WINDOW
(-10,
-1000)-(10,
1000)
which is far from a 4:3 ratio. Since the graph of the LOG function has a vertical asymptote at x = 0 and is not defined for negative values of x, the function was evaluated only to the right of its asymptote. Often there are points on both sides of a vertical asymptote. Also, vertical asymptotes are typically drawn as dashed lines. To draw a dashed line, use the LINE statement in one of the following modified forms: LINE
(@,
Imes,
LINE
=(a,
b)?
Gis. 5
5 4 So
5 3855
2
See Figure 10.11.
EXAMPLE 2
Write a program to draw the graph of f(x) = 5 + ae (x—1)(x-2)
SOLUTION
The objective is to have the graph exhibit the key features of the function. Since the function has vertical asymptotes at x = 1 and x = 2, it has three pieces: the piece to the left of 1, the piece between | and 2, and the piece to the right of 2. These three pieces are each graphed by a separate call to the subprogram Graph. Evaluating the function at x = 1 and x = 2 produces a “Division by zero” error message. In addition, evaluating the function at a value of x very close to 1 or 2 might result in a number so large that an Overflow error message is generated. Therefore, the program stays s units from 1 and 2. (In extreme cases, a distance
of 2*s or more may be required.) Experimentation was used to obtain the arguments for the WINDOW statement. REM Graph a function with asymptotes DERSEN T(x) > 2. Set alOesixeo ha) (Xero) UENea0=5-9< LET be=—5 "Extent LET c = -200: LET d = 200 "Extent
PEqest=y(b CALL CALL CALL CALL CALL CALL DO:
0a)
7720
eke (Knee), of x-axis of y-axis
"Step size
Initialize(a, b, c, d) Graph(a, 1 - s, s) VerticalAsymptote(1, c, Graph(1 + s, 2 - s, s) VerticalAsymptote(2, c, Graph(2 + s, b, s) LOOP
"Draw
in FOR/NEXT
the
piece
from
-3 to
‘Draw the
piece
from
1 to 2
‘Draw the "Suppress
piece from "Press any
FORT
X= = x19
LINE NEXT END
SUB
x
-(x,
interval
10=xZ2eSiERSs
FNf(x))
l
d)
d)
END
SUB Graph (xl, x2, s) REM Draw graph over Ee (oak, aa}
loop
[xl,
x2]
with
STEP
s
2 to 5 key to continue"
10.3.
SUB
Initialize
REM
Set
(a,
graphics
b,
c,
mode,
DRAWING GRAPHS OF FUNCTIONS
d) coordinate
SCREEN 2 "For WINDOW (a, c)-(b, d) LINE (a, 0)-(b, 0) ‘Draw x-axis LINE (0, c)-(0, d) ‘Draw y-axis END SUB
SUB VerticalAsymptote REM
Draw
LIME (es END SUB
the
vertical
Glee,
Figure 10.11
(r,
yh
421
c, dashed
scales,
draw
VGA
SCREEN
use
axes
12
d) line
x = r
5 5 SE05
10x”
Graph of f(x) = 5 + (x -1)(x-2)
Euler’s Method for Graphing the Solution to a Differential Equation Consider a differential equation of the form y =g(t,y), ,
to “ape”) OR (“earth’>“moon”) is true since “apple”>“ape” is true, while (1>2) OR (“moon”2) and (“moon’“ape”) XOR (“earth”>“moon”) is true since “apple” >“ape” is true and “earth”>“moon” is false. XOR (Bitwise Operator) The expression byte! XOR byte2 is evaluated by expressing each byte as an 8-tuple binary number and then XORing together corresponding digits, where 1 XOR O and 0 XOR 1 both equal 1, while 1 XOR 1 andO XOR 0 both equal 0. For example, the expression 37 XOR 157 translated to binary 8-tuples becomes 00100101 XOR 10011101. XORing together corresponding digits gives the binary 8-tuple 10111000 or decimal 184. Thus 37 XOR 157 is 184.
Supporting Topics [1] Default values. Before a numeric, variable-length string, or fixed-length string variable of length n has been assigned a value by the program, its value is O, the null string (“”), or a string of n CHR$(0) characters respectively. [2] Radian measure.
The radian system of measurement measures angles in
terms of a distance around the circumference of the circle of radius 1. If the vertex of an angle between 0 and 360 degrees is placed at the center of the circle, then the length of the arc of the circle contained between the two sides of the angle is the radian measure of the angle. An angle of d degrees has a radian measure of (J/180)*d radians. [3] Directories.
Think of a disk as a master folder holding other folders, each
of which might hold yet other folders. Each folder, other than the master folder, has a name. Each folder is identified by a path: a string beginning with a drive letter, a colon, and a backslash character, ending with the name of the folder to be identified, and listing the names of the intermediate folders (in order)
separated by backslashes. For instance the path “C:\DAVID\GAMES” identi-
fies the folder GAMES which is contained in the folder DAVID, which in turn is contained in the master folder of drive C. Each folder is called a directory and the master folder is called the root directory. When a folder is opened, the revealed folders are referred to as its subdirectories. Think of a file as a piece of paper inside one of the folders. Thus,
each directory contains files and subdirectories.
Appendix C — QBasic Statements
547
At any time, one of the directories is said to be the current directory. Initially the root directory is the current directory. The current directory can be changed from DOS with the CD command or from QBasic with the CHDIR command. DOS and QBasic statements that access files, such as DIR and FILES, act on the
files in the current directory unless otherwise directed.
The default drive is the drive whose letter appeared in the DOS prompt when QBasic was invoked. If a drive is missing from a path, then the drive is assumed to be the default drive. [4] Filespec.
The filespec of a file on disk is a string consisting of the letter of
the drive, a colon, and the name of the file. If directories are being used, then
the file name is preceded by the identifying path. [5] Colors. Sixteen predefined colors, identified by the numbers 0 through 15, are available on color monitors: O 1 2 3
Black Blue Green Cyan
4 5 6 7
Red 8 Gray Magenta 9 Light Blue Brown 10 Light Green White 11 Light Cyan
12 13 14 15
Light Red Light Magenta Yellow Intense White
In text mode, which is invoked with the statement SCREEN
0, any of the
colors are available as foreground colors and the first eight are also available as background colors. In medium resolution graphics mode, which is invoked with the statement SCREEN 1, two palettes of four colors each are available. Palette 0:
0. Background color
1. Green
2. Red
3. Brown
Palette 1:
0. Background color
1. Cyan
2.Magenta
3. White
In high resolution graphics mode, invoked with the statement SCREEN 2, only two colors, black (0) and white (1) are available. See the discussion of
SCREEN for the ranges of colors available in the higher graphics modes. [6] Palettes.
A palette can be thought of as a collection of numbered jars that
can hold paint. The number of jars available varies with the screen mode. Although the jars hold specified default colors, EGA, MCGA, and VGA adapters allow the colors to be changed with the PALETTE statement. Statements of the form PSET (x,y),c and CIRCLE (x,y),r,c use the color in the cth
paint jar. In the absence of aCOLOR statement, the PRINT statement displays characters with the color in jar 0 as the background color and the color in the highest numbered jar as the foreground color. [7] Last point referenced. At any time, one point on the screen is designated as the “last point referenced.” Initially it is the point in the center of the graphics screen. After a graphics statement is executed, the point changes to one of the points used in the statement. For instance, after a circle is drawn, the center of the circle becomes the last point referenced. After a line is drawn, the right point named in the LINE statement becomes the last point referenced. [8] Graphics coordinate systems. The standard graphics coordinate system is called the physical coordinate system. For the high resolution screen mode (SCREEN 2), the y-coordinates range from 0 to 199 moving from the top to the bottom of the screen, and the x-coordinates range from 0 to 639, moving from the left to the right side of the screen. See the discussion of SCREEN for the
548
Appendix
C — QBasic Statements
ranges in the higher graphics screen modes. The WINDOW statement can be used to specify a different coordinate system, called a natural or logical coordinate system. Points can also be specified in terms of relative coordinates. The phrase STEP (x,y) refers to the point obtained by starting at the last point referenced and moving x units in the horizontal direction and y units in the vertical direction. Relative coordinates can be used in all statements that produce graphics. [9] Memory.
Each memory location holds an integer from 0 to 255. This unit
of data or memory is called a byte. The computer’s memory is divided into blocks of memory locations called segments. Each segment is 65,536 bytes in size. Within a segment, a particular memory location can be specified by giving its offset (a number from 0 to 65,535) from the beginning of the segment. Thus, to locate an item in memory, both its segment and offset within that segment must be known, although in many cases just the offset is sufficient. Segments overlap, that is, the same portion of memory may be considered to be within different segments. Segment 0 extends from location 0 to location 65535. Segment 1 extends from location 16 to location 65551. Segment 2 extends from location 32 to 65567, and so on. For instance, the 34th memory location can be identified
as segment 0: offset 34, segment 1: offset 18, or segment 2: offset 2. QBasic reserves a special segment, called the Default Data Segment or DGROUP, where it stores variables, special values such as the current row and column of the cursor, and the value of the random seed. The current segment of memory is used in conjunction with the offsets given in BLOAD, BSAVE, PEEK, and POKE statements. At the start of program execution, the current segment of memory is the Default Data Segment. It can be changed at any time by the DEF SEG statement. [10] Device.
Some examples of devices are the video screen, keyboard, printer,
modem, and diskette drives. The computer’s microprocessor receives data from and sends data to the various devices of the computer through what are called ports. Each port is identified by a number from 0 to 65535. A byte of data consists of a number from 0 to 255.
[11] Random-access files. The two methods for writing records to and reading records from random-access files are the “record variable method” and the “buffer method.” The record variable method is discussed in Chapter 9. With the buffer method, a portion of memory referred to as a buffer is set aside for the file. A FIELD statement specifies fixed-length string field variables whose values are held in the buffer. LSET and RSET statements assign values to the field variables, and PUT and GET statements move the contents of the buffer into a record of the file, and vice versa, respectively. The functions MKI$, MKL$, MKS$, and MKD$ are used to convert numbers to fixed-length strings prior to being placed into the buffer by LSET and RSET statements. After a GET statement places a record in the buffer, the functions CVI, CVL, CVS, and CVD are used to convert
the these strings back into numbers of the appropriate type. [12] Binary file. A file that has been opened with a statement of the form OPEN “filespec” FOR BINARY AS #n is regarded simply as a sequence of characters occupying positions 1, 2, 3,.... At any time, a specific location in
the file is designated as the “current position.” The SEEK statement can be is used to set the current position. Collections of consecutive characters are written
Appendix
C — QBasic Statements
549
to and read from the file beginning at the current position with PUT and GET statements, respectively. Aftera PUT or GET statement is executed, the position following the last position accessed becomes the new current position.
[13] Label. QBasic supports two mechanisms for identifying program lines that are the destinations of statements such as GOTO and GOSUB: line numbers and descriptive labels. Descriptive labels are named using the same rules as variables, and are followed by a colon. When a label appears in a GOTO or GOSUB statement, execution jumps to the statement following the line containing the label. We use the word label to refer to either a descriptive label or a line number. [14] Subroutines. A subroutine is a sequence of statements beginning with a label and ending with a RETURN statement. A subroutine is meant to be branched to by a GOSUB statement and is usually placed so that it cannot be entered inadvertently. For instance, in the main body of a program, subroutines might appear after an END statement.
[15] Event trapping. Special events, such as the pressing of a function key or the occurrence of an error, can be set to trigger a jump to a subroutine. These events are specified by statements of the general form Event ON and ON Event GOSUB label that cause the computer to check for the event after the execution of each statement. If the event has occurred, the computer then performs a GOSUB to the subroutine at label. Trapping is disabled with Event OFF and deferred with Event STOP. [16] Metacommand.
The statements $STATIC, and $DYNAMIC
are called
metacommands. Metacommands instruct the interpreter to insert certain code into the program
or to treat certain QBasic
statements
in a particular way.
Because metacommands are not executed, they are preceded by the reserved word REM (or an apostrophe). For instance, the statement REM $STATIC or ’$STATIC tells the interpreter to store arrays in a special way. [17] Static vs. dynamic. QBasic uses two methods of storing arrays, dynamic and static. The memory locations for a static array are set aside at compile time and this portion of memory may not be freed for any other purpose. The memory locations for a dynamic arrai are assigned at run-time and can be freed for other purposes. Although dynamic arrays are more flexible, static arrays can be accessed faster. QBasic uses the dynamic allocation of arrays if either the range in a DIM statement is specified by a variable or the programmer insists on dynamic allocation with a $DYNAMIC metacommand.
Appendix D
OBasic Debugging Tools Bee in programs are called bugs and the process of finding and correcting them is called debugging. Since the QBasic interpreter does not discover errors due to faulty logic, they present the most difficulties in debugging. One method of discovering a logical error is by desk-checking, that is, tracing the values of variables on paper by writing down their expected value after “mentally executing” each line in the program. Desk checking is rudimentary and highly impractical except for small programs. Another method of debugging involves placing PRINT statements at strategic points in the program and displaying the values of selected variables or expressions until the error is detected. After correcting the error, the PRINT statements are removed. For many programming environments, desk checking and PRINT statements are the only debugging methods available to the programmer. The QBasic debugger, used in conjunction with the Immediate window, offers an alternative to desk checking and PRINT statements. The debugging tools are invoked from the Debug menu.
Using the Immediate Window The F6 key moves the cursor back and forth between the Immediate window and the View window. The Immediate window can hold several lines of QBasic statements. When the cursor is placed on one of these lines and the Enter key is pressed, the line is executed immediately. The following walkthrough uses the Immediate window to display and alter the values of variables. 1. Notice that the title bar, centered above the View window, is highlighted.
2. Press the function key F6 to activate the Immediate window. Notice that the bar containing the word “Immediate” is highlighted and the cursor is located in the Immediate window.
3. Press F6 to reactivate the View window. The title bar is now highlighted and the cursor is in the View window.
4. Press Alt/F/N to clear any previous program from memory and then type the following program into the View window. Do not run this program yet. CIES LET x = 1 LET y= 2 PRINT
END
550
x + y
Appendix D — QBasic Debugging Tools
551
5. Activate the Immediate window and type the line PRINT
[X=os °xXp
yes
y,
x >-y
into the Immediate window.
6. With the cursor on the line, press the Enter key. The values of the variables x and y and the condition x > y, all zero, will be displayed in the output window. The value of a condition is displayed as —1 if the condition is true and 0 if the condition is false. 7. Press any key to return to the Immediate window. 8. Activate the View window and run the program.
9. Activate the Immediate window, move the cursor to the line typed in 5, and press the Enter key. The new values of the variables and the value of the condition will be displayed on the Output screen. 10. Press any key to return to the Immediate window. 11. On a new line in the Immediate window, type the statement EET
©x7=
100
12. Press the Enter key with the cursor on this new line. The Output screen reappears, but is unchanged, since no new items have been displayed. 13. Press any key to return to the Immediate window, move the cursor to the PRINT statement, and press the Enter key. The values of x, y, and the condition x > y are displayed, with new values for x and the condition. Since x > y is now true, its value appears as —1.
Using the QBasic Debugger The two main features of the QBasic debugger are stepping and breakpoints. The program can be executed one statement at a time, with each press of an appropriate function key executing a statement. This process is called stepping. After each step, values of variables, expressions, and conditions can be displayed from the Immediate window, and the values of variables can be changed. When a procedure is called, the lines of the procedure can be executed one at a time, referred to as “stepping through the procedure,” or the entire procedure can be executed at once, referred to as “stepping over a procedure.” A step over a procedure is called a procedure step. Normally, stepping begins with the first statement of the program, and proceeds to execute the statements in order. However, at any time the programmer can specify the next statement to be executed. As another debugging tool, QBasic allows the programmer to specify certain lines as breakpoints. Then, when the program is run, execution will stop at the first breakpoint reached. The programmer can then either step through the program or continue execution to the next breakpoint. The tasks discussed above are summarized below, along with a means to carry out each task. The tasks invoked with function keys can also be produced from the menu bar.
552
Appendix D— QBasic Debugging Tools
Press F8
Step (ordinary):
Procedure step: Press F10 Set a breakpoint:
Move cursor to line, press F9
Remove a breakpoint:
Move cursor to line containing breakpoint, press F9
Clear all breakpoints:
Press Alt/D/C
Set next statement:
Press Alt/D/N
Execute program to the line containing the cursor: Press F7 Continue execution to next breakpoint or the end of the program: Toggle between View window and Output screen:
Press F5
Press F4
Six Walkthroughs The following walkthroughs use the debugging tools with the programming structures covered in Chapters 3, 4, 5, and 6.
Stepping Through an Elementary Program: Chapter 3 The following walkthrough demonstrates several capabilities of the debugger.
1. Type the following program into the View window. cls INPUT
"Enter
a number:
LET
num
= num
+
LET
num
= num
+ 2
PRINT
",
num
1
num
END
2. Press F8. The CLS statement is highlighted to indicate that it is the next statement to be executed. 3. Press F8. The CLS statement is executed and the INPUT statement is highlighted to indicate that it is the next statement to be executed. To confirm that CLS really was executed, press F4 to see the blank Output screen. (Press F4 again to return to the View window.)
4. Press F8 to execute the INPUT statement and respond to the request by entering 5. 5. Press F8 four more times to execute the rest of the program.
6. Move the cursor to the line LET num = num + 2. Press F9 to highlight the line and set it as a breakpoint. (Pressing F9 has the same consequence as invoking the “Toggle Breakpoint” option from the Debug menu by pressing Alt/D/B.) 7. Press Shift+F5. The program executes the first three lines and stops at the breakpoint. The breakpoint line is not executed. (Again, respond to the INPUT statement with 5.)
Appendix D — QBasic Debugging Tools
553
8. Type the statement PRINT
"num
=";
num
into the Immediate window and then press Enter to execute the statement. The appearance of num = 6 in the Output window confirms that the breakpoint line was not executed. 9. Press any key and then F6 to return to the View window.
10. Move the cursor to the line LET num = num + 1 and then press Alt/D/N to specify that line as the next line to be executed. 11. Press F8 to execute the selected line.
12. Use the Immediate window to confirm that the value of num is now 7, and then return to the View window.
13. Move the cursor to the breakpoint line and press F9 to deselect the line as a breakpoint.
14. Press F5 to execute the remaining lines of the program. The value displayed 1s 9.
Stepping Through Programs Containing Selection Structures: Chapter 4 IF Blocks The following walkthrough demonstrates how an IF statement evaluates a condition to determine whether to take an action. 1. Type the following program into the View window. CES INPUT
wage
IF wage < 4.25 THEN PRINT "Below minimum EUSE PRINT "Wage Ok." END IF END
wage."
2. Press F8 twice. The CLS statement will be highlighted and executed, and then the INPUT statement will be highlighted.
3. Press F8 once to execute the INPUT statement. Type a wage of 3.25 and press the Enter key. The IF statement is highlighted, but has not been executed. 4. Press F8 once and notice that the highlight for the current statement has jumped to the statement PRINT “Below minimum wage.” Since the condition “wage < 4.25” is true, the action associated with THEN was selected.
554
Appendix
D— QBasic Debugging Tools
5. Press F8 to execute the PRINT statement. Notice that ELSE, the statement
immediately following the PRINT statement, is highlighted.
the h wit h oug thr are we ed, ass byp is ion act E ELS the ce Sin n. agai 6. Press F8 IF block and the statement following the IF block, END, is highlighted. 7. Press F8 once more to complete execution of the program.
8. If desired, try stepping through the program again with 5.75 entered as the wage. Since the condition “wage < 4.25” will be false, the ELSE action will be executed instead of the THEN
action.
SELECT CASE Blocks the uses k bloc E CAS ECT SEL a how tes stra illu gh rou kth wal g owin foll The selector to choose from among several actions. 1. Type the following program into the View window. GES INPUT age SELECT CASE age CASE US e= 65 LET price = 4 CASE ELSE LET price = 5.5 END SELECT PRINT USING "Your ticket END
price
is
$#.##";
price
2. Press F8 twice. The CLS statement will be highlighted and executed, and then the INPUT statement will be highlighted. 3. Press F8 once to execute the INPUT statement. Type an age of 8 and press the Enter key. The SELECT CASE statement is highlighted, but has not been executed. 4. Press F8 once and observe that the action associated with CASE IS < 12 is
highlighted. 5. Press F8 once to execute the LET statement. Notice that the clause following the LET statement, “CASE IS < 18,” is highlighted. 6. Press F8 once. Observe that although the selector, age, is less than 18, the
action associated with that CASE clause was ignored and the highlight jumped outside the SELECT CASE block to the PRINT USING statement. This demonstrates that when more than one CASE clause is true, only the first is acted upon. 7. Press F8 twice to complete execution of the program.
8. If desired, step through the program again, entering a different age and predicting which CASE clause will be acted upon.
Appendix D — QBasic Debugging Tools
555
Stepping Through a Program Containing a DO Loop: Chapter 5 DO Loops
The following walkthrough demonstrates use of the Immediate window to monitor the value of a condition in a DO loop that searches for a name. 1. Enter the following program into the View window. REM Look for a specific name CLS INPUT "Name"; searchName$ 'Name to search for READ name$ DO WHILE (searchName$ name$) AND (name$ READ name$ LOOP PRINT name$ ‘Print found name or EOD REM
DATA
---
Data:
Bert,
in
list
"EOD")
name
Ernie,
Grover,
Oscar,
EOD
END
2. Press F6 to activate the Immediate window.
3. Type, but do not press the Enter key, PRINT
searchName$,
name$,
(searchName$
name$)
AND
(name$
"EOD")
4. Press F8 three times to execute CLS and the INPUT statement. Enter the
name “Grover” at the prompt. 5. Press F8 once to execute the READ statement.
6. Press F6 to activate the Immediate window, move the cursor to the PRINT
statement, and press the Enter key. The variable name$ has been assigned the first item in the DATA statement, “Bert”, and the value of the WHILE
condition is displayed as —1. (True conditions are displayed as —1; false conditions are displayed as 0.) Since the two conditions (searchName$ name$) and (name$ “EOD”) are both true, the compound condition is
true. (Press any key to continue.)
7. Press F8 once. Since the WHILE condition is true, the DO loop is entered. 8. Press F8 once to READ the next DATA item. 9. Execute the statement in the Immediate window. The value of name$ is now
“Ernie.” (Press any key to continue.) Although the highlight is on the word LOOP, QBasic is really preparing to evaluate the WHILE condition to see if the loop should be executed again. 10. Press F8. Since the WHILE condition is true, the statement inside the loop
is highlighted. 11. Press F8 to READ the next item from the DATA statement.
12. Execute the statement in the Immediate window. Since searchName$ and name$ have the value “Grover”, the condition (searchName$ name$)
is false. Hence the entire WHILE condition is false, and is displayed with the value 0.
556
Appendix
D— QBasic Debugging Tools
t ligh high the , false ome bec has ion dit con LE WHI the e Sinc . once F8 s 13. Pres will move from the LOOP statement to the statement immediately following the DO loop, that is, PRINT name$.
14. Press F8. The value displayed on the screen by PRINT is the same as the value of name$ most recently displayed from the Immediate window. (Press F4 to view the Output screen.) 15. Press F8 once to complete execution of the program.
Stepping Through a Program Containing a Procedure: Chapter 6 The following walkthrough uses the single-stepping feature of the debugger to trace the flow through a program and a subprogram CALL. 1. Type the following program into the View window. CLS LET p = 1000 ‘Principal CALL GetBalance(p, b) PRINT "The balance is";
b
END
SUB GetBalance (prin, bal) REM Calculate the balance LET interest = .05 * prin LET bal = prin + interest END SUB
at
5%
interest
rate
2. Press F8. The CLS statement is highlighted to indicate that it is the next statement to be executed. 3. Press F8 two more times. The CALL statement is highlighted. 4. Press F8 once and observe that the subprogram GetBalance is now displayed on the screen with its first executable statement highlighted. (The subprogram heading and REM statement have been skipped.) 5. Press F8 twice to execute the LET statements and to highlight the END SUB statement. 6. Press F8 and notice that the main body is again displayed in the View window with the highlight on the statement immediately following the CALL statement. 7. Press F8 twice to execute the PRINT statement and the END statement.
Communication Between Arguments and Parameters
The following walkthrough uses the Immediate window to monitor the values of arguments and parameters during the execution of a program.
1. If you have not already done so, type the preceding program into the View window.
Appendix D — QBasic Debugging Tools
557
2. Press F6 to activate the Immediate window. Type in, but do not execute, the following two lines. (Use the Home key and cursor-down key to move to the beginning of a new line instead of pressing the Enter key.) PRINT
to)
PRINT
"prin
=.
Ds
"b
="5
=" 3 prin,
b
"bal
="3
bal
3. Press F8 three times to highlight the CALL statement. 4. Activate the Immediate window, place the cursor on the first PRINT statement created in step 2, and press the Enter key to display the values of p and b. 5. Press any key, and then Press F8 to call the subprogram.
6. Activate the Immediate window, place the cursor on the second PRINT statement created in step 2, and press the Enter key to display the values of prin and bal. The variables prin and bal have inherited the values of p and
b. 7. Press any key, and then press F8 twice to execute the subprogram.
8. Activate the Immediate window and display the values of prin and bal. 9. Press any key, and then press F8 to return to the main body of the program.
10. Activate the Immediate window and display the values of p and b. The variable b now has the same value as the variable bal.
11. Press F8 twice to complete execution of the program.
12. Activate the Immediate window and display the values of prin and bal. These variables both have value 0 since they are not recognized by the main body of the program.
Appendix E
A Summary of QBasic Editing Commands he charts below summarize the editing commands presented in Chapter 1. These charts are followed by some advanced editing commands that use QBasic’s Clipboard. Commands
to Move Cursor
Left one character Right one character Left to start of word Right to start of word Left to start of line Right to end of line Up one line Down one line Up to first line in program Down to last line in program
Left Arrow Right Arrow Ctrl+Left Arrow Ctrl+Right Arrow Home End Up Arrow Down Arrow Ctrl+Home Ctrl+End
Commands to Scroll Up to Down Scroll Scroll
a new page to a new page view up one line in program view down one line in program
Commands
PgUp PeDn Ctrl+Up Arrow Ctrl+Down Arrow
to Delete Text
Delete character left of cursor Delete character at cursor Delete from cursor to end of word
Backspace Del Ctrl+T
Delete from cursor to end of line Delete entire line
Shift+End/Del Ctrl+Y
Using the Clipboard QBasic sets aside a part of memory, called the Clipboard, to assist in moving and copying selected portions of text. Whenever text is deleted with one of the commands Ctrl+T (erase word) or Ctrl+Y (erase current line) the text is placed
in the Clipboard. At any time, pressing Shift+Ins inserts the contents of the Clipboard at the cursor position. The following steps can be used to move a line of code to a new location. 1. Place the cursor on the line.
2. Press Ctrl+Y to erase the line and place it into the Clipboard. 558
Appendix E — A Summary of QBasic Editing Commands
559
3. Move the cursor to the desired new location for the line.
4. Press Shift+Ins to duplicate the line at the cursor position.
Note: After the contents of the Clipboard are copied text remains in the Clipboard and therefore can locations. Larger portions of contiguous text, called blocks, Clipboard. To select a segment of text as a block,
at the cursor position, the be duplicated in several
also can be stored in the move the cursor to the beginning of the segment, hold down the shift key, move the cursor to the end of the segment of text, and then release the shift key. The selected block will be highlighted. (Moving the cursor deselects the portion of text as a block.) After highlighting a block, the following commands can be applied to the selected block.
Shift+Del
— Erases the selected block and places it in the Clipboard
Ctrl+Ins
Places a copy of the selected block in the Clipboard while leaving the block intact
Del
Erases the selected block without placing it in the Clipboard
After placing a block of text into the Clipboard, the following steps can be used to copy the contents of the Clipboard anywhere in a program. 1. Move the cursor to the location where the block stored in the Clipboard should be inserted. 2. Press Shift+Ins to insert the block at the cursor position.
Appendix F
The QBasic Environment his appendix discusses the eight Menu bar selections and their pull-down menus. The File Menu Commands Pressing F from the Menu bar (or Alt/F from the View or Immediate window)
pulls down the File menu, presenting the following six command options. New
The New command clears any current program from the editor’s memory, allowing a new program to be written. The new program is given the default name of Untitled.BAS. If the New command is given when a recently edited program is in memory, QBasic provides an opportunity to save this edited program before the editor’s memory is loaded with the new program. Open
The Open command copies a program from a disk into the View window so that the program can be edited or run. If the Open command is given when a recently edited program is in memory, QBasic provides an opportunity to save this edited program before the editor’s memory is loaded with the new program.
The Open command exhibits a box with the cursor in a rectangle entitled “File Name.” To load a file, type the filename (including the drive and path if warranted) into the rectangle and press the Enter key. If the file name has the standard extension of BAS, you need not include the extension. (To specify a file whose name has no extension, include the period at the end of the file name.) If the file you request is not present, QBasic assumes you want to start working on a new program that will later be saved in a file with this new name. An alternate way of loading a file is provided by the Files rectangle which displays the names of all the files with extension BAS in the current directory of the current drive. A program can be loaded by pressing the Tab key, moving to the desired name with the cursor-moving keys, and pressing the Enter key. The drive can be changed by making a selection from the Dir/Drives rectangle. The drive and/or directory of the programs displayed in the Files rectangle can be changed by typing and entering the identifying path in the File Name rectangle. Wild card characters, the asterisk and question mark, can be used to request a class of file names from the directory. A question mark in a file name indicates that any character can occupy that position. An asterisk in either part of the file name, the first eight positions or the extension, indicates that any
character can occupy that position and all the remaining positions in the part.
560
Appendix
F — The QBasic Environment
561
For instance, typing and entering A: \TOM \?R*.BAS displays all files on the A drive in the directory TOM having R as the second letter and having the extension BAS. Save
The Save command copies the program currently in memory onto a disk. If the program has not been named (that is, if its current name appears as Untitled in the Title bar), QBasic exhibits an input box titled File Name that provides the
opportunity to give the file a meaningful name. If the file name ends with a period, then it will be saved with no extension. Otherwise, if the file name has
no extension, the extension BAS will automatically be added. The file is saved in the current directory of the current drive unless its name is preceded with a drive and/or path. The drive also can be selected from the Dir/Files rectangle. Save As
The Save As command copies the program currently in memory onto a disk after providing an opportunity to save the program under a name other than the current name. The dialog box is identical to the one for Save. Print
The Print command prints a hard copy of the part of the program that has been selected as a block, the current window (that is, the View window, the Immediate
window, or a procedure), or the entire program, depending on which option is selected.
Exit The Exit command abandons QBasic and returns to DOS. If the Exit command is given when the program in the View window has not been saved in its current form, the user is given the opportunity to save before QBasic is abandoned. The Edit Menu Commands Pressing E from the Menu bar (or Alt/E from the View or Immediate windows)
pulls down the Edit menu, presenting the following six command options. Cut
The Cut command removes the selected block of text from the View window
and places it in the clipboard. Copy
The Copy command places a copy of the selected block of text into the clipboard. The copied text will still be in the View window. Paste
The paste command inserts, at the cursor, a copy of the contents of the clipboard.
562
Appendix
F — The QBasic Environment
Clear
The Clear command removes the selected text without saving it in the clipboard. (Clipboard contents remain unaltered.) New SUB
The New SUB command opens a dialog box in which the programmer enters the name of anew subprogram. After pressing the Enter key, the new subprogram
will be created and the cursor will appear below the heading. New FUNCTION The New FUNCTION command opens a dialog box in which the programmer enters the name of a new function. After pressing the Enter key, the new function will be created and the cursor will appear below the heading. The View Menu Commands Pressing V from the Menu bar (or Alt/V from the View or Immediate window)
pulls down the View menu, presenting the following three command options. SUBs
The SUBs command displays a dialog box used to select a procedure to view or delete. Split
The Split command divides the View window horizontally so two parts of a program can be accessed at the same time. The F6 and Shift+F6 keys move between the windows. The size of the active window can be expanded one line at a time with Alt+Plus and shrunk with Alt+Minus. Ctrl+F10 toggles between an expanded View window and its regular size. Output Screen
The Output Screen command toggles to and from the display of the output screen. The same function is performed by the F4 key. The Search Menu Commands Pressing S from the Menu bar (or Alt/S from the View or Immediate window)
pulls down the Search menu, presenting the following three command options.
Find The Find command begins at the cursor and searches for the first occurrence of a specified symbol, word, or phrase.
Repeat Last Find
The Repeat Last Find command looks for the next occurrence of the text most recently searched for by the Find command.
Appendix F — The QBasic Environment
563
Change
The Change command begins at the cursor, finds the first occurrence of specified text, and replaces it with new text. The Run Menu Commands Pressing R from the Menu bar (or Alt/R from the View or Immediate windows) pulls down the Run menu, presenting the following three command options.
Start
The Start command executes the program currently in memory, beginning with the first line. Pressing Shift+F5 performs the same function. Restart When a program has been suspended before completion, the Restart command specifies that the next call for execution of the program should restart the program from the beginning. Continue
When a program has been suspended before completion, the Continue command resumes execution at the suspension point. The same function is performed by the F5 key.
The Debug Menu Commands Pressing D from the Menu bar (or Alt/D from the View or Immediate windows) pulls down the Debug menu, presenting the following six command options. Step
The Step command executes the program one statement invocation of the command executes the next statement.
at a time. Each
Procedure Step
The Procedure Step command executes the program one statement at a time without stepping through the statements inside procedures one at a time. An entire procedure is executed as if it were a single statement. Trace On
The Trace On line shows the current status of the Trace toggle. When Trace On is preceded by a dot, each statement will be highlighted as it is executed. This feature lets you observe the general flow of the program.
Toggle Breakpoint
A breakpoint is a line of the program at which program execution is automatically suspended by QBasic. The Toggle Breakpoint command toggles (that is, sets or clears) the line containing the cursor as a breakpoint.
564
Appendix F — The QBasic Environment
Clear All Breakpoints
The Clear All Breakpoints commands removes all breakpoints that have been set with the toggle breakpoint command. Set Next Statement
The Set Next Statement specifies that the line containing the cursor be the next line executed when program execution continues.
The Options Menu Commands Pressing O from
the Main
Menu
(or Alt/O from
the View
or Immediate
windows) pulls down the Options command menu, presenting the following three command options.
Display The Display command generates a dialog the foreground and background of text statements highlighted during debugging, by a mouse, and to specify the number of
box that can be used to custom-color typed into the View windows and to select or deselect the scroll bars used spaces tabbed by the Tab key.
Help Path
The Help Path command is used to tell QBasic where to look for the file QBasic.HLP, the file containing the Help information. Normally, the file is in the same directory as QBasic.EXE. If not, the path specifying the directory containing QBasic.HLP should be entered in the rectangle invoked by the Help Path command. A complete path consists of a disk drive followed by a sequence of subdirectories.
Syntax Checking Normally, checks the to improve ceded with
when a line of text is Entered, QBasic’s smart editor automatically correctness of the line, capitalizes key words, and adds extra spaces readability. This feature is enabled when Syntax Checking is prea dot. The Syntax Checking command toggles this state.
The Help Menu Commands Pressing H from the Menu bar (or Alt/H from the View or Immediate windows)
pulls down the File menu, presenting the following five command options.
Index The Index command displays an alphabetical list of keywords. Information on a keyword can be obtained by placing the cursor on the keyword and pressing the Enter key or F1. Pressing a letter key moves the cursor to the first keyword beginning with that letter.
Appendix
F — The QBasic Environment
565
Contents
The Contents command displays a menu of topics on which information is available. After the Tab or direction keys are used to move the cursor to a topic,
pressing Enter or F1 displays the information. Topic
When the cursor is located at a keyword in the View window, you can invoke the Topic command to obtain information about that word. Using Help
The Using Help command displays information about how to obtain online help. About
The About command displays the version number and copyright dates of the QBasic currently in use.
Appendix G
How To (QBasic) HOW
TO: Invoke and Exit QBasic
(We assume that the computer has a hard disk with DOS 5.0 or a later version of DOS installed.)
A.
Invoke QBasic.
1. 2. 3.
Turn on the computer and monitor. At the DOS prompt, type QBASIC and press the Enter key. When the screen querying about the Survival Guide appears, press the Esc key.
Note: If step 2 does not work, enter DIR \QBASIC.EXE /S at the DOS prompt to determine the directory in which QBASIC resides. (Normally, this will be the directory C:\ DOS.) Then enter CD nameOfDirectory and repeat step 2. (For example, in the most common case, enter CD \DOS and then enter QBASIC.) . Allow graphics when the monitor is a Monochrome display that is attached to a Hercules card.
1.
Before invoking QBasic, enter MSHERC at the DOS prompt.
Note 1: If this does not work, enter DIR \MSHERC.COM
/S at the DOS
prompt to determine the directory in which MSHERC resides. (Normally, this will be the directory C:\DOS.) Then enter CD nameOfDirectory and repeat step 1. (For example, in the most common case, enter CD \DOS and then enter MSHERC.) Note 2: The statement SCREEN 3 must appear in any program prior to the use of graphics statements.
C.
Exit QBasic.
1.
Press the Esc key.
2.
Press Alt/F/X.
3.
If the program in the View window has not been saved, QBasic will prompt you about saving it.
Note: In many situations, step | is not needed.
HOW A.
Runa 1.
566
TO: Manage Programs program from QBasic. Press Alt/R/S.
Appendix
G — How To (QBasic)
567
Or,
1.
Press Shift+F5. (Normally, F5 alone will run the program. However, if
the program has been stopped before its end, F5 continues execution from the stopping point, whereas Shift+F5 executes the program from the beginning.)
B.
Save the current program on a disk. 1.
Press Alt/F/S or Alt/F/A.
2.
‘Type the name of the program, if requested, and press the Enter key.
Note: After a program has been saved once, updated versions can be saved under the same name by pressing Alt/F/S. Alt/F/A is used to save the program under a new name. C.
D.
Begin a new program in the View window. 1.
Press Alt/F/N.
2.
If an unsaved program is in the View window, QBasic will prompt you about saving it.
Open a program stored on a disk. 1. 2.
3. E.
Name a program. 1.
HOW
A.
2.
TO: Use the Editor
Look at the pair of numbers at the bottom right of the screen separated by acolon on the status bar. The first number gives the row, and the second number gives the column.
Mark a section of text as a block.
1. 2. 3.
C.
Save it with Alt/F/A.
Determine the row and column position of the cursor. 1.
B.
Press Alt/F/O. Type a filespec into the top rectangle of the dialog box and press the Enter key. Alternately, press the Tab key to penetrate the region containing the names of the files on the disk, and then use the cursor-moving keys and the Enter key to select one of the listed files. If the program in the View window has not been saved, QBasic will prompt you about saving it.
Move the cursor to the beginning or end of the block. Hold down a Shift key and use the direction keys to highlight a block of text. To unblock text, release the Shift key and press a cursor key.
Delete a line of a program. 1. 2.
Or,
Move the cursor to the line. Press Ctrl+Y.
568
Appendix
G— How To (QBasic)
1. 2.
Mark the line as a block. (See item B of this section.) Press Shift+Del.
Note: In the maneuvers above, the line is placed in the clipboard and can be retrieved by pressing Shift+Ins. To delete the line without placing it in the clipboard, mark it as a block and press Del. D.
E.
Move a line within the View window.
1. 2.
Move the cursor to the line and press Ctrl+Y. Move the cursor to the target location.
3.
Press Shift+Ins.
Use the clipboard to move or duplicate statements. 1.
Place the cursor on the first character of the statement (or group of statements).
2.
3. 4. 5. FE.
Search for specific text in program.
1. jes 3. 4. 5. G.
I.
Press Alt/S/E
Type sought-after text into rectangle. Select desired options if different from the defaults. Press the Enter key. ‘To repeat the search, press F3.
Search and change.
Ik 2 3 4. 5. 6. H.
Hold down a Shift key and move the cursor to the right (and/or down) to highlight the selected block of text. Press Shift+Del to delete the block and place it into the clipboard. Or, press Ctrl+Del to place a copy of the block into the clipboard. Move the cursor to the location where you desire to place the block. Press Shift+Ins to place a copy of the text in the clipboard at the cursor.
Press Alt/S/C.
Type sought-after text into first rectangle. Press Tab.
Type replacement text into second rectangle. Select desired options if different from the defaults. Press the Enter key.
Change from “Syntax Checking On” to “Syntax Checking Off’ or vice versa. 1.
Press Alt/O.
2.
“Syntax checking” is preceded by a dot if the feature is active. Press S if you want to change the selection, or press the Esc key to exit.
Check the syntax of a line. (Assuming “Syntax checking” is enabled.) 1.
Move the cursor to the line.
2. 3.
Edit the line in some way. For example, type = and then press Backspace. Press the Down Arrow key.
Note: The syntax of a line is automatically checked whenever the cursor is moved off an edited line, either by pressing the Enter key or a cursor moving key.
Appendix G — How To (QBasic)
J.
Cancel changes made to a line. 1.
Do not move the cursor from the line.
2.
Press Ctrl+Q/L to restore the line to the form it had when the cursor was last moved from the line.
HOW A.
569
TO: Get Help
View the syntax and purpose of a QBasic keyword.
1. 2.
Type the word into the View window. Place the cursor on, or just following, the keyword.
3.
Press Fl.
Or,
B.
C.
1.
Press Alt/H/I/[first letter of keyword].
2. 3.
Use the direction keys to highlight the keyword. Press the Enter key.
Display an ASCII table. 1. 2.
Press Alt/H/C. Press the letter
3.
press the Enter key. Use PgDn and PgUp to move between the extended and standard ASCII character sets.
Obtain a list of common editing and debugging commands. 1.
D.
E.
1.
Press Alt/H/C.
2. 3.
Use Tab and Shift+Tab to highlight a topic. Press the Enter key.
Obtain general information about using the help menu. Press Shift+F1.
Obtain information about the selections in a pull-down menu.
1. G.
Press Alt/H/C/S/Enter.
Obtain other useful reference information.
1.
FE.
A to move the cursor to “ASCII Character Codes” and
See item D in HOW TO: Manage Menus.
Obtain a list of QBasic’s reserved words.
1.
Press Alt/H/I and use the Down Arrow key to scroll through the list.
Note: To obtain information about a word, move the cursor to the word and
press the Enter key.
HOW A.
TO: Manipulate a Dialog Box
Use a dialog box. A dialog box contains three types of items: rectangles, option lists, and command buttons. An option list is a sequence of option buttons of the form (_) option or [ | option, and a command button has the form < command
>.
570
Appendix G — How To (QBasic)
1.
Move from item to item with the Tab key. (The movement is from left to right and top to bottom. Use Shift+Tab instead of Tab to reverse the direction.)
2.
3.
4.
5.
Inside a rectangle, either type in the requested information or use the direction keys to make a selection. Inan option list, an option button of the form ( ) option can be activated with the direction keys. A dot inside the parentheses indicates that the option has been activated. Inan option list, an option button of the form [] option can be activated or deactivated by pressing the space bar. An X inside the brackets indicates that the option has been activated. A highlighted command button is invoked by pressing the Enter key.
Cancel a dialog box.
1.
Press the Esc key.
Or,
1.
HOW
Press the Tab key until the command button < Cancel > is highlighted and then press the Enter key.
TO: Manage Menus
A. Close a pull-down menu. 1.
Press the Esc key.
Open a pull-down menu. 1. 2.
Press Alt. Press the first letter of the name of the menu. Alternately, press the Down Arrow key, use the direction keys to move the highlighted cursor bar to the menu name, and press the Enter key.
- Make a selection from a pull-down menu.
1.
2.
Open the pull-down menu. One letter in each item that is eligible to be used will be emphasized by being highlighted or having a different color than the other letters. Press the emphasized letter. Alternately, use the Down Arrow key to move the cursor bar to the desired item and then press the Enter key.
» Obtain information about the selections in a pull-down menu.
1. 2. 3. 4.
Open the pull-down menu. Use the Down Arrow key to move the highlighted cursor bar to the desired item. The status bar at the bottom of the screen will give a brief description of the item. Pressing Fl gives additional information.
Look at all the menus in the menu bar.
1.
Press Alt/E
2.
Press the Right Arrow key each time you want to see a new menu.
Appendix G — How To (QBasic)
571
HOW TO: Manage Procedures A.
Look at an existing procedure.
1.
Press Shift+F2 repeatedly to cycle through all the procedures.
Or,
1.
Press F2. The top entry is the main body of the program and the remaining entries are procedures.
2.
B.
Use the direction keys and the Enter key to select the desired procedure.
Create a procedure. 1. 2. 3. 4.
Move to a blank line. Type SUB (for a subprogram) or FUNCTION (for a function) followed by the name of the procedure and any parameters. Press the Enter key. (A new window will appear containing the procedure heading and an END statement.) Type the procedure into the new window.
Or,
1.
2.
3. 4.
Press Alt/E/S (for a subprogram) or Alt/E/F (for a function). (A dialog
box will appear.) Type the name of the procedure and any parameters into the Name rectangle. Press the Enter key. (A new window will appear containing the procedure heading and an END statement.) Type the procedure into the new window.
Note: To return to the main body of the program, press F2/Enter. C.
Alter a procedure.
1. 2.
Press Shift+F2 until the desired procedure is displayed. Make changes as needed.
(OM
D.
lL.
Press F2.
2. 3.
Move the cursor bar to the desired procedure. Press the Enter key.
Remove a procedure. IévePress F2. 2. Move the cursor bar to the desired procedure. 3. Press Tab/D/Enter. Insert an existing procedure into a program.
1. 2.
Open the program containing the procedure and press Shift+F2 until the procedure appears on the screen. Mark the procedure as a block. That is, move the cursor to the first statement of the procedure, hold down a Shift key, and move the cursor
1S)
E.
4.
to the last statement of the procedure. Press Ctrl+Ins to place the procedure into the clipboard. Open the program in which the procedure is to be inserted.
572
Appendix
G — How To (QBasic)
5. 6.
HOW A.
Move the cursor to a blank line. Press Shift+Ins to place the contents of the clipboard into the program.
TO: Manage Windows
Change the active window, that is, the window which contains the cursor
and has its title highlighted. 1.
B.
Press F6 until desired window becomes active.
Split a screen to obtain multiple View windows. Option I: Both parts will contain same text. 1.
Press Alt/V/P.
Option II: Second part will contain any procedure. 1. 2. 3. 4. 5.
C.
D.
1.
Use F6 to select window to be retained.
2.
Press Alt/V/P.
Zoom the active window to fill the entire screen.
HOW
Press Alt+Plus to enlarge by one line. Press Alt+Minus to contract by one line.
TO: Alter the Appearance of the View Window
Remove the scroll bars from or add them to the View window. (The scroll bars are needed when a mouse is used.) 1.
Press Alt/O/D/Tab/Tab/Tab.
2.
The space bar can be pressed to alternate between having and not having an X at the cursor. The presence of an X produces scroll bars. Press the Enter key.
3. B.
Press Cel E10: To return window to original size, press Ctrl+F10 again.
Make a small change in the size of the active window. 1. 2.
A.
Alt/V/P. F6. F2. cursor bar to desired procedure. Enter.
Unsplit a screen.
le 2.
E.
Press Press Press Move Press
Change certain colors used by QBasic. 1.
Press Alt/O/D.
2. 3.
Press Tab or Shift+Tab to move around the dialog box. Use the direction keys to make a selection within each region of the dialog box. To change a toggled selection, such as “Scroll bars,” press the Space bar. When all selections have been made, press the Enter key.
4. 5.
Note: When QBasic is exited, these selections will be saved in a file named QB.INI. If this file is present on the same disk and directory as QBASIC.EXE when QBasic is next invoked, it will determine QBasic’s display settings.
Appendix
C.
G — How To (QBasic)
573
Invoke QBasic in black & white.
1.
Type QBASIC /B and press the Enter key when invoking QBasic from DOS.
D. Invoke QBasic with the maximum number of lines supported by the adapter. 1.
HOW
A.
Type QBASIC /H and press the Enter key when invoking QBasic from DOS:
TO: Use the Printer
Obtain a printout of a program. 1. 2.
Press Alt/F/P. Press the Enter key.
Note: To print just the text selected as a block or the active (current) window, use the direction keys to select the desired option. Obtain a printout of a text Output window. 1. 2.
Press F4 to switch to the Output window if necessary. Press Shift+Print Screen. Tip: After the program terminates, the phrase “Press any key to continue” can be removed by pressing F4 twice.
. Obtain a printout of a graphics Output window. The command needed to ready the printer for graphics depends on the type of printer. 1.
(Dot matrix printer) Before invoking QBasic, enter GRAPHICS at the DOS prompt.
Or,
1. 2.
(Laser printer) Before invoking QBasic, enter GRAPHICS HPDEFAULT at the DOS prompt. Press Shift+Print Screen. Tip: After the program terminates, the phrase “Press any key to continue” can be removed by pressing F4 twice.
Note: The above steps will produce an improper printout with certain types of printers. See the discussion of the GRAPHICS graphics command in the DOS reference manual for details.
HOW TO: Use the Debugger A. Stop a program at a specified line. 1.
Place the cursor at the beginning of the desired line.
2.
Press F9. (This highlighted line is called a breakpoint. When the program is run it will stop at the breakpoint before executing the statement.)
Note: To remove this breakpoint, repeat steps 1 and 2.
Remove all breakpoints. 1.
Press Alt/D/C.
574
Appendix
G — How To (QBasic)
C.
Runa
program with each statement highlighted as it is executed.
1.
Press Alt/D.
2.
If the “Trace On” selection is preceded by a mark, press F5. Otherwise, Press T/F5.
Note: To turn off tracing, press Alt/D/T. D.
Run a program one statement at a time. 1. 2.
Press F8. The first executable statement will be highlighted. Press F8 each time you want to execute the currently highlighted statement.
Note: At any time you can view the Output screen by pressing F4. E.
Run the program one statement at a time, but execute each procedure call without stepping through the statements in the procedure one at a time. 1. 2.
Press F10. The first executable statement will be highlighted. Press F10 each time you want to execute the currently highlighted statement.
Note: At any time you can view the Output screen by pressing F4. FE.
Continue execution of a program that has been suspended. 1.
Press F5.
Note: Each time a change is made in a suspended program that prevents the program from continuing, QBasic displays a dialog box with two options to choose from: continue without the change, or restart the program from the beginning. G.
Execute a program up to the line containing the cursor. 1.
H.
Have further stepping begin from the top of the program with all variables cleared. 1.
I.
Press F7.
Press Alt/R/R.
Have further stepping begin at the line containing the cursor (no variables are cleared).
1.
J.
Press Alt/D/N.
Execute a statement from the Immediate window.
1. 2. 3.
Press F6 to move the cursor to the Immediate window. ‘Type the statement into the Immediate window. Press the Enter key with the cursor on the statement.
Appendix H
An Introduction To Windows Pree such as Visual Basic, which are designed for Microsoft Windows, are supposed to be easy to use—and they are once you learn a little jargon and a few basic techniques. This appendix explains the jargon, giving you enough of an understanding of Windows to get you started in Visual Basic. Although Windows may seem intimidating if you’ve never used it before, you only need to learn a few basic techniques, which are covered right here. Mice Pointers
When you use Windows, think of yourself as the conductor and Windows as the orchestra. The conductor in an orchestra points to various members, does something with his or her baton, and then the orchestra members respond in certain ways. For a Windows user, the baton is called the pointing device, most often it is a mouse. The idea is that as you move the mouse across your desk, a pointer moves along the screen in sync with your movements. There are two basic types of mouse pointers you will see in Windows—arrows and hourglasses. The arrow is the ordinary mouse pointer you use to point at various Windows objects before activating them. You will usually be instructed to “move the pointer to...” This really means “move the mouse around your desk until the mouse pointer is at...” The hourglass mouse pointer pops up whenever Windows is saying: “wait a minute; I’m thinking.” This pointer still moves around when you move the mouse, but you can’t tell Windows to do anything until it finishes what it’s doing and the mouse pointer no longer resembles an hourglass. (Sometimes you can press the Esc key to tell Windows to stop what it is doing.)
Note: The mouse pointer can take on many other shapes, depending on which program you are using and what task you are performing. Mouse Actions
Now when you get the (arrow) pointer to a place where you want something to happen, you need to do something with the mouse. There are four basic things you can do with a mouse—pointing, clicking, double-clicking, and dragging. Tip: You can pick the mouse up off your desk and replace it without moving the mouse pointer. This is useful, for example, when the mouse pointer is in the
center of the screen but the mouse is about to fall off your desk! Pointing means moving your mouse across your desk until the mouse pointer is over the desired object on the screen. 519
576
Appendix H — An Introduction To Windows
Clicking (sometimes people say single-clicking) means pressing a mouse button (usually the left button) once and then quickly releasing it. Whenever a sentence begins “Click on,” you need to
1. Move the mouse pointer until it is at the object you are supposed to click on. 2. Press and release the (left) mouse button.
An example of a sentence using this jargon might be “Click on the button marked Yes.” You also will see sentences that begin “Click inside the.” This means to move the mouse pointer until it is inside the boundaries of the object,
and then click. Double-clicking means clicking a mouse button (usually the left button) twice in quick succession (that is, pressing it, releasing it, pressing it, and releasing it again quickly so that Windows doesn’t think you single-clicked twice). Whenever a sentence begins “Double-click on,” you need to:
1. Move the mouse pointer until it is at the object you are supposed to double-click on. 2. Press and release the (left) mouse button twice in quick succession.
For example, you might be instructed to “double-click on the little box at the far left side of your screen.”
Note: An important Windows convention is that clicking selects an object so you can give Windows or the program further directions about it but doubleclicking tells Windows (or the program) to do something. Dragging usually moves a Windows object. If you see a sentence that begins “Drag the,” you need to:
1. Move the mouse pointer until it is at the object. 2. Press the (left) mouse button and hold it down.
3. Now move the mouse pointer until the object moves to where you want it to be.
4. Finally, release the mouse button.
Sometimes this whole activity is called drag and drop.
Starting Windows It’s possible that, when you turn on your computer, Windows starts without your needing to do anything. If this is the case, you’ll see a Windows copyright notice, an hourglass pointer while you wait, and then something that looks like Figure H.1. (Your screen will look a little different because one exciting feature of Windows is that you can change the way it looks to reflect your way of working.) What should remain the same is that the top line of your screen will say “Program Manager.”
Appendix H — An Introduction To Windows
f=
%
577
Program Manager
on 466 # Options
File Manager
Window
Control Panel
a PIF Editor
Help
PrintManager
— Clipboard
Windows Setup
Solitaire
Reversi
4 | @ 228 Read Me
Control
ATM Control
Minesweeper
Accessories
Paintbrush
Figure H.1
Terminal
Notepad
JS
B
Write
Calculator
Recorder
®& Character Map
Program Manager
If instead you see something that looks like this: Ce
then you’re at the (infamous) C prompt. This means that DOS is in control. Type WIN and press Enter to start Windows. If your machine responds with something like “Bad Command,” Windows may not be installed on your machine, in which case. you'll need to get it installed before you can continue! If you know Windows is installed on your system and the above didn’t work, then consult the documentation that came with it—or the guru who decided to set Windows up in a nonstandard way. Windows and its Little Windows
Windows gets its name from the way it organizes your screen into rectangular regions. Each rectangular region in the Program Manager is called a program
group window. The whole region is called the Windows desktop. When you run a program, the program runs inside a bordered rectangular box. Unfortunately Windows jargon calls all of these windows, so there’s only a lower case “Ww” to distinguish them from the program called Windows. Think of a program group window as analogous to organizing your desk efficiently by grouping related piles together—as opposed to keeping all your papers in one unwieldy mess. The Program Manager in the windows desktop starts out with four program windows. When you install a program like Visual Basic, the installation procedure will usually add another program group window to the Program Manager for the program and its files. Each rectangular program group window contains little icons. These icons represent files stored on your computer and are usually called program items. Some of these icons represent programs that you can run, and some represent data stored in your computer. You manipulate a window or the objects represented by the icons inside of it by various combinations of clicking, double-clicking, and dragging.
578
Appendix H — An Introduction To Windows
Starting Programs from the Program Manager The general rule in Windows is that double-clicking on the icon that represents a program usually starts the program. When Windows’ attentions are focused on a specific window, the title bar of the window is highlighted and the window is said to be active. The active window is the only one that can be affected by your actions. An example of a sentence you might see is “Make the window active.” This means if the title bar of the window is not already highlighted, click inside the window. At this point the (new) window will be responsive to your actions. Many title bars contain little buttons that you can click to reduce the window to an icon (minimize it), make it fill up the whole screen (maximize it), or close it entirely. The following title bar shows you what to look for:
Control box
Minimize button
Maximize button
Program Manager
Figure H.2
A Title Bar
Typical jargon you might see might include sentences that begin “Minimize the. .. .” This means to turn the object into an icon. An example of this usage might be “Minimize the Program Manager.” You minimize items to give you more room to see the other objects on your desktop. Similarly, “Maximize the. . .” means to make your object fill the whole screen. You do this when you want to concentrate on only that object. An example of this usage might be “Maximize the Program Manager.” Tip: If you have used the Minimize button to make a window into an icon, double-click on the icon to restore it to its previous size.
If you have maximized a window, the Maximize button changes to look like a double-headed arrow called the Restore button. Click on this button to return the window to its previous size.
Tip: You can close any window by double-clicking on the control box. You can also close the active window by holding down the Alt key and pressing the F4 function key. When you close the Program Manager window by double-clicking in its Control box (or using Alt+F4), Windows
itself starts to shut down. You are
presented with the message box for shutting down Windows. Click on the OK button if you want to shut down Windows,
and click on the button marked
Cancel if you don’t want to shut down Windows. Finally, as long as the window isn’t maximized, you can usually move an active window around the screen by dragging its title bar. (Recall that this means to move the mouse pointer until it is in the title bar, hold down the left mouse button, move the mouse until the window is where you want it to be, and then release the mouse button.)
Note: You can also drag the icons inside a window to rearrange them.
Appendix H — An Introduction To Windows
579
Resizing a Window You can change the size of a window by minimizing, maximizing, or restoring it. In addition, you can change the size of most windows to exactly suit your needs. To adjust the size of a non-maximized window: 1. Move the mouse pointer until it is at the place on the boundary you want to adjust. The mouse pointer changes to a double-headed arrow.
2. Drag the border to the left or right or up and down to make it smaller or larger. Which border you want to effect determines which one you drag.
3. When you are satisfied with the new size of the window, release the left mouse button. Scroll Bars
If a window or other Windows object contains more information than can fit on the screen, you need a way to move through this information so you can see it all. For example, you will certainly be writing procedures in Visual Basic that are longer than one screen. You can use the mouse to march through your code with small steps or giant steps. A vertical Scroll bar lets you move from the top to the bottom of the Window; a horizontal Scroll bar lets you move within the left and right margins of the window. Use this scroll bar when the contents of the window are too wide to fit on the screen. Figure H.3 shows both vertical and horizontal Scroll bars.
Case "1" Let flag$
Case "2" Let flag$ Case
Let
Figure H.3
i 1519-1685"
= “France
1685-1696"
= “Mexico
1821-1836"
Vertical scroll bar
"3"
flag$
Case "4" Let flag$ Case "5"
Scroll box
“Spain
Scroll box
+]
Sub GetFlag (a$, flag$) Rem Six Flags of Texas Select Case a$
“Republic
of
Texas
1836-1845"
Horizontal scroll bar
A Visual Basic Code Window
As you can see, a scroll bar has two arrows at the end of a channel that also contains a little box (usually called the Scroll box). The Scroll box is the key to
moving rapidly; the arrows are the key Dragging the Scroll box enables you to approximate location in your window. For to the middle of the channel, you'll scroll window.
to moving in smaller increments. quickly move long distances to an example, if you drag the Scroll box to approximately the middle of your
580
Appendix H — An Introduction To Windows
Menus
The jargon is to say that Windows programs are menu driven. This just means that you can control the features of the program by choosing items from menus. If you tried to close a window by double-clicking but only clicked once on the control box by mistake you may have seen the Control menu shown here: Restore Move
Maximize
Figure H.4
Close
Alt+FA
Switch To...
CtrltEsc
Control Menu
The jargon says “The menu is dropped down” (or “pulled down”). Once a menu is dropped down, there are two ways to pick a menu item (the jargon says “choose the item” or “activate the item”). 1. Click on the item.
2. Use the Up Arrow and Down Arrow keys to move through the list of menu items. Each item is successively highlighted. Press Enter when you get to the item you want to choose. For example, the jargon might say: “An alternate way to close a window is to drop down the Control Menu and choose Close.” Every Windows program has a main menu bar that runs right below the title bar; this is how you activate the program’s features. (In contrast, the Control Menu lets you manipulate the window that the program is sitting in.)
The menu bar for Program Manager in Figure H.1 contains four items. One way to open a menu is to move the mouse pointer to the name of the menu and click. This has the disadvantage that you have to take your hands off the keyboard temporarily. Windows also makes it easy to open a menu with the keyboard. The easiest way to open a menu using the keyboard is to look for the underlined letter of the desired option in the menu bar and then to press Alt and the underlined letter. Underlined letters are usually called accelerator keys or hotkeys. For example, if the Program Manager window is active, press Alt+F to open the File menu shown here.
New... Open Move...
Enter F7
Copy... Delete
F8 Del
Properties...
Alt+Enter
Exit Windows...
Figure H.5
The Program Manager File Menu
Appendix H — An Introduction To Windows
581
Notice that all of these menu items have underlined access keys. You can just press the letter while the menu is open to select the command. (For example, you can press “X” to exit Windows.) Tip: You can activate a menu item in one step if you know its access key. For
example, if you press the Alt key, the F key and the X key in succession, Windows opens the File menu and chooses the Exit item. Some items like Move or Properties have keys (or key combinations) listed
to their right. These are called shortcut keys. A shortcut key is a key or combination of keys you can press to activate an item without opening a menu. Some
menu
items have
a three-dot ellipsis after their names
(like Exit
Windows in the screen above). The ellipsis indicates that choosing the item is not enough: You need to do more work. Usually choosing one of these options displays a dialog box that you will need to work with. Dialog boxes allow you to give the program a lot more information than a simple click on a button can do. We cover dialog boxes in the next section. Finally, if you cannot use a menu item at the moment, it will appear grayed and clicking on it will have no effect. The jargon is to say that the menu item is disabled.
Finding Program Groups from the Program Manager’s Window menu As you install more Windows programs, you may no longer be able to see the program group window that contains the program you want to work with. There is a surefire method of finding a program group window—if you remember its name: 1. Choose Window from the Program Manager’s main menu bar (remember you can do this by pressing Alt/W). This drops down a (long) list of items. If the program group is listed on this list, click on it or type the number to the left of its name. If not, click on the More Windows item and look through the next list (and so on as needed) until
you find the program group you want. Windows opens the program group window for the item you selected.
Starting Programs from the Program Manager’s File Menu The general rule in Windows is that double-clicking on the icon that represents a program usually starts the program—but suppose you can’t find the icon. As with program group windows, there is a surefire method of starting a program—if you can remember its name. To do this, open the File menu in the Program Manager and choose Run (Alt/F/R). This opens a little dialog box. Now type
the name of the program in the box labeled Command Line and click on the OK button. (You will usually need the full name of the program in order for this to work; for Visual Basic Primer Edition this is most likely C: \WBPRIMER \ VB.)
Dialog Boxes Working with a dialog box is probably the most common task you will do with a program in order to get it to do what you want. In the previous section, you
582
Appendix
H — An Introduction To Windows
saw the Run dialog box available from the File menu in the Program Manager. Generally, you need to fill in the information requested in the dialog box or close it before you can continue working with the program. Almost all dialog boxes have a command button marked Cancel that you can click on if you decide you don’t want to work with the dialog box. Often you can press the Esc key to achieve the same effect. Caution: Dialog boxes frequently have a button that goes into effect when you press Enter. This is often but not always the OK button. You can tell which button will be activated when you press Enter by looking for the button with a bold outline around it. (The jargon calls this the default command button for the dialog box or just the default button.) Note: If a command button has an underlined access key in its name, you can press Alt and then the access key to have the same effect as clicking on the button. This is useful when you don’t want to take your hands off the keyboard.
The Open and Save Dialog Boxes In Windows programs, you will also encounter dialog boxes for working with files. Here is the Open dialog box from Visual Basic, which is typical of the dialog boxes you'll see for working with files.
Open Project File Name:
Directories: c:\vbprimer
autoload. mak
project] mak text] mak
List Files of Type:
Project Files(MAK)
Figure H.6
||
An Open Dialog Box
Most of the elements in these dialog boxes are the same as you saw in the previous section. There are command buttons, a couple of check boxes, dropdown list boxes for List Files of Type, Drives, and so on. For example, if you click on the drop-down list box marked Drives, you see a list of drives on your machine. You would now click on the drive to tell Windows to look at the files contained in the new drive. The list of file names on the left side of the Open dialog box is an example of an ordinary list box. The idea is you click once to select a file in this list box (it will then fill the text box marked File Name), or you can double-click to
actually open the file.
Appendix H — An Introduction To Windows
583
Remember: The Windows convention is that clicking on an item selects it; double-clicking activates it. Obviously, what “activate” means depends on the dialog box. In our example, double-clicking a file in a dialog box called Open would, naturally enough, open it.
The Directories list box ina file handling dialog box works a little differently than a regular list box. Think of a directory as a kind of file in a giant filing cabinet. These files are special in that they can contain other files—which can in turn contain other files and so on. The little icons next to the name of the directories make this clear. The file icon is shown as open if Visual Basic is looking at files inside this “cabinet.” You can have a whole chain of these open filing cabinets (also know as open directories), When you see the directory you want the program to look for files in, double-click on its name. If the directory contains other directories, doubleclicking forces the program to look at only those directories above and below the directory you clicked on. If the directory contains other directories, this forces the programs attention deeper into the cabinet. The jargon for this is “To move up and down the directory tree.” You should also be aware that the jargon sometimes talks about subdirectories. This is simply a directory that is inside another directory. The directory that contains the subdirectory is called the parent directory. The top directory is called the root directory. Note: All Windows programs automatically update the File Name list whenever you move up the directory tree by double-clicking or change drives via the Drives drop-down list box.
Ending Windows To close Windows from the Program Manager, hold down the Alt key and the F4 function key at the same time. (That is, Press Alt+F4.) You are presented
with a message box that looks like this:
Exit Windows
e
Figure H.7
This will end your Windows session.
Dialog Box for Ending Windows
Click on the OK command button if you want to shut down Windows, or click on the command button marked Cancel (or press Esc) if you don’t want to leave Windows. Caution: It is a bad idea to end Windows by just shutting off your machine.
Appendix I
How To (Visual Basic) HOW
TO: Install, Invoke, and Exit Visual Basic
Install the Primer Edition of Visual Basic onto a hard disk.
A.
. Invoke Windows. Insert the Primer Edition diskette into one of the drives, say the A drive. . Invoke Window’s Program Manager if it is not already invoked. Press Alt/F/R to execute the Run command from the File menu.
. Type A:\ VBPRIMER\SETUP into the Command Line box. . Press the Enter key or click on the OK button. . After a few seconds a Welcome screen will appear. Press the Enter key to continue.
8. A Location screen will appear. Press the Enter key to use the default directory as displayed. 9. When you are advised that the directory does not yet exist, press the Enter key to allow the creation of the directory. 10. When the Installation Complete screen appears, press the Enter key to proceed and invoke Visual Basic. .
Install the Standard or Professional edition of Visual Basic onto a hard disk.
SS se Pees
1. 2.
-
Invoke Windows Place the first (Setup) Visual Basic diskette into one of the diskette drives, say the A drive. Invoke Window’s Program Manager if it is not already invoked. Press Alt/F/R to execute the Run command from the File menu.
Type A:\SETUP and press the Enter key. Follow the directions given by SETUP.
Invoke Visual Basic after installation.
1.
Invoke Windows.
2. 3.
Invoke Window’s Program Manager if it is not already invoked. Double-click on the Visual Basic icon.
Note: The first time you invoke Visual Basic, the ToolBox may not be visible.
If so, press Alt/W/T to display it. . Exit Visual Basic.
1.
Press the Esc key.
2.
Press Alt/F/X.
3.
If an unsaved program is present, Visual Basic will prompt you about saving it.
Note: In many situations, Step | is not needed. 584
Appendix I — How To (Visual Basic)
HOW A.
Runa
1.
585
TO: Manage Programs program from Visual Basic.
Click on the Run icon (right arrowhead).
Or, 1.
B.
Press Alt/R and make a selection from the Run menu.
Save the current program on a disk. 1.
Press Alt/F/V.
2.
Fill in the requested information. Do not give an extension as part of the project name or the file name. Two files will be created—one with extension .MAK and the other with extension .FRM. The .MAK file holds a list of files related to the project. The .FRM file actually holds the program.
Note: After a program has been saved once, updated versions can be saved under the same name by pressing Alt/F/V. Alt/F/E is used to save the program under a new name. C.
Begin a new program. 1.
Press Alt/F/N.
2.
If an unsaved program is present, Visual Basic will prompt you about saving it.
D.
Open a program stored on a disk. 1.
Press Alt/F/O.
2.
Type a filespec into the top rectangle of the dialog box and press the Enter key. Alternatively, press the Tab key to penetrate the region containing the names of the files on the disk, and then use the direction keys and the Enter key to select one of the listed files. (If an unsaved program is present, Visual Basic will prompt you about saving it.)
Note: The form for the project does not appear, but the title of the Project window shows that the project has been opened. E.
Display the form associated with a program. 1. 2.
FE
Name a program. 1}
G.
Press Alt/W/R to activate the Project window. Click on View Form.
SSaveit.
Save a program as a text file readable by other word processors. 1.
Press Alt/F/A.
2.
Ifthe box preceding the phrase Save as Text is not marked with an X, then click in the box or press Alt+S. Make any other desired changes to the information displayed regarding the saving of this program. Click on Ok. The .FRM file for the program is now a text file.
3. 4.
Appendix I — How To (Visual Basic)
HOW A.
TO: Use the Editor
Mark a section of text as a block.
1. 2.
Move the cursor to the beginning or end of the block. Hold down a Shift key and use the direction keys to highlight a block of text.
3.
Release the Shift key.
Or,
1.
Move the mouse to the beginning or end of the block.
2.
Hold down the left mouse button and move the mouse to the other end of the block. Release the left mouse button.
3.
Note: To unblock text, press a direction key or click outside the block. . Delete a line of a program. 1. 2.
Move the cursor to the line. Press Ctrl+Y.
Or,
1. 2.
Mark the line as a block. (See item A of this section.) Press Shift+Del.
Note: In the maneuvers above, the line is placed in the clipboard and can be retrieved by pressing Shift+Ins. To delete the line without placing it in the clipboard, mark it as a block and press Del. - Move a line within the Code window.
1. 2.
Move the cursor to the line and press Ctrl+Y. Move the cursor to the target location.
3.
Press Shift+Ins.
. Use the clipboard to move or duplicate statements.
1. 2. 3. 4.
Mark the statements as a block. Press Shift+Del to delete the block and place it into the clipboard. Or, press Ctrl+Ins to place a copy of the block into the clipboard. Move the cursor to the location where you desire to place the block. Press Shift+Ins to place a copy of the text from the clipboard at the cursor.
BB
Whe
. Search for specific text in program.
Mm
586
Press Alt/E/E Type sought-after text into rectangle.
Select desired options if different from the defaults. Press the Enter key. To repeat the search, press F3.
Appendix
I — How To (Visual Basic)
587
Search and change.
ON
Press Alt/E/R.
Type sought-after text into first rectangle. Press Tab. Type replacement text into second rectangle. Select desired options if different from the defaults. Press the Enter key.
. Check the syntax of a line.
1. 2. 3.
Move the cursor to the line. Edit the line in some way. For example, type = and then press Backspace. Press the Down Arrow key.
Note: The syntax of a line is automatically checked whenever the cursor is moved off an edited line either by pressing the Enter key or a direction key. . Cancel changes made to a line. 1.
Press Alt/E/U to undo the last set of changes made to the most recently edited line.
Note: A set of changes is all changes made to a line without moving the cursor off the line. Moving the cursor off a line ends the current set of changes and causes the syntax of the line to be checked.
HOW TO: Get Help (Standard and Professional Editions only) A. View the syntax and purpose of a Visual Basic keyword. 1. 2.
Type the word into the Code window. Place the cursor on, or just following, the keyword.
3.
Press Fl.
Or, 1.
Press Alt/H/S
2. 3.
Type in the keyword or term of interest and press the Enter key. Double click on the topic of interest in the second list.
Display an ANSI table. 1. 2. 3.
Press Alt/H/S. Type ANSI and press the Enter key twice. Press the Tab key followed by the Enter key to move between the displays for ANSI characters 0-127 and 128-255.
. Obtain general help on designing a form. 1.
Press Alt/H/C.
2. 3.
Click on Creating the Interface. Click on the topic of interest in the window that appears.
. Obtain general help on setting properties. 1.
Press Alt/H/C.
588
Appendix I — How To (Visual Basic)
2. 3.
E.
Click on Setting Properties. Click on the topic of interest in the window that appears.
Obtain general help on writing and debugging code. 1. Ub Press Alt/H/C.
2. 3. E
Obtain other useful reference information.
1. 2.
G.
Click on Writing and Debugging Code. Click on the topic of interest in the window that appears.
Press Alt/H/C. Click on the topic of interest.
Obtain general information about using the Help menu. 1. 2.
Press Alt/H/C and then press Alt/H/H. Click on the topic of interest.
H. Obtain information about the selections in a pull-down menu. 1. I.
See item D in HOW TO: Manage Menus.
Obtain a list of Visual Basic’s reserved words.
1.
Press Alt/H.
2. 3.
Click on Programming Language in the Reference list. Click on the first letter of the keyword(s) of interest, or use the mouse with the vertical elevator to scroll through the list.
Oe
1. 2.
Place the cursor on a blank line in the Code window and press F1. Proceed as in step 2 above.
Note: To obtain information about a keyword, click on it. When finished, close this window by pressing Alt/F/X J.
Exit Help. 1.
HOW
Press Alt/F/X.
TO: Manipulate a Dialog Box
See Appendix G. In Visual Basic, ( ) becomes a circle, [ ] becomes a square, and becomes a command button.
HOW A.
TO: Manage Menus
Open a pull-down menu. 1.
Click on the menu name.
Or,
1.
Press Alt.
2.
Press the first letter of the name of the menu. Alternatively, use the Right Arrow key to move the highlighted cursor bar to the menu name, then press the Down Arrow key.
Appendix I — How To (Visual Basic)
B.
589
Make a selection from a pull-down menu.
1. 2.
Open the pull-down menu. Click on the desired item.
Or,
1. 2. C.
E.
1.
Press Alt/E
2.
Press the Right Arrow key each time you want to see a new menu.
Close a pull-down menu.
HOW
2.
2. 3.
Mark the section of code as a block as described in the HOW the Editor section. Press Ctrl+Ins.
TO: Use
Hold down the Alt key and repeatedly press the Tab key until Program Manager appears, then release the Alt key. Double click on the Accessories icon. Double click on the Notepad icon.
Display all characters in a font.
WAR wD
1.
D.
TO: Utilize the Windows Environment
Access Windows’ Notepad. 1.
C.
Press the Esc key or click anywhere outside the menu.
Place a section of code in the Windows clipboard. 1.
B.
Press Fle Click on name of the menu of interest. Click on selection of interest.
Look at all the menus in the menu bar.
1.
A.
pull-down menu. One letter in each item that is eligible to be be underlined. underlined letter. Alternatively, use the Down Arrow key to cursor bar to the desired item and then press the Enter key.
Obtain information about the selections in the pull-down menu currently displayed. (Not available with Primer Edition.) ler 2. 3.
D.
Open the used will Press the move the
Hold down the Alt key and repeatedly press the Tab key until Program Manager appears, then release the Alt key. Double click on the Accessories icon. Double click on the Character Map icon. Click on the underlined down arrow at the right end of the Font box. Highlight the desired font and press the Enter key or double click on the desired font.
Display an ANSI or ASCII code for a character with a code above 128.
1.
Proceed as described in item C of this section to display the font containing the character of interest.
Appendix I — How To (Visual Basic)
IE
Click on the character of interest. Displayed at the right end of the bottom line of the font table is Alt+Oxxx, where xxx is the code for the character.
E.
Temporarily go to DOS.
ae
le
OE
590
HOW A.
TO: Design a Form
Display the ToolBox. ile
B.
Hold the Alt key down and repeatedly press the Tab key until Program Manager appears, then release the Alt key. Double click on the Main icon. Double click on the MS-DOS Prompt icon. Enter one or more desired commands at the DOS prompt. Enter EXIT to return to Windows. Hold the Alt key down and repeatedly press the Tab key until Microsoft Visual Basic appears, then release the Alt key.
Press Alt/W/T.
Place a new control on the form.
Option I: (new control with default size and position) ih
2
Double click on the control’s icon in the ToolBox. The new control appears at the center of the form. Size and position the control as described in item H below.
Option II: (a single new control sized and positioned as it is created) ip a 3.
4.
5, 6.
Click on the control’s icon in the ToolBox. Move the mouse to the approximate position on the form desired for the upper-left corner of the control. Press and hold the left mouse button. Move the mouse to the position on the form desired for the lower-right corner of the control. A dashed box will indicate the overall shape of the new control. Release the left mouse button. The control can be resized and repositioned as described below.
Option III: (create multiple instances of the same control) if 2;
3s C.
Click on the control’s icon in the ToolBox while holding down the Ctrl key. Repeatedly use steps 2 through 5 of Option II to create instances of the control. When finished creating instances of this control, click on the arrow icon in the ToolBox.
Create a related group of controls. ibs
a
To hold the related group of controls, place a PictureBox control (top right in ToolBox) on the form. Use Option II or II in item B of this section to place controls on the PictureBox.
Appendix I — How To (Visual Basic)
D.
591
Set the focus to a particular control.
1.
Click on the control.
Or
1. E.
FE.
Delete a control. 1.
Set the focus to the control to be deleted.
2.
Press the Del key.
Delete a related group controls. 1. 2.
G.
2.
3.
3.
Set the focus to the Move the mouse to edge of the control. which points in the Drag to the desired
desired control. one of the eight sizing handles located around the The mouse pointer will change to a double arrow direction that resizing can occur. size.
Set the focus to the form. Move the mouse to the edge or corner of the form that is to be stretched or shrunk. The mouse pointer will change to a double arrow which points in the direction that resizing can occur. Drag to the desired size.
Use the color palette to set foreground and background colors.
1.
Set the focus to the desired control or the form.
2.
Press Alt/W/C to activate the Color Palette.
3.
If the Color Palette obscures the object you are working with, you may wish to use the mouse to grab the Color Palette by its title bar and move it so that at least some of the object shows. To set the foreground color, click on the square within a square at the far left in the Color Palette. To set the background color, click on the region within the outer square but outside the inner square. Click on the desired color from the palette.
4.
5.
HOW A.
the
Change the size of a form.
1. 2.
J.
Move the mouse onto the control, the PictureBox containing related group of controls, or the title of the from. Drag the object to the new location.
Change the size of a control. 1. 2.
I.
Set the focus to the PictureBox holding the related group of controls. Press the Del key.
Move a control, related group of controls, or form to a new location. 1.
H.
Press the Tab key until the control receives the focus.
TO: Work with the Properties of an Object
Activate the Properties window. 1.
Press Alt/W/O.
592
Appendix I — How To (Visual Basic)
Or, 1.
Press F4.
. Highlight a property in the Properties window. 1. 2.
Activate the Properties window and press the Enter key. Use the Up or Down Arrow keys to move the highlight bar to the desired property.
Or,
1. 2.
3.
Activate Click on bar at the is visible. Click on
the Properties window. the up or down arrow located at the ends of the vertical scroll right side of the Properties window until the desired property
the desired property.
. Select or specify a setting for a property. 1. 2.
Highlight the property whose setting is to be changed. Click on the settings box or press Tab to place the cursor in the settings box.
aE a.
b.
c.
Ifa black, underlined down arrow appears at the right end of the settings box. Use the Up or Down Arrow keys to display the allowed settings for the property. When the desired setting is displayed, press the Enter key. Alternatively, click on the down arrow at the end of the settings box to display a list of all allowed settings, then click on the desired setting. If an ellipsis (three periods: . . .) appears at the right end of the settings box. Press F4 or click on the ellipsis to display a dialog box or a color palette. Answer the questions in the dialog box and click on Ok, or click on the desired color in the color palette. If a gray, underlined down arrow appears at the right end of the settings box. Type in the new setting for the property.
Note: The settings box refers to the second box below the title “Properties.” It is preceded by X and check mark icons. . Change a property setting of an object. 1. 2. 3. 4.
Set the focus to the desired object. Activate the Properties window . Highlight the property whose setting is to be changed. Select or specify the new setting for the property.
Let a label change size to accommodate its caption. 1.
Set the label’s AutoSize property to True. (The label will shrink to the smallest size needed to hold the current caption. If the caption is changed, the label will automatically grow or shrink to accommodate the new caption.)
Appendix I — How To (Visual Basic)
593
Let a label caption use more than one line. 1.
Set the label’s WordWrap property to True. (If the label is not wide enough
to accommodate
the entire caption on one line, part of the
caption will wrap to additional lines. If the label height is too small, then part or all of these wrapped lines will not be visible.)
. Let a text box display more than one line.
1.
Set the text box’s MultiLine property to True. (If the text box is not wide enough to accommodate the text entered by the user, the text will scroll down to new lines. If the text box is not tall enough, lines will scroll up out of view, but can be redisplayed by cursoring up.)
. Assign a hot key to a label or command button.
1.
When assigning a value to the Caption property, precede the desired hot key character with an ampersand (&).
Place the initial focus on a particular command button. 1.
Set the command button’s Default property to True.
WR WN
Adjust the order in which the Tab key moves the focus. Set the focus to the first object in the tabbing sequence. Change the setting of the TabIndex property for this object to 1. Set the focus to the next object in the tabbing sequence. Change the setting of the TabIndex property for this object to 2. Repeat steps 3 and 4 until all objects on the form have been assigned a new TabIndex setting.
. Allow the pressing of Esc to activate a particular command button. 1.
Set the command button’s Cancel property to True. (Setting the Cancel property True for one command button automatically sets it False for all other command buttons.)
HOW A.
Access the Code Window.
1.
B.
TO: Manage Procedures
Press the Esc key followed by F7. (It is not always necessary to press the Esc key.)
Look at an existing procedure. 1. 2.
Access the Code Window. Press Ctrl+Down Arrow or Ctrl+Up Arrow repeatedly to cycle through all the procedures.
Or, 1.
Access the Code Window.
2.
Press F2. The top entry is the declarations section of the program and the remaining entries are procedures. Use the direction keys and the Enter key to select the desired procedure.
3.
594
Appendix I — How To (Visual Basic)
C.
Create a procedure. Access the Code Window. Move to a blank line.
Type SUB (for a subprogram) or FUNCTION (for a function) followed by the name of the procedure and any parameters. Press the Enter key. (The Code Window will now display the new procedure heading and an END statement.) Type the procedure into the Code Window.
6. D.
Alter a procedure. L.
Z. E.
2;
3:
Bring the procedure into the Code Window as described in item B of this section. Mark the entire procedure as a block. That is, press Ctrl+Home to move the cursor to the beginning of the procedure, then hold down a Shift key and press Ctrl+End to move the cursor to the end of the procedure. Press the Del key.
Insert an existing procedure into a program.
1. 2. 3. 4. 5. 6. 7.
HOW A.
Bring the procedure into the Code Window as described in item B of this section. Make changes as needed.
Remove a procedure.
Ie
FE.
Access the Code Window. Press Alt/V/N. (A dialog box will appear.) Type the name of the procedure into the Name rectangle. Select the type of procedure (subprogram or function) by clicking on the procedure type or pressing Alt+S for a subprogram or Alt+F for a function. Press the Enter key. (The Code window will now display the new procedure heading and an END statement.) Type the procedure into the Code Window.
Open the program containing the procedure. Bring the procedure into the Code Window as described in item B of this section. Mark the entire procedure as a block. Press Ctrl+Ins to place the procedure into the clipboard. Open the program in which the procedure is to be inserted and access the Code Window. Move the cursor to a blank line. Press Shift+Ins to place the contents of the clipboard into the program.
TO: Manage Windows
Zoom the active window to fill the entire screen.
IW
Click on the maximize (up arrow) button in the upper-right corner of the active window.
Appendix I — How To (Visual Basic)
2.
To return the window to
595
its original size, click on the restore (double
arrow) button that has replaced the maximize button. B.
Move a window.
iE dp
C.
Move the mouse to the title bar of the window. Drag the window to the desired location.
Change the size of a window. i. ee
HOW
Move the mouse to the edge of the window which is to be adjusted or to the corner joining the two edges to be adjusted. When the mouse becomes a double arrow, drag the edge or corner until the window has the desired size. TO: Use the Printer
A. Obtain a printout of a program when using the Primer Edition of Visual Basic.
1.
Save the program in a form readable by other word processors (i.e., in a text file).
2. 3.
Access Windows’ Notepad. Press Alt/F/O to specify a file to open.
4.
If desired, enter *.FRM to see a list of form files saved in the current
5.
6. 7.
B.
directory. Type in the name under which the program is saved, or press the Tab key to penetrate the displayed list of files, then highlight the desired file name. In either case, press the Enter key to open the file. Press Alt/F/P to print the program. Press Alt/F/X to close Notepad, then hold down the Alt key and press the Tab key repeatedly until Microsoft Visual Basic appears, then release the Alt key.
Obtain a printout of a program when using the Standard or Professional Edition of Visual Basic. ibe Me
Press Alt/F/P.
Press the Enter key.
Note: To print just the text selected as a block or the active (current) window, use the direction keys to select the desired option. C.
Obtain a printout of the form during runtime.
it
Place the statement PrintForm in the Form_Click() or other appropriate procedure of the program at the point when the desired output will be on the form.
HOW A.
TO: Use the Debugger
Stop a program at a specified line. 1s toy
Place the cursor at the beginning of the desired line. Press F9. (This highlighted line is called a breakpoint. When the program is run it will stop at the breakpoint before executing the statement.)
Note: To remove this breakpoint, repeat steps 1 and 2.
596
Appendix I — How To (Visual Basic)
B.
Remove all breakpoints. 1.
Press Alt/D/L.
C. Run a program one statement at a time. 1. 2.
Press F8. The first executable statement will be highlighted. Press F8 each time you want to execute the currently highlighted statement.
Note: The Code Window may need to be reduced and/or moved in order to see the output appearing on the form. Also, to guarantee that output is retained while stepping through the program, the AutoRedraw property of the form and any picture boxes may need to be set to True. Run the program one statement at a time, but execute each procedure call without stepping through the statements in the procedure one at a time. 1. 2.
Press Shift+F8. The first executable statement will be highlighted. Press Shift+F8 each time you want to execute the currently highlighted statement.
Continue execution of a program that has been suspended. 1)
(Press. F5.
Note: Each time an attempt is made to change a suspended program in a way that would prevent the program from continuing, Visual Basic displays a dialog box warning that the program will have to be restarted from the beginning and gives the option to cancel the attempted change.
Have further stepping begin at the line containing the cursor (no variables are cleared). 1.
Press Alt/D/N.
Appendix J
Visual Basic Statements, Events,
Functions, Methods, Properties, Data Types, and Operators his appendix applies to the following objects: form, printer, text box, command button, label, and picture box. The last four are also called controls. Terms in brackets follow some of the discussions. These terms refer to supporting topics presented at the end of this appendix.
Abs
See Appendix C.
Alignment The Alignment property of a text box or label affects how the text assigned to the Text property is displayed. If the Alignment property is set to 0 (the default), then text is displayed left justified, if set to 1, then text is right
justified, and if set to 2, then text is centered. And
(Logical Operator) See Appendix C.
And
(Bitwise Operator) See Appendix C.
Asc
Characters are stored as numbers from 0 to 255. If a$ is astring of characters,
then Asc(a$) is the number corresponding to the first character of a$. For any n from 0 to 255, Asc(Chr$(n)) is n.
Atn
See Appendix C.
AutoRedraw The AutoRedraw property determines what happens to graphics and Printed material on a form or picture box after another object (for example, another picture box) temporarily obscures part of the form or picture box. If AutoRedraw is True, then Visual Basic will restore the graphics and Printed material from a copy that it has saved in memory. If AutoRedraw is False, then Visual Basic does not keep track of what graphics and Printed material have been obscured, but does invoke the Paint event of the form or picture box when the obstruction is removed. Thus only graphics and Printed material generated by the Paint event will be restored when AutoRedraw is False.
AutoSize Ifthe AutoSize property of a label is True, then Visual Basic automatically sets the width and height of the label so that the entire caption can be accommodated. If the AutoSize property is False, then the size of the label is not adjusted by Visual Basic, and captions are clipped if they do not fit. BackColor The BackColor property determines the background color of an object. For a Command Button, the background color is the color of the dotted rounded rectangle that surrounds the caption when the command button has the focus. If the BackColor of a form or picture box is changed while a program 597
598
Appendix J — Visual Basic Statements
is running, all graphics and Printed text directly on the form or picture box are erased. BackStyle The BackStyle property of a label is opaque (1) by default. The rectangular region associated with the label is filled with the label’s background color and caption. If the BackStyle is set to transparent (0), then whatever is behind the label remains visible; the background color of the label essentially becomes “see through.” Beep
See Appendix C.
BorderStyle The BorderStyle property determines the type of border on a form, label, picture box, or text box. A BorderStyle of 0 results in no border. This is the default for labels. A BorderStyle of 1 produces a single-line border. This is the default for a picture box or text box. For forms, a BorderStyle of 1 also means that the size of the form cannot be changed by the user when the program is running. For forms, the default BorderStyle is 2 which produces a single-line border and allows the user to change the size of the form when the program is running. Finally, for forms, a BorderStyle of 3 produces a double-line border which cannot be resized by the user. Call
See Appendix C.
Cancel The Cancel property provides a means of responding when the user presses the Esc key. At most one command button on a form may have its Cancel property set to True. If the Esc key is pressed while the program is running, then Visual Basic will execute the click event procedure of the command button whose Cancel property is True. Caption The Caption property holds the text which is to appear as the caption for a form, command button, or label. If an ampersand (&) is placed in the caption of acommand button or label, then the ampersand will not be displayed, but the character following the ampersand will become a hot key. Hot keys provide a quick way to access a command button or the control (usually a text box) following (in tab index order) a label. Hot keys are activated by holding down the Alt key and pressing the hot key character.
CCur The function CCur converts integer, long integer, single-precision, and double-precision numbers to currency numbers. If x is any number, then the value of CCur(x) is the currency number determined by x. CDbl
ChDir
See Appendix C.
See Appendix C.
ChDrive The statement ChDrive drive$ changes the default drive to the drive specified by drive$. For example, ChDrive “A” specifies the A drive as the new default drive. Chr$ If n is a number from 0 to 255, then a statement of the form objectName.Print Chr$(n) displays the nth character of the current font.
CInt
See Appendix C.
Circle The graphics method objectName.Circle (x,y),7,c,r1,r2,a draws on objectName a portion, or all, of an ellipse as describe for the Circle statement in
Appendix C. If k is a number corresponding to one of the 16 standard colors
Appendix J — Visual Basic Statements
599
listed in footnote [5] of Appendix C, then using QBColor(k) for c will produce
an ellipse in color k. In general, c may be any valid RGB color. [color] Clear The method ClipBoard.Clear clears the clipboard, setting its contents to the null string. Click The Click event applies to command buttons, picture boxes, labels, and forms. A Click event occurs whenever the left mouse button is pressed and released while the mouse cursor is over the control, or over a blank area on the form. In the case of a command button, the Click event is also called if the
spacebar is pressed while the command button has the focus, or if the button’s access key is used. CLng
See Appendix C.
Close
See Appendix C.
Cls The method formName.Cls clears the form formName of all text and graphics which have been placed directly on the form with methods like formName.Print, formName.Circle, etc. The method pictureBox.Cls clears the named picture box. The Cls method resets the CurrentX and CurrentY properties of the cleared object to the coordinates of the upper left corner (usually
(0,0)). Const
See Appendix C.
Control The Control data type may be used in the parameter lists of Sub and Function definitions to allow the passing of control names to the procedure. ControlBox The ControlBox property determines whether or not a form has a ControlBox button in the upper left corner. If the ControlBox property is set to True (the default), then the ControlBox button is displayed. Among the opera-
tions available from the ControlBox menu is the ability to close the form and thereby end the program. If the ControlBox property of a form is set to false, then the ControlBox button is not displayed. Since, in this case, the user cannot end the program using the ControlBox or by pressing Alt+F4, it is important to provide a command button for this purpose.
Cos CSng
See Appendix C. See Appendix C.
CStr The function CStr converts integer, long integer, single-precision, double-precision, currency, and variant numbers to strings. If x is amy number, then the value of CStr(x) is the string determined by x. Unlike the Str$ function,
CStr does not place a space in front of positive numbers. [variant] CurDir$
The value of the function CurDir$(drive$) is a string specifying the
current directory on the drive specified by drive}. The value of CurDir$(“”) or CurDir$ is a string specifying the current directory on the default drive. Currency The currency data type is extremely useful for calculations involving money. A variable of type Currency requires 8 bytes of memory and can hold any number from —922,337,203,685,477.5808 to 922,337,203,685,477.5807 with at most four decimal places. Currency values and variables are indicated by the type tag @: 21436587.01@, Balance@.
600
Appendix J — Visual Basic Statements
CurrentX, CurrentY The properties CurrentX and CurrentY give the horizontal and vertical coordinates of the point on a form or picture box at which the next Print or graphics method will begin. Initially, CurrentX and CurrentY are the coordinates of the upper left corner of the form or picture box. The default coordinate system defines the upper left corner of the form or picture box as (0,0), with x increasing from left to right and y increasing from top to bottom in twips. After a graphics method, (CurrentX, CurrentY) are the coordinates of
the last point referenced. CVDate The function CVDate converts a numeric or string expression to an equivalent serial date. If x is any expression representing a valid date, then the value of CVDate(x) is the serial date determined by x. Valid numeric values are —657434 (January 1, 100 AD.) to 2958465 (December 31, 9999). Valid string
expressions either look like one of these valid numeric values (e.g. “19497” corresponding to May 18, 1953) or look like a date (e.g., “10 Feb 1955”, “August 13, 1958”, etc.) [date]
CVar The function CVar converts strings and integer, long integer, single-precision, double-precision, and currency numbers to variants. If x is any string or number, then the value of CVar(x) is the variant determined by x. [variant]
Date$
See Appendix C.
DateSerial The value of the function DateSerial(year,month,day) is the serial date corresponding to the given year, month, and day. Values from 0 to 9999 are acceptable for year, with 0 to 99 interpreted as 1900 to 1999. Values of 1 to 12
for month, and 1 to 31 for day are normal, but any Integer value is acceptable. Often, numeric expressions are used for month or day which evaluate to numbers outside these ranges. For example, DateSerial(1993, 2, 10 + 90) is the date 90 days after Feb. 10, 1993. [date] DateValue
The value of the function DateValue(a$)
is the serial date corre-
sponding to the date given in a$. DateValue recognizes the following date formats: “2-10-1955”,“2/10/1955”, “February 10, 1955”, “Feb 10, 1955”, “10-Feb1955”, and “10 February 1955”. For the years 1900 through 1999, the initial “19” is optional. [date]
Day The function Day extracts the day of the month from a serial date. If d is any valid serial date, then the value of Day(d) is an integer from 1 to 31 giving the day of the month recorded as part of the date and time stored in d. [date] DblClick The DblClick event applies to picture boxes, labels, and forms. A DblClick event occurs whenever the left mouse button is pressed and released twice, in quick succession, while the mouse cursor is over the control, or over a
blank area on the form. Double-clicking on an object will first cause that object’s Click event to occur, followed by its DblClick event.
Default When the Default property of a command button is set to True and the focus is on an object that is not another command button, then pressing the Enter key has the same effect as clicking on the button. At most one command button on a form can have True as the value of its Default property.
DefInt, DefLng, DefSng, DefDbl, DefStr, DefCur, DefVar See Appendix C for a general discussion of DefType statements. The statements DefCur and
Appendix J] — Visual Basic Statements
601
DefVar specify which starting letters for the names of variables are to identify the default variable types currency and variant respectively. DefType statements are placed in the declarations section of (general). [variant]
Dim See Appendix C for a general discussion of Dim. Visual Basic also permits currency and variant variables. Variables and arrays Dimmed in the declarations section of (general) are available to all procedures. In procedures, Dim may be used to declare variables, but ReDim must be used to dimension arrays. [variant] Dir$ If fileTemplate$ then the value of the matching the pattern then the value of the
specifies function specified function
a file (or a collection of files by including ? or *), Dir$(fileTemplate$) is the filespec of the first file by fileTemplate$. If this value is not the null string, Dir$ is the next file that matches the previously
specified pattern. For example, the value of Dir$(“*.BAS”) will be a string specifying the first file in the current directory of the default drive whose name
has the .BAS extension.
Do/Loop
See Appendix C.
DoEvents Executing the statement DoEvents permits Visual Basic to act upon any events which may have occurred while the current event procedure has been executing.
Double
See Appendix C.
DrawMode
The property DrawMode determines whether graphics are drawn
in black, white, foreground color, or some interaction of these colors with the
current contents of the form or picture box. The following table lists the allowed values for the DrawMode property and the rules for what RGB color number will be assigned at a given point when the RGB color number for the color currently displayed at that point is display and the RGB color number for the draw color is draw. [color] DrawMode
Color produced
1
&HO00000000& (Black)
2
Not draw And Not display
3
display And Not draw
(inverse of #14)
4
Not draw
(inverse of #13)
5
draw And Not display
(inverse of #12)
6
Not display
(inverse of #11)
7
draw Xor display
8
Not draw Or Not display
7
draw And display
—_ (inverse of #15)
(inverse of #9)
10
Not (draw Xor display)
(inverse of #7)
11
display
(transparent)
12
display Or Not draw
13
draw
14
draw Or Not display
15
draw Or display
16
SHOOFFFFFF& (White)
(draw color)
602
Appendix J — Visual Basic Statements
DrawStyle
When DrawWidth is 1 for a form or picture box (the default), the
property DrawStyle determines whether graphics are drawn using a solid line or some combinations of dots and dashes. Use a DrawStyle of 0 (the default) for solid lines, 1 for dashed lines, 2 for dotted lines, 3 for dash-dot lines, or 4 for
dash-dot-dot lines. A DrawStyle of 5 produces “invisible” graphics. When thick lines are drawn as a result of setting Draw Width to values greater than 1, graphics are always drawn using solid lines. In this case, DrawStyle can be used to either center the thick line over where line with a DrawWidth of 1 would be drawn or, when drawing closed figures like ellipses and rectangles, to place the thick line just inside where the line with a Draw Width of 1 would be drawn. To draw thick graphics inside the normal closed figure, use a DrawStyle of 6. DrawStyles | through 4 will center thick graphics over the normal location. DrawWidth The property DrawWidth determines the width in pixels of the lines which are drawn by graphics methods. The default is 1 pixel. Values from 1 to 32,767 are permitted.
Enabled The property Enabled determines whether or not a form or control responds to events. If the Enabled property of a form or control is set to True (the default), then if an event occurs for which an event procedure has been
written, then the event procedure will be executed. When the Enabled property of a form or control is set to False, all events relating to that control are ignored;
no event procedures are executed. End
See Appendix C.
EndDoc
The method Printer.EndDoc is used to indicate that the document
currently being printed is complete and should be released to the printer.
Environ$
See Appendix C.
Eof See Appendix C. Eqv Erase
See Appendix C. See Appendix C.
Err and Erl Err Error
(Functions) See Appendix C.
(Statement) See Appendix C. See Appendix C.
Error$ The value of the function ERROR$ is the error message corresponding to the run-time error which has most recently occurred. The value of the function ERROR$(errnum) is the error message corresponding to the run-time error designated by errnum. Exit
See Appendix C.
Exp
See Appendix C.
False A predefined constant whose value is 0. False is used when setting the value of properties that are either True or False. For example, Picturel.FontlItalic = False. FileAttr
See Appendix C.
Appendix J — Visual Basic Statements
FileCopy
603
The statement FileCopy source$, destination$ creates the file specified
by destination$ by making a copy of the file specified by source$. Both source$ and destination$ may specify drive and path information. If the file specified by destination$ already exists, it will be overwritten without a warning being issued. FileDateTime
The value of the function FileDateTime(filename$)
is a string
giving the date and time that the file specified by filename$ was created or last modified. FileLen The value of the function FileLen(filename$) is the length in characters (bytes) of the file specified by filename$.
FillColor When the FillStyle property of a form or picture box is set to a value other than the default of 1, the property FillColor determines what color is used to paint the interior of ellipses and rectangles drawn with the Circle and Line graphics methods. The FillColor property may be set using the QBColor function or any valid RGB color. The default value for FillColor is black (0). [color]
FillStyle The property FillStyle determines what pattern is used to paint the interior of ellipses and rectangles drawn on forms or picture boxes with the Circle and Line methods. The default value for FillStyle is transparent (1), which
means that interiors are not painted. Other values available for FillStyle are solid (0), horizontal lines (2), vertical lines (3), diagonals running upwards to the
right (4), diagonals running downwards to the right (5) vertical and horizontal lines [cross hatched] (6), and diagonal cross hatched (7). Note: Using BF in a
Line method has the same effect as setting the FillStyle to 0 and the FillColor to the color of the bordering line. Fix
See Appendix C.
FontBold The property FontBold determines whether or not the characters Printed on a form, picture box, or printer, or assigned to a text box, command button, or label appear in bold or normal type. If the FontBold property is set to True (the default), then for a form, picture box, or printer, subsequent Printed characters appear bold. For a text box, command button, or label, the text or caption is immediately changed to bold. If the FontBold property is set to False, then subsequent characters are Printed in normal type while characters assigned to the text or caption property change immediately to normal type. FontCount The value available for use on Printer.FontCount is FontCount property is ally used to determine
of the property Screen.FontCount is the number of fonts the screen. Similarly, the value of the property the number of fonts available on the printer. The set according to your Windows environment, and generthe limit on the index for the Fonts property.
FontlItalic The property FontItalic determines whether or not the characters Printed on a form, picture box, or printer, or assigned to a text box, command button, or label appear in italic or upright type. If the Fontltalic property is set to True, then for a form, picture box, or printer, subsequent characters appear in italic. For a text box, command button, or label, the text or caption is immediately changed to italic. If the Fontltalic property is set to False (the default), then subsequent characters are Printed in upright type while characters assigned to the text or caption property change immediately to upright type.
604
Appendix J — Visual Basic Statements
FontName The property FontName determines what type face is used when characters are Printed on a form, picture box, or printer, or assigned to a text box, command button, or label. If the FontName property of a form, picture box, or printer is set to a font obtained from the Fonts property, then all subsequently Printed characters will appear in the new type face. When the FontName property of a text box, command button, or label is set to a new font, characters assigned to the text or caption property change immediately to the new type face. Fonts The value of the property Screen.Fonts(fontNum) is the name of a screen font available in the current Windows environment. The index fontNum can range from 0 to Screen.FontCount—1. Similarly, the value of the property Printer.Fonts(fontNum) is the name of an available printer font. The values in the Fonts property are set by your Windows environment, and are generally used to determine which fonts are available for setting the FontName property. FontSize The property FontSize determines the size, in points, of characters Printed on forms, picture boxes, and the printer or displayed in text boxes and on command buttons and labels. Available font sizes depend on your Windows environment, but will always be between 1 and 2048. Default font sizes are usually between 8 and 12 point. Note: One point equals 1/72nd of an inch. FontStrikeThru The property FontStrikeThru determines whether or not the characters Printed on a form, picture box, or printer, or assigned to a text box, command button, or label appear in a strikethru or standard font. If the FontStrikeThru property is set to True, then for a form, picture box, or printer, subsequent Printed characters appear with a horizontal line through the middle of each character. For a text box, command button, or label, the text or caption
is immediately changed so that a horizontal line goes through the middle of each character. If the FontStrikeThru property is set to False (the default), then subsequent characters are Printed in standard type while characters assigned to text or caption property change immediately to standard type.
FontTransparent The property FontTransparent determines the degree to which characters Printed to forms and picture boxes obscure existing text and graphics. If the FontTransparent property is set True (the default), the existing text and graphics is only obscured by the dots (pixels) needed to actually form the new character. If the FontTransparent property is set False, then all text and graphics are obscured within the character box (small rectangle surrounding a character) associated with the new character. Those dots (pixels) not needed to
form the character are changed to the background color. FontUnderline The property FontUnderline determines whether or not the characters printed on a form, picture box, or printer, or assigned to a text box, command button, or label appear with an underline. If the FontUnderline property is set to True, then for a form, picture box, or printer, subsequent characters Printed appear underlined. For a text box, command button, or label, the text or caption is immediately changed to underlined. If the FontUnderline property is set to False (the default), then subsequent characters are Printed
without underlines while characters assigned to the text or caption property change immediately to non-underlined. For/Next
See Appendix C.
Appendix J — Visual Basic Statements
605
ForeColor The property ForeColor determines the color used to display text, captions, graphics, and Printed characters. If the ForeColor property of a form or picture box is changed, then subsequent characters will appear in the new color. For a text box, command button, or label, then immediately changed to the new color. [color]
text or caption
is
Format$ The value of the function Format$(expression, a$) is a string representing expression (a number, date, time, or string) formatted according to the
tules given by a$. Format$ is useful when assigning values to the Text property and when Printing to a form, picture box, or the printer. Numeric output can be formatted with commas, leading and trailing zeros, preceding or trailing signs (+ or —), and exponential notation. This is accom-
plished either by using for af the name of one of several predefined numeric formats or by combining in af one or more of the following special numeric formatting characters: #, 0, decimal point (period), comma, %, E-, and E+. The
expression to be formatted can evaluate to one of the numeric types or a string representing a number. Predefined numeric formats include “General Number” which displays a number as is; “Currency” which displays a number with a leading dollar sign, commas every three digits to the left of the decimal, displays two decimal places, and encloses negative numbers in parentheses; “Fixed” which displays two digits to the right and at least one digit to the left of the decimal point; “Standard” which displays a number with commas and two decimal places but does not use parentheses for negative numbers; “Percent” which multiplies the value by 100 and displays a percent sign after two decimal places; and “Scientific” which displays numbers in standard scientific notation. For example, Format$(5432.352, “Currency”) gives the string “($5,432.35)”.
The symbol # designates a place for a digit. If the number being formatted does not need all the places provided by the #’s given in a$, then the extra #’s are ignored. The symbol 0, like #, designates a place for a digit. However, if the number being formatted does not need all the places provided by the 0’s given in a$, then the character 0 is displayed in the extra places. If the number being converted has more whole part digits than there is space reserved by #’s and 0’s, then additional space is used as if the format string had more #’s at its beginning. For example, Format$(56, “####”) yields “56”, Format$(56, “#”) yields “56”, Format$(0, “#”) yields “’, Format$(56, “O000”) yields “0056”, Format$(56, “O”) yields “56”, and Format$(0, “O”) yields “O”. The decimal point symbol (.) marks the location of the decimal place. It
separates the format rules into two sections, one applying to the whole part of the number and the other to the decimal part. When included in the format string, a decimal point will always appear in the resulting string. For example, Format$(56.246, “#.4#”) yields “56.25”, Format$(.246, “#.##”) yields “.25”, Format$(.246, “O.#¥#”) yields “0.25”, and Format$(56.2, “0.00”) yields “52.20”. The comma symbol (,) placed to the left of the decimal point between #’s
and/or 0’s causes commas to be displayed to the left of every third digit to the left of the decimal point, as appropriate. If commas are placed to the immediate left of the decimal point (or to the right of all #’s and 0’s when the decimal point symbol is not used), then before the number is formatted, it is divided by 1000 for each comma, but commas will not appear in the result. In order to divide by 1000s and display commas in the result, use format strings like “#,#,.00”, which
606
Appendix J] — Visual Basic Statements
displays the number with commas in units of thousands, and “#,#,,.00”, which
displays the number with commas in units of millions. For example, Format$(1234000, “#,#”) yields “1,234,000”, Format$(1234000, “#,”) yields “1234”, Format$(1234000, “#,.”) yields “1234.”, Format$(1234000, “#,,.0”) yields “1.2”, and Format$(1234000, “#,0,.0”) yields “1,234.0”.
The percent symbol (%) placed to the right of all #’s, 0’s, and any decimal point causes the number to be converted to a percentage (multiplied by 100) before formatting and the symbol % to be displayed. For example, Format$(.05624, “#.##%”) yields “5.62%”, and Format$(1.23, “#%”) yields “123%”.
The symbols E+ and E- placed to the right of all #’s, 0’s, and any decimal point causes the number to be displayed in scientific notation. Places for the digits in the exponent must be reserved to the right of E+ or E— with #’s or O's. When E+ is used and the exponent is positive, a plus sign appears in front of the exponent in the result. When E- is used and the exponent is positive, no sign or space precedes the exponent. When scientific notation is used, each position reserved by #’s to the left of the decimal point is used whenever possible. For example, Format$(1234.56, “#.##E+##”) yields “1.23E+3”, Format$(1234.56, “aH ##E—##”) yields “12.34E2”, Format$(1234, “###.00E+##”) yields “123.40E+1”, and Format$(123, “#4*E+00”) yields “123E+00”.
Date & time output can be formatted using numbers or names for months, putting the day, month, and year in any order desired, using 12 hour or 24 hour notation, etc. This is accomplished either by letting a$ be the name one of several predefined date/time formats or by combining in a$ one or more special date/time formatting characters. The expression to be formatted can evaluate to a number which falls within the range of valid serial dates or to a string representing a date/time. Predefined date/time formats include “General Date” which displays a date in mm/dd/yyyy format and, if appropriate, a time in hh:mm:ss PM format; “Long Date” which displays the day of week, the full name of month, the day, and a four digit year; “Medium Date” which displays the day, abbreviated month name,
and two digit year; “Short Date” which displays mm/dd/yy“; ”Long Time“ which displays the time in hh:mm:ss PM format; "Medium Time“ which displays time in hh:mm PM format; and ”Short Time which display time in 24 hour format as hh:mm. For example, let dt = DateSerial(55,2,10) + TimeSerial(21,45,30). Then Format$(dt, “General Date”) yields “2/10/55 9:45:30 PM”, Format$(dt, “Medium Date”) yields “10-Feb-55”, and Format$(dt, “Short Time”) yields
2145". Format symbols for the day, month, and year include d (day as number but no leading zero), dd (day as number with leading zero), ddd (day as three letter name), dddd (day as full name), m (month as number but no leading zero), mm (month as number with leading zero), mmm (month as three letter name),
mmmm (month as full name), yy (year as two-digit number), and yyyy (year as four-digit number). Separators such as slash, dash, and period may be used as desired to connect day, month, and year symbols into a final format. For example, Format$(“August 13, 1958”, “dddd, d.mmm.yy”) yields “Wednesday, 13.Aug.58” and Format$(“July 4, 1776”, “ddd: mmmm dd, yyyy”) yields “Thu: July 04, 1776”. Additional format symbols for dates include w (day-of-week as number 1-7), ww
(week-of-year as number 1-53), q (quarter-of-year as number 1-4), y (day-of-year as number 1-366), ddddd (same as short date), and dddddd (same as long date).
Appendix J — Visual Basic Statements
607
Format symbols for the second, minute, and hour include s (seconds with no leading zero), ss (seconds as two-digit number), n (minutes with no leading zero), nn (minutes as two-digit number), h (hours with no leading zero), hh (hours as two-digit number), AM/PM (use 12 hour clock and uppercase), am/pm (use 12 hour clock and lowercase), A/P (use 12 hour clock and single uppercase letter), a/p (use 12 hour clock and single lowercase letter), and ttttt (same as general date). Separators such as colons and periods may be used as desired to connect hour, minute, and second symbols into a final format. For example, Format$ (“14:04:01”, “h:nn AM/PM”) yields “2:04 PM”, Format$(“14:04:01”, “h.n.s”) yields “14.4.1”, and Format$(0.75, “h:nna/p”) yields “6:00p”.
String output can be formatted as all uppercase, all lowercase, left-justified or right justified. Symbols used to format strings are @ (define a field for at least as many characters as there are @ symbols; if less characters than @ symbols, fill remainder of field with spaces; if more characters than @ symbols, display the extra characters—don'’t clip), & (reserve space for entire output string), < (convert all characters to lowercase before displaying), > (convert all characters to uppercase before displaying), ! (left justify within field defined by @ symbols; default is to right justify). For example, Format$(“Red”, “@”) yields “Red”, Format$(“Red”, “@@@@@@"”) yields“ — Red” (3 leading spaces), Format$(“Red”, _” (3 trailing spaces), and Format$(“Red”, “@@@@@@") yields “RED
yields “red”. FreeFile
Function
See Appendix C.
See Appendix C.
Get (Files) See Appendix C. Note: The buffer method of working with random-access files is not available in Visual Basic. GetAttr
The value of the function GetAttr(filename$) is a number indicating
the file attributes associated with the file specified by filename$. Let attrib be a variable holding the value returned by GetAttr. Then the file specified by filename$ is a read-only file if attrib And 1 = 1, is a hidden file if attrib And 2 = 2, is a system file if attrib And 4 = 4, is a volume label if attrib And 8 = 8, is a
directory name if attrib And 16 = 16, or has been modified since the last back-up if attrib And 32 = 32.
GetText The value of the method ClipBoard.GetText is a string containing a copy of the data currently stored in the clipboard. GoSub See Appendix C. Note: Both the GoSub statement and its target must be in the same procedure. GotFocus The GotFocus event applies to command buttons, text boxes, and picture boxes. A GotFocus event occurs when an object receives the focus, either through a user action or through code, via the SetFocus method.
GoTo See Appendix C. Note: The GoTo statement and its target must be in the same procedure.
Height The property Height determines the vertical size of an object. Height is measured in units of twips. For the Printer object, Height may be read (ph = Printer.Height is OK) but not assigned (Printer.Height = 100 causes an error).
Hex$
See Appendix C.
608
Appendix J — Visual Basic Statements
Hour The function Hour extracts the hours from a serial date. If d is any valid serial date, then the value of Hour(d) is a whole number from 0 to 23 indicating the hours recorded as part of the date and time store in d. [date]
If (single line)
See Appendix C.
See Appendix C.
If (block)
If TypeOf To test for the type of a control when the control name is passed to a procedure, use If TypeOf controlName Is controlType Then action! Else action2 in either the single line or block form of the If statement. Elself TypeOf is also permitted. For controlType, use one of the control names which appear in the Form Design ToolBox (CommandButton, Label, TextBox, etc.) For example, If
TypeOf objectPassed Is Label Then... . Imp
See Appendix C.
Input#
See Appendix C.
Input$ The statement a$ = Input$(n,m) assigns the next n characters from the file with reference number m to a.
InputBox$ The value of the function InputBox$(prompt$) is the string entered by the user in response to the prompt given by prompt$. The InputBox$ function automatically displays the prompt, a text box for user input, an OK button, and a Cancel button in a dialog box in the center of the screen. If the user selects Cancel, the value of the function is the null string (“”). For greater control, use the function InputBox$(prompt$, title}, default$, xpos, ypos) which titles the dialog box with title$, displays default$ as the default value in the text box, and
positions the upper left corner of the dialog box at coordinates (xpos, ypos) on the screen. Instr See Appendix C. Int See Appendix C. Integer
See Appendix C.
IsDate
The
value of the function IsDate(a$)
is True
(-1)
if the string a$
represents a date between January 1, 100 and December 31, 9999. Otherwise, the value is False (0). [date] IsEmpty
The value of the function IsEmpty(v) is True (-1) if v is a variable of
unspecified type (i-e., is a variant) which has not yet been assigned a value. In all other cases the value of IsEmpty is False (0). [variant] IsNull
The value of the function IsNull(v) is True (-1) if v is a variant variable
which has been assigned the special value Null. In all other cases the value of IsNull is False (0). [variant]
IsNumeric
The value of the function IsNumeric(v) is True (—1)
if v is a number,
numeric variable, or a variant variable which has been assigned a number or a string which could be obtained by Formatting a number. In all other cases the value of IsNumeric is False (0). [variant]
KeyPress The KeyPress event applies to command buttons, text boxes, and picture boxes. A KeyPress event occurs whenever the user presses a key while one of the above controls has the focus. A code identifying which key was pressed
Appendix J] — Visual Basic Statements
609
will be passed to the event procedure in the KeyAscii parameter. This information can then be used to determine what action should be taken when a given key is pressed.
Kill See Appendix C.
LBound
See Appendix C.
LCase$
See Appendix C.
Left The property Left determines the position of the left edge of a form or control. The units of measure are twips for forms. The units of measure for a control are determined by the ScaleMode property of the container (form, picture box, etc.) upon which the control has been placed, with the position of
the control measured from the edge of its container using the coordinate system established by the various Scale. . . properties for the container. By default, the unit of measure for a container is twips, with a value of O for the Left property placing the control against the left edge of the container. Left$ Len
See Appendix C. See Appendix C. If var is a variant variable, then Len(var) is the number
of bytes needed to store var as a string. [variant] Let Line
See Appendix C. The graphics method objectName.Line (x1,y1)—(x2,y2),c,rect,s draws a line
or rectangle on objectName as describe for the Line statement in Appendix C. If k is a number corresponding to one of the 16 standard colors listed in footnote [5] of Appendix C, then using QBColor(k) for c will produce a line or rectangle in color k. In general, c may be any valid RGB color. [color] Line Input#
See Appendix C.
Load The Load event applies only to forms and occurs only once, immediately when a program starts. This is the appropriate place to put code that should be executed every time a program is run, regardless of the user’s actions. LoadPicture The statement objectName.Picture = LoadPicture(pictureFile$), where objectName is a form or picture box, places the picture defined in the file
specified by pictureFile$ on objectName
Loc Lock
See Appendix C. See Appendix C.
Lof
See Appendix C.
Log
See Appendix C.
Long
See Appendix C.
LostFocus The LostFocus event applies to command buttons, text boxes, and picture boxes. A LostFocus event occurs when an object loses the focus, either through a user action or through code, via the SetFocus method. LSet
Ifa$ is astring variable, then the statement LSet a$ = b$ replaces the value
of a$ with a string of the same length consisting of b$ truncated or padded on the right with spaces. LSet also can be used to assign a record of one user-defined type to a record of a different user-defined type.
610
Appendix J — Visual Basic Statements
LTrim$
See Appendix C.
MaxButton The MaxButton property determines whether or not a form has a maximize button in the upper right corner. If the value of the MaxButton property is set to True (the default), a maximize button is displayed when the program is run. The user then has the option to click on the maximize button to cause the form to enlarge and fill the entire screen. If the value of the MaxButton property is set to False, then the maximize button is not displayed when the program is run, and the user is thus unable to “maximize” the form. MaxLength The property MaxLength determines the maximum number of characters that a text box will accept. If the MaxLength property for a text box is set to 0 (the default), then an unlimited number of characters may be entered in the text box.
Mid$
See Appendix C.
MinButton The MinButton property determines whether or not a form has a minimize button in the upper right corner. If the value of the MinButton property is set to True (the default), a minimize button is displayed when the program is run. The user then has the option to click on the minimize button to cause the form to be replaced by a small icon at the bottom of the screen. If the value of the MinButton property is set to False, then the minimize button is not displayed when the program is run, and the user is thus unable to “minimize” the form.
Minute The function Minute extracts the minutes from a serial date. If d is any valid serial date, then the value of Minute(d) is a whole number from 0 to 59 giving the minutes recorded as part of the date and time stored in d. [date] MkDir Mod
Month
See Appendix C. See Appendix C.
The function Month extracts the month from a serial date. If d is any
valid serial date, then the value of Month(d)
is a whole number from 1 to 12
giving the month recorded as part of the date and time stored in d. [date]
MousePointer The property MousePointer determines what shape the mouse pointer takes when the mouse is over a particular form or control. Valid values for the MousePointer property are whole numbers from 0 to 12. A value of 0 (the default) indicates that the mouse pointer should take on the normal shape for the control it is over. (The normal shape over text boxes is an I-beam, while for a form, picture box, label, or command button it is an arrow.) Use a MousePointer value of 1 for an arrow, 2 for cross-hairs, 3 for an I-beam, 4 for a small square
within a square, 5 for a four-pointed arrow, 6 for a double arrow pointing up to the right and down to the left, 7 for a double arrow pointing up and down, 8 for a double arrow pointing up to the left and down to the right, 9 for a double arrow pointing left and right, 10 for an up arrow, 11 for an hourglass, and 12 for a “do not” symbol (circle with diagonal line). Move The control so positioning positioning
method objectName.Move xpos, ypos moves the named form or that its upper left corner has coordinates (xpos, ypos). For forms, is relative to the upper left corner of the screen. For controls, is relative to the upper left corner of the form, frame, or picture box
Appendix J — Visual Basic Statements
611
to which the control is attached. The method objectName.Move xpos, ypos, width,
height also resizes the named form or control to be width units wide and height units high. The Move method may be used whether or not a form or control is visible. If you wish to specify just a new width for an object, you CANNOT use objectName.Move ,,width. Instead, use objectName.Move objectName.Left, object-
Name.Top, width. Similar considerations apply for changing just ypos, height, width and height, etc. MsgBox
(Statement and Function) The statement MsgBox(message$) displays
message$ in a dialog box with an OK button. The more general statement MsgBox(message$, buttons, title$) displays message$ in a dialog box titled with title$ and containing from one to three buttons as determined by the value of buttons. The value of buttons also determines which button is the default (has the focus) and which if any of 4 icons is displayed. The value to use for buttons can be computed as follows: buttons = set number + default number + icon number
where set number, default number and icon number are determined from the following tables: Buttons Set
Set Number
OK OK, Cancel Abort, Retry, Ignore Yes, No, Cancel Yes, No
0 1 2 3 4
Retry, Cancel
5
Focus Default
Default Number
First Button Second Button Third Button
@) 256 Sly
Icon
Icon Number
Stop sign Question mark
16 32
Exclamation mark Information
48 64
The value of the function MsgBox(message$, buttons, title$) indicates which of the displayed buttons the user pushed; in all other aspects the MsgBox statement
and function act in the same manner. The values returned for each of the possible buttons pressed are | for OK, 2 for Cancel (or Esc), 3 for Abort, 4 for Retry, 5
for Ignore, 6 for Yes, and 7 for No. MultiLine The property MultiLine determines whether or not a text box can accept and display multiple lines. If the MultiLine property of a text box is set to True, then text entered in the text box will wrap to a new line when the right side of the text box is reached. Pressing the Enter key will also start a new line. If the MultiLine property of a text box is set to False (the default), then input is restricted to a single line which scrolls if more input is entered than can be displayed within the width of the text box.
612
Appendix J — Visual Basic Statements
Name (Property) The property Name is used at design time to give a meaningful name to a form or control. This new name will then be used by Visual Basic in naming all event procedures for the form or control. Name (Statement) See Appendix C. NewPage
The method Printer.NewPage
indicates that the current page of
output is complete and should be sent to the printer. A form feed (Chr$(12))
will also be sent to the printer to cause the paper to advance to the top of a new page. Not
(Logical Operator) See Appendix C.
Not
(Bitwise Operator) See Appendix C.
Now
The value of the function Now() is the serial date for the current date and
time as recorded on the computer’s internal clock. [date]
Oct$
See Appendix C.
On Error See Appendix C. Note: The On Error statement and its target must be in the same procedure. On. . .GoSub and On. . .GoTo See Appendix C. Note: The On. . .GoSub or On. . .GoTo statement and its target must be in the same procedure. Open
See Appendix C.
Option Base
See Appendix C.
Option Compare
The statement Option Compare Text, placed in the declara-
tions section of (general), causes string comparisons to be case insensitive. Thus,
if Option true. The produces character
Compare Text is in effect, the comparison “make” = “MaKe” will be statement Option Compare Binary placed in the declarations section the default comparison rules which are case sensitive and use the order given in the ANSI/ASCII character tables.
Option Explicit
If the statement Option Explicit appears in the declarations
section of (general), then each variable must be declared before it is used. A
variable is declared by appearing in a Const, Dim, Global, ReDim, or Static statement, or by appearing as a parameter in a Sub or Function definition. Or
(Logical Operator) See Appendix C.
Or
(Bitwise Operator) See Appendix C.
Picture The property Picture allows a form or picture box to be assigned a picture or icon for display. If iconOrPicture is a file defining an icon or bitmapped picture, then objectName.Picture = LoadPicture(iconOrPicture) places the icon
or picture on the form or picture box identified by objectName. Point The value of the method objectName.Point(x,y) is the RGB number of the color of the point with coordinates (x,y) on the form or picture box identified
by objectName. Thus if the point with coordinates (x,y) has been painted using color RGB(7,g,b), then the value of Point(x,y) will be r+256*g+65536*b. If the
coordinates (x,y) identify a point which is not on objectName, then the value of Point(x,y) will be —1. [color]
Appendix J — Visual Basic Statements
613
Print The method objectName.Print displays information on the form, printer, or picture box identified by objectName in much the same manner as described for the Print statement in Appendix C. In Visual Basic, there is no limit to the number of characters or the number of print zones on a line. Printer The Printer object provides access to the printer. Methods available are Print to send text to the printer, NewPage to execute a form feed to begin a new
page, EndDoc to terminate the printing process, and the graphics methods. Many properties available for forms and picture boxes, such as fonts and scaling, are also available for the printer.
PrintForm The method formName.PrintForm prints on the printer an image of the named form and all its contents. PSet
The graphics method objectName.PSet(x,y) displays the point with coor-
dinates (x,y) in the foreground color. The method objectName.PSet(x,y),c causes
the point (x,y) to be displayed in the RGB color specified by c. The size of the point is determined by the value of the Draw Width property. The actual color(s) displayed depend on the values of the DrawMode and DrawStyle properties. [color]
Put (Files)
See Appendix C. Note: The buffer method of working with random-
access files is not available in Visual Basic.
QBColor The value of the function QBColor(colorAttrib) is the RGB color number associated with the QBasic color attribute colorAttrib. Valid values for colorAttrib are whole numbers from 0 to 15. This function is included in Visual Basic for easy access to QBasic’s 16 standard colors. [color]
Randomize
See Appendix C.
ReDim See Appendix C. ReDim may only be used within procedures; it may not be used in the declarations section of (general). To establish a global array which may be resized, Dim it with empty parentheses in the declarations section of (general) and then ReDim it as needed within appropriate procedures. Refresh The method objectName.Refresh causes the named form or control to be refreshed, that is, redrawn reflecting any changes made to its properties. Generally, refreshing occurs automatically, but if not, it may be forced with the Refresh method.
Rem
See Appendix C. See Appendix C.
Reset Resume Return RGB
See Appendix C. See Appendix C.
The value of the function RGB(red, green, blue) is the color number
corresponding to a mixture of red red, green green, and blue blue. This color number is assigned to color properties or used in graphics methods to produce text or graphics in a particular color. Each of the three color components may have a value from 0 to 255. The color produced using RGB(0,0,0) is black, RGB(255,255,255) is white, RGB(255,0,0) is bright red, RGB(10,0,0) is a dark
red, etc. (The value of the function RGB(7,g,b) is the long integer r+256*g+ 65536*b.) [color]
614
Appendix J] — Visual Basic Statements
Right$
See Appendix C.
RmDir
See Appendix C.
Rnd
See Appendix C.
RSet If a$ is a string variable, then the statement RSet a$ = b$ replaces the value of a$ with a string of the same length consisting of b$ truncated or padded on the left with spaces.
RTrim$ Scale
See Appendix C.
The method objectName.Scale (x1, yl) — (x2, y2) defines a coordinate
system for the form or picture box identified by objectName. This coordinate system has horizontal values ranging from x1 at the left edge of objectName to x2 at the right edge and vertical values ranging from yl at the top edge of objectName to y2 at the bottom edge. Subsequent graphics methods and control positioning place figures and controls in accordance with this new coordinate system. As a result of using the Scale method, the ScaleMode property of objectName is set to 0, the ScaleLeft property to x1, the ScaleTop property to yl, the ScaleHeight property to y2~yl, and the ScaleWidth property to x2—x1. The method objectName.Scale without arguments resets the coordinate system of objectName to the standard coordinate system where the unit of measure is twips and the upper left corner of objectName has coordinates (0,0).
ScaleHeight The property ScaleHeight determines the vertical scale on a form or picture box. After the statement objectName.ScaleHeight = hght is executed, the vertical coordinates range from objectName.ScaleTop at the top edge of objectName to objectName.ScaleTop + hght at the bottom edge. The default value of the ScaleHeight property is the height of objectName when measured in the units specified by objectName’s ScaleMode property.
ScaleLeft The property ScaleLeft determines the horizontal coordinate of the left edge of a form or picture box. After the statement objectName.ScaleLeft = left is executed, the horizontal coordinates will range from left at the left edge of objectName to left + objectName.ScaleWidth at the right edge. The default value of the ScaleLeft property is 0. ScaleMode The property ScaleMode determines the horizontal and vertical unit of measure for the coordinate system on a form or picture box. If the ScaleMode property of a form or picture box is set to 1 (the default), then the unit of measure become twips. Other possible values for ScaleMode are 2 for points (72 points = 1 inch), 3 for pixels, 4 for characters (1 horizontal unit = 120 twips; 1 vertical unit = 240 twips), 5 for inches, 6 for millimeters, and 7 for
centimeters. measure are ScaleWidth of an object
A value of 0 for the ScaleMode property indicates that units of to be determined from the current settings of the ScaleHeight and properties. Visual Basic automatically sets the ScaleMode property to 0 when any of the object’s Scale. . . properties are assigned values.
ScaleTop The property ScaleTop determines the vertical coordinate of the top edge of a form or picture box. After the statement objectName.ScaleTop = top is executed, the vertical coordinates range from top at the top edge of objectName to top + objectName.ScaleHeight at the bottom edge. The default value for the ScaleTop property is 0.
Appendix J — Visual Basic Statements
615
ScaleWidth The property ScaleWidth determines the horizontal scale on a form or picture box. After the statement objectName.ScaleWidth = wdth is executed, the horizontal coordinates range from objectName.ScaleLeft at the left edge of objectName to objectName.ScaleLeft + wdth at the right edge. The default value of the ScaleWidth property is the width of objectName when measured in the units specified by objectName’s ScaleMode property. Second The function Second extracts the seconds from a serial date. If d is any valid serial date, then the value of Second(d) is a whole number from 0 to 59 giving the seconds recorded as part of the date and time stored in d. [date]
Seek
See Appendix C.
Select Case
See Appendix C.
SendKeys The statement SendKeys a$ places in the keyboard buffer the characters and keystrokes specified by a$. The effect is exactly the same as if the user had typed the series of characters/keystrokes at the keyboard. The statement SendKeys a$, True places keystrokes in the keyboard buffer and waits until these keystrokes are processed (used) before allowing program execution to continue with the next statement in the procedure containing the SendKeys statement. Keystrokes can be specified which do not have a displayable character or which result from using the Shift, Ctrl, or Alt keys. See the Visual Basic reference manual or Help for further details. Set The statement Set objectVar = objectExpression associates the name objectVar with the object identified by objectExpression. For example, if the statements Dim
Scenery
AS
PictureBox
Set
Scenery
= picturel
are executed, then Scenery becomes another name for picturel, and references like Scenery.Print message$ are equivalent to picturel.Print message$. SetAttr
The statement SetAttr filename$, attribute sets the file attribute of the
file specified by filename$. A file’s attribute can be 0 for “Normal” or a combination of 1, 2, or 4 for “Read-only”, “Hidden”, and “System.” In addition, a file can
be marked as “changed since last backup” by adding 32 to its attribute. Thus, for example, if a file’s attribute is set to 35, (1+2+32)
then file is classified as a
Read-only Hidden file which has been changed since the last backup. SetFocus The method objectName.SetFocus moves the focus to the named form or control. Only the object with the focus can receive user input from the keyboard or the mouse. If objectName is a form, the form’s default control, if any, receives the focus. Disabled and invisible objects cannot receive the focus. If an attempt is made to set focus to a control which cannot receive the focus, the next control in tab order receives the focus. SetText
The
method ClipBoard.SetText info$ replaces the contents of the
clipboard with the string info$. Sen Shell
See Appendix C. See Appendix C.
Sin See Appendix C.
616
Appendix J — Visual Basic Statements
See Appendix C. While QBasic’s default variable type is Single, Visual
Single
Basic’s default variable type is variant. [variant]
See Appendix C.
Space$ Spe
See Appendix C.
Sqr
See Appendix C.
Static See Appendix C. In a procedure, arrays created by ReDim are lost when the procedure is exited. Arrays which are local to a procedure yet retained from one invocation of the procedure to the next can be created by dimensioning the array in the procedure with a Static statement rather than a ReDim statement. Dimensions for static arrays must be numeric constants. See Appendix C.
Stop
Str$ See Appendix C. StrComp The value of the function StrComp(a$, b$, compMode) is -1, 0, 1, or Null depending on whether a$ < b$, a$ = b$, af > b$, or either of a$ and b$ is
Null. The comparison will be case sensitive if compMode is 0 and case insensitive if compMode is 1. String
See Appendix C.
String$
See Appendix C.
Sub/End Sub Tab
See Appendix C.
See Appendix CG:
TabIndex The property TabIndex determines the order in which the tab key moves the focus about the objects on a form. Visual Basic automatically assigns successive tab indexes as new controls are created at design time. Visual Basic also automatically prevents two controls on the same form from having the same tab index by renumbering controls with higher tab indexes when the designer or program directly assigns a new tab index to a control. Tan
See Appendix C.
Text The property Text holds the information assigned to a text box. A statement of the form textBoxName. Text = a$ changes the contents of textBoxName to the string specified by a$. A statement of the form a$ = textBoxName.Text assigns the contents of textBoxName to af. TextHeight The value of the method objectName.TextHeight(strVar$) is the amount of vertical space required to display the contents of strVar$ using the font currently assigned for objectName. These contents may include multiple lines of text resulting from the use of carriage return/line feed pairs (Chr$(13) + Chr$(10)) in strVar$. The units of height are those specified by the ScaleMode and ScaleHeight properties of objectName (the default is twips). TextWidth
The value of the method objectName.TextWidth(strVar$)
is the
amount of horizontal space required to display the contents of strVar$ using the font currently assigned for objectName. When carriage return/line feed pairs (Chr$(13) + Chr$(10)) create multiple lines in serVar$, this will be the space required for the longest line.
Appendix J — Visual Basic Statements
Time$
See Appendix C.
Timer
See Appendix C.
TimeSerial
The value of the function TimeSerial(hour,minute,second)
617
is the
serial date corresponding to the given hour, minute, and second. Values from 0 (midnight) to 23 (11 P.M.) for hour, and 0 to 59 for both minute and second are normal, but any Integer value may be used. Often, numeric expressions are used for hour, minute, or second which evaluate to numbers outside these ranges. For example, TimeSerial(15—5, 20-30, 0) is the serial time 5 hours and 30 minutes before 3:20 P.M. TimeValue
The value of the function TimeValue(a$) is the serial date corre-
sponding to the time given in a$. TimeValue recognizes both the 24-hour and 12-hour time formats: “13:45:24” or “1:45:24PM”, .
Top The property Top determines the position of the top edge of a form or control. The units of measure are twips for forms. The units of measure for a control are determined by the ScaleMode property of the container (form, picture box, etc.) upon which the control has been placed, with the position of
the control measure from the edge of its container using the coordinate system established by the various Scale. . . properties for the container. By default, the unit of measure for a container is twips, with a value of 0 for the Top property placing the control against the top edge of the container. True A predefined constant whose value is —1. True is used when setting the value of properties that are either True or False. For example, Picture1.Fontltalic = True.
Type/End Type
See Appendix C. User-defined types may also include currency
or variant elements. [variant]
UBound
See Appendix C.
UCase$
See Appendix C.
Unlock
See Appendix C.
Val
See Appendix C.
Variant A variable of type variant can be assigned numbers, strings, and several other types of data. Variant variables are written without type declaration tags. [variant]
VarType The value of the function VarType(var) is a number indicating the type of value stored in var. This function is primarily used to check the type of data stored in a variant variable. The values returned by VarType are O for “Empty,” | for “Null,” 2 for Integer, 3 for Long Integer, 4 for Single Precision, 5
for Double Precision, 6 for Currency, 7 for Date, and 8 for String. [variant]
Visible The property Visible determines whether or not a form or control is displayed. If the Visible property of an object is True, then the object will be displayed (if not covered by other objects) and respond to events if its Enabled property is True. If the Visible property of an object is set to False, then the object will not be displayed and cannot respond to events.
618
Appendix J — Visual Basic Statements
WeekDay The value of the function WeekDay(d) is a number giving the day of the week for the date store in d. These values will range from 1 for Sunday to 7 for Saturday.
While/Wend
See Appendix C.
Width (Property) The property Width determines the horizontal size of an object. Width is measured in units of twips. For the Printer object, Width may be read (pw = Printer. Width is ok) but not assigned (Printer. an error).
Width = 100 causes
Width (Statement) Ifs is an integer less than 255 and n is the reference number of a file opened in sequential mode, then the statement Width #n,s causes Visual Basic to permit at most s characters to be printed on a single line in the file. Visual Basic will send a carriage return/line feed pair to the file after s characters have been printed on a line, even if the Print# or Write# statement would not otherwise start a new line at that point. The statement Width #n,0 specifies infinite width; that is, a carriage return/line feed pair will be sent to the printer only when requested by Print# or Write#.
WordWrap The WordWrap property of a label with AutoSize property set to True determines whether or not long captions will wrap. (When a label’s AutoSize property is False, word wrap always occurs, but the additional lines will not be visible if the label is not tall enough.) Assume a label’s AutoSize property is True. If its WordWrap property is set to True, then long captions will wrap to multiple lines, while if its WordWrap property is False (the default), then the caption will always occupy a single line. Ifa label has its WordWrap and AutoSize property set to True, then the label’s horizontal length is determined by its Width property, with long captions being accommodated by having the label expand vertically so that word wrap can spread the caption over several lines. If a label’s WordWrap property is set to False while its AutoSize property is True, then the label will be one line high and will expand or shrink horizontally to exactly accommodate its caption. Write#
See Appendix C.
Xor
(Logical Operator) See Appendix C.
Xor
(Bitwise Operator) See Appendix C.
Year The function Year extracts the year from a serial date. If d is any valid serial date, then the value of Year(d) is a whole number from 100 to 9999 giving the
year recorded as part of the date and time stored in d. [date]
Supporting Topics [color]: Numbers written in base 16 are referred to as hexadecimal numbers. They are written with the digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A (=10), B (=11), C (=12), D (=13), E (=14), and F (=15). A hexadecimal number such as rst corresponds to the decimal integer t + 16*s + 162*r. Each color in Visual Basic is identified by a long integer (usually expressed as a hexadecimal number of the form GH. . .&) and referred to as an RGB color number. This number specifies the amounts of red, green, and blue combined to produce the color. The amount
of any color is a relative quantity, with 0 representing none of the color and 255 representing the maximum available. Thus black corresponds to 0 units each of
Appendix J — Visual Basic Statements
619
ted, green, and blue, while white corresponds to 255 units each of red, green,
and blue. The RGB color number corresponding to r units of red, g units of green, and b units of blue is r+256*g+65536*b, which is the value returned by the function RGB(r,g,b). Hexadecimal notation provides a fairly easy means of specifying RGB color numbers. If the amount of red desired is expressed as a two digit hexadecimal number, rr, the amount of green in hexadecimal as gg, and the amount of blue in hexadecimal as bb, then the RGB color number for this color is GHOObbggrr&. For example, the RGB color number for a bright green would come from 255 (FF in hexadecimal) units of green, so the RGB color number in hexadecimal is GHOOOOFFOO&.
[date]:
Functions dealing with dates and times use the type 7 variant data type.
Dates and times are stored as serial dates, double-precision numbers, with the
whole part recording the date and the decimal part recording the time. Valid whole parts range from —657434 to 2958465 which correspond to all days from January 1, 100 to December, 31, 9999. A whole part of 0 corresponds to December 30, 1899. All decimal parts are valid, with .0 corresponding to midnight, .25 corresponding to 6 a.m., .5 corresponding to noon, and so on. In general, the decimal equivalent of sec/86400 corresponds do sec seconds past midnight. If a given date corresponds to a negative whole part, then times on that day are obtained by adding a negative decimal part to the negative whole part. For example, October, 24, 1898, corresponds to a whole part of -432. A time of 6 p.m. corresponds to .75, so a time of 6 p.m. on 10/24/1898 corresponds to 432 + —.75 = 432.75. [variant]:
Variant is a new variable type that is not present in QBasic. Any
variable which is used without a type declaration tag ($, %, &, !, #, @) or without
being declared as a specific type using an As clause or a DefType statement is treated as a variant variable. A variable of type Variant can hold any type of data. When values are assigned to a variant variable, Visual Basic keeps track of the “type” of data which has been stored. Visual Basic recognizes 8 types of data: type O for “Empty” (nothing yet has been stored in the variable; the default), type 1 for “Null” (the special value Null has been assigned to the variable), type 2 for
Integer, type 3 for Long integer, type 4 for Single precision, type 5 for Double precision, type 6 for Currency, type 7 for Date/time, and type 8 for String. A single variant variable may be assigned different data types at different points in a program, although this is usually not a good programming technique. The data assigned to a variant array need not all be of the same type. As a result, a variant array can be used in much the same way as a user-defined type to store related data.
A ae
ay
Viv’
q
Se
aie
a
shi
a Pore
ENT Fie p Lcaee
et
©
Dies i _
"
smerny
ieee
ter
ire
stats Lorene
cal fears =" eel 15 Cre hi Thia —_ ie,
ev T
Answers
To Selected Odd-Numbered Exercises CHAPTER
1
Exercises 1.2 1. View window
3.
Disk Operating System
5. Untitled 9. Crrl+Y 13. Del 17. Shift+F5
7. 11. 15. 19.
A toggle key changes back and forth between two states. Backspace Home Cursor down
21.
23.
Ctrl+End
27. 31.
Vab Enter
35.
PgUp
Alt/F/X
DoMmESC 29.
Alt/F/N
33. 37.
Fl Alt/H/I or Alt/H/C
Exercises 1.3 CORY. 5. DIR 9. RD
3. RENAME 7. MD 11. NAME
CHAPTER Exercises 3.1 ih Ie te ON 2333333 13. 4E-08
3
17.
Valid
3.03125 fie ws 11. 3E+09 15. Valid 19. Not valid
Iles
10)
23-16
Dea
25.09 ZO
31
CUS
PRINT
> Guta}
PRINTO76
35.
CLS PRINT
17
*
(3
+
CLS LET xe= 95 +02.5 7" (9\ =" 3.25) DETeye=420-(7a/ (8)et oe) 4 Oey PRINT x / y
BOE
"(21 23)
xX Ay a) 2 6 11
116 ial
6
lig)
END
END
41.
* 20
CLS PRINTe
162)
END
37s
.055
END
END
33.
CEs
AS
ee
iil 7 | =
balance";
THEN
below
$150"
cost
627
Answers to Selected Odd-Numbered Exercises
628
43.
45.
REM Lottery
REM Convert to Pig Latin GES
CLS
LET
= 7)
(d3
= 7)
(d3
AND
= 7)
word$ "The
PRINT
THEN
+ "way"
= MID$(word$,
LEN(word$)
2,
- 1)
+ f$ + “ay"
word
in
pig
latin
is
";
word$
END
lucky$
PRINT
= word$
0 THEN
IF
END
ELSE (d2
f$)
LET
IF
IF
1)
ELSE
PRINT lucky$ END
f$ = LEFT$(word$, LET word$
THEN
word$
",
a word:
INSTR(“aeiou",
IF
= 7) OR
IF (d2
"Enter
INPUT
d3
d2,
= 7 THEN
dl
IF
dl,
",
seven"
= “Lucky
lucky$
LET
three
“Enter
INPUT
digits:
IF
END IF
END END
47.
REM Test if year is a leap year CLS MOD
((year
AND
4 = 0)
MOD
(year
IF
", year
a year:
“Enter
INPUT
PRINT
“This
is a leap year."
ELSE PRINT
“This
is not a leap year."
END
100
OR
0)
(year
MOD
400
= 0))
THEN
IF
END 49.
REM
of digits
number
Display
in a number
CLS a number
INPUT
"Enter
PRINT
“The number 1000
IF num >=
from
has
1 through
9999:
",
num
“;
THEN
"4 digits."
PRINT
ELSEIF num >= 100 THEN PRINT "3 digits." num >=
ELSEIF PRINT ELSE PRINT END
10 THEN
"2 digits." "1 digit."
IF
END
Exercises 4.3 he S05) 315
3.
5. Sorry, 1945. Work on the ENIAC began in June 1943. Correct. No, 1945. By then IBM had built a stored program computer. 9. Hi Hi 13. First CASE is executed even when num > 5, unclear Also, END SELECT is missing
17. Improper item in value list of second case 21. Valid 25. Invalid 29. SELECT CASE a CASE CASE
“one”
IS > 5
PRINT
END SELECT
7. The less things change, the more they remain the same. Less is more. Time keeps everything from happening at once. 11.
Needs a CASE clause before the PRINT statement.
15.
Error in second CASE. 30000
“two"
Should be CASE
10000 TO
19. Selector is a condition and cases are strings. 23. Invalid 27. Invalid 31. SELECT CASE a CASE
1
PRINT
Begins with a lowercase letter. Begins with an uppercase letter. Does not begin with a letter.
2
PRINT
CASE
"yes"
IS =< 5
PRINT
END SELECT
"no"
Answers to Selected Odd-Numbered Exercises
33.
REM Determine degree of cloudiness CLS INPUT
"Percentage
SELECT
CASE
of cloud
cover";
percent
percent
CASE
0 TO 30 PRINT "Clear"
CASE
31 TO 70
PRINT
"Partly
cloudy"
CASE
71 TO 99 PRINT "Cloudy" CASE 100 PRINT
CASE
"Overcast"
ELSE
PRINT
END
"Percentage
must
be
between
0 and
100."
SELECT
END
35.
REM Give number of days
in month
CLS
INPUT
"Enter
SELECT
CASE
a month
(do
not
abbreviate):
", month$
UCASE$(month$)
"FEBRUARY"
CASE
INPUT IF
"Is
it a leap year";
UCASE$(LEFT$(ans$,
LET
days
= 29
LET days
= 28
1))
ans$ = "Y"
THEN
ELSE END
CASE
"APRIL",
LET
CASE
days
"JUNE",
"SEPTEMBER",
"NOVEMBER"
= 30
"JANUARY",
LET
END
IF
days
"MARCH",
"MAY",
"JULY",
"AUGUST",
"OCTOBER",
"DECEMBER"
= 31
SELECT
PRINT
month$;
" has";
days;
"days."
END
37.
REM Give letter grade for number score CUS
39.
REM Determine cash award CLS
INPUT
"What
SELECT
CASE
CASE
is
score";
score
score
90 TO
CASE
Grade$
= "A" "B"
Grade$
CASE = "C"
LET Grade$ CASE
END PRINT END
END PRINT
END
= "Invalid"
SELECT "The
letter
grade
amount
75000 = .1 * amount 100000 = 7500
+
.05
*
(amount
- 75000)
amount
= 8750
+ .01
*
(amount
- 100000)
> 50000
LET amount IF
THEN
= 50000
END SELECT
= "F"
ELSE
LET GRADE$
amount
IF amount
IS 0 TO 59
recovered";
IS > 100000
LET
CASE 60 TO 69 LET Grade$ = "D" CASE
amount IS = 0) AND (celsius highest
THEN
highest
= num
number:
", num
* num
UNTIL
product
> 400
"The
highest
number was";
highest
END
close
all
doors."
IF
PRINT
LOOP
UNTIL
INPUT
(belt$
= "Y")
"How
many
gallons
"You
may
proceed."
AND
(doors$
of gas
are
= "Y") in
the
tank";
gas
PRINT PRINT
IF gas
< 2 THEN
PRINT
END
"Get
gas."
IF
END
REM Perfect squares
35.
CLS
REM Solve linear equation ELS
PRINT LET
"This
num
displays
the
perfect
squares
less
= 1
DO WHILE PRINT
LET
program
num num
num
than
100."
PRINT
"The
equation
is
ax
+ b = c"
PRINT
* num < 100
INPUT
* num
“Enter
the
values
of
a,
b,
solution
is
";
(c - b)
and
c:
IF a O THEN
= num + 1
PRINT
LOOP
"The
/a
ELSE IF b = c THEN
END
PRINT
“Every
number
is
a solution."
ELSE PRINT
END END
END
37.
",
REM Bounce a ball
and find total
distance traveled
CLS
ball"
PRINT
"
1)
tennis
PRINT
"
2)
basketball"
PRINT
“"
3)
super
PRINT
"
4)
softball"
ball"
PRINT
INPUT
"What
SELECT
CASE
CASE
type
of
ball";
bal]Num
1
LET
bounceFactor
=
.7
CASE 2 LET bounceFactor
=
.75
CASE 3 LET bounceFactor
=
.9
=
.3
CASE
4
LET
END
bal1Num
bounceFactor
SELECT
INPUT
"From
LET
height
LET
bounces
LET
distance
how many = height
meters * 100
= 1 = height
will
it drop"; ' convert
' first
height to
bounce
centimeters
IF
IF
"No
number
is a solution."
a,
400."
is highest."
IF
PRINT
IF doors$ END
numbers
DO
IF doors$
END
= 0
PRINT
IF
END
highest
LET product = 1 PRINT "Continue entering PRINT "The computer will
DO
33.
631
b,
c
632
Answers to Selected Odd-Numbered Exercises
bounces
LET
height
LET
distance
' up then
+ 2 * height
= distance
account
= 0
LET yrs
again
down
amt
",
in account:
amount
"Enter
INPUT
* bounceFactor
= height
savings
to deplete
Years
REM CLS
+ 1
= bounces
LET
39.
10
>=
* bounceFactor
height
DO WHILE
DO
LOOP "The
PRINT
USING
##.#
about
traveled
"and
"times
bounces;
bounced";
ball
PRINT
";
meters";
distance
/
100
LET
oldAmt
LET
amt
= amt -
1000
OR
(amt
1.05
*
= amt
CET yrse=synsital
END
never
will
"Account
PRINT
>= oldAmt)
THEN
oldAmt
>=
IF amt
=
1000000
PRINT
"years
are
yrs;
1980
age
+ age
= age
+
age
* age
1
LOOP
+, 1
LOOP UNTIL
= 1
age
END
required
to
reach
one
million
dollars."
END
45.
REM Greatest common divisor of two positive
integers
CLS INPUT
"Enter
DO WHILE LET
two
integers:
",
m,
n
n 0 t=n
LET
n =m
PET
im) ==
MOD
n
LOOP PRINT
m
END
Exercises 5.2 Ths 5.
413}
3.
Chicago New York le 3 8 5 —l 11. LOOP missing
I think I can. | think I can.
9. counters 13. EOD will be printed. 15.
REM
Find
largest
of a collection
of numbers
CLS
REM
Convert
"Enter largest
-1
when
finished."
PRINT
= 0
INPUT
INPUT
"Enter
a number:
IF num > largest LET LOOP PRINT END
to
kilometers
when
finished."
largest
",
num
"The
-1
"Enter
a distance
DO WHILE
THEN
LET
= num
PRINT
IF UNTIL
"Enter
PRINT
DO
END
miles
CLS
PRINT LET
17.
miles
kilometers
in miles:
-1
= 1.6
* miles
miles;
"miles
"Enter
a distance
is
equal
to";
kilometers;
PRINT num
= -1
largest
INPUT number
is";
largest
LOOP END
in miles:
",
miles
"kilometers."
Answers to Selected Odd-Numbered Exercises
19.
REM Report grades of eggs
21.
CLS
REM Translate doctors'
abbreviations
CLS
INPUT
"Weight
DO WHILE
of egg
ounces
in ounces";
ounces
INPUT
>= 0
< 1.5
THEN
PRINT
"Send
it to the
“ac. PRINT "before
bakery."
CASE
"The
SELECT
grade
CASE
CASE CASE
";
ounces
CASE
CASES
CASE
“at
Large"
CASE
"four
END
SELECT
times
a day"
ELSE
PRINT "Jumbo"
bedtime"
"qid"
PRINT
ELSE
PRINT
"hs"
CASE
"Extra
daily"
“a drop"
PRINT
ISt=
(-1
to stop):
",
score
0
> highest
THEN
LET
nextHighest
LET
highest
IF score LET
= highest
= score
INPUT LOOP
= totGrowth
growth
state,
California,
DATA
Illinois,
36.9, 13.5,
/ counter
for these
population
states
is";
aveGrowth;
21.4,
New
Florida,
13.0,
EOD,
York, 0
20.3
nextHighest
THEN
= score
IF "Enter
PRINT
"The
PRINT
"The next
END
in millions
Texas,
"percent."
> nextHighest
IF
END
"percent."
growth;
by";
pop2010
DATA END
a score
score
+ growth
grew
population
average
Data:
= 0
ELSE
state$,
"The
= 0
"Enter
END
aveGrowth ---
nextHighest
IF score
LOOP PRINT
LET
"EOD"
PRINT READ
highest
DO WHILE
= counter
totGrowth
PRINT
LET
INPUT
pop2010
PRINT
LET
REM Report two highest scores
a score
highest
(-1
score
to highest
to stop): is";
",
score
highest
score
is";
nextHighest
633
634
29.
Answers to Selected Odd-Numbered Exercises
their
and
parentheses
Remove
REM
contents
from
a sentence
31.
CLS
available
liquids
Display
REM
sent$
"Sentence"; = 0
parensFlag
letter$
SELECT
= MID$(sent$,
CASE
CASES
PRINT
"You
position,
1)
END
LET parensFlag LET
CASE
= 0
REM
ELSE
THEN
liquid$
IF
---
DATA
IF parensFlag PRINT
= 0 THEN
DATA:
price
Apple
liquid,
Cider,
DATA Gasoline,
letter$;
DATA
IF
Pancake
cost
2.60,
1.30, Syrup,
per
Beer,
gallon
6.00,
SELECT
LET
position
= position
2.30,
Gatorade,
15.50,
Spring
Water,
+ 1
LOOP END
.202 is a zero
Exercises 5.3
Sy
Pass # 1 # 2
Pass
# 3
Pass
# 4
8
7
9.
13.
17.
21.
3.
BO
20
tn
a
1
4
7
6
2
5
8
11
6
9
12
a5
oDDDD
7.
2
4
6
3:46.31
SteverScottum
3-016
Mary
4:20.5
Slaney
11,
***...****Hooray***. ..****
15.
Temperature
Density
AAAAA
40
62.423
TTTTT
45
62.419
AAAAA
50
62.409
55 60 65
62.39 62.198 62
1000 Kilo 1000 Kilo 1000000
mega
1000000
mega
1.0E+09
giga
1.0E+09
giga
1.0E+12
tera
1.0E+12
tera
1.0E+15
peta
1.0E+15
peta
Improper nesting of loops
19,
For without Next
23.
FOR num = 1 to 10 STEP 2 PRINT NEXT
25.
8 Who do we appreciate?
Steve Cram
REM Display a row of ten stars CLS FOR
END
num
num
REM Display
10 x 10 array of stars
CLS i
= 1
PRINT NEXT
27.
“**;
FOR
i
= 1 TO
FOR
j = 1 TO 10
PRINT
ul
NEXT
j
PRINT NEXT
END
10
i
ae
Bleach,
Milk,
END
END
Pass
following:"
Loop
parensFlag
END
36
THEN
LET
x = 72
Deflection"
FOR
i = 1709
NEXT
6
payments
made:
",
n
= prin
Balance
LET
interest:
of
=
* Balance
(1 + r / 1200)
- pmt
7
"The
amount
still
owed
is";
Balance
END -d
IF
PETEME= PRINT NEXT
Balance
PRINT
LET
END
LET
(inches) "
(inches)
d = 0 TO
"
Maximum
from
pmt
ate SOR(S)
hp Sex USING
"—
##
Re. (ee
(2a =
2)
e277
ed
Ht #Htt";
ds;
es
ED)
M
d
END
CHAPTER
6
Exercises 6.1 1.
kilogram is the unit of mass in the metric system.
3.
5.
Least said, soonest mended. Source: Fortune cookie. 30% of M&M’s Plain Chocolate Candies are brown.
7.
9. 13.
It was the best of times. It was the worst of times.
11. 15.
Divorced, beheaded, died; Divorced, beheaded, survived.
144 items in a gross The time required for a population to double in size is 34.65736 years. Your name has 7 letters. The first letter is G
Answers to Selected Odd-Numbered Exercises
7
You look dashing in blue
19.
7is\be The molarity of the salt water solution is Zo. abcde atk
M = nmoles / volume = .5 25. The number of members of the U.S. Senate is 100 Zo:
Sle Gabriel, in the year 2000 your age will be 20 3S). Your will receive a BS degree at age 22 39. A string parameter is missing in the subprogram.
33. Sk 41.
43.
45.
REM
Display
a lucky
number
CLS
M
1000000
milli
m
-001
Unicorn
168 hours in a week 76 trombones in the big parade The Statue of Liberty weighs 250 tons All’s well that ends well. Since Print is a keyword, it cannot be used as the name of a subprogram. REM
Courses
CLS
LET
num
CALL
= 7
CALL
PrintInfo("Civil
Lucky (num)
CALL
PrintInfo("Mathematics",
END Lucky
REM
SUB PrintInfo
(num)
Display
PRINT
num;
message "is
END
SUB
REM
Undergraduate
a lucky
majors
number."
at
U of MD,
College
Park
49.
"Analysis
of Structures")
“Calculus")
enrolled)
Majors(major$,
CALL
enrolled
READ major$, ---
REM
Data:
computer
DATA
SUB
REM
Return
the
(major$,
Display
"In
1992,
PRINT
enrolled;
", word$
and
its
length
LEN(word$)
enrolled)
major
PRINT
of a word
SUB Length (word$) REM Output the word
556
economics,
914,
science,
enrolled
of students
number
major,
PRINT word$; END SUB
REM
"; major$
END
END
Majors
length
of
enrolled)
Majors(major$,
CALL
END
subject$)
" is a subject
CLS INPUT "Enter a word: CALL Length(word$)
enrolled
READ major$,
(major$,
subject$;
PRINT
CLS
SUB
Engineering",
END
SUB
47.
mega
information
the
University
of Maryland
“undergraduate
";
major$;
had"; " majors."
END SUB
51.
637
REM
Display
the
average
of
three
53.
numbers
REM
Years
and
days
old
CLS
CLS "Enter
INPUT
CALL
",
numbers:
three
Average(first,
second,
first,
second,
third)
END
third
INPUT
“What
is your
year
CALL
ShowYears (birthYr)
CALL
ShowDays (birthYr)
of
birth";
birthYr
END SUB
Average
REM
Display
second,
(first, the
END SUB
"The
SUB ShowDays
average
LET ave = (first PRINT
third)
average
+ second is";
+ third) ave
/ 3
REM
Display
PRINT
"You
PRINT
(1994
(birthYr) age have
in days lived
for
- birthYr)
more
* 365;
than";
"days."
END SUB SUB
ShowYears
REM
Display
PRINT
END
SUB
"You
(birthYr) age
are
in years
now";
1994
- birthYr;
“years
old."
Answers to Selected Odd-Numbered Exercises
638
55.
in courses
Enrollments
REM
CLS "In
PRINT
READ CALL
READ CALL REM
students, course$ ShowEnrolled(students,
course$)
students, course$ ShowEnrolled(students,
course$)
---
Data:
number
Spanish,
533600,
DATA
1990,"
year
the
of
students
enrolled,
course
French
272600,
END SUB
ShowEnrolled
REM
course$)
Display
enrollment
and
PRINT
USING
"###,###";
students;
PRINT
“ college
END
57.
(students,
students
course
took
a course
in
";
course$
SUB
REM Display speeds of waves CLS
CALL
PrintSpeed("light",
3E+08)
CALL
PrintSpeed("sound",
360)
END
SUB
PrintSpeed
PRINT END
59.
(wave$,
"The
speed
of
speed) ";
wave$;
“ is";
speed;
“meters
per
second."
SUB
REM Display WOW vertically
61.
CLS
REM Compute tips for services
rendered
CLS
CALL
DrawW
INPUT
"Enter
the
person's
CALL
Draw0
INPUT
"Enter
the
amount
CALL
DrawW
INPUT
"Enter
the
percentage
END
CALL
Tip(job$,
occupation: of
the
bill,
percent)
bill,
percent)
bill:
tip:
",
END
SUB
Draw0
REM
Draw
PRINT
"
PRINT
"|
the
letter
SUB
eee XT
**
PRINT PRINT
0
"
Display
ae
LET
total
cats
PRINT
“Tip
PRINT
USING
eee
SUB
DrawW
END
SUB
REM
Draw
the
PRINT
"**
PRINT
3" **
PRINT
"
PRINT
"
(job$,
REM
PRINT END
Tip
letter
the
tip
= bill the
* percent ";
/ 100
job$;
"$$##.##";
total
SUB
W
EASE as
Kk **
kK
ORK **H
PRINT
END
SUB
Exercises 6.2 1
9
3.. ‘Can'Can
By
75)
7.
9. Approximate Annual Wage: 20000 13. NE io Ci
11. 15. 19.
35
Dim. A) | 25. DATA cannot be in a subprogram.
The number is
1,234.57
Gabriel was born in the year 1980 Buckeyes Hello Ray and Bob and Bob
23
discovered Florida
", ",
job$ bill
percent
Answers to Selected Odd-Numbered Exercises
Zi.
REM Calculate
sales
29:
tax
CLS
InputPrice(price)
CALL Compute(price, CALL
tax,
ShowData(price,
cost)
tax,
cost)
END
Compute
(price,
tax,
REM
Calculate
the
LET
tax
* price
LET
cost
SUB
=
.05
= price
InputPrice
REM
Get
INPUT
InputName(name$)
CALL
GetFirst(first$,
CALL
ShowLetter(first$)
cost + tax
price
of
"Enter
the
price
SUB
SUB
ShowData
REM
(price)
the
END
(price,
Display
name$)
PRINT
"Tax:
PRINT
"----------- J
PRINTS
"Costs
REM
Convert
",
";
LET
n = INSTR(name$,
LET
first$
InputName
cost)
"3; tax
full
"What
SUB
SUB
ShowLetter
PRINTS
tDear
PRINT
"We
name
is your
END
price
n - 1)
(name$)
Input
INPUT
" ")
= LEFT$(name$,
SUB
price
name
first
Extract
REM
item:
name$)
REM
SUB
item
of the
(first$,
END
bill
“Price:
SUB
the
tax,
PRINT
END
full
name";
name$
(first$) is
are
ahinstSsw
proud
ss
to
accept
you
to
Gotham
END SUB
“sicost
feet
and
inches
to
centimeters
CLS
33;
REM
Calculate
meal
cost
CLS
CALL
InputLngth(feet,
CALL
Convert(centimeters,
CALL
ShowSize(centimeters)
inches)
feet,
inches)
END
CALL
InputBil} (subTotal)
CALL
Compute(subTotal,
CALL
ShowData(subTotal,
tip, tip,
total) total)
END
SUB
Convert
(centimeters,
REM
Convert
to
LET
totalInches
= 12
LET
centimeters
= 2.54
feet,
SUB Compute
inches)
SUB
Input
(feet,
length
total
+ inches
LET
tip
* subTotal
* totalInches
LET
total
the
in feet
INPUT
"Number
of feet";
INPUT
“Number
of
SUB
length
and in
inches";
inches
=
.15
tip
= subTotal
feet
and
InputBill
REM inches."
feet
+ tip
Display "The
(centimeters) size length
in in
Input
INPUT
the
"Enter
END
SUB
SUB
ShowData
REM
ShowSize
(bill) price the
of
the meal
price
of
the
meal:
inches
SUB
SUB
and
the
inches)
"Give
PRINT
total)
Calculate
* feet
PRINT
REM
tip,
END SUB
InputLngth
REM
(subTotal,
REM
centimeters
END SUB
END
acceptance
CALL
SUB GetFirst
cost)
END SUB
SUB
of
END
SUB
END
Letter
CLS
CALL
31.
REM
centimeters centimeters
is";
centimeters
(subTotal,
Display
tip,
charges
PRINT
"Subtotal:";
subtotal
PRINT
"
tp
PRINT
"----------- «
PRINT
2)
END
SUB
ips
Total: ss total
total)
",
bill
College."
639
Answers to Selected Odd-Numbered Exercises
640
35.
3
percentage markup
REM Calculate
REM
Calculate
batting
average
CALL
ReadStats(name$,
atBats,
CALL
ComputeAverage(atBats,
CALL
DisplayInfo(name$,
DATA
Sheffield,
CLS
CLS
CALL
InputAmounts(cost,
CALL
ComputeMarkup(cost,
CALL
DisplayMarkup (markup)
price)
markup)
price,
END
557,
hits) hits,
ave)
hits,
ave)
ave)
184
END
SUB ComputeMarkup (cost, price, markup) LET markup = 100 * ((price - cost) / cost)
SUB ComputeAverage
LET
SUB
END
SUB DisplayMarkup PRINT
"The
SUB
SUB
DisplayInfo
markup
InputAmounts
is";
markup;
(cost,
"percent."
"Enter
the
cost:
",
INPUT
“Enter
the
selling
cost price:
",
PRINT
name$,
PRINT
USING
“.###";
ave
END
SUB
Rack
mall
comparison
table
CLS CALL
DisplayHeader
FORM
= 1 10\3
CALL
ReadInfo(mall$,
CALL
ComputeRent(rentPerFoot,
CALL
DisplayInfo(mall$,
NEXT
i
REM
---
DATA
Data:
Green
mall,
Mall,
rentPerFoot,
squareFeet)
squareFeet,
rentPerFoot,
rent
per
6.50,
583,
(rent,
feet,
foot, Red
rent)
squareFeet,
square
Mall,
rent)
feet
7.25,
426,
Blue
Mall,
5.00,
823
END SUB
ComputeRent
REM
Compute
LET
total
total
rent
= rent
total)
given
rent/foot
and
number
of
feet
* feet
END SUB SUB
DisplayHeader
PRINT
"Mall
Name
Rent
per
Square
Foot
Total
Feet
Monthly
Rent"
END SUB SUB
DisplayInfo
(mall$,
rentPerFoot,
\
S$tt tt
LET a$ = "\ PRINT
USING
a$;
mall$;
rentPerFoot;
squareFeet,
ReadInfo
READ
END SUB
mall$,
(mall$,
rentPerFoot,
rentPerFoot,
squareFeet;
squareFeet)
squareFeet
rent)
HHT
END SUB
SUB
"Batting
Average"
SUB
ReadStats
(name$,
atBats,
atBats,
hits
price
END
Hat
ave)
"Name",
READ
Display
(name$,
PRINT
price)
INPUT
REM
/ atBats
(markup)
END SUB
59:
= hits
END
END SUB SUB
ave
(atBats,
rent
SH, tee
ee"
SUB
name$,
hits)
641
Answers to Selected Odd-Numbered Exercises
41.
REM Display equation
of a line
43.
CUS CALL
GetCoefficients(c,
d,
CALL
DisplayEquation(c,
d, e)
e)
END
REM Raise a complex
number to the nth power
CLS CALL CALL
GetData(n, ReX, ImX) ComputeAnswer(n, ReX,
CALL
ShowResult(ReY,
ImX,
ReY,
ImY)
ImX,
ReY,
ImY)
ImY)
END
SUB
DisplayEquation
REM
Display
PRINT
the
"The
(c,
d,
e)
equation
in
equation
of
the
the
form
line
is:
x = a or
y= mx
+ b
SUB
";
LET
ReY
= Rex
LET
ImY
=
FOR
i
IF d = 0 THEN BRUNT
exe
ELSEIF
="
sen
ComputeAnswer
C
e / d < 0 THEN
END END
MultiplyComplex(ReX,
LET ye
suse—
Gu) dXa
ImX ImX,
ReY,
ImY,
ReZ,
ImZ)
BBE
ELSE BRUNT
ReX,
= 2 7T0n
CALL
PRINT "y ="; -c / ds "x -"3 ABS(e / d)
(n,
seemed
NEXT
IF
END
ImY
=
ImZ
7
SUB
SUB
SUB GetData SUB
GetCoefficients
REM Get PRINT DO
(c,
coefficients "The
WHILE
= 0)
e)
of the
equation (c
d,
of
AND
a (d
equation
line
in
of a line
standard
form
in standard is
cx
+ dy
form = e"
= 0)
INPUT
"Enter
the
value
of
the
coefficient
c:
",
c
INPUT
"Enter
the
value
of
the
coefficient
d:
",
d
INPUT
"Enter
the
value
of the
coefficient
e:
",
e
ReX,
"Enter
a positive
INPUT
"Enter
real
INPUT
"Enter
imaginary
SUB
SUB
MultiplyComplex
SUB
Imx)
INPUT
END
LOOP END
(n,
number:
part
",
of a complex part
(ReX,
of
ImX,
ReY,
Perform
LET
ReZ
= ReX
* ReY
-
ImX
*
LET
ImZ
= ReX
*
+
ImX
* ReY
END
ImY,
multiplication:
ImY
",
Rex
number:
ReZ,
",
ImX
ImZ)
Z = x * Y
ImY
SUB
SUB ShowResult
(ReY,
PRINT
"Real
PRINT
"Imaginary
END
number:
a complex
REM
complex
n
ImY)
part
of power:"; part
of
ReY
power:";
ImY
SUB
Exercises 6.3 1935 3. The population will double in 24 years. 5. The function value is .5 7. You can park about 500 cars. 9. The day is Wed 11. train 13. moral has the negative amoral 15. Missing $ sign at end of Greeting. political has the negative apolitical 17. Twice should be a numeric function, and no argument should be given in the assignment of Twice. 19.
REM Convert
Celsius
to Fahrenheit
21.
CLS
REM Round a positive number m to n decimal CLS
CALL
InputTemp(t)
CALL
InputData(m,
CALL
ShowNewTemp(t)
CALL
RoundIt(m,
END
REM
CtoF
Calculate
Fahrenheit
temperature
from
Celsius END
END
FUNCTION
SUB
InputTemp INPUT
“Enter
a temperature
in Celsius:
",
t
ShowNewTemp SUB
t;
"Enter
a positive
INPUT
"Round
it to how many decimal
"degrees
Celsius
is";
CtoF(t);
"degrees
number
to
round:
",
places";
m
n
SUB
REM
(t)
n)
(m,
INPUT
(m,
Rounded
FUNCTION
(t)
Round
a number LOUA
LETEYS=
Mie
Rounded
= INT
SUB
PRINT
END
n)
InputData
SUB
(t)
CtoF = (9 / 5) * t + 32
SUB
n)
END
FUNCTION
END
places
END
FUNCTION
SUB
RoundIt
(r)
n) to a given neta.
number
of decimal
places
5
/ (10 * n)
Fahrenheit" PRINT END
SUB
m;
(m,
n)
“rounded
to";
n;
"places
is";
Rounded(m,
n)
642
23.
Answers to Selected Odd-Numbered Exercises
25.
REM Popcorn Profits CLS CALL
InputAmounts(popCost,
CALL
ShowProfit(popCost,
REM Cost of airmail cLS
butterCost, butterCost,
bucketCost, bucketCost,
price) price)
CALL
InputWeight (weight)
CALL
ShowCost (weight)
END
END
SUB
InputAmounts
(popCost,
butterCost,
bucketCost,
INPUT
"What
is the
cost
of the
popcorn
kernels";
INPUT
"What
is
the
cost
of the
butter";
butterCost
INPUT
"What
is
the
cost
of the
bucket";
bucketCost
INPUT
“What
is the
sale
price";
price
Ceil = -INT(-x) END FUNCTION
END SUB
FUNCTION
Profit
(popCost,
REM Calculate
Profit
END
the
= price
butterCost,
profit
bucketCost,
on a bucket
- (popCost
SUB
InputWeight
profit
"The
PRINT
butterCost,
of an airmail
letter
- 1)
bucketCost,
(weight) of
the
letter
in
(weight) cost of mailing
the
letter
is";
weight
the
"Enter
INPUT
(popCost,
cost
the
+ bucketCost)
FUNCTION
SUB ShowProfit
(weight)
Cost = .05 + .10 * Ceil(weight END FUNCTION
price)
of popcorn
+ butterCost
Cost
Calculate
REM FUNCTION
up
Round
REM
popCost
(x)
Ceil
FUNCTION
price)
",
ounces:
END SUB
price)
is";
PRINT Profit(popCost, END SUB
butterCost,
bucketCost,
price)
SUB ShowCost PRINT "The
Cost(weight)
END SUB 27.
REM
Display
CLS INPUT
a greeting
for
a senator
29.
REM
Determine
the
senator's
name:
"; name$
DIM
PRINT PRINT
“The Honorable
"; name$
PRINT
"United
Senate”
PRINT
"Washington,
States
count(1
of Stirling
approximation
TO 3)
FOR n = 1 TO 34 LET f = Factorial (n) LET s = Stirling(n)
DC 20001"
IF ABS(s
PRINT
PRINT
accuracy
CLS “Enter
- f)
/ f
b) AND Largest
sp a
primes
CET n=
= primes
+ 1
"; c is"; Largest(a,
b,
c)
a,
b,
and c
(a > c) THEN
= c
Largest
IF
END END
= b
IF
FUNCTION
= primes
FUNCTION
FUNCTION Atan2 REM
(y, x)
Returns
the
37.
value
of the
standard
position
angle
in radians
REM Convert from meters to feet and vice versa
LET pi
= 4 * ATN(1)
OS INPUT
SELECT
CASE
x
INPUT
"Enter
IS > 0
PRINT
"Length
CASE
Atan2 = ATN(y / x) CASE CASE
= SGN(y)
END
the
input
the
length
* pi
/ 2
FUNCTION IF
= ATN(y
/ x) + SGN(y)
Convert
Convert END
REM Display Arccos(x)
41.
>=
(x
-1)
x;
“Arccos(";
AND
")
the
in
a number
"Enter
=";
(x
0 THEN
END
CASE
unit:
is";
length)
THEN
IF
MySGN
CASE
"M"
FUNCTION MySGN
DO
FUNCTION
(inUnit$,
FUNCTION
IF
CLS
PRINT
unit
ELSE END
UNTIL
=
Convert
FUNCTION
LOOP
(M or F):
in that
in the other
inUnit$
* pi
SELECT
INPUT
unit
END
IS < 0
Atan2 END
"Enter
0
Atan2
39.
number
b
ELSE
LOOP
END
number:
";
ELSEIF c > b THEN
ni / F
NumberOfPrimes
number:
=a
Largest
LET
"; a
FUNCTION Largest (a, b, c) REM Find largest number among
ELSE
END
largest
number:
in n
f 0 THEN
MA
35.
643
IF FUNCTION
= 0
",
inUnit$
",
length
Convert(inUnit$,
length)
Answers to Selected Odd-Numbered Exercises
644
43.
an
to
due
interest
Calculate
REM
45.
of a number
representation
Binary
REM
balance
unpaid
GES
CLS INPUT
"Enter
PRINT
"The
num
",
integer:
an
representation
binary
is
";
Binary$(num)
"Enter
PRINT
"Interest
Interest (balance)
$";
is
balance
",
balance:
unpaid
INPUT END
END
Calculate
REM
= ""
a$
LET
LOOP END
.015
be
paid
* balance
- 1000)
* .01
FUNCTION
END
IF
= num \ 2
UNTIL
Binary$
THEN
to
END IF
LET a$ = "1" + a$ LET num
1000
interest
of
= 15 + (balance
Interest
ELSE END
amount
ESE
+ a$
"0"
=
a$
LET
the =
Interest
2 = 0 THEN
IF num MOD
4). 17. elect$(1) elect$(2) elect$(3)
21.
11. 15. 19,
Array subscript out of range (eventually). Improper syntax in DIM statement. a) Apr Sep b) Dec,Jan,Feb
23.
REM
Calculate
Replace lines 11 through 17 with: REM
Display
name
LET
highest
= 0
LET
sum
= 0
FOR
i
8
FOR
i
2 10.9
=
110
of
the
student
with
the
highest
NEXT
END
PRINT
=
LET
IF
sum
the
sum
STEP
of odd
indexed
"The
sum
of
the
odd
indexed
entries
name$(i)
PRINT IF
END
i
NEXT
REM Compare arrays a$() LET
differFlag
FOR
i = 1 TO 10
IF
a$(i)
LET END NEXT
and b$()
for same values
= 0
t
=
110
b$(i)
THEN
differFlag
NEXT
7
12
LET grades(i)
= grades(i)
+ 7
i
= 1
i
IF differFlag
= 1 THEN
PRINT
"The
arrays
are
"The
arrays
have
REM
Curve
FOR
i
=
grades 1 TO
not
identical."
identical
values.”
NEXT
i
by adding
5 percent
12
LET grades(i)
ELSE IF
REM Curve grades by adding FOR
IF
PRINT
27.
array
i
THEN
= highest
IF score(i)
in
= sum + a(i)
= 11708
i
entries
2
i
FOR
END
score
IF score(i) > highest THEN LET highest = score(i) NEXT
25.
NOMS 14
watt
volt
ohm
|
coulomb
elect$(4)
Stuhldreher Crowley
= (1.05)
* grades(i)
is";
sum
a()
Answers to Selected Odd-Numbered Exercises
29.
REM Array m() stores the same numbers as array n(), REM
but with
DIM r(1 FOR
no duplications
TO 50)
i = 1 TO
LET
100
n(n),
NEXT
31.
= 1
REM Create and display the frequency of scores BES DIM
frequency(1
REM
Set
LET
count
FOR
i = 1 TO
= 0
IF r(i) END
50 = count
+ 1
DIM m(1
TO count)
LET
index
FOR
i
IF
1 TO
r(i) LET
m(index)
LET
index
END NEXT
scores
in each
of
five
intervals
= 1 TO 30
score
LET
frequency(range)
= INT(score
/ 10)
+ 1
‘Number
= frequency(range)
in
=
i
= index
+ 1
IF
Display
frequency
"Interval
LET
a$
FOR
interval
=
"##
PRINT
7
NEXT
DATA
to
in each
##
+ 1
interval
5
a$;10*(interval
- 1),10*in frequency (interval terv al, )
interval
---
Data:
10,
5, 4,
arbitrary
25, LU,
23,
list
45,
46,
125230, l/s
lOse
of
49,
scores
47,
315) 40545, Sal
4 el oce
2,
44
205,21 Zed
teelO)
END
REM Inventory processing
35.
CLS REM
Read
TO
5),
item
FOR bin
sold(1
costs
REM
Compute
PRINT
and
"Bin
LET
af
LET
totalRev
and
5),
amtLeft(1
quantities
TO 5)
sold
sold(bin) display
Quantity
and
remaining
revenue
Revenue"
## = 0
Het ##" ‘Total
LET
totalRev
PRINT
= 45
revenue
+ revenue
bin;
amtLeft(bin);
revenue
"Total
"The
PRINT
revenue:
bin
following
";
totalRev
bins
contain
PRINT
END
DATA’ END
fewer
than
20
";
items:
= 1 TO 5
IF amtLeft(bin)
REM
i =
< 20 THEN
bin;
IF bin
---
Data:
3-005,
105.
item
into
the
array
messages
in
1 TO 8 STEP
two
lines
2
messages$(i);
" "3;
7
cost,
12.255,-30,
sold
quantity
37-45,
95
i = 1 TO 8 STEP
NEXT
i
REM
---
END
PRINT
NEXT
FOR
DATA
PRINT
FOR
Print
PRINT
bin
PRINT
messages
REM
FOR
* cost(bin)
= totalRev a$;
i = 1708
NEXT
- sold(bin)
= sold(bin)
USING
FOR
TO 8)
PRINT
LET amtLeft(bin) revenue
Read
PRINT
= 1 T0 5
LET
REM
in two lines
READ messages$(i) NEXT i
inventory
= " #
FOR bin
NEXT
TO
REM Place messages CLS DIM messages$(1
= 1 T0 5
READ cost(bin), NEXT bin
1-5
##"
= 1 T0
DATATIO SS Gs
cost(1
of
Frequency"
USING
DATA135)
DIM
range
PRINT
REM
33.
the
dataElement
PRINT
1 THEN
= 0
count
range
REM 50
=
scores,
LET NEXT
= 1
=
Read
READ
i
to 0
= 1 T0 5
FOR dataElement
IF
NEXT
elements
range
REM
count
TO 5)
frequency(range)
NEXT
= 1 THEN
LET
array
FOR range
i
LET
645
7.49542,
24.95,
17
messages$(i Data:
This,
It,
2 + 1);
" "3
messages is,
seems,
a,
you,
test,
passed
Answers to Selected Odd-Numbered Exercises
646
#7.
Histogram
Distribution
Frequency
REM
CLS DIM
frequency(1
REM
Read
READ
vel
TO 6)
-1
vel
DO WHILE
measurements
velocity
missile
- 500)
= INT((vel
LET
index%
LET
frequency(index%)
+ 1
/ 100)
+ 1
= frequency(index%)
vel
READ
LOOP Display
FOR
i = 1 T0 6 + 100 * i + 99;
frequency(i)
j = 1 TO
FOR
"3; 400 + 100 * i; 400
- ####
"####
USING
PRINT
frequencies
with
histogram
REM
22 tts
PRINT. j
NEXT
frequency(i)
PRINT
NEXT
i
REM
---
measurements
Data:
, 750, 1020 980,660, 850,1010,930,880,970,960 970,890,970,900, 1030,950,1000,940,970,600,-1
DATA DATA END
Exercises 7.2 1. No.
3. 7.
Michigan less than greater than equals less than Total rainfall for the 1st quarter is 10 Parameter should be planet$() in the CALL statement and subprogram.
5.
The sum of the first 4 elements is 30
9.
South Pacific
11.
Duplicate DIM statement in subprogram.
15.
17. nis set | too high 21. Array subscript will be out of range when i = 5.
19.
hue$ will be unknown in the subprogram.
23.
25.
REM Determine
13.
SUB CopyArray REM
Place
FOR
i
=
1
(a(), a's
values
to
UBOUND(a)
BET sbi) NEXT END
b()) in
b
="a i)
LET
order
FOR
i
=
=
if array is ascending 1
1 TO
49
IF scores(i)
i
LET
SUB
END NEXT
> scores(i
order
+ 1)
THEN
= 0
IF 1
IF order PRINT
= 1 THEN "Array
is
ascending"
“Array
is
not
ELSE PRINT
END 27.
REM
Determine
LET
ascend
LET
descend
FOR
i = 1 TO 49
if order
=
ELSEIF LET END NEXT
IF
ascending,
both,
=
1
> scores(i
ascend
+ 1)
THEN
= 0
scores(i) descend
< scores(i
+ 1)
THEN
= 0
IF i
(ascend
= 1)
PRINT
"Array
ELSEIF PRINT
ELSEIF PRINT
(ascend "Array
(ascend
AND
(descend
is
both
= 0) is
ascending
AND
neither
= 1)
= 1)
(descend
PRINT IF
THEN and
THEN
"Array
is ascending"
"Array
is descending"
descending"
= 0)
ascending
ELSE END
descending,
1
IF scores(i) LET
is
THEN
nor
descending"
or
neither
IF
ascending"
647
Answers to Selected Odd-Numbered Exercises
29.
REM
Merge
DIM
c(1
LET
indexA
= 1
LET
indexB
= 1
LET
doneA
= 0
LET
LET
doneB
= 0
DO WHILE
FOR
i = 1 TO 40
IF
ascending
arrays,
with
31.
duplications
SUB FindMinMax
TO 40)
c(i)
max
THEN
LET max
= k2
ENDIF = 1
doneB
LET
LET
IF
n =n+2
LOOP
IF n = UBOUND(arrayVar)
i
NEXT
IF
+ 1
ELSE
END
THEN
= kl
IF kl < min END
< 20 THEN indexB
+ 1)
IF
ELSE LET c(i)
+ 1)
LET kl = k2 LET k2 = temp
+ 1
ELSE LET
n < UBOUND(arrayVar)
LET k2 = arrayVar(n) IF arrayVar(n) < arrayVar(n
= a(indexA)
LET
END IF
array
inv=r2
LET
IF indexA
END
of a large
values
LET min = arrayVar(1) LET max = arrayVar(1)
((a(indexA) LET
min, max)
maximum
and
minimum
Find
REM
(arrayVar(),
IF arrayVar(n) LET min ELSEIF
END
< min
THEN
= arrayVar(n)
arrayVar(n)
LET max END
THEN
> max
THEN
= arrayVar(n)
IF
IF
END SUB
33.
REM
Maintain
a list
DIM state$(1 LET
ans
LET
count
of
35.
states
TO 3)
= 0 ans
Report
PRINT
4
students
scoring
above
class
average
num)
Ave(grades(),
num);
"students
scored
above
the
average"
END
PRINT
"1)
Enter
PRINT
"2)
Delete
PRINT
"3)
Display
PRINT
"4)
Quit"
a State" FUNCTION
a State" the
States"
PRINT
INPUT
"Please
SELECT
CASE
CASE
(grades(),
Compute
the
LET
sum
= 0
LET
tot
= 0
FOR
i = 1 TO num
NEXT
count)
IF
count)
0 THEN
LET
count)
classAve
IF
FOR
i = 1 TO num
IF grades(i) EET
END END
INPUT (Hai
"Enter
NEXT
count)
a state
the
from
a State
Ave
list
to Delete:
", name$
a} ceat
DO WHILE Wi
(i
at Seat
< count)
(name$
AND
> state$(i))
seal
LOOP
(name$
state$(i))
PRINT
"State
does
INPUT
"Press
ENTER
OR not
= sum / num
END
LOOP
Delete
number
EUSE
SELECT
REM
and
7 num
3
(state$(),
average
LET classAve
CALL Display(state$(),
Del
num)
LET sum = sum + grades(i)
1
CASE
Ave
REM
ans
CALL Del(state$(),
END
ans
",
1-4:
enter
CALL Enter(state$(), CASE 2
IF
of
PRINT
ELS
SUB
number
DIM grades(1 TO 100) CALL InputGrades(grades(),
= 0
DO WHILE
REM
(count
= 0)
THEN
exist"
to continue.",
dummy
END
IF i
= tot
FUNCTION
tote=
= 0
> classAve tote
tat
THEN
of
students
above
it
648
Answers to Selected Odd-Numbered Exercises
ELSE
"Shuffle
LET
count
FOR
k = 7 TO
LET
rest
= count
-
array
down
by
= state$(k
+ 1)
the
grades,
LET
num
LET
grd
list
IF grd LET
state$(i)
-1)
-1
num
AND
END
= num
+ 1
IF
LOOP
PRINT
"Press
ENTER
to
Continue.",
dummy
END SUB
END SUB
REM
(state$(),
Enter
a new
IF count
count)
state
in
the
= UBOUND(state$)
correct
position
already
been
THEN
PRINT
"Fifty
states
INPUT
"Press
ENTER
"Enter
a State:
have
to
continue.",
entered."
dummy
ELSE INPUT
state$(count EN
+ 1)
",
name$
= name$
eon
DO WHILE WP
state$(i)
Ul
< name$
eS ay axe al
LOOP
IF
(name$
= state$(i))
AND
PRINT
"State
already
INPUT
"Press
ENTER
ELSE
' Shuffle
FOR
j
(i previousNumber
ELSEIF
INPUT
finish):
= number
descend
LET
to
= number
number
(-1
AND
(descend
to
finish):
",
number
LOOP IF
(ascend
= 0)
PRINT
"Sequence
ELSEIF
(ascend
PRINT
is
= 0)
THEN
neither"
= 1)
THEN
"Sequence
is
"Sequence
is descending"
ascending"
ELSE PRINT
END
IF
END
43.
FUNCTION
ScalarProduct
REM
Compute
the
LET
product
= 0
FOR
i = 17T0n
LET NEXT
scalar
q(),
45.
n)
product
of p()
and
q()
REM
Read
product
+ p(i)
substance$(1), highest
FOR
index
READ
7
FUNCTION
PRINT END
Convert
test
range(1
TO
score
to
letter
grade
CLS
DIM
13),
letter$(1
ReadData(range(),
CALL
InputScore(score)
CALL
ShowGrade(range(),
REM
---
Data:
87,
A-,
score)
grades
(000-07.
Ct5)7450C.)
DAVAR/ 748
letter
90,
A,
94,
13)
letter$(),
ranges,
At,
97,
DATA
TO
letter$())
CALL
B,
Bt,
84,
Dt,
0045.
80,
B-
60551D=51.05
oF
END
(score)
InputScore
SUB
number
Input
REM
END
SUB
SUB
ReadData
FOR
i = 1 TO
NEXT
converted:
",
score
scores
to
letter
grades
13
range(i),
READ
converted
letter$())
linking
data
Read
be
to
(range(),
REM
be
to
score
score
“Enter
INPUT
letter$(i)
7
END
SUB
SUB
ShowGrade
REM
Convert
LET
index
DO WHILE LET
LOOP PRINT END SUB
to
score
letter
grade)
grade
= 1
range(index)
index
“The
letter$(),
(range(),
=
index
letter
> grade + 1
grade
boiling
for this
score
is
“;
letter$(index)
SUB
points.
boilingPoint(1)
= 1 = 2 T0 8
substance$(index), LET
NEXT
REM
and
IF boilingPoint(index)
= product
END
49.
substances
LET
* q(i)
boilingPoint())
(substance$(),
SUB Display READ
product
ScalarProduct
END
(p(),
highest
boilingPoint (index)
> boilingPoint(highest)
= index
IF
index
substance$(highest),
boilingPoint (highest)
THEN
649
Answers to Selected Odd-Numbered Exercises
650
Exercises 7.3 100 1. 200 5. Variables being swapped are not of the same type. 9.
4 swaps
13.
5 swaps
17.
Determine the number of times that each of the four integers occurs and then list the determined number of 1s, followed by the determined number of 2s, etc.
21.
REM
Insertion
DIM
b$(1
READ
Assume
Sort.
are
items
100
stored
in
DATA
7 Numbers interchanged. 11 3. 7. Sequential se ao, 2 Il aE GA) Maks Gav 15. 12 comparisons. 19. 16; 84; 5
statements.
100)
to
b$(1)
FOR
i
= 2 TO
100
23.
READ temp$ LET k=i-1
Keak
(temp$
< b$(k))
temp
LET
x=
= x y
LET y = temp
= b$(k)
+ 1)
LET b$(k LET
AND
(k > 1)
DO WHILE
LET
of x and y
the values
REM Interchange
1.
LOOP
IF (k = 1) AND (temp$ < b$(1)) LET b$(k + 1) = b$(k) VET
END
ke=nka=
THEN
1
IF
LET b$(k NEXT
i
REM
---
+ 1)
Data
= temp$
statements
go
here
END 27.
REM
Input
array
of measurements
and
determine
GES
median
29.
REM
Determine
number
of
occurences
CLS
CALL DIM
their
InputNumberOfMeasurements (n) nums(1
TO
n)
DIM
nums(1
TO 200)
DIM
dist(0
TO
63)
CALL InputNums (nums ()) CALL DisplayMedian(nums () )
CALL FillArray(nums()) CALL GetOccurrences(nums(),
END
CALL
dist())
ShowDistribution(dist())
END
SUB
DisplayMedian
(nums())
REM Display the median PRINT "The median is";
of the
n measurements
Median(nums())
END SUB
SUB
FillArray
(nums())
REM Generate
numbers
LET nums(1) FOR
SUB
InputNumberOfMeasurements
REM
Input
INPUT END
number
"Number
(n)
of measurements
of measurements";
= 2 TO
LET
nums(i)
NEXT n
0 to 63
and
- 1)
+ 7)
place
in
= 5 200
= (9 * nums(i
MOD
64
i
END SUB
SUB
SUB
SUB InputNums (nums()) REM Input list of measurements
FOR i = 1 TO UBOUND(nums) INPUT “Enter number: ", nums(i) NEXT
END
i
from
i
GetOccurrences
(nums(),
REM Record occurrences FOR i = 1 TO 200
LET dist(nums(i)) NEXT i END
SUB
SUB
ShowDistribution
dist())
for each
number
= dist(nums(i))
+ 1
SUB
REM
Display
(dist())
distribution
array
FOR
i = 1 TO 63 PRINT USING "## NEXT i END SUB
##
Se
wis) dist (iye
array
Answers to Selected Odd-Numbered Exercises
FUNCTION
CALL
Median
(nums())
SortNums (nums () ) n = UBOUND(nums)
LET
IF INT(n
/ 2)
= n / 2 THEN
'n is even
LETm=n/2 LET med
= (nums(m)
+ nums(m
ELSE
'n
LET med END
= nums((n
+ 1)
is
/ 2 odd
/ 2)
IF
Median
END
+ 1))
= med
FUNCTION
SUB SortNums REM
(nums())
Bubble
sort
list
of
numbers
LET n = UBOUND(nums) FORi=1T0n-1 FOR
j =
1 T0n
IF nums(j)
NEXT NEXT END
31.
i
> nums(j
SWAP END
-
nums(j),
+ 1)
THEN
nums(j
+ 1)
IF j
7
SUB
REM Translate an American word to English
33.
CLS
REM Compute average of five highest test scores CLS
DIM
american$(1
CALL
TO 12), english$(1 TO 12) ReadWords(american$(), english$())
CALL
InputData(name$,
CALL
InputWord(word$)
CALL
SortData(score())
CALL
FindWord(word$,
CALL
ShowData(score(),
---
REM
attic,
DATA
flashlight,
DATA
ice
DATA
sneakers,
chips,
loud
hailer,
megaphone,
ice,
cream,
fries,
lorrie,
truck,
plimsolls,
gasoline,
zero,
radio,
petrol
wireless
INPUT
“Student's
Perform
LET
foundFlag
LET
first:
LET
last
DO WHILE
= 1
= 12
(first
CASE
NEXT
= 0)
SUB
SUB
ShowData
LET
sum
FOR
passNum
END
first
+ 1
= middle
REM
Bubble
FOR
passNum
(score(),
name$)
= 1 TO
5
sum / 5
= 1 THEN
"The
English word
word
is
is
not
";
listed"
english$(middle)
END
NEXT
END SUB
IF
SUB
SUB
InputWord
(word$) word
"Word
to
index
(score()) sort
scores
in descending
order
= 1 TO 6 = 1 TO
7 - passNum
IF score(index) < score(index + 1) THEN SWAP score(index), score(index + 1) NEXT
END
SUB
score(i)
SUB
FOR
"The
PRINT
END
score";
passNum
SUB SortData
- 1
ESE
INPUT
name$
= 0
PRINT name$,
SELECT
Input
scores
LET sum = sum + score(passNum) NEXT
ELSE
PRINT
REM
"Test
END
/ 2)
= 1
= middle
last
foundFlag
END
test
7
LOOP IF
name";
seven
IS > word$
LET END
+ last)
= INT((first
foundFlag
LET CASE
(foundFlag
AND
last)
name$)
(search$
OPEN
filename$
(NOT
filename$) #1
AS
INPUT
FOR
AND
(NOT
EOF (1))
copies
title$,
#1,
INPUT
searchTitle$)
(title$
WHILE
DO
EOF(1))
year
name$,
#1,
INPUT
InputData(searchTitle$,
LET title$ = ""
LET name$ = "" WHILE
CALL
LOOP
LOOP
IF name$
“ is
search$;
PRINT
(searchTitle$, filename$) REM Input book name and determine file INPUT “Title of book"; searchTitle$
name
copies
IF
END
#1
CLOSE
#1
listed."
not
is
"Book
PRINT
in YOB.DAT"
not
IF
CLOSE
is",
ELSE
BUSE END
inventory
in
copies
of
"Number
PRINT
- year
1994
is";
age
"'s
name$;
PRINT
THEN
= searchTitle$
IF title$
THEN
= search$
END
END
InputData
SUB
(H or P)";
or Paperback
“Hardback
INPUT
bookType$
IF bookType$ = "H" THEN LET
filename$
= "HARDBACK. INV"
filename$
=
ELSE LET END
"PAPERBCK.INV"
IF
END
SUB
REM
Add
Exercises 8.2 1.
to
AVERAGE.DAT
Create
REM
hold
batting
3.
averages
the
end
"AVERAGE.DAT"
FOR
APPEND
the
file
AVERAGE.DAT
CLS
CLS
“Enter
INPUT
"Player";
WHILE
DO
to end
EOD
PRINT
name$
OUTPUT
FOR
"AVERAGE.DAT"
OPEN
AS
OPEN
#1
input"
“Enter
INPUT
"Player";
name$
0,
name$,
WRITE
#1,
INPUT
"Player";
"Initialize
0
counters
name$
name$
WHILE
DO
"EOD"
end
to
EOD
PRINT
AS
#1
update”
name$
"EOD"
0,
name$,
WRITE
#1,
INPUT
"Player";
0
name$
LOOP
LOOP CLOSE
#1
CLOSE
#1
END
END
17.
of
to
players
Split the file into two or more files which can be stored in arrays, sort these files using arrays, and then merge them.
CHAPTER Exercises 9.1 1. Pacific Mississipp
9
3.
heights are same 170 eye colors are same
5.
Variables used in LET statements invalid.
9.
astrology.nom and astrology.sign. NUMBER is an invalid data type.
11.
TYPE planet planetName TYPE
7.
AS
STRING
AS
* 20
SINGLE
Reserved word “name” used as field name and no END
TYPE statement. 13.
distanceFromSun END
Should be
TYPE car make
AS
model year
AS AS
mileage
END
TYPE
STRING
* 20
STRING SINGLE
AS
SINGLE
* 20
Answers to Selected Odd-Numbered Exercises
15.
REM
Input
three
words
and
display
them
in
first
three
655
zones
CLS DIM namel DIM name2
AS STRING AS STRING
* 14
DIM
AS
* 14
name3
* 14
STRING
INPUT
"Input
name
1";
namel
INPUT
"Input
name
2";
name2
INPUT
“Input
name
3";
name3
PRINT
namel;
name2;
name3
END
Exercises 9.2
1. VA
ci
5. Virginia Tech Harvard
VA
1872
MA
1636
IDA WI VA 3 7. Milwaukee Area Tech. Col.
9. Cannot take length of a variable type. Should be
WI
11.
Cannot PRINT record variable.
15.
REM Make random file YOB2.DAT
1912
LEN (actor). 13.
TYPE typeNums numl
AS SINGLE
CLS
num2
AS
SINGLE
TYPE
num3
AS
SINGLE
DIM
STRING
* 15
yr AS SINGLE
numbers
OPEN
file YOB.DAT
typePerson
nom AS
END TYPE
from sequential
AS
typeNums
"NUMBERS.DAT"
FOR
RANDOM
AS
#1
LEN
= LEN(numbers)
END
TYPE
DIM
person
AS
typePerson
OPEN
"YOB.DAT"
OPEN
"YOB2.DAT"
LET
recNum
DO WHILE
=
NOT
FOR
INPUT
AS #1
FOR RANDOM
AS #2
LEN
= LEN(person)
1
EOF(1)
INPUT #1, name$, year LET person.nom = name$ LET
person.yr
PUT
#2,
LET
recNum
= year
recNum,
person
= recNum
+
1
LOOP CLOSE CLOSE END
CHAPTER
#1 #2
10
Exercises 10.2 1. 5.
WINDOW REM
(-1,
-5)-(7, and
axes
Draw
SCREEN
2
WINDOW
(-2,
LINE
(-2,
LINE LINE
(0, (3,
30)
Sh 7.
line
"For -40)-(12, 0)-(12,
VGA
(3,
CIRCLE
(10,
SCREEN
12
240)
0)
‘Draw
-40)-(0, 240) 200)-(10, 150)
CIRCLE
use
x-axis
150),
"Draw y-axis "Draw line
REM
LINE
40)
"y-axis
REM
(0,
-8)-(0,
SCREEN
2
WINDOWS
(=52° (G2)
line
and
axes
Draw
"For VGA 9450-02)
4545
* 7S)
O)a(1-25~
(450-3)
CIRGUER
.05
use SCREEN 2d
12
ml ecevar.5)
94, 10) tee
"Draw
+ 355)
a circle
Draw
2
WINDOW
(-10,
CIRCLE
(0,
0),
in
center
the
"For
VGA
-10)-(10,
10)
4
use
of
the
SCREEN
screen
12
11.
REM
Draw
2 (-10,
SCREEN WINDOW LINE
(-10,
LINE
(0,
LINE
(1,
END:
a tick
5ure0S at
mark
70
on
‘For VGA use -10)-(100, 100)
the y-axis
SCREEN
0)
"x-axis
-10)-(0,
100)
"y-axis
70)-(-1,
70)
0)-(100,
x-axis
‘Draw y-axis ‘Draw line
END
SCREEN
END
‘x-axis
its (0, ao Ses LINE (2, .5)-(4, 3) CIRCEEN(Zs6-5)ian 03
END 9.
0)
DINE
.05
200),
(hile (El, MeGs
12
Answers to Selected Odd-Numbered Exercises
656
13.
REM
corners
four
in the
points
Draw
is
19:
WINDOW
(0,
0)-(10,
10)
10) 2.5)
STEP
=9.5
FORD
LINE
(0,
LINE
(5,
LINE
(5,
0)-(0, 5)-(5,
5) 5)
5)-(5, 0)-(0,
0) 0)
2
WINDOW
(0,
1 10)
0)-(6,
(6,
12
SCREEN
10)
0)-(10, 5)
use
VGA
‘For
SCREEN
line
and a tangent
REM Draw a circle
LINE END
r
NEXT
(0,
CIRGHEN(539
0 And
rate!
> 0 Then
Picturel.Print
DoubleYears(amount!,
Picture2.Print
MillionYears(amount!,
End
Let Textl.Text
= Val(Text1l.Text)
If amount!
= "Centigrade"
= "Convert
661
rate!) rate!)
If
Sub
= "Fahrenheit"
= "Convert
to Centigrade"
Function
If
Sub
DoubleYears!
Let
bal!
Let
years!
Do
(a!,
r!)
= a!
While
= 0
bal!
Let
bal!
Let
years!
< 2 * a!
= (1 +r!)
* bal!
= years!
+
1
Loop
End
Function
Function
MillionYears!
Let
bal!
Let
years!
Do While
(a!,
r!)
= a! = 0
bal!
Let
bal!
Let
years!
=
< 1000000 (1 + r!)
* bal!
= years!
+
1
Loop
End
Object
Property
Form]
Caption Alignment Caption
Labell Text Command1 Label2
Function
Setting Stamps 1 — Right Justify Number of Sheets of Paper
(blank)
Caption Alignment Caption
Determine Stamps Required 1 — Right Justify Number of stamps
Picture Sub
Command1
Let If
Click
stamps!
()
= Val(Textl.Text)
stamps!
>
Int(stamps!)
/ 5
Then
Int(stamps!)
stamps!
+ 1
Picturel.Cls Picturel.Print End
stamps!
Sub
PresidentialT
Object Form] Labell
Property Caption Caption
Setting Presidential Trivia Last name of one of the four most recent Presidents
Textl Text
Command! Picture! Sub Commandi Click ( ) Let pres$ = Textl.Text
Select Case UCase$(pres$) Case
Is
= "CARTER"
= "Georgia"
Let
state$
Let
trivia$
= "The
Let
trivia$
= trivia$
Case
Is
state$
Let
trivia$
Let
Is
soft
+ "White
in
served
drink
House
was
the
Carter
Coca-Cola."
= "REAGAN"
Let Case
only
= "California" = "His
secret
service
code
name
was
Rawhide."
= "BUSH"
state$
Let trivia$
= "Texas"
= "He was
the third
left-handed
president."
"
Alignment (blank) Caption
1 — Right Justify
Ok
Answers to Selected Odd-Numbered Exercises
662
Case
Is = "CLINTON"
Let state$ Let
End
= "Arkansas" = "In
trivia$
imitation
a good
he did
college
of
Elvis
Presley.”
Select
Picturel.Cls
Picturel.Print Picturel.Print
"President " + pres$ + "'s"; " home state was "+ state$ + "."
Picturel.Print Let Textl.Text
trivia$ = ""
Text1.SetFocus End
Sub
Sub
Commandl Click
Let Textl.Text End
Object Form1 Labell
Property Caption Caption Alignment
Textl Text Command!
(blank) Caption
Command2
Caption
()
= UCase$(Text1.Text)
Sub
Sub Command2 Click () Let sentence$ = Textl.Text Let End
Textl.Text
= CapFirst$(sentence$)
Sub
Function CapFirst$
(a$)
Let af = af
+ """
Let
= ""
result$
Do While Rem
‘cause ‘initial
Rtrim$(a$)
Find
end
of next
input
string
variable
to end
to hold
in a space
converted
sentence
"" word
(include
all
trailing
spaces)
Let place! = InStr(a$, " ") Do While Mid$(a$, place! +1, 1) =" " Let place! = place! + 1 Loop Rem Record next word and remove it from a$ Let word$ = Left(a$, place!) Let a$ = Mid$(a$, place! + 1) Rem
Capitalize
first
letter,
make
Let word$ = UCase$(Left$(word$, Rem Add word to results Let result$ = result$ + word$
sure
1))
other
letters
are
+ LCase$(Mid$(word$,
lowercase
2))
Loop
Let CapFirst$ End
result$
Function
Exercises 12.4 1. Goodbye
5,
1 2 3
9. The event procedure Command1_Click does not allow parameters. 11. Cannot have a string variable named num$ if you already have a single-precision variable named num!. 13.
The reserved word name cannot be used as a variable.
15. The Swap statement is not supported in Visual Basic; use Let temp = num1: Let num1 = num2: Let num2 = temp.
3.
$1,234.57
Setting Capitalization Sentence 1 — Right Justify Capitalize GEntire Sentence Capitalize GFirst Letter of Each Word
Answers to Selected Odd-Numbered Exercises
Wie
Picturel.Print
Format$(3.52*1000000000000,
"Currency")
(Note: 1 trillion is 1 followed by 12 zeros.)
a Nes
Let
Picturel.ScaleMode
Let
Picturel.CurrentX
= 2
‘Third
column
Let
Picturel.CurrentY
= 1
"Second
row
(first
using
units
Picturel.Print
23%
"Visual
Let
Picturel.ScaleMode
Let
Picturel.CurrentY
Picturel.Print
Let
sign$
Let
a$
MsgBox
Zo:
= 4
‘Position
=
1
"display
on
=
.5
‘display
half
a$,
can't
steal
, "Taking
is your second
Risks
Let Printer.FontBold Printer.Print
units
of characters
(first
column row
is
is 0) 0)
2nd
of characters
row
way
between
lst
& 2nd
row
zodiac
base
and
sign?") keep
one
foot
on
first."
Proverb"
= True
Sule
"Hello"
Let
Temp$
Let
Textl.Text
= Textl.Text
Let Text2.Text
33%
"#,#")
"4"
= InputBox$("What
= "You
using
Format$(2*10,
Basic"
Picturel.CurrentY
Let
‘Position
Picturel.Print
"x";
Picturel.Print
Weis Zi.
= 4
19.
ReDim a$(1975 To 1994)
35.
= Text2.Text
= Temp$
In the declarations section of (general) place the statement Dim nom$
Bile
Dim marx$(1
To 4)
‘in declaration
section
of
(general)
39.
Picturel.FontName Picturel.Print
Sub
41.
"S"
)
Form _Load( Let marx$(1)
= "Chico"
Let marx$(2)
= "Harpo"
Let marx$(3)
= "Groucho"
Let marx$(4)
= "Zeppo"
End
= "Symbol"
Sub
Picturel.DrawWidth
= 3
Picturel.Scale
4)-(10,
(0,
-4)
Picturel.Line
(1,
0)-(9,
0)
Picturel.Line
(9,
0)-(8,
2)
Picturel.Line
(9,
0)-(8,
-2)
Picturel.CurrentX
= 1
Picturel.Currenty
= -.1
Picturel.Print
"EAST"
Object Labell
Property Alignment Caption
Setting 1 — Right Justify How many quarters do you have?
Textl Command1
Text Caption
(blank) Display Dollars and Cents
Object Labell
Property Alignment Caption
Setting 1 — Right Justify Letter
Text 1
Text
(blank)
Label2
Alignment Caption
1 — Right Justify Number
Text2
Text
(blank)
Command!
Caption
Display Number as Subscript of Letter
Picturel Sub
Command1
Click
()
Picturel.Cls Picturel
Print
Picturel.Print End
Textl.Text
Format$(.25
+ " quarters
is";
* Val(Textl.Text),
"currency")
Sub
Picture
663
Answers to Selected Odd-Numbered Exercises
664
Sub
Commandl
Click
()
‘character
= 4
Picturel.ScaleMode
units
Picturel.Cls
Picturel.Print
Textl.Text;
Picturel.CurrentY Picturel.Print
End
= Picturel.CurrentY
+
.3
Text2.Text
Sub
Object Labell
- 1. Street Address
~ | =| od al
Property Alignment Caption
Setting 1 — Right Justify Name
City, State. Zip Code
r
Text]
Text
(blank)
Pica| eee eee
Alignment Caption Text Alignment Caption
1 — Right Justify Street Address (blank) 1 — Right Justify City, State, Zip Code
Text3
Text
(blank)
Command!
Caption
Print Letterhead
Label2 Text2
Label3
Sub
Command1
Rem
The
Click
number
() 93
was
chosen
Printer.ScaleMode
= 4
‘characters
Printer.CurrentX Printer.Print
& error
- Len(Textl.Text))
/ 2
=
(93
- Len(Text2.Text))
/ 2
- Len(Text3.Text))
/ 2
Text2.Text
Printer.CurrentX Printer.Print
(93
trial
Textl.Text
Printer.CurrentX Printer.Print
=
by
=
(93
Text3.Text
Printer.EndDoc
End
Sub
Object Picture Command!
Dim
instance!
‘in declaration
Sub Command1 Click If
instance! Let
section
instance!
=
1
Command1.Caption instance!
Picturel.Circle
End End
If
Sub
(general)
= 0 Then
= "Draw
-10) a Bigger
Else Let
Caption
()
Picturel.Scale (-10, 10)-(10, Picturel.Circle (0, 0), 1 Let
of
Property
= instance!
(0,
0),
+ 1
instance!
Circle"
__ Setting Draw Circle
Answers to Selected Odd-Numbered Exercises
J
An eres
beset
Object
Property
Setting
Text Text2 Command!
Text Text Caption FontSize Caption 12 Caption FontSize
(blank) (blank) F 12 -
Command2 FontSize Command3
Command4 Labell Picturel Label2 Command1
Sub
()
Click
Picturel.Cls
Picturel.Print End
Sub
Sub
Command2
+ Val(Text2.Text)
Val(Textl.Text)
Click
()
Picturel.Clis
Picturel.Print End
- Val (Text2.Text)
Val(Textl.Text)
Sub
()
Sub Command3 Click Picturel.Cls
Picturel.Print End
Sub
Sub
Command4
* Val(Text2.Text)
Val(Textl.Text)
Click
()
Picturel.Cls
Let
denom!
If denom! MsgBox
= Val(Text2.Text) = 0 Then "Division
by
zero
is
not
possible"
Else Picturel.Print
End If End Sub
Val(Textl.Text)
/ denom!
FontSize Caption
x 12 = Symbol 12 =
Caption
Enter numbers, then select operation to perform
Caption FontName
665
Index
! single-precision tag, 84 # format character, 94
# double-precision tag, 84 $ format character, 95
$ string tag, 53 % integer tag, 84 & long integer tag, 84 ’ for remark, 68
* multiplication operator, 40 \ \ / _ 4
format character, 96 integer division operator, 85 exponentiation operator, 40 format character, 99 to 3 ratio rule, 414
search of ordered, 288 shuffling of elements, 431 sorting, 305 static, 549 two-dimensional, 323, 345 variable, 272
ASC function, 59, 520 Ascending order, 287 ASCII table, 55, 515-516, 569 table display, 59 value, 55, 515-516
Breakpoint, 551, 596 removing and setting, 552, 595-596 Bricklin, Dan, 25 Bubble sort, 305, 307,345
flagged, 371 Bug, 29, 550 Button, Tom, 26 Byron, Augusta Ada, 22 CALL statement, 208, 521
Capitalization, 45, 214
Asterisk, 40 Asymptote, graphing vertical, 420 Atanasoff, John V., 23 AIN function, 80, 520
Caps Lock key, 7 Caption property, 466, 511, 598
Absolute value, 79 Accelerator keys, 580 Access key, 465
AutoRedraw property, 489, 597
Accumulator, 167, 171, 201 Addition, 40 Aiken, Howard, 23
BackColor property, 468, 512, 597-598 Background color, 415 Backslash, 96
CASE clause, 132, 541 Ceiling function, 91, 251 Chart flowchart, 31 hierarchy, 33
ABS function, 79, 520
Algebraic function, 79 Algorithm, 4, 29 merge, 290 Newton-Raphson, 206 Alignment property, 466, 511, 597 Allen, Paul, 25 Alt key, 8, 11, 13 AND logical operator, 112 Apostrophe, 70 Appending to a file, 358
Babbage, Charles, 22
Backspace key, 6, 13, 558
BackStyle property, 468, 598 Backus, John, 24 Bar menu, 5, 11 status, 5, 6
Arctangent, 80
title, 5 Bardeen, John, 24 Barnaby, Robert, 26 Base in exponentiation, 46 Base of a file name, 17 BASIC, 4 Binary file, 549 Binary search, 293, 313, 345 Binomial coefficient, 243
Argument, 212 Arithmetic operation, 40, 105
Bisection method, 173 Block of text, 559
Array, 272, 346
Body FOR...NEXT loop, 185
Arccosecant, 86 Arccosine, 86
Arccotangent, 86 Arcsecant, 86 Arcsine, 86
determining range, 294 dimension, 273
dynamic, 549
main, 209 Bohm, Corrado, 24
key field, 317 ordered, 287
Boole, George, 22
parallel, 278
Box model, 206 Branching, 256 Brattain, Walter, 24 Break, 372
passing, 291 range, 273, 276
removing, 278
BorderStyle property, 468, 512, 598
Caret, 40 Carriage return, 44
top-down, 31, 33
Checkbook case study, 502-511 Check-out receipt, 377 CHR$ function, 55, 521 Circle method, 493, 512, 598 CIRCLE statement, 413, 426, 521
Clearing a program from memory, 560, 567 Clipboard, 561, 568, 586 CLOSE statement, 358, 522
Closing a file, 357 Cls method, 472, 512, 599 CLS statement, 9, 522 Coding a program, 29 COLOR statement, 415, 522 Command button, 462, 465, 583 Common logarithm, 86 Comparison, 112 Compiler, 24 Complex numbers
addition and display, 136 nth root, 149, 226 Concatenation, 54 Condition, 112, 117, 147, 152 Confusing IF block, 121 Constant numeric, 40, 104 string, 53, 104
667
668
Index
Control character, 59 variable, 186, 201, 372 Control break processing, 371 Control variable, 186, 201, 372 Cooper, Alan, 26 Coordinate axes, drawing, 411
Coordinate systems, 409, 548 COPY command (DOS), 19 Copying text, 561, 586 COS function, 523 Cosecant, 86 Cosine, 80 Cotangent, 86 Coulomb’s law, 250 Counter, 167, 171 Counter variable, 288
Ctrl key, 7 Ctrl+End key, 11 Ctrl+Home key, 11 Currency, 486, 599
CurrentX property, 486, 495, 512, 599 CurrentY property, 486, 495, 512, 599 Cursor, 5
Cursor Down key, 13
Diskette, 2, 15
DOS, 4 drive, 2 QBasic, 4 Displaying a procedure, 214, 562, 593 Divide and conquer method, 34 Division, 40 DO loop, 152, 200, 524 Documentation, 30, 67-68, 70
Dollar sign, 53, 95
DOS 7 DOUBLE identifier in DIM, 396 Double-precision, 84, 85, 396
Debugging, 23, 29, 433, 550ff, 563-564, 595-596 Decision structure, 34 DECLARE statement, 215, 523 DEF FN statement, 83, 524
Default drive, 17 value, 46, 546 Del key, 7, 13, 558 Deleting a breakpoint, 552, 596 DeMorgan’s laws, 115 Derivative of a function, 175
Descending order, 287 Design modular, 214, 254-256 top-down, 214, 234, 254-256 Desk-checking, 38, 550 Dialog box, 9, 21, 581ff
(QB), 569-570 (VB), 588 Differential equations, graphing solutions to, 422 Dijkstra, Edsger W., 24 DIM statement, 273, 324, 393, 524 Dimension of an array, 273 DIR command (DOS), 19
Directory, 17, 546-547 root, 17, 583 subdirectory, 17 Direct-access file, 401 Disk, 17
Exiting QBasic, 11 Exiting Visual Basic, 584 EXP function, 79, 526 Exponent, 41, 46
Exponential function, 79 Exponentiation, 40 Expression, 105
numeric, 43
string, 54
Double-subscripted variable, 323
Extension of a file name, 17
Dragging mouse, 576 DrawStyle property, 493, 602 DrawWidth property, 495, 512, 602 Driver, 258 Dynamic array, 549
Fl key, 11 F2 key, 214 F4 key, 10
Eckert, J. Presper, 23 Editing commands, 558, 567-568,
586-587 Editor, 6 smart, 12 using (QB), 561, 567-568 Efficiency of sorts, 311 Element, 272 ELSE clause, 117, 132 Empty string, 58 END FUNCTION, 242 END IE 117 End key, 7, 13, 558 End of data, 167 END SELECT, 132
Notepad, 492
data, 17 direct-access, 401 length, 401
END statement, 525 End statement, 478, 489,
END SUB, 208 END TYPE, 393 EndDoc method, 488, 602 Ending Windows, 583 Enter a line, 12 Enter key, 8, 13 Environment, 561ff EOD (End Of Data), 167 EOF function, 359, 362, 526
ERASE command (DOS), 19 ERASE statement, 278 190
illegal function call, 85 NEXT without FOR, 190 out of data, 69 subscript out of range, 278 syntax, 10, 45, 69 Esc key, 5, 8, 13 Euler’s method, 421
Event trapping, 549
F6 key, 550 F7 key, 552 F8 key, 552 F9 key, 552 F10 key, 552 Faggin, Federico, 25 Field, 94, 392
binary, 549 closing, 357 creating with Windows’
ELSEIF clause, 120
Error, 10 FOR without NEXT,
F5 key, 552, 596
length, 392 File, 17
using (VB), 586-587
DATA statement, 63, 214, 523 Data file, 17
Event procedures, 472 Events, Visual Basic, 471ff Execute, 9 to cursor, 552
merging, 370 name, 17, 20, 356, 382 opening for append, 358 opening for input, 359 opening for output, 357 random-access, 361, 399, 405,
548-549 reading from, 359 reference number of, 356, 382 relative, 401
sequential, 356 sorting, 368-369 writing to, 357 Filespec, 18, 20, 362, 382, 547 FillColor property, 493, 603
FillStyle property, 493, 603 FIX function, 82, 527 Fixed-length string, 390-391, 405 Flag, 167, 171, 201
Flagged bubble sort, 317 Flowchart, 31, 257
Flowline, 31 Focus, 465 FontBold property, 468, 512, 603 Fontltalic property, 468, 512, 603
Index
FontSize property, 463, 511, 604 FOR...NEXT loop, 185, 201, 527 body, 185 control variable, 186, 201 initial value, 185
terminating value, 185 FOR without NEXT error, 190 ForeColor property, 463, 512, 605 Form, 461
design, 590-591
Format$, 485, 512, 605-607 Form_Load event, 506 FORMAT command (DOS), 18
Format string, 94 Frequency table, 277 Function, 78, 103, 242ff, 527-528 ABS, 79, 520 algebraic, 79 ASC, 59, 520 ATN, 80, 520 ceiling, 91, 251
CHR$,55, 521 COS; 0; 523) derivative of a, 175
EOE 359, 362, 526 EXP=79; 526 exponential, 79 FIX, 82, 527 graph of a, 418ff
Games of chance, 436ff
Integration, 259ff, 451
Gap in a Shell sort, 309
Interactive programming, 66 Interpreter, 24
Gates, Bill, 25, 458 General procedures (VB), 472, 475 GET statement, 400, 528 GotFocus event, 512, 607
GOTO statement, 38, 121, 256 Graphics, 408ff
Hercules card, 408 high-resolution, 409 with Visual Basic, 493ff GRAPHICS.COM, 409 Graphing functions, 418ff solutions to differential equations, 422 vertical asymptotes, 420 Greatest integer, 82
Iteration, 185, 256
Jacket, diskette, 16
Jacopini, Guiseppe, 24 Jobs, Stephen, 25 John Hancock building, 137 Kapor, Mitchell D., 26
Kemeny, John G., 24 Key Alt, 8, 11, 13 Backspace, 6, 13, 558
Caps Lock, 7 Hard copy of a program, obtaining, 1 S6R 513 Hard copy of output, 97-98 Hardware, 4 Height of projectile, 84 Help, 564, 565, 569, 587-588 Help screen, 11 Hercules graphics card, 408 Hierarchy chart, 33
High-resolution graphics, 409
INSTR, 57, 529 INT, 82, 529 key, 6 LBOUND, 294, 530 LEFT$, 56, 399, 530 LEN N17 995590 LOC, 401, 531 LOG, 79, 534 managing, 571-572 MID$, 56, 532 numeric, 78 Poisson probability, 253 RIGHTS, 56, 539 RND, 82, 428ff, 454, 539
Hoff, Ted, 25 Hollerith, Herman, 22
SGN, 82, 541 SIN, 80, 541 SOR, 79, 542 STR$, 542 string-valued, 56 TAB, 93, 98, 543 TAN, 80, 543 trigonometric, 80 UBOUND, 294, 544 UCASE$, 56, 544 user-defined, 83, 242 VAL, 544 zero of a, 173, 206 Fylstra, Dan, 25
Invoking QBasic, 566 Invoking Visual Basic, 461, 584 IS keyword in CASE, 133, 138
coordinate systems, 548
illegal call error, 85
RTRIM$, 392, 540
Inverse tangent, 80
Home key, 7, 13, 558 Hopper, Grace M., 23 Hotkey, 580 IF statement, 117, 529 block, 117, 147 block, confusing, 121 ELSEIF clause, 120
Illegal function call, 85 Immediate window, 5, 6, 550
using, 574 Increment, 186, 187 Index hole of a diskette, 15
Inequality, 112, 138 Infinite loop, 158 Initial value, 185 Input, 3, 28 INPUT statement, 66, 529
Inputting from a file, 359 Ins key, 7, 13, 559 Insert mode, 7 Installing Visual Basic, 461, 584 INSTR function, 57, 529 INT function, 82, 529 INTEGER identifier in DIM, 396 Integer,84, 85, 396 division, 85 long, 85
Cirle Ctrl+End, 11 Ctrl+Home, 11 Cursor Down,
13
Del, 7, 13558 End, 7, 13, 558 Enter, 8, 13 Esey 50, 19
Jel, Wl, Sxei7/ F2, 214 F4, 10 P55 ll; SS F6, 550 F7, 552, 596 lett, ‘oy? F9, 552 F10, 552 function, 6 Home, 7, 13, 558 Insy 7) 164559
Num Lock, 6, 13 PgDn, 558 PgUp, 558 PrtSc, 409 sequence,
11
Shift, 7, 13 Shift+F1, 6, 11, 569 Shift+F2, 214 Shift+F5, 10, 11, 567 Tab, 7, 467 toggle, 6 Key field of an array, 317 Keyboard, 2, 6 Keypad, numeric, 6 Keyword, 9, 45 KeyPress event, 512, 608 KILL statement, 20, 530 Knuth, Donald E., 25 Kurtz, Thomas E., 24
669
Index
670
Label, 15, 121, 549 Label (VB), 462, 466, 511 Last point referenced,413, 547-548 LBOUND function, 294, 530 Leading space, 44
Managing (VB) menus, 588-589 procedures, 593-594
Least squares approximation,
Mathematical notation, 40 Matrix, 327
203-204 LEFT$ function, 56, 530 LEN function, 57, 399, 530
Length field, 392
of file, 401 LET statement, 42, 53, 530 Library, 233
Line method, 493, 512, 609 LINE statement, 411, 413, 426, 530-531 Line choosing starting point when debugging, 553 clipping, 413 drawing a, 411 entering a, 12
feed, 44 number, 121 Loading a program, 560-561, 567
programs, 585 windows, 594-595
and vector multiplication, 328 Mauchley, John, 23 Mazer, Stan, 25 Memory, 2, 548 Menu bar, 5, 6, 11 Menus, 569-570, 588-589 Windows 580-581
Menu-driven program, 155 Merge algorithm, 290 Merging files, 370 Metacommand, 549
Methods, 477 Microprocessor, 2 Midpoint rule, 199, 259 MID$ function, 56, 532 Mills, Harlan B., 25
LOG function, 79, 531
MOD operator, 85 Mode graphics, 409 insert and overwrite, 7 text, 408 Modular design, 214, 254-256 Module, 33, 254 Modulo, 85
Logarithm
Monitor, 2
arbitrary base, 86 common, 86 natural, 79 Logical operator,112, 113, 147 LONG identifier in DIM, 396
Monte Carlo method, 446 Mouse, 575
LOC function, 401, 531 Local variable, 232, 267 LOCATE statement, 94, 531
LOF function, 401, 531
Long integer, 84, 85, 396 integer variable, 396 Lookup, table, 315 Loop, 152 DO, 152, 200, 524 FOR...NEXT, 189, 201, 527 infinite, 158 nested, 170, 190 structure, 36 LostFocus event, 473, 512, 609 LPRINT statement, 98, 532
Machine language, 3 Main body, 209 Managing (QB) debugger, 573-574 dialog box, 569-570 editor, 567-568 menus, 570 procedures, 571-572
programs, 566-567 windows, 572-573
scientific, 41 NotePad, 492 Noyce, Robert, 25 Null string, 58 Num Lock key, 6, 13, Numeric constant, 40, 104 expression, 43 function, 78 keypad, 6 variable, 42 variable types, 84 Objects (VB), 461ff, 511 OPEN statement, 356, 534 Opening a file for append, 358 for input, 359 for output, 357 Open, environment command, 560 Operator arithmetic, 40, 105 integer division, 85 logical, 112, 113, 147 MOD, 85 relational, 112, 147 OR logical operator, 113 Order, ascending and descending, 287 Ordered array, 287 search of, 288 Out of data error, 69 Output, 3, 28 Output screen, 10 Overwrite mode, 7
clicking, 576 double-clicking, 576
Parallel array, 278
dragging, 576 pointing, 575 using a, 517ff
Parameter, 211, 212, 242 Parent directory, 583 Parenthesis, 45 Pascal, 158
Moving text, 558-559, 568, 586 MsgBox, 488, 512, 611
MultiLine property, 464, 468, 611 Multiplication, 40
Name property, 467, 477, 612 NAME
statement, 20, 532
Naming a program, 567, 585 Natural logarithm, 79 Nested loop, 170, 190
Nesting, 121 NewPage method, 488, 612 New program, starting, 10 Newton-Raphson Algorithm, 206 New, environment command, 560 NEXT statement, 186 NEXT without FOR error, 190
NOT logical operator, 113, 532-533 Notation
mathematical, 40 QBasic, 40
Pass, 306 Passing, 209
arrays, 291 by reference, 228 records, 395 values, 227 variables, 227, 242 Path, 17 Pause, 70 Personal computer, 2 PgDn key, 558 PgUp key, 558 Pi, 80 Picture box, 462, 466-467, 512 Picture property, 466, 512, 612 Point, last referenced, 413, 547-548 Precision, double and single, 84, 85 Print method, 472, 512, 613 PRINT statement, 40, 44, 92, 536-537
Index
PRINT USING statement, 94, 99, 537 Print zone, 92, 98
Printed output, obtaining, 97-98 Printer, 2
Radian measure, 546 Random number, 82, 428 Random walk, 456 RANDOMIZE statement, 429, RANDOMIZE
PrintForm method, 489, 613 Printing a program, 561, 573, 595 Printing the screen, 97, 409 Problem solving, 4 Procedure, 208, 245
431, 454 Randomz-access file, 361, 399, 405, 548-549 Range array, 273, 276 determining for an array, 294 specifying in CASE, 133 subscript out of error, 278 Rational addition, 406
event, 472 general, 472, 475
managing, 571-572, 593-594 Procedure, function, 242 Procedure step, 551, 552, 596 Processing, 3, 28 control break, 371 Program, 3 choosing a starting line, 553
clearing from memory, 560, 567 development cycle, 29
TIMER statement,
READ statement, 63, 539
Reading from a file, 359 Read/write window, 16 Receipt, check-out, 377
Record, 392, 405
passing, 395 type, 392 variable, 393
menu-driven, 155 naming, 567, 585
ReDim, 489, 512, 613 Reference number of a file, 356, 382 Relational operator, 112, 147 Relative file, 401 REM statement, 67-68, 70, 539
printing, 561, 573, 595
Removing a breakpoint, 552, 596
running, 563, 566-567, 585 saving, 10, 561, 567 starting new, 10
Removing an array, 278 RENAME command (DOS), 20 Reserved word, 9, 45, 490 Restore button, 578 RESTORE statement, 65, 539 RIGHTS$, 56, 539 RND function, 82, 428, 454, 539 Root directory, 17, 583 Roulette, 436 Rounding, 82-83, 84 RTRIM$ function, 392, 540
item, 577
loading, 560-561, 567 Manager, 576-577
Programmer, 4 Programming development cycle, 29 interactive, 66
structured, 24, 25, 256
stub, 258 style, 70, 121, 158, 214, 278 Project, 460, 464 Project window, 462 Prompt, 66 Properties window, 462 how to access, 591-592 PrtSc key, 409 PSet method, 493, 512, 613 PSET statement, 412, 426, 538 Pseudocode, 31, 33, 38 Pseudo-random, 433 PUT statement, 399, 538 QBasic, 4 converting programs to Visual
Basic, 485ff exiting, 11, 561, 566 invoking, 566 notation, 40 QBColor, 493, 512, 613 Question mark, 66 Quotation mark, 59
Run, 9 Running a program, 563,
566-567, 585
Sampling, 432 Saving a program, 10, 561, 567 Scalar product, 303
Scale property, 493, 512, 614 ScaleMode property, 487 Scientific notation, 41 SCREEN statement, 409, 540 Screen
dump, 409 help, 11 output, 9, 10
printing, 97, 409 Scroll bar, 579 Search and replace, editor command,
562, 568
binary, 293, 313, 345
of ordered array, 288 sequential, 293, 313, 345
Searching, 313 Secant, 86
454, 538
Printer object, 488
displaying, 214, 562, 593
671
Seeding random number generator, 429 SELECT CASE statement, 132,
147, 541 Selector, 133, 147 Semicolon, 44 Sentinel, 167, 172, 200 Sequence structure, 34
Sequential file, 356 file sorting, 368 search, 293, 313, 345 SetFocus method, 477-478, 615
Setting a breakpoint, 552 Settings box, 463 SGN function, 82, 541 Shell sort, 24, 309, 345
gap, 309 Shell, Donald, 24 Shift key, 7, 13 Shift+F1 key, 6, 11, 569 Shift+F2 key, 214 Shift+F5 key, 10, 11, 567 Shockley, William, 24 Shortcut keys, 581 Shuffling of array elements, 431 Sign function, 82
Simple variable, 272 Simpson’s rule, 261 Simulation, 430 SIN function, 80, 541 SINGLE identifier in DIM, 390, 396
Single-precision, 84, 85, 396 variable, 390, 396
Single-subscripted variable, 323 Sizing handles, 462 Slope of a function, 175 Slot machine, 439 Smart editor, 12
Software, 4 Sort bubble, 305, 307, 345 DOS SORT command, 373 efficiency, 311 flagged bubble sort, 317 gap in Shell sort, 309 of a file, 368-369 of an array, 305 Shell, 24, 309, 345 Sorting, 305, 309
Space, leading and trailing, 44 Spaghetti code, 256 Specifying a coordinate system, 409 Spindle hole, 15 Spreadsheet, 25, 337ff
672
Index
SOR function, 79, 542 Square root, 79 Standard BASIC, 4 Standard deviation of data, 346 Starting line for debugging, 553 Statement, 9 Static array, 549 Status bar, 5, 6 STEP keyword in FOR, 187, 201 Step, ordinary and procedure, 552 Step value, 187 Stepping while debugging 551, 596 Stepwise refinement, 254 Stop execution at cursor, 552 STR$, 58, 542 STRING identifier in DIM, 390 String constant, 53, 104 empty, 58
expression, 54 fixed-length, 390-391, 405 format, 94 null, 58
string-valued function, 56 substring, 56 variable, 53 variable-length, 53 String-valued function, 56 Structure decision, 34
loop, 36 sequence, 34 Structured programming, 24, 25, 256 Stub programming, 258 SUB statement, 208, 543 Subdirectory, 17, 575
Subprogram, 208 managing, 571-572 Subroutine, 549 Subscript, 272
TAN function, 80, 543 Tangent, 80 Terminating value, 187
Text block, 559 copying, 561, 586 mode, 408 moving, 558-559, 568, 586 property, 463, 511, 616
numeric types, 84 passing, 227, 242
THEN keyword in IK 117 Title bar, 5,578 TO
string, 53
in CASE statement, 133 in FOR loop, 185
Toggle key, 6 Toolbox, 462 Top-down chart, 31, 33
design, 214, 234, 254-256 Trailer value, 167, 200 Trailing space, 44 Trapezoidal rule, 260
single-precision, 390, 396
single-subscripted, 323 subscripted, 272 Vector, 327 Vertical asymptote, graphing, 420 View window, 5 altering appearance of, 572-573 Visual Basic, 458-513 controls, 461 ff events, 47 Lff exiting, 584
HOW TOs, 584-596 installing, 461, 584 introduction to, 458-461 invoking, 461, 584
Truncate, 82
Primer edition of, 461
Truth value, 114 Turing, Alan, 23 Two-dimensional array, 323, 345 TYPE statement, 393, 543-544
printing programs, 595 properties, 462ff Standard edition of, 461
Type-declaration tag, 84 UBOUND
Statements, etc., 597-619 versions, 460-461 Von Neumann, John, 23
function, 294, 544
UCASE$ function, 56, 544 Ulam, Stanislaw, 23 Universal product code, 377 UNTIL keyword in DO loop, 152 WRC BT User, 4, 66 User-defined function, 83, 242 Using the editor, 561, 567-568,
Subtraction, 40 SWAP statement, 305, 317, 543 Sydnes, William L., 26 Syntax error, 10, 45, 69
VAL, 57, 544 Value ASCII, 55, 515-516, 569 default, 46, 546 initial, 185
list 132
Tab key, 7, 467 Table ASC, 55,515-516,569 display of ASCII, 59 editing commands, 558 frequency, 277 lookup, 315 Tag type-declaration, 84 Onis! %, &, !, and #, 84
simple, 272
objects, 461ff
586-587 Using the Immediate window, 574
TAB function, 93, 98, 543
record, 393
Trapping of events, 549 Trigonometric function, 80
Subscript out of range error, 278 Subscripted variable, 272 Substring, 56
System unit, 2
local, 232, 267 long integer, 396 numeric, 42
WHILE keyword in DO loop, 152 Wild card characters, 20, 560 Wilkes, Maurice V., 24 Window,
dialog, 9, 21, 569-570 Immediate, 5, 6, 550 Immediate, using, 574 managing, 572-573, 594-595 read/write, 15, 16 View, 5
View, altering appearance of, 5712-573 WINDOW statement, 410-411, 426, 546 Windows ending, 583
array, 272
how to utilize environment, 589-590 introduction to, 575-583 starting, 576-577 starting programs in, 578, 581 Wozniak, Stephen, 25 WRITE statement, 357, 546 WRITE# statement, 357, 546
control, 186, 201, 372 counter, 288
Write-protect notch, 15 Writing to a file, 357
passing, 227 step, 187 terminating, 187 trailer, 167, 200 truth, 114 Variable, 42, 104, 272
double-precision, 84, 396 double-subscripted, 323 integer, 84, 396
Zero of a function, 173, 206
Index of Selected Engineering, Mathematics, and Science Applications Chapter 3
Water use in the United States (Exercise 69, p. 51) Weight in grams of a mole (Exercise 70, p. 52) Distance of Sirius from Earth (Exercise 72, p. 52)
Time required for a baseball to reach home plate (Exercise 74, p. 52) Volume of the Earth (Exercise 46, p. 61) Pressure of a liquid (Exercise 6, p. 71)
Potential and kinetic energy (Exercise 8, p. 72) Stress produced on a bar by a force (Exercise 18, p. 73) Distance of a storm (Exercise 25, p. 75)
Ductility of a material in tension (Exercise 26, p.74) Calories burned during exercise (Exercise 27, p. 75) Training heart rate (Exercise 28, p. 75) Acceleration of gravity as a function of elevation (Exercise 30, p. 76) Atom density of isotopes (Exercise 34, p. 77)
Pythagorean theorem (Example 2, p. 79-80) Ballistic trajectory (Example 4, p. 81) Conversion of degrees to radians (Example 5, p. 82) Surveying (Example 5, p. 82) Distance of a point from the origin (Example 9, p. 84) Hyperbolic functions (Exercise 32, p. 88)
Stopping distance for a car (Exercise 39, p. 89) Velocity of a neutron (Exercise 40, p. 89) Moment of a force (Exercise 42, p. 89) Radioactive decay (Exercise 43, p. 89) Age of a rock (Exercise 44, p. 89) Law of cosines (Exercise 45, p. 90) Impedance of a circuit (Exercise 46, p. 90) Period of a pendulum (Exercise 47, p. 90) Harmonic mean of two numbers (Exercise 48, p. 90)
Conversion of polar to rectangular coordinates (Exercise 49, p. 90) Trajectory of a shot put (Exercise 50, p. 90) Taylor polynomial approximation of the sine function (Exercise 51, p. 90) Distance between two points (Exercise 52, p. 90) Radius of a circle in terms of its area (Exercise 53, p. 90) Rounding of a number to n decimal places (Exercise 57, p. 91) Conversion of nautical to standard hours (Exercise 59, p. 91) Base units of the metric system (Exercise 34, p. 102-103)
Conversion of U.S. to metric system lengths (Programming Project 6, p. 107) Number of calories in a food (Programming Project 7, p. 107) Construction of a trigonometric table (Programming Project 10, p. 108) Resistance of a conductor (Programming Project 11, p. 108) General law of perfect gases (Programming Project 12, p. 109) Kepler’s Third Law (Programming Project 13, p. 109) Chapter 4
Equivalent resistance for a circuit (Exercise 10, p. 124) Behavior of perfect gases (Exercise 12, p. 124-125)
Volumes of geometric objects (Exercise 16, p. 126) Force on a particle (Exercise 38, p. 129)
Mass number of chemical elements (Exercise 40, p. 129) Work done in changing the elongation of a spring and bar (Exercise 46, p. 130) Determination of the number of digits in a number (Exercise 49, p. 131)
673
674
Index
Addition and display of complex numbers (Example 5, p. 135-137) Rotation of a body with constant angular acceleration (Exercise 10, p. 141) Cloudiness descriptors (Exercise 33, p. 144) Areas of geometric objects (Exercise 36, p. 145) Percent of calories from fats (Programming Project 1, p. 147) Real roots of a quadratic equation (Programming Project 2, p. 147) Impedance of a circuit (Programming Project 4, p. 148-149) The nth root of a complex number (Programming Project 5, p. 149) Solution of a pair of linear equations (Programming Project 7, p. 149) Genetics (Programming Project 8, p. 149-150) Chapter 5
Decibel level of a sound (Example 2, p. 153)
Length, midpoint, and slope of the line joining two points (Example 5, p. 156-157) Resultant of forces acting on a body along the same axis (Exercise 4, p. 160) Atmospheric pressure (Exercise 11, p. 162) Molality of a solution (Exercise 12, p. 162)
Number of revolutions per minute of a generator (Exercise 24, p. 163) Conversion of Celsius to Fahrenheit (Exercise 25, p. 163)
Newton’s 2nd law and the equation of motion (Exercise 26, p. 163) Grains of wheat on a chess board (Exercise 32, p. 164) Solution of a linear equation (Exercise 35, p. 164) Coefficient of restitution of a ball (Exercise 37, p. 165) Current-voltage relationship in an ideal diode (Exercise 40, p. 165)
Change in the dimensions of a block due to a change in temperature (Exercise 42, p. 165) Prime factors of a number (Exercise 44, p. 166) Greatest common divisor (Exercise 45, p. 166)
Speed of a boat after the motor is turned off (Exercise 46, p. 167) Bisection method for finding a zero of a function (Example 7, p. 174-175) Derivative of a function (Example 8, p. 176) Surface tension of certain liquids (Exercise 10, p. 179) SI units and their symbols (Exercise 16, p. 180)
Equivalent capacitance in a parallel circuit (Exercise 20, p. 181) Physician’s abbreviations (Exercise 21, p. 181-182) Recursive algorithm (Exercise 23, p. 182)
Kingdoms of living things (Exercise 24, p. 182-183) Bisection method for finding all zeros of a function (Exercise 32, p. 184)
Determination of a zero of a polynomial (Exercise 33, p. 184) Average acceleration (Exercise 21, p. 193)
Sum of the reciprocals of integers (Exercise 29, p. 194) Sum of an arithmetic sequence (Exercise 30, p. 194) Mean value of a resistance (Exercise 32, p. 194) Voltage and current in an R-C series circuit (Exercise 34, p. 195) Ideal weights for men and women (Exercise 35, p. 195) Magnetic field produced by an electric current (Exercise 38, p. 196) Radioactive decay (Exercise 43, p. 196) Recursive generation of a sequence of numbers (Exercise 48, p. 197-198)
Proper divisors of an integer (Exercise 52, p. 198) Deflection of a beam (Exercise 53, p. 198-199)
Midpoint rule for approximating a definite integral (Exercise 54, p. 199) Snell’s Law (Exercise 56, p. 200) Half-life of radioactive elements (Programming Project 2, p. 201)
Least squares line (Programming Project 6, p. 203-204) Height of a ball thrown in the air (Programming Project 7, p. 205) Modeling of air pollution in a city (Programming Project 9, p. 206) Newton-Raphson algorithm for finding a zero of a function (Programming Project 10, p. 206)
Chapter6
Angular frequency (Exercise 16, p. 219) Force needed to stretch a spring (Exercise 20, p. 220)
675
Molarity of a solution (Exercise 21, p. 220)
Pressure produced by a force acting on specific area (Exercise 56, p. 225) The n nth roots of a complex number (Exercise 62, p. 226)
Flash point of a liquid (Exercise 6, p. 235) Change in the length of an axially loaded bar under compression (Exercise 10, p. 236) Temperature rise from the compression of a perfect gas (Exercise 20, p. 238) Conversion of feet and inches to centimeters (Exercise 31, p. 240) Different forms for the equation of a line (Exercise 41, p. 241) Number of positive, negative, and zero values of a function (Exercise 42, p. 241)
Power of a complex number (Exercise 43, p. 241) Hypotenuse of a right triangle (Example 2, p. 243) Binomial coefficients (Example 3, p. 243-244) Flexibility of an axially loaded steel bar (Exercise 2, p. 246-247) Number of atoms in a substance (Exercise 4, p. 247) Oil consumption (Exercise 10, p. 248-249) Number of moles of atoms in a substance (Exercise 16, p. 250) Coulomb’s law (Exercise 18, p. 250) Training heart rate (Exercise 22, p. 251) Factorial of a number (Exercise 28, p. 252)
Accuracy of Stirling’s formula (Exercise 29, p. 252) Number of real roots of a quadratic equation (Exercise 30, p. 252) Number of prime factors of a number (Exercise 31, p. 252) Least common multiple of two numbers (Exercise 32, p. 252) Heron’s formula (Exercise 34, p. 252) FORTRAN’s ATAN2(y,x) function (Exercise 35, p. 252)
Amount of water displaced by a sphere (Exercise 36, p. 252-253) Conversion of feet to meters Prime numbers (Exercise 38, Arccosine function (Exercise Poisson probability function
and vice versa (Exercise 37, p. 253) p. 253) 39, p. 253) (Exercise 42, p. 253)
Binary representation of a positive integer (Exercise 43, p. 253) Average value of a function (Exercise 44, p. 254)
Numerical integration (Case Study, p. 259-267) Velocity and acceleration of the moon (Programming Project 1, p. 267-268) Mass composition of a substance (Programming Project 2, p. 268) Heat necessary to increase the temperature of a metal (Programming Project 3, p. 268) Conversion between deg-min-sec, decimal degrees, and radians (Prog. Pr. 4, p. 268)
Analysis of a quadratic function (Programming Project 5, p. 268-269) Number palindromes (Programming Project 6, p. 269) Perfect numbers (Programming Project 7, p. 269)
Symbolic addition (Programming Project 8, p. 269) Taylor polynomial approximation (Programming Project 9, p. 270) Chapter 7
Effect of an increase in temperature on the length of a bar (Exercise 4, p. 279-280) Power received at the Earth’s surface (Exercise 6, p. 280) Morse code (Exercise 32, p. 284-285) Velocity flow of a fluid (Exercise 34, p. 285) Tensile strength test of steel (Exercise 36, p. 285-286)
Histogram of missile velocities (Exercise 37, p. 286) Current at a branch point (Exercise 32, p. 301) Speed of sound in various substances (Exercise 36, p. 301) Moh’s hardness scale for minerals (Exercise 38, p. 302) Inner product of two vectors (Exercise 43, p. 303)
Center of mass of a system of particles (Exercise 44, p. 303) Boiling points of substances (Exercise 45, p. 303) Atomic data for some elements (Exercise 48, p. 304) Planet data (Exercise 26, p. 320)
Chemical elements found in animals (Exercise 32, p. 322)
676
Index
Boiling points of metals (Exercise 34, p. 322) Nutritional components of foods (Example 2, p. 325-327)
Multiplication of a vector by a matrix (Example 3, p. 328-329) Heat capacity of a material (Exercise 2, p. 329) Magnetic energy stored in an inductor (Exercise 8, p. 330) Period of a pendulum (Exercise 16, p. 331) Matrix multiplication (Exercise 18, p. 332) The nth power of a matrix (Exercise 20, p. 332) Matrix addition (Exercise 21, p. 332)
Transpose of a matrix (Exercise 22, p. 332) Chemical composition of substances (Exercise 25, p. 332-333)
Widths of two-lane highways (Exercise 27, p. 333) Magic squares (Exercise 34, p. 335-336) Monthly precipitation (Exercise 35, p. 336)
Perimeter of a polygon (Exercise 36, p. 336) Euclidian norm of a matrix (Exercise 37, p. 336)
Calculating with a spreadsheet (p. 337-345) Conversion of lengths to various units (Programming Project 1, p. 346) Mean and standard deviation used to curve grades (Programming Project 2, p. 346) Language translation (Programming Project 3, p. 347) Evaluation, differentiation, and integration of polynomials (Prog. Pr. 7, p. 348-349) Elementary row operations on matrices (Programming Project 8, p. 349) Matrix inversion (Programming Project 9, p. 350) Intersection and union of sets (Programming Project 10, p. 350) Solving an electric circuit (Programming Project 11, p. 350-351) Game of Life (Programming Project 12, p. 351) Linear shift registers (Programming Project 13, p. 352-353 Chapter 8
Thermal conductivity (Exercises 23, 25, 26, p. 366-367) Flow of heat through a material (Exercise 24-26, p. 367) Quality control (Exercise 30, p. 367) Radioactive elements (Exercises 5-7, p. 374) Densities of metals (Exercise 10, p. 375) Burn rates of rocket propellants (Exercise 12, p. 375) Prime factorization of a number (Programming Project 5, p. 384)
Frequencies for the visible spectrum (Programming Project 6, p. 384-385) Astronomical data (Programming Project 7, 8, p. 385-386) Fuel economy (Programming Project 9, p. 387)
Chapter9
Chapter 10
— Rational addition (Programming Project 3, p. 406)
Graphs of straight lines (Exercises 27 & 28, p. 417) Graphs of functions (Examples 1 & 2, p. 418-421) Euler’s method for solving differential equations (Example 3, p. 422-423) Taylor polynomial approximations of e* (Exercises 19 & 20, p. 424) Tangent line to a graph (Exercise 24, p. 425) Secant line approximation of the tangent line (Exercise 25, p. 425) Inverse of a function (Exercise 27, p. 425)
Polar coordinate graphs (Programming Project 1, p. 426) The derivative of a function (Programming Project 3, p. 426) Chapter 11
Simulation of a line at the box office (Exercise 24, p. 434) Selection of a subset of a set (Exercise 27, p. 434-435)
Birthday problem (Exercise 29, p. 435) Simulation of tellers serving bank lines (Examples 1 & 2, p. 446-449) Monte Carlo estimation of the area under a curve (Example 4, p. 451-452) Simulation of airline overbooking of a flight (Exercise 8, p. 453) Game Theory (Programming Project 2, p. 455) Random walk (Programming Project 3, p. 456) Knight’s tour (Programming Project 4, p. 456)
The diskette in this book has two subdirectoriee—EXAMPLES and VBPRIMER.
Examples The subdirectory EXAMPLES contains all the programs from the examples and case studies of this textbook. The QBASIC case study programs have the suggestive names INTEGRAL.BAS, SPRSHEET.BAS, and CHECKOUT.BAS. The other QBasic programs have names of the form chapter-section-number.BAS. For instance, the program in Chapter 3, Section 2, Example 4 has the name 3-2-4.BAS. Visual Basic examples have
the same type base name, but end in .MAK. The following steps open these programs. (Assume that the diskette is in the A drive.) 1. Press Alt/F/O
2. Enter
A:\EXAMPLES
3. Press Tab
4. Cursor to the desired program (Note: To move quickly to the beginning of the programs from Chapter 3, press 3.) 5. Press the Enter key.
VBPRIMER The files in this subdirectory are used to install the Primer Edition of Visual Basic 2.0 on the hard disk of a computer on which Windows has been installed. To install Visual Basic follow the steps in part A on page 584. Note: If your computer does not have a standard configuration, you might be asked one or two additional questions during the installation process.
MICROSOFT SOFTWARE LICENSE READ THIS FIRST. Your use of the Microsoft software (the “SOFT WARE”)
is governed by the legal agreement below.
MS TER THE BY ND BOU BE TO NG EEI AGR ARE YOU E KAG PAC ETTE DISK ED SEAL THE G NIN OPE BY YOU NS, ITIO COND AND S TERM SUCH WITH E AGRE NOT DO YOU IF W. BELO SET S ION DIT CON AND E PLAC THE TO BOOK THE WITH ER ETH TOG E KAG PAC ETTE DISK ED PEN UNO THE URN RET ULD SHO YOU OBTAINED THEM FOR A REFUND. 1. GRANT OF LICENSE. Microsoft grants to you the right to use the enclosed SOFTWARE. You may make additional copies for demonstration purposes. 2. COPYRIGHT. The SOFTWARE is owned by Microsoft or its suppliers and is protected by United States copyright laws and international treaty provisions. 3. OTHER
RESTRICTIONS.
You may not rent, sell, or lease the SOFTWARE.
You may not reverse engineer,
decompile or disassemble the SOFTWARE.
DISCLAIMER OF WARRANTY
AND LIMITED WARRANTY
THE SOFT WARE AND ACCOMPANYING WRITTEN MATERIALS (INCLUDING INSTRUCTIONS FOR USE) ARE PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND. FURTHER, MICROSOFT DOES NOT WARRANT, GUARANTEE, OR MAKE ANY REPRESENTATIONS REGARDING THE USE, OR THE RESULTS OF THE USE, OF THE SOFTWARE OR WRITTEN MATERIALS IN TERMS OF CORRECTNESS, ACCURACY, RELIABILITY, CURRENTNESS, OR OTHERW&3E. THE ENTIRE RISK AS TO THE RESULTS AND PERFORMANCE OF THE SOFTWARE IS ASSUMED BY YOU. IF THE SOFTWARE OR WRITTEN MATERIALS ARE DEFECTIVE YOU, AND NOT MICROSOFT OR ITS DEALERS, DISTRIBUTORS, AGENTS, OR EMPLOYEES, ASSUME THE ENTIRE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. The diskette in this book was reproduced by Dellen Publishing Company under a special arrangement with Microsoft Corporation. For this reason, Dellen Publishing Company is responsible for the product warranty and for support. If your diskette is defective, please return it to Dellen Publishing Company, which will arrange for its replacement. In no event shall Microsoft’s liability and your exclusive remedy as to defective software, written materials, and disks be other than either (a) return of the purchase price or (b) replacement of the disk which is returned to
Microsoft with a copy of the receipt. If failure of the disk has resulted from accident, abuse or misapplication, Microsoft shall have no responsibility to replace the disk or refund the purchase price. Any replacement disk will be warranted . for thirty (30) days. NO OTHER WARRANTIES. MICROSOFT DISCLAIMS ALL OTHER WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, WITH RESPECT TO THE SOFTWARE AND ANY ACCOMPANYING HARDWARE. THIS LIMITED WARRANTY GIVES YOU SPECIFIC LEGAL RIGHTS. YOU MAY HAVE OTHERS, WHICH VARY FROM STATE TO STATE. NO LIABILITY FOR CONSEQUENTIAL DAMAGES. IN NO EVENT SHALL MICROSOFT OR ITS SUPPLIERS BE LIABLE FOR ANY DAMAGES WHATSOEVER (INCLUDING WITHOUT LIMITATION DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OR INABILITY TO USE THIS MICROSOFT PRODUCT EVEN IF MICROSOFT HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. BECAUSE SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES, THE ABOVE LIMITATION MAY NOT APPLY TO TOU;
U.S. GOVERNMENT
RESTRICTED RIGHTS
The SOFTWARE and documentation are provided with RESTRICTED RIGHTS. Use, duplication, or disclosure by the Government is subject to restrictions as set forth in subparagraph (c)(1)(ii) of the Rights in Technical Data and Computer software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and (2) of the Commercial Computer Software—Restricted Rights at 48 CFR 52.227-19, as applicable. Manufacturer is Microsoft Corporation/One Microsoft Way/Redmond. WA 98052-6399.
If you acquired this product in the United States, this Agreement is governed by the laws of the State of Washington. If you acquired this product in Canada, this Agreement is governed by the laws of the Province of Ontario, Canada. Each of the parties hereto irrevocably attorns to the jurisdiction of the courts of the Province of Ontario and further agrees to commence any litigarionadwhich easy, arise hereunder in the courts located in the Judicial District of York, Province of Ontario.
KE MEMORIAL LIBRARY ea C. SMITH UNIVERSITY CHARLOTTE, N. C. 28216
DATE DUE pe
PRINTED IN U.S.A.
GAYLORD
005.1383
BSch5q
schneider,
QBASIC
David
1994 I.