Preface
1 of 10
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
This book gives an introd...
175 downloads
1332 Views
21MB Size
Report
This content was uploaded by our users and we assume good faith they have the permission to share this book. If you own the copyright to this book and it is wrongfully on our website, we offer a simple DMCA procedure to remove your content from our site. Start by pressing the button below!
Report copyright / DMCA form
Preface
1 of 10
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
This book gives an introduction into C++ and computer programming that focuses on the essentials—and on effective learning. The book is suitable for a first course in programming for computer scientists, engineers, and students in other technical or scientific disciplines. No prior programming experience is required, and only a modest amount of high school algebra is needed. Here are the key features of this new book: • A Visual Approach Motivates the Reader and Eases Navigation. This book contains many more photographs, diagrams, and tables than other programming books. It is easy to get the “lay of the land” by browsing the visuals, before focusing on the textual material.
Visual features help the reader with navigation.
• Guidance and Worked Examples Help Students Succeed. Beginning programmers often ask “How do I start? Now what do I do?” Of course, an activity as complex as programming cannot be reduced to cookbook-style instructions. However, step-by-step guidance is immensely helpful for building confidence and providing an outline for the task at hand. The book contains a large number of “How To” guides for common tasks, together with additional worked examples on the web. • Practice Makes Perfect. Of course, programming students need to be able to implement nontrivial programs, but they first need to have the confidence that they can succeed. This book contains a substantial number of self-check questions (at the end of each section), simple programming assignments, and an electronic test bank. • Teach Computer Science Principles, Not Just C++ or Object-Orientation. This book uses the C++ programming language as a vehicle for introducing computer science concepts. A substantial subset of the C++ language is covered, focusing on the modern features of standard C++ that make students productive. The book starts gently by showing how to use objects (in particular, strings and streams). Then it takes a traditional route, stressing functions and procedural decomposition, before turning to the design of classes in the final chapters. • Focus on the Essentials While Being Technically Accurate. An encyclopedic coverage is not helpful for a beginning programmer, but neither is the opposite—reducing the material to a list of simplistic bullet points. In this book, the essential essentials of each subject are presented in digestible chunks, with separate notes that go deeper into good practices or language features when the reader is ready for the additional information. You will not find artificial over-simplifications that give an illusion of knowledge.
2/1/2010 2:56 PM
Preface
2 of 10
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
The core material of the book is: Chapter 1. Introduction Chapter 2. Fundamental Data Types Chapter 3. Decisions Chapter 4. Loops Chapter 5. Functions Chapter 6. Arrays and Vectors In a course for engineers with a need for systems and embedded programming, you will want to cover Chapter 7 on pointers. Sections 7.1 and 7.4 are sufficient for using pointers with polymorphism in Chapter 10. File processing is the subject of Chapter 8. Section 8.1 is sufficient for an introduction into reading and writing text files. The remainder of the chapter gives additional material for practical applications. Chapters 9 and 10 introduce the object-oriented features of C++. Chapter 9 contains an introduction to class design and implementation. Chapter 10 covers inheritance and polymorphism. Four additional chapters are available on the Web. They can be used individually for a capstone chapter, or they can be combined for teaching a two-semester course. (They can also be incorporated into a custom print version of the text; ask your Wiley sales representative for details.) Chapter 11. Recursion Chapter 12. Sorting and Searching Chapter 13. Lists, Queues, and Stacks Chapter 14. Sets, Maps, and Priority Queues Figure 1 shows the dependencies between the chapters.
2/1/2010 2:56 PM
Preface
3 of 10
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
Figure 1 Chapter Dependencies
Appendices Appendix A contains a programming style guide. Using a style guide for programming assignments benefits students by directing them toward good habits and reducing gratuitous choice. The style guide is available in electronic form so that instructors can modify it to reflect their preferred style. Appendices B and C summarize C++ reserved words and operators. Appendix D lists character escape sequences and ASCII character code values. Appendix E documents all of the library functions and classes used in this book. An expanded version of this Appendix that includes the functions and classes used in the four optional chapters, 11—14, is available on the Web and in WileyPLUS. Appendices F, G, and H cover number systems, bit and shift operations, and a comparison of C++ and Java; all three are on the Web and in WileyPLUS.
2/1/2010 2:56 PM
Preface
4 of 10
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
The pedagogical elements in this book work together to focus on and reinforce key concepts and fundamental principles of programming, with additional tips and detail organized to support and deepen these fundamentals. In addition to traditional features, such as chapter objectives and a wealth of exercises, each chapter contains elements geared to today's visual learner.
2/1/2010 2:56 PM
Preface
5 of 10
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
Special Features Seven special features add detail and provide step-by-step guidance. Identified with the icons shown here, they are set off so they don't interrupt the flow of the main material. Some of these are quite short; others extend over a page. Each topic is given the space that is needed for a full and convincing explanation—instead of being forced into a one-paragraph “tip”. You can use the tables on pages xxii—xxv to see the features in each chapter and the page numbers where they can be found.
2/1/2010 2:56 PM
Preface
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
6 of 10
2/1/2010 2:56 PM
Preface
7 of 10
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
The book is supplemented by a complete suite of online resources and a robust WileyPLUS course.
Student and Instructor Resources The following resources for students and instructors can be obtained by visiting www.wiley.com/college/horstmann (or the WileyPLUS course for the book). Two companion web sites accompany the book—one for students, and a password-protected site for instructors only. • Solutions to all exercises (for instructors only)
2/1/2010 2:56 PM
Preface
8 of 10
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
• A test bank (for instructors only) • Lecture presentation slides that summarize each chapter and include code listings and figures from the book (for instructors only) • Source code for all examples in the book • Additional worked examples and appendices (identified by an icon,
)
• Four additional chapters on recursion, sorting and searching, and data structures • The programming style guide in electronic form, so you can modify it to suit local preferences
Students can locate the Worked Examples and other content marked with a plus icon, or on the web site for the book at www.wiley.com/college/horstmann.
, in the WileyPLUS course
WileyPLUS
The first two pages of this book describe an innovative online tool for teachers and students: WileyPLUS is an online learning environment that combines all of the resources of a learning management system with an ebook. With WileyPLUS, instructors can manage reading and homework assignments, create tests, assign quizzes, and store results in an online gradebook. A WileyPLUS adoption also enables students to purchase an eBook at a fraction of the price of the print edition. In addition to the eBook, WileyPLUS integrates all of the instructor and student web resources into an online version of this text. For more information and a demo, please visit the web site listed on pages i-ii, or talk to your Wiley representative.
Many thanks to Dan Sayre, Lauren Sapira, Lisa Gee, and Carolyn Weisman at John Wiley & Sons, and to the team at Publishing Services for their hard work and support for this book project. An especially deep acknowledgment and thanks to Cindy Johnson, who, through enormous patience and attention to detail, made this book a reality. We would also like to thank Jonathan Tolstedt, North Dakota State University, for working with us to prepare the solutions. We are very grateful to the many individuals who reviewed the book and made many valuable suggestions for improvement. They include:
2/1/2010 2:56 PM
Preface
9 of 10
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
Charles D. Allison, Utah Valley State College
Fred Annexstein, University of Cincinnati
Stefano Basagni, Northeastern University
Noah D. Barnette, Virginia Tech
Peter Breznay, University of Wisconsin, Green Bay
Kuang-Nan Chang, Eastern Kentucky University
Joseph DeLibero, Arizona State University
Subramaniam Dharmarajan, Arizona State University
Stephen Gilbert, Orange Coast Community College
Barbara Guillott, Louisiana State University
Jon Hanrath, Illinois Institute of Technology
Neil Harrison, Utah Valley University
Debbie Kaneko, Old Dominion University
Mir Behrad Khamesee, University of Waterloo
Sung-Sik Kwon, North Carolina Central University
W. James MacLean, University of Toronto
Ethan V. Munson, University of Wisconsin, Milwaukee
Philip Regalbuto, Trident Technical College
John P. Russo, Wentworth Institute of Technology
2/1/2010 2:56 PM
Preface
10 of 10
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
Kurt Schmidt, Drexel University
William Shay, University of Wisconsin, Green Bay
Michele A. Starkey, Mount Saint Mary College
William Stockwell, University of Central Oklahoma
Jonathan Tolstedt, North Dakota State University
Kerstin Voigt, California State University, San Bernardino
David P. Voorhees, Le Moyne College
Salih Yurttas, Texas A&M University
Copyright © 2009 John Wiley & Sons, Inc. All rights reserved.
2/1/2010 2:56 PM
Chapter Goals To learn abo ...
1 of 1
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
Chapter
Chapter Goals • To learn about the architecture of computers • To learn about machine languages and higher-level programming languages • To become familiar with your compiler • To compile and run your first C++ program • To recognize syntax and logic errors • To understand the notion of an algorithm • To understand the activity of programming This chapter contains a brief introduction to the architecture of computers and an overview of programming languages. You will learn about the activity of programming: how to write and run your first C++ program, how to diagnose and fix programming errors, and how to plan your programming activities.
Copyright © 2009 John Wiley & Sons, Inc. All rights reserved.
2/1/2010 8:21 AM
What is a Computer?
1 of 2
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
You have probably used a computer for work or fun. Many people use computers for everyday tasks such as electronic banking or writing a term paper. Computers are good for such tasks. They can handle repetitive chores, such as totaling up numbers or placing words on a page, without getting bored or exhausted. Computers execute very basic operations in rapid succession.
The flexibility of a computer is quite an amazing phenomenon. The same machine can balance your checkbook, print your term paper, and play a game. In contrast, other machines carry out a much narrower range of tasks; a car drives and a toaster toasts. Computers can carry out a wide range of tasks because they execute different programs, each of which directs the computer to work on a specific task. The computer itself is a machine that stores data (numbers, words, pictures), interacts with devices (the monitor, the sound system, the printer), and executes programs. A computer program tells a computer, in minute detail, the sequence of steps that are needed to fulfill a task. The physical computer and peripheral devices are collectively called the hardware. The programs the computer executes are called the software. A computer program is a sequence of instructions and decisions.
Today's computer programs are so sophisticated that it is hard to believe that they are composed of extremely primitive operations. A typical operation may be one of the following: • Put a red dot at this screen position. • Add up these two numbers. • If this value is negative, continue the program at a certain instruction. The computer user has the illusion of smooth interaction because a program contains a huge number of such operations, and because the computer can execute them at great speed. The act of designing and implementing computer programs is called programming. In this book, you will learn how to program a computer—that is, how to direct the computer to execute tasks. Programming is the act of designing and implementing computer programs.
To write a computer game with motion and sound effects or a word processor that supports fancy fonts and pictures is a complex task that requires a team of many highly skilled programmers. Your first programming efforts will be more mundane. The concepts and skills you learn in this book form an important foundation, and you should not be disappointed if your first programs do not rival the sophisticated software that is familiar to you. Actually, you will find that there is an immense thrill even in simple programming tasks. It is an amazing experience to see the computer precisely and quickly carry out a task that would take you hours of drudgery, to make small changes in a program that lead to immediate improvements, and to see the computer become an extension of your mental powers.
Self Check 1. What is required to play music on a computer? 2. Why is a CD player less flexible than a computer? 3. What does a computer user need to know about programming in order to play a video game?
2/1/2010 8:21 AM
The Anatomy of a Computer
1 of 3
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
To understand the programming process, you need to have a rudimentary understanding of the building blocks that make up a computer. We will look at a personal computer. Larger computers have faster, larger, or more powerful components, but they have fundamentally the same design. At the heart of the computer lies the central processing unit (CPU) (see Figure 1). It consists of a single chip, or a small number of chips. A computer chip (integrated circuit) is a component with a plastic or metal housing, metal connectors, and inside wiring made principally from silicon. For a CPU chip, the inside wiring is enormously complicated. For example, the Pentium chip (a popular CPU for personal computers at the time of this writing) is composed of several million structural elements, called transistors.
Figure 1 Central Processing Unit
Copyright © 2008, Intel Corporation. The CPU performs program control and data processing. That is, the CPU locates and executes the program instructions; it carries out arithmetic operations such as addition, subtraction, multiplication, and division; it fetches data from external memory or devices and stores data back. All data must travel through the CPU whenever it is moved from one location to another. The central processing unit (CPU) performs program control and data processing.
The computer stores data and programs in memory. There are two kinds of memory. Primary storage is made from memory chips: random-access memory (RAM) and read-only memory (ROM). Read-only memory contains certain programs that must always be present—for example, the code needed to start the computer. Random-access memory might have been better called “read-write memory”, because the CPU can read data from it and write data back to it. That makes RAM suitable to hold changing data and programs that do not have to be available permanently. RAM memory has two disadvantages. It is comparatively expensive, and it loses all its data when the power is turned off. Secondary storage, usually a hard disk (see Figure 2), provides less expensive storage that persists without electricity. A hard disk consists of rotating platters, which are coated with a magnetic material, and read/write heads, which can detect and change the magnetic flux on the platters. Programs and data are typically stored on the hard disk and loaded into RAM when the program starts. The program then updates the data in RAM and writes the modified data back to the hard disk.
2/1/2010 8:22 AM
The Anatomy of a Computer
2 of 3
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
Figure 2 A Hard Disk
PhotoDisc, Inc./Getty Images.
Storage devices include random-access memory (RAM) and secondary storage.
To interact with a human user, a computer requires peripheral devices. The computer transmits information (called output) to the user through a display screen, speakers, and printers. The user can enter information (called input) for the computer by using a keyboard or a pointing device such as a mouse. Some computers are self-contained units, whereas others are interconnected through networks. Through the network cabling, the computer can read data and programs from central storage locations or send data to other computers. For the user of a networked computer it may not even be obvious which data reside on the computer itself and which are transmitted through the network. Figure 3 gives a schematic overview of the architecture of a personal computer. Program instructions and data (such as text, numbers, audio, or video) are stored on the hard disk, on a CD-ROM, or elsewhere on the network. When a program is started, it is brought into RAM memory, from where the CPU can read it. The CPU reads the program one instruction at a time. As directed by these instructions, the CPU reads data, modifies it, and writes it back to RAM memory or the hard disk. Some program instructions will cause the CPU to place dots on the display screen or printer or to vibrate the speaker. As these actions happen many times over and at great speed, the human user will perceive images and sound. Some program instructions read user input from the keyboard or mouse. The program analyzes the nature of these inputs and then executes the next appropriate instructions.
2/1/2010 8:22 AM
The Anatomy of a Computer
3 of 3
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
Figure 3 Schematic Design of a Personal Computer
Self Check 4. Where is a program stored when it is not currently running? 5. Which part of the computer carries out arithmetic operations, such as addition and multiplication?
Copyright © 2009 John Wiley & Sons, Inc. All rights reserved.
2/1/2010 8:22 AM
RANDOM FACT 1.1 The ENIAC and the Dawn of Computing
1 of 2
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
Random Fact 1.1
RANDOM FACT 1.1 The ENIAC and the Dawn of Computing
The ENIAC (electronic numerical integrator and computer) was the first usable electronic computer. It was designed by J. Presper Eckert and John Mauchly at the University of Pennsylvania and was completed in 1946—two years before transistors were invented. The computer was housed in a large room and consisted of many cabinets containing about 18,000 vacuum tubes (see Figure 4). Vacuum tubes burned out at the rate of several tubes per day. An attendant with a shopping cart full of tubes constantly made the rounds and replaced defective ones. The computer was programmed by connecting wires on panels. Each wiring configuration would set up the computer for a particular problem. To have the computer work on a different problem, the wires had to be replugged.
Figure 4 The ENIAC
Courtesy of Sperry Univac, Division of Sperry Corporation. Work on the ENIAC was supported by the U.S. Navy, which was interested in computations of ballistic tables that would give the trajectory of a projectile, depending on the wind resistance, initial velocity, and atmospheric conditions. To compute the trajectories, one must find the numerical solutions of certain differential equations; hence the name “numerical integrator”. Before machines like the ENIAC were developed, humans did this kind of work, and until the 1950s the word “computer” referred to these people. The ENIAC was later used for peaceful purposes such as the tabulation of U.S. Census data.
2/1/2010 8:22 AM
Machine Code and Programming Languages
1 of 2
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
On the most basic level, computer instructions are extremely primitive. The processor executes machine instructions. A typical sequence of machine instructions is 1. Move the contents of memory location 40000 into the CPU. 2. If that value is > 100, continue with the instruction that is stored in memory location 11280. Actually, machine instructions are encoded as numbers so that they can be stored in memory. On a Pentium processor, this sequence of instruction is encoded as the sequence of numbers
Computer programs are stored as machine instructions in a code that depends on the processor type.
On a processor from a different manufacturer, the encoding would be different. When this kind of processor fetches this sequence of numbers, it decodes them and executes the associated sequence of commands. How can we communicate the command sequence to the computer? The simplest method is to place the actual numbers into the computer memory. This is, in fact, how the very earliest computers worked. However, a long program is composed of thousands of individual commands, and it is a tedious and error-prone affair to look up the numeric codes for all commands and place the codes manually into memory. As already mentioned, computers are really good at automating tedious and error-prone activities. It did not take long for computer programmers to realize that the computers themselves could be harnessed to help in the programming process. A special computer program, a compiler, translates the higher-level description into machine instructions for a particular processor. For example, in C++ , the high-level programming language that we will use in this book, you might give the following instruction:
This means, “If the interest rate is over 100, display an error message”. It is then the job of the compiler program to look at each C++ instruction and translate it into the machine instructions for the particular processor. High-level languages are independent of the underlying hardware. C++ instructions work equally well on an Intel Pentium and a processor in a cell phone. Of course, the compiler-generated machine instructions are different, but the programmer who uses the compiler need not worry about these differences. High-level programming languages are independent of the processor.
Self Check 6. Is the compiler a part of the computer hardware or software? 7. Does a person who uses a computer for office work ever run a compiler?
2/1/2010 8:22 AM
The Evolution of C++
1 of 1
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
C++ is built upon the C programming language, which was developed to be translated into fast machine code with a minimum of housekeeping overhead. C++ built on C by adding features for “object-oriented programming”, a programming style that enables modeling of real-world objects. The initial version of the C language was designed about 1972. Additional features were added to it over the years. Because different compiler writers added different features, the language actually sprouted various dialects. Some programming instructions were understood by one compiler but rejected by another. Such divergence is a major obstacle to a programmer who wants to move code from one computer to another. An effort got underway to iron out the differences and come up with a standard version of C. The design process ended in 1989 with the completion of the ANSI (American National Standards Institute) standard. In the meantime, Bjarne Stroustrup of AT&T added features of the language Simula (an object-oriented language designed for carrying out simulations) to C. The resulting language was called C++. From 1985 until today, C++ has grown by the addition of many features. A standardization process culminated in the publication of the international C++ standard in 1998. A minor update to the standard was issued in 2003, and a major revision is expected to come to fruition around 2010. At this time, C++ is the most commonly used language for developing system software such as databases and operating systems. Just as importantly, C++ is increasingly used for programming “embedded systems”, small computers that control devices such as automobile engines or cellular telephones. C++ is a general-purpose language that is in widespread use for systems and embedded programming.
Self Check 8. What was added to the C language to create C++? 9. What are the most important uses for C++?
Copyright © 2009 John Wiley & Sons, Inc. All rights reserved.
2/1/2010 8:23 AM
RANDOM FACT 1.2 Standards Organizations
1 of 1
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
Random Fact 1.2
RANDOM FACT 1.2 Standards Organizations
Two organizations, the American National Standards Institute (ANSI) and the International Organization for Standardization (ISO), have jointly developed the definitive standard for the C++ language.
iStockphoto.
Why have standards? You encounter the benefits of standardization every day. When you buy a light bulb, you can be assured that it fits in the socket without having to measure the socket at home and the bulb in the store. In fact, you may have experienced how painful the lack of standards can be if you have ever purchased a flashlight with nonstandard bulbs. Replacement bulbs for such a flashlight can be difficult and expensive to obtain. The ANSI and ISO standards organizations are associations of industry professionals who develop standards for everything from car tires and credit card shapes to programming languages. Having a standard for a programming language such as C++ means that you can take a program that you developed on one system with one manufacturer's compiler to a different system and be assured that it will continue to work.
Copyright © 2009 John Wiley & Sons, Inc. All rights reserved.
2/1/2010 8:29 AM
Becoming Familiar with Your Computer
1 of 3
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
As you use this book, you may well be doing your work on an un-familiar computer system. You should spend some time making yourself familiar with the computer. Because computer systems vary widely, this book can only give an outline of the steps you need to follow. Using a new and unfamiliar computer system can be frustrating. Look for training courses that your campus offers, or just ask a friend to give you a brief tour. Set aside some time to become familiar with the computer system and the C++ compiler that you will use for your class work.
Step 1 Log In If you use your own home computer, you don't need to worry about logging in. Computers in a lab, however, are usually not open to everyone. Access is usually restricted to those who paid the necessary fees and who can be trusted to use the lab responsibly. You will likely need an account number and a password to gain access to the system. Step 2 Locate the C++ Compiler Computer systems differ greatly in this regard. Some systems let you start the compiler by selecting an icon or menu. On other systems you must use the keyboard to type a command to launch the compiler. On many personal computers there is an integrated environment in which you can write and test your programs. On other computers you must first launch one program that functions like a word processor, in which you can enter your C++ instructions; then launch another program to translate them to machine code; and then run the resulting machine code. Step 3 Understand Files and Folders As a programmer, you will write C++ programs, try them out, and improve them. You will be provided a place on the computer to store them, and you need to find out where that place is. You will store your programs in files. A C++ file is a container of C++ instructions. Files have names, and the rules for legal names differ from one system to another. Some systems allow spaces in file names; others don't. Some distinguish between upper, and lowercase letters; others don't. Most C++ compilers require that C++ files end in an extension , or ; for example, . Files are stored in folders or directories. These file containers can be nested. A folder can contain files as well as other folders, which themselves can contain more files and folders (see Figure 5). This hierarchy can be quite large, especially on networked computers where some of the files may be on your local disk, others elsewhere on the network. While you need not be concerned with every branch of the hierarchy, you should familiarize yourself with your local environment. Different systems have different ways of showing files and directories. Some use a graphical display and let you move around by clicking the mouse on folder icons. In other systems, you must enter commands to visit or inspect different locations.
2/1/2010 8:30 AM
Becoming Familiar with Your Computer
2 of 3
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
Figure 5 A Directory Hierarchy
Step 4 Write a Simple Program In the next section, we will introduce a very simple program. You will need to learn how to type it in, run it, and fix mistakes. Step 5 Save Your Work Develop a strategy for keeping backup copies of your work before disaster strikes.
You will spend many hours typing C++ programs in and improving them. The resulting program files have some value, and you should treat them as you would other important property. A conscientious safety strategy is particularly important for computer files. They are more fragile than paper documents or other more tangible objects. It is easy to delete a file by accident, and occasionally files are lost because of a computer malfunction. Unless you keep another copy, you must retype the contents. Because you are unlikely to remember the entire file, you will likely find yourself spending almost as much time as you did to enter and improve it in the first place. This lost time may cause you to miss deadlines. It is therefore crucially important that you learn how to safeguard files and get in the habit of doing so before disaster strikes. You can make safety or backup copies of files by saving copies on a memory stick or on another computer.
2/1/2010 8:30 AM
Becoming Familiar with Your Computer
3 of 3
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
Self Check 10. How are programming projects stored on a computer? 11. What do you do to protect yourself from data loss when you work on programming projects?
Copyright © 2009 John Wiley & Sons, Inc. All rights reserved.
2/1/2010 8:30 AM
PRODUCTIVITY HINT 1.1 Backup Copies
1 of 1
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
Productivity Hint 1.1
PRODUCTIVITY HINT 1.1 Backup Copies
Backing up files on a memory stick is an easy and convenient storage method for many people. Another increasingly popular form of backup is Internet file storage. Here are a few pointers to keep in mind. • Back Up Often. Backing up a file takes only a few seconds, and you will hate yourself if you have to spend many hours recreating work that you could have saved easily. I recommend that you back up your work once every thirty minutes. • Rotate Backups. Use more than one directory for backups, and rotate them. That is, first back up onto the first directory. Then back up onto the second directory. Then use the third, and then go back to the first. That way you always have three recent backups. If your recent changes made matters worse, you can then go back to the older version. • Back Up Source Files Only. The compiler translates the files that you write into files consisting of machine code. There is no need to back up the machine code files, since you can recreate them easily by running the compiler again. Focus your backup activity on those files that represent your effort. That way your backup disks won't fill up with files that you don't need. • Pay Attention to the Backup Direction. Backing up involves copying files from one place to another. It is important that you do this right—that is, copy from your work location to the backup location. If you do it the wrong way, you will overwrite a newer file with an older version. • Check Your Backups Once in a While. Double-check that your backups are where you think they are. There is nothing more frustrating than to find out that the backups are not there when you need them. • Relax, then Restore. When you lose a file and need to restore it from backup, you are likely to be in an unhappy, nervous state. Take a deep breath and think through the recovery process before you start. It is not uncommon for an agitated computer user to wipe out the last backup when trying to restore a damaged file.
Copyright © 2009 John Wiley & Sons, Inc. All rights reserved.
2/1/2010 8:30 AM
Compiling a Simple Program
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
You are now ready to write and run your first C++ program. The traditional choice for the very first program in a new programming language is a program that displays a simple greeting: “Hello, World!” We follow that tradition. Here is the “Hello, World!” program in C++. ch01/hello.cpp
Program Run
We will explain this program in a minute. For now, you should make a new program file and call it . Enter the program instructions and compile and run the program, following the procedure that is appropriate for your compiler. (The line numbers are not part of the program. They are included so that your instructor can reference them during lectures.) When you type in this program, be aware that C++ is case-sensitive. You must enter upper- and lowercase letters exactly as they appear in the program listing. Do not type or . On the other hand, C++ has free-form layout. The amount of spaces, tabs, and line breaks (collectively called white space) used for layout is not important. You can even write the entire program on a single line:
However, you should always use a layout that makes your programs easy to read. When you run the program, the message
will appear on the screen. On some systems, you may need to switch to a different window to find the message. Now that you have seen the program working, it is time to understand its makeup. The basic structure of a C++ program is shown in Syntax 1.1. The first line,
tells the compiler to include a service for “stream input/output”. You will learn in Chapter 8 what a stream is. For now, you should simply remember to add this line into all programs that perform input or output. The next line,
tells the compiler to use the “standard namespace”. Namespaces are a mechanism for avoiding naming conflicts in large programs. You need not be concerned about namespaces. For the programs that you will be writing in this book, you will
1 of 3
2/1/2010 8:24 AM
Compiling a Simple Program
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
always use the standard namespace. Simply add the directive write, just below the directives. Every C++ program contains and a function called .
; at the top of every program that you
directives
The construction
that “returns” the integer 0 (which indicates that the program finished successfully). A defines a function called function is a collection of programming instructions that carry out a particular task. Every C++ program must have a function. Most C++ programs contain other functions besides , but it will take us until Chapter 5 to discuss functions and return values. For now, it is a good idea to consider all these parts as the plumbing that is necessary to write a simple program. Simply place the code that you want to execute inside the braces of the function. To display values on the screen, you send them to an entity called example, the statement
. The > operator, only one word is placed into the string variable. For example, suppose the user types
as the response to the prompt. This input consists of two words. After the call into the variable . Use another input statement to read the second word.
, the string
is placed
2.4.4 String Functions The number of characters in a string is called the length of the string. For example, the length of is 5. You can compute the length of a string with the function. Unlike the or function, the function is invoked with the dot notation. That is, you write the string whose length you want, then a period, then the name of the function, followed by parentheses:
Many C++ functions require you to use this dot notation, and you must memorize (or look up) which do and which don't. is invoked on the variable These functions are called member functions. We say that the member function
.
The member function yields the number of characters in a string.
A member function is invoked using the dot notation.
Once you have a string, you can extract substrings by using the
member function. The member function call
returns a string that is made from the characters in the string , starting at character Here is an example:
sub is "
, and containing
characters.
"
The operation makes a string that consists of five characters taken from the string . Indeed, is a string of length 5 that occurs inside . A curious aspect of the operation is the starting position. Starting position 0 means “start at the beginning of the string”. The first position in a string is labeled 0, the second one 1, and so on. For example, here are the position numbers in the string:
The position number of the last character (12) is always one less than the length of the string.
2/1/2010 9:20 AM
Strings
3 of 5
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
Table 9
String Operations
Statement
Result
is set to
Error
Comment
When applied to strings, + denotes concatenation. Error: You cannot concatenate twostring literals.
contains
The operator places the next word into the variable.
(User input: Harry Morgan) contains , contains
Use multiple operators to read more than one word.
(User input: Harry Morgan) is set to 5
;
is set to
Extracts the substring of length 3 starting at position 1. (The initial position is 0.)
is set to
If you omit the length, all characters from the position until the end are included.
is set to the initial letter in is set to the last letter in
Each space counts as one character.
Extracts the substring of length 1 starting at position 0. The last letter has position . We need not specify the length.
Let's figure out how to extract the substring . Count characters starting at 0, not 1. You find that , the 8th character, has position number 7. The string you want is 5 characters long. Therefore, the appropriate substring command is
If you omit the length, you get all characters from the given position to the end of the string. For example,
is the string
(including the exclamation mark).
Here is a simple program that puts these concepts to work. The program asks for your name and that of your significant other.
2/1/2010 9:20 AM
Strings
4 of 5
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
It then prints out your initials. The operation does the same for the string of length 3, the
makes a string consisting of one character, taken from the start of . The program . Then it concatenates the resulting one-character strings with the string literal "&" to get a string. (See Figure 5.)
Figure 5 Building the
String
Initials are formed from the first letter of each name.
Rich Legg/iStockphoto.
ch02/initials.cpp
2/1/2010 9:20 AM
Strings
5 of 5
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
Program Run
Self Check 21. What is the length of the string
?
22. Consider this string variable.
Give a call to the
member function that returns the substring
23. Use string concatenation to turn the string variable str from Self Check 22. to
. .
24. What does the following statement sequence print?
25. Give an input statement to read a name of the form “John Q. Public”.
Copyright © 2009 John Wiley & Sons, Inc. All rights reserved.
2/1/2010 9:20 AM
RANDOM FACT 2.2 The First Programmer
1 of 2
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
Random Fact 2.2
RANDOM FACT 2.2 The First Programmer
Before pocket calculators and personal computers existed, navigators and engineers used mechanical adding machines, slide rules, and tables of logarithms and trigonometric functions to speed up computations. Unfortunately, the tables—for which values had to be computed by hand—were notoriously inaccurate. The mathematician Charles Babbage (1791–1871) had the insight that if a machine could be constructed that produced printed tables automatically, both calculation and typesetting errors could be avoided. Babbage set out to develop a machine for this purpose, which he called a Difference Engine because it used successive differences to compute polynomials. For example, consider the function f (x) = x3. Write down the values for f(1), f(2), f(3), and so on. Then take the differences between successive values:
Repeat the process, taking the difference of successive values in the second column, and then repeat once again:
Now the differences are all the same. You can retrieve the function values by a pattern of additions—you need to know the values at the fringe of the pattern and the constant difference. This method was very attractive, because mechanical addition machines had been known for some time. They consisted of cog wheels, with 10 cogs per wheel, to represent digits, and mechanisms to handle the carry from one digit to the next. Mechanical multiplication machines, on the other hand, were fragile and unreliable. Babbage built a successful prototype of the Difference Engine (the Babbage's Difference Engine figure) and, with his own money and government grants, proceeded to build the table-printing machine. However, because of funding problems and the difficulty of building the machine to the required precision, it was never completed. While working on the Difference Engine, Babbage conceived of a much grander vision that he called the Analytical Engine. The Difference Engine was designed to carry out a limited set of computations—it was no smarter than a pocket calculator is today. But Babbage realized that such a machine could be made programmable by storing programs as well as data. The internal storage of the Analytical Engine was to consist of 1,000 registers of 50 decimal digits each. Programs and constants were to be stored on punched cards—a technique that was, at that time, commonly used on looms for weaving patterned fabrics.
2/1/2010 9:20 AM
RANDOM FACT 2.2 The First Programmer
2 of 2
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
Babbage's Difference Engine
Topham/The Image Works. Ada Augusta, Countess of Lovelace (1815–1852), the only child of Lord Byron, was a friend and sponsor of Charles Babbage. Ada Lovelace was one of the first people to realize the potential of such a machine, not just for computing mathematical tables but for processing data that were not numbers. She is considered by many to be the world's first programmer.
Copyright © 2009 John Wiley & Sons, Inc. All rights reserved.
2/1/2010 9:20 AM
Chapter Summary
1.
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
A variable is a storage location with a name.
Javier Larrea/Age Fotostock America, Inc.
2.
When defining a variable, you usually specify an initial value.
3.
When defining a variable, you also specify the type of its values.
Graham Harrison/drr.net.
4.
Use the
5.
Use the
6.
Use comments to add explanations for humans who read your code. The compiler ignores comments.
7.
An assignment statement stores a new value in a variable, replacing the previously stored value.
8.
The assignment operator
9.
The
type for numbers that cannot have a fractional part. type for floating-point numbers.
does not denote mathematical equality.
operator adds 1 to a variable; the
operator subtracts 1.
10. Use the operator to read a value and place it in a variable. 11. You cannot change the value of a variable that is defined as
.
12. If both arguments of are integers, the remainder is discarded. 13. The operator computes the remainder of an integer division.
Michael Flippo/iStockphoto.
(square root) and 14. The C++ library defines many mathematical functions such as to specify how values should be formatted. 15. You send manipulators to
1 of 2
(raising to a power).
2/1/2010 9:20 AM
Chapter Summary
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
Rich Koele/iStockphoto.
16. String are sequence of characters. 17. Use the operator to concatenate strings; that is, put them together to yield a longer string. member function yields the number of charcters in a string. 18. The 19. A member function is invoked using the dot notation. 20. Use the
member function to extract a substring of a string.
Rich Legg/iStockphoto.
Copyright © 2009 John Wiley & Sons, Inc. All rights reserved.
2 of 2
2/1/2010 9:20 AM
Review Exercises
1 of 3
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
R2.1. Write the following mathematical expressions in C++.
R2.2. Write the following C++ expressions in mathematical notation. (a) (b) (c) (d) R2.3. What are the values of the following expressions? In each line, assume that
(a) (b) (c) (d) (e) (f) (g) (h) (i) (j) R2.4. Find at least five syntax errors in the following program.
R2.5. Find at least four logic errors in the following program.
2/1/2010 9:20 AM
Review Exercises
2 of 3
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
R2.6. Explain the differences between ,
,
, and
.
R2.7. Explain what each of the following program segments computes: (a)
(b)
R2.8. Write pseudocode for a program that reads a word and then prints the first character, the last character, and the characters i the middle. For example, if the input is , the program prints . R2.9. Write pseudocode for a program that reads a name (such as consisting of the initial letters of the first, middle, and last name (such as
) and then prints a monogram ).
R2.10. Write pseudocode for a program that computes the first and last digit of a number. For example, if the input is program should print out and . Hint: %, . R2.11. Modify the pseudocode for the program in How To 2.1 on page 61 so that the program gives change in quarters, dimes, a nickels. You can assume that the price is a multiple of 5 cents. R2.12. The following pseudocode describes how to obtain the name of a day, given the day number (0 = Sunday, 1 = Monday, a so on.) Define a string called names containing "SunMonTueWedThuFriSat". Compute the starting position as 3 × the day number. Extract the substring of names at the starting position with length 3. Check this pseudocode, using the day number 4. Draw a diagram of the string that is being computed, similar to Figure 5 R2.13. The following pseudocode describes how to swap two letters in a word. We are given a string str and two positions i and j. (i comes before j) Set first to the substring from the start of the string to the last position before i. Set middle to the substring from positions i + 1 to j - 1. Set last to the substring from position j + 1 to the end of the string. Concatenate the following five strings: first, the string containing just the character at position
2/1/2010 9:20 AM
Review Exercises
3 of 3
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
middle, the string containing just the character at position i, and last. Check this pseudocode, using the string computed, similar to Figure 5.
and positions 2 and 4. Draw a diagram of the string that is being
R2.14. Run the following program, and explain the output you get.
Note the trace messages that are inserted to show the current contents of the program? (The program has two separate errors.)
variable. How do you fix the
R2.15. Write a program that prints the values
Explain the results. R2.16. This chapter contains a number of recommendations regarding variables and constants that make programs easier to read and maintain. Briefly summarize these recommendations.
Copyright © 2009 John Wiley & Sons, Inc. All rights reserved.
2/1/2010 9:20 AM
Programming Exercises
1 of 3
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
P2.1. Write a program that reads a number and displays the square, cube, and fourth power. Use the power.
function only for the fo
P2.2. Write a program that prompts the user for two integers and then prints • The sum • The difference • The product • The average • The distance (absolute value of the difference) • The maximum (the larger of the two) • The minimum (the smaller of the two) Hint: The and functions are defined in the
header.
P2.3. Write a program that prompts the user for a measurement in meters and then converts it to miles, feet, and inches. P2.4. Write a program that prompts the user for a radius and then prints • The area and circumference of a circle with that radius • The volume and surface area of a sphere with that radius P2.5. Write a program that asks the user for the lengths of the sides of a rectangle. Then print • The area and perimeter of the rectangle • The length of the diagonal (use the Pythagorean theorem) P2.6. Improve the program discussed in the How To on page 61 to allow input of quarters in addition to bills. P2.7. Write a program that helps a person decide whether to buy a hybrid car. Your program's inputs should be: • The cost of a new car • The estimated miles driven per year • The estimated gas price • The estimated resale value after 5 years Compute the total cost of owning the car for 5 years. (For simplicity, we will not take the cost of financing into account.) realistic prices for a new and used hybrid and a comparable car from the Web. Run your program twice, using today's gas p and 15,000 miles per year. Include pseudocode and the program runs with your assignment. P2.8. The following pseudocode describes how a bookstore computes the price of an order from the total price and the number books that were ordered. Read the total book price and the number of books. Compute the tax (7.5% of the total book price). Compute the shipping charge ($2 per book). The price of the order is the sum of the total book price, the tax, and the shipping charge. Print the price of the order. Translate this pseudocode into a C++ program. P2.9. The following pseudocode describes how to turn a string containing a ten-digit phone number (such as a more readable string with parentheses and dashes, like this: . Take the substring consisting of the first three characters and surround it with "(" and ")". This area code. Concatenate the area code, the substring consisting of the next three characters, a hyphen, and
2/1/2010 9:21 AM
Programming Exercises
2 of 3
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
substring consisting of the last four characters. This is the formatted number. Translate this pseudocode into a C++ program that reads a telephone number into a string variable, computes the formatte number, and prints it. P2.10. The following pseudocode describes how to extract the dollars and cents from a price given as a floating-point value. Fo example, a price 2.95 yields values 2 and 95 for the dollars and cents. Assign the price to an integer variable dollars. Multiply the difference price - dollars by 100 and add 0.5. Assign the result to an integer variable cents. Translate this pseudocode into a C++ program. Read a price and print the dollars and cents. Test your program with inpu and 4.35. P2.11. Giving change. Implement a program that directs a cashier how to give change. The program has two inputs: the amount and the amount received from the customer. Display the dollars, quarters, dimes, nickels, and pennies that the customer s receive in return. P2.12. Write a program that asks the user to input • The number of gallons of gas in the tank • The fuel efficiency in miles per gallon • The price of gas per gallon Then print the cost per 100 miles and how far the car can go with the gas in the tank. P2.13. File names and extensions. Write a program that prompts the user for the drive letter ( ), the path ( name ( ), and the extension ( ). Then print the complete file name UNIX or a Macintosh, skip the drive name and use instead of \ to separate directories.)
), (If
P2.14. Write a program that reads a number greater than or equal to 1,000 from the user and prints it with a comma separating thousands. Here is a sample dialog; the user input is in color:
P2.15. Write a program that reads a number between 1,000 and 999,999 from the user, where the user enters a comma in the inp Then print the number without a comma. Here is a sample dialog; the user input is in color:
Hint: Read the input as a string. Measure the length of the string. Suppose it contains n characters. Then extract substring consisting of the first n – 4 characters and the last three characters. P2.16. Printing a grid. Write a program that prints the following grid to play tic-tac-toe.
Of course, you could simply write seven statements of the form
You should do it the smart way, though. Define string variables to hold two kinds of patterns: a comb-shaped pattern and bottom line. Print the comb three times and the bottom line once. P2.17. Write a program that reads in an integer and breaks it into a sequence of individual digits. For example, the input 16384
2/1/2010 9:21 AM
Answers to Self-Check Questions
1 of 2
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
1. One possible answer is
You may choose a different variable name or a different initialization value, but your variable should have type
.
2. There are three errors: • You cannot have spaces in variable names. because it holds a fractional value. • The variable type should be • There is a semicolon missing at the end of the statement. 3.
4. 5. Change the definition of
6. You need to use a
to
delimiter to close a comment that begins with a
:
Liters in a 12-ounce can 7. The program would compile, and it would display the same result. However, a person reading the program might find it confusing that fractional cans are being considered. 8. The variable changes it to 0.
is initialized to 1. The assignment statement changes
9. The last statement is a variable definition, but statement.
to –1. The increment statement
has already been defined. Remedy: Drop the
in the last
10. Assignment would occur when one car is replaced by another in the parking space. 11. There is no prompt that alerts the program user to enter the quantity. variable is defined as an 12. The into the variable.
. If the user were to enter a price such as
, only the 1 would be placed
13. Their values are modified by the input statements. 14. 15. 16.
17. 172 and 9 18. 19. The output is
Note that there is no space between the
and
.
2/1/2010 9:21 AM
Answers to Self-Check Questions
2 of 2
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
20.
Note that the setw manipulator appears twice. Also note the added spaces in the string
.
21. The length is 11. The space counts as a character. 22. 23.
;
24. 25.
Copyright © 2009 John Wiley & Sons, Inc. All rights reserved.
2/1/2010 9:21 AM
sc_ch02_we1.fm Page 1 Friday, September 5, 2008 3:11 PM
Worked Example 2.1 • Computing the Cost of Stamps
1
W O R K E D E X A M P L E 2.1 Computing the Cost of Stamps You are asked to simulate a postage stamp vending machine. A customer inserts dollar bills into the vending machine and then pushes a “purchase” button. The vending machine gives out as many first-class stamps as the customer paid for, and returns the change in penny (one-cent) stamps. A first-class stamp cost 42 cents at the time this book was written. Step 1
Understand the problem: What are the inputs? What are the desired outputs?
In this problem, there is one input: • The amount of money the customer inserts There are two desired outputs: • The number of first-class stamps the machine returns • The number of penny stamps the machine returns Step 2
Work out examples by hand.
Let’s assume that a first-class stamp costs 42 cents and the customer inserts $1.00. That’s enough for two stamps (84 cents) but not enough for three stamps ($1.26). Therefore, the machine returns two first-class stamps and 16 penny stamps. Step 3
Write pseudocode for computing the answers.
Given an amount of money and the price of a first-class stamp, how can you compute how many first-class stamps can be purchased with the money? Clearly, the answer is related to the quotient amount of money price of first-class stamp For example, suppose the customer paid $1.00. Use a pocket calculator to compute the quotient: $1.00/$0.42 ≈ 2.38. How do you get “2 stamps” out of 2.38? It’s the quotient without the remainder. In C++, this is easy to compute if both arguments are integers. Therefore, let’s switch our computation to pennies. Then we have number of first-class stamps = 100 / 42 (integer division, without remainder) What if the user inputs two dollar? Then the numerator becomes 200. What if the price of a stamp goes up? A more general equation is number of first-class stamps = 100 x dollars / price of first-class stamps in cents How about the change? Here is one way of computing it. When the customer gets the stamps, the change is the customer payment, reduced by the value of the stamps purchased. In our example, the change is 16 cents—the difference between 100 and 2 · 42. Here is the general formula: change = 100 x dollars – number of first-class stamps x price of first-class stamp
C++ for Everyone, Cay Horstmann, Copyright © 2009 John Wiley & Sons, Inc. All Rights Reserved.
sc_ch02_we1.fm Page 2 Friday, September 5, 2008 3:11 PM
2
C++ for Everyone • Step 4
CHAPTER
2
Define the variables and constants that you need, and specify their types.
Here, we have three variables: • dollars • first_class_stamps • change There is one constant, FIRST_CLASS_STAMP_PRICE. The variables dollars and FIRST_CLASS_STAMP_PRICE must be of type int since the computation of first_class_stamps uses integer division. The remaining variables are also integers, counting the number of first-class and penny stamps. Thus, we have const int FIRST_CLASS_STAMP_PRICE = 42; // Price in pennies int dollars; // Filled through input statement int first_class_stamps = 100 * dollars / FIRST_CLASS_STAMP_PRICE; int change = 100 * dollars - first_class_stamps * FIRST_CLASS_STAMP_PRICE;
Step 5
Turn the pseudocode into C++ statements.
Our computation depends on the number of dollars that the user provides. Translating the math into C++ yields the following statements: first_class_stamps = 100 * dollars / FIRST_CLASS_STAMP_PRICE; change = 100 * dollars - first_class_stamps * FIRST_CLASS_STAMP_PRICE;
Step 6
Provide input and output.
Before starting the computation, we prompt the user for the number of dollars: cout > dollars;
When the computation is finished, we display the result. cout start2 { s = start1 }
2/1/2010 9:56 AM
Review Exercises
3 of 5
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
Else { s = start2 } If end1 < end2 { e = endl } Else { e = end2 } If s < e { The appointments overlap. } Else { The appointments don't overlap. } Trace this algorithm with an appointment from 10-12 and one from 11-13, then with an appointment from 10-11 and one from 12-13. Exercise R3.10. Write pseudocode for a program that prompts the user for a month and day and prints out whether it is one of the following four holidays: • New Year's Day (January 1) • Independence Day (July 4) • Veterans Day (November 11) • Christmas Day (December 25) Exercise R3.11. Write pseudocode for a program that assigns letter grades for a quiz, according to the following table:
Exercise R3.12. Explain how the lexicographic ordering of strings in C++ differs from the ordering of words in a dictionary or telephone book. Hint: Consider strings such as , wiley.com, , and . Exercise R3.13. Of the following pairs of strings, which comes first in lexicographic order? (a) (b) (c) (d)
2/1/2010 9:56 AM
Review Exercises
4 of 5
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
(e) (f) (g) (h) (i) Exercise R3.14. Explain the difference between an
sequence and nested if statements. Give an example for each.
Exercise R3.15. Give an example for an the order of the tests matters.
sequence where the order of the tests does not matter. Give an example where
Exercise R3.16. Give a set of test cases for the tax program in Exercise R3.18.. Manually compute the expected results. Exercise R3.17. Make up another C++ code example that shows the dangling problem, using the following statement. A student with a GPA of at least 1.5, but less than 2, is on probation. With less than 1.5, the student is failing. Exercise R3.18. Complete the following truth table by finding the truth values of the Boolean expressions for all combinations of the Boolean inputs and .
… 5 more combinations … Exercise R3.19. True or false? A
B is the same as B
A for any Boolean conditions A and B.
Exercise R3.20. The “advanced search” features of many search engines allow you to use Boolean operators for complex queries, such as “(cats OR dogs) AND NOT pets”. Contrast these search operators with the Boolean operators in C++. Exercise R3.21. Suppose the value of
is
and the value of
is 0. What is the value of the following expressions?
(a) (b) (c) (d) (e) (f) (g) (h) Exercise R3.22. Simplify the following expressions. Here,
is a variable of type
.
(a)
2/1/2010 9:56 AM
Review Exercises
5 of 5
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
(b) (c) (d) Exercise R3.23. Simplify the following statements. Here,
is a variable of type
and
is a variable of type
.
(a) (Hint: What is the value of
)
(b) (c) (d) Exercise R3.24. What is wrong with the following program?
Exercise R3.25. Reading numbers is surprisingly difficult because a C++ input stream looks at the input one character at a time. First, white space is skipped. Then the stream consumes those input characters that can be a part of a number. Once the stream has recognized a number, it stops reading if it finds a character that cannot be a part of a number. However, if the first non-white space character is not a digit or a sign, or if the first character is a sign and the second one is not a digit, then the stream fails. Consider a program reading an integer:
For each of the following user inputs, circle how many characters have been read and whether the stream is in the failed state or not. (a) (b) (c) (d) (e) (f) (g) (h) (i)
Copyright © 2009 John Wiley & Sons, Inc. All rights reserved.
2/1/2010 9:56 AM
Programming Exercises Exercise P3.1. Write a program that reads a temperature value and the letter C for Celsius or F for Fahrenheit. Print whether water is liquid, solid, or gaseous at the given temperature at sea level. Exercise P3.2. The boiling point of water drops by about one degree centigrade for every 300 meters (or 1,000 feet) of altitude. Improve the program of Exercise P3.1. to allow the user to supply the altitude in meters or feet. Exercise P3.3. Write a program that translates a letter grade into a number grade. Letter grades are A, B, C, D, and F, possibly followed by + or -. Their numeric values are 4, 3, 2, 1, and 0. There is no F+ or F-. A + increases the numeric value by 0.3, a - decreases it by 0.3. However, an A+ has value 4.0. Enter a letter grade: BThe numeric value is 2.7.
Exercise P3.4. Write a program that translates a number between 0 and 4 into the closest letter grade. For example, the number 2.8 (which might have been the average of several grades) would be converted to B-. Break ties in favor of the better grade; for example 2.85 should be a B. Exercise P3.5. Write a program that takes user input describing a playing card in the following shorthand notation: A
Ace
2 … 10 Card values J
Jack
Q
Queen
K
King
D
Diamonds
H
Hearts
S
Spades
C
Clubs
Your program should print the full description of the card. For example, Enter the card notation: QS Queen of Spades
Exercise P3.6. Write a program that prompts the user for a wavelength value and prints a description of the corresponding part of the electromagnetic spectrum, as given in Table 6.
Table 6 Type
Electromagnetic Spectrum
Wavelength (m)
Frequency (Hz)
Radio Waves
> 10
< 3 × 109
Microwaves
10-3 to 10-1
3 × 109 to 3 × 1011
Infrared
7 × 10-7 to 10-3
3 × 1011 to 4 × 1014
Visible light
-1
4 × 10-7 to 7 × 10-7 4 × 1014 to 7.5 × 1014
Ultraviolet
10-8 to 4 × 10-7
7.5 × 1014 to 3 × 1016
X-rays
10-11 to 10-8
3 × 1016 to 3 × 1019
Gamma rays
< 10-11
> 3 × 1019
Exercise P3.7. Repeat Exercise P3.6., modifying the program so that it prompts for the frequency instead. Exercise P3.8. Repeat Exercise P3.6., modifying the program so that it first asks the user whether the input will be a wavelength or a frequency. Exercise P3.9. Write a program that reads in three floating-point numbers and prints the largest of the three inputs. For example: Please enter three numbers: 4 9 2.5 The largest number is 9.
Exercise P3.10. Write a program that reads in three strings and sorts them lexicographically. Enter three strings: Charlie Able Baker Able Baker Charlie
Exercise P3.11. When two points in time are compared, each given as hours (in military time, ranging from 0 and 23) and minutes, the following pseudocode determines which comes first. If hour1 < hour2 { time1 comes first. } Else if hour1 and hour2 are the same { If minute1 < minute2 { time1 comes first. } Else if minute1 and minute2 are the same { time1 and time2 are the same. } Else
{ time2 comes first. } } Else { time2 comes first. }
Write a program that prompts the user for two points in time and prints the time that comes first, then the other time. Exercise P3.12. The following algorithm yields the season (Spring, Summer, Fall, or Winter) for a given month and day. If month is 1, 2, or 3 { season = "Winter"} Else if month is 4, 5, or 6 { season = "Spring" } Else if month is 7, 8, or 9 { season = "Summer" } Else if month is 10, 11, or 12 { season = "Fall" } If month is divisible by 3 and day >= 21 { If season is "Winter" { season = "Spring" } Else if season is "Spring" { season = "Summer" } Else if season is "Summer" { season = "Fall" } Else { season = "Winter" } }
Write a program that prompts the user for a month and day and then prints the season, as determined by this algorithm. Exercise P3.13. Write a program that reads in two floating-point numbers and tests whether they are the same up to two decimal places. Here are two sample runs. Enter two floating-point numbers: 2.0 1.99998 They are the same up to two decimal places. Enter two floating-point numbers: 2.0 1.98999 They are different.
Exercise P3.14. Write a program to simulate a bank transaction. There are two bank accounts: checking and savings. First, ask for the initial balances of the bank accounts; reject negative balances. Then ask for the transactions; options are deposit, withdrawal, and transfer. Then ask for the account; options are checking and savings. Then ask for the amount; reject transactions that overdraw an account. At the end, print the balances of both accounts. Exercise P3.15. Write a program that reads in the name and salary of an employee. Here the salary will denote an hourly wage, such as $9.25. Then ask how many hours the employee worked in the past week. Be sure to accept fractional hours. Compute the pay. Any overtime work (over 40 hours per week) is paid at 150 percent of the regular wage. Print a paycheck for the employee. Exercise P3.16. Write a program that prompts for the day and month of the user's birthday and then prints a horoscope. Make up fortunes for programmers, like this: Please enter your birthday (month and day): 6 16 Gemini are experts at figuring out the behavior of complicated programs.
You feel where bugs are coming from and then stay one step ahead. Tonight, your style wins approval from a tough critic.
Each fortune should contain the name of the astrological sign. (You will find the names and date ranges of the signs at a distressingly large number of sites on the Internet.) Exercise P3.17. The original U.S. income tax of 1913 was quite simple. The tax was • 1 percent on the first $50,000. • 2 percent on the amount over $50,000 up to $75,000. • 3 percent on the amount over $75,000 up to $100,000. • 4 percent on the amount over $100,000 up to $250,000. • 5 percent on the amount over $250,000 up to $500,000. • 6 percent on the amount over $500,000. There was no separate schedule for single or married taxpayers. Write a program that computes the income tax according to this schedule. Exercise P3.18. Write a program that computes taxes for the following schedule. If your status is Single and if the taxable income is over
but not over
the tax is
of the amount over
$0
$8,000
10%
$0
$8,000
$32,000
$800 + 15%
$8,000
$4,400 + 25%
$32,000
$32,000 If your status is Married and if the taxable income is over
but not over
the tax is
of the amount over
$0
$16,000
10%
$0
$16,000
$64,000
$1,600 + 15%
$16,000
$8,800 + 25%
$64,000
$64,000
Exercise P3.19. The tax.cpp program uses a simplified version of the 2008 U.S. income tax schedule. Look up the tax brackets and rates for the current year, for both single and married filers, and implement a program that computes the actual income tax. Exercise P3.20. Unit conversion. Write a unit conversion program that asks the users from which unit they want to convert (fl. oz, gal, oz, lb, in, ft, mi) and to which unit they want to convert (ml, l, g, kg, mm, cm, m, km). Reject incompatible conversions (such as gal → km). Ask for the value to be converted, then display the result: Convert from? gal Convert to? ml Value? 2.5 2.5 gal = 9462.5 ml
Exercise P3.21. Write a program that prompts the user to provide a single character from the alphabet. Print Vowel or Consonant, depending on the user input. If the user input is not a letter (between a and z or A and Z), or is a string of length > 1, print an error message. Exercise P3.22. Roman numbers. Write a program that converts a positive integer into the Roman number system. The Roman number system has digits I
1
V
5
X
10
L
50
C
100
D
500
M 1,000 Numbers are formed according to the following rules. (1) Only numbers up to 3,999 are represented. (2) As in the decimal system, the thousands, hundreds, tens, and ones are expressed separately. (3) The numbers 1 to 9 are expressed as I
1
II
2
III
3
IV
4
V
5
VI
6
VII
7
VIII 8 IX
9
As you can see, a I preceding a V or X is subtracted from the value, and you can never have more than three I's in a row. (4) Tens and hundreds are done the same way, except that the letters X, L, C and C, D, M are used instead of I, V, X, respectively. Your program should take an input, such as 1978, and convert it to Roman numerals, MCMLXXVIII. Exercise P3.23. Write a program that asks the user to enter a month (1 for January, 2 for February, and so on) and then prints the number of days in the month. For February, print “28 or 29 days”.
Enter a month: 5 30 days
Exercise P3.24. A year with 366 days is called a leap year. A year is a leap year if it is divisible by four (for example, 1980), except that it is not a leap year if it is divisible by 100 (for example, 1900); however, it is a leap year if it is divisible by 400 (for example, 2000). There were no exceptions before the introduction of the Gregorian calendar on October 15, 1582 (1500 was a leap year). Write a program that asks the user for a year and computes whether that year is a leap year.
Copyright © 2009 John Wiley & Sons, Inc. All rights reserved.
Answers to Self-Check Questions
1 of 2
1. Change the
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
statement to
2. 85. 90. 85. 3. The only difference is if one sets it to 80.
is 100. The statement in Self Check 2. sets
to 90; this
4. 95. 100. 95 5.
6. (a) and (b) are both true, (c) is false. 7. 8. The values should be compared with == , not = . 9. 10. 11.
12.
13. You could first set s to one of the three values:
14. The
can be omitted, making it clear that the
branch is the sole alternative.
15. No destruction of buildings 16. Add a branch
17. 3200 18. No. Then the computation is 0.10 × 32000 + 0.25 (32000 - 32000).
2/1/2010 9:58 AM
Answers to Self-Check Questions
2 of 2
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
19. No. Their individual tax is $5,200 each, and if they married, they would pay $10,400. Actually, taxpayers in higher tax brackets (which our program does not model) may pay higher taxes when they marry, a phenomenon known as the marriage penalty. 20. Change
in line 36 to
and add another branch after line 47:
21. The higher tax rate is only applied on the income in the higher bracket. Suppose you are single and make $31,900. Should you try to get a $200 raise? Absolutely: you get to keep 90 percent of the first $100 and 75 percent of the next $100. 22. 23. 24. 25. The same as the value of
.
26. You are guaranteed that there are no other values. With strings or integers, you would need to check that no values such as or -1 enter your calculations. 27. (a)
. (b) . (c)
(d)
.
28. , to make sure a researcher didn't supply an input such as . Check for , 29. Check for since any rat must surely have a positive weight. We don't know how giant a rat could be, but the New Guinea rats weighed no more than 2 kg. A regular house rat (rattus rattus) weighs up to 0.2 kg, so we'll say that any weight > 10 kg was surely an input error, perhaps confusing grams and kilograms. Thus, the checks are
30. The first input fails. The value of is unchanged. Because a previous input failed, the next input doesn't even try to get additional keystrokes. It also fails, and is unchanged. The program prints .
Copyright © 2009 John Wiley & Sons, Inc. All rights reserved.
2/1/2010 9:58 AM
sc_ch03_we1.fm Page 1 Friday, September 5, 2008 4:07 PM
Worked Example 3.1 • Extracting the Middle
1
W O R K E D E X A M P L E 3.1 Extracting the Middle Your task is to extract a string containing the middle character from a given string str. For example, if the string is "crate", the result is the string "a". However, if the string has an even number of letters, extract the middle two characters. If the string is "crates", the result is "at". Step 1
Decide upon the branching condition.
We need to take different actions for strings of odd and even length. Therefore, the condition is Is the length of the string odd? In C++, you use the remainder of division by 2 to find out whether a value is even or odd. Then the test becomes str.length() % 2 == 1? Step 2
Give pseudocode for the work that needs to be done when the condition is fulfilled.
We need to find the position of the middle character. If the length is 5, the position is 2. c
r
a
t
e
0
1
2
3
4
In general, position = str.length() / 2 (with the remainder discarded) result = str.substr(position, 1) Step 3 Give pseudocode for the work (if any) that needs to be done when the condition is not fulfilled.
Again, we need to find the position of the middle character. If the length is 6, the starting position is 2, and the ending position is 3. c
r
a
t
e
s
0
1
2
3
4
5
In general, position = str.length() / 2 - 1 result = str.substr(position, 2) Step 4
Double-check relational operators.
Do we really want str.length() % 2 == 1? For example, when the length is 5, 5 % 2 is the remainder of the division 5 / 2, which is 1. In general, dividing an odd number by 2 leaves a remainder of 1. (Actually, dividing a negative odd number by 2 leaves a remainder of –1, but the string length is never negative.) Therefore, our condition is correct.
C++ for Everyone, Cay Horstmann, Copyright © 2009 John Wiley & Sons, Inc. All Rights Reserved.
sc_ch03_we1.fm Page 2 Friday, September 5, 2008 4:07 PM
2
C++ for Everyone • Step 5
CHAPTER
3
Remove duplication.
Here is the statement that we have developed: If str.length() % 2 == 1 { position = str.length() / 2 (with remainder discarded) result = str.substr(position, 1) } Else { position = str.length() / 2 - 1 result = str.substr(position, 2) } The second statement in each branch is almost identical, but the length of the substring differs. Let’s set the length in each branch: If str.length() % 2 == 1 { position = str.length() / 2 (with remainder discarded) length = 1 } Else { position = str.length() / 2 - 1 length = 2 } result = str.substr(position, length) Step 6
Test both branches.
We will use a different set of strings for testing. For an odd-length string, consider We get
"monitor".
position = str.length() / 2 = 7 / 2 = 3 (with remainder discarded) length = 1 result = str.substr(3, 1) = "i" For the even-length string "monitors", we get position = str.length() / 2 - 1 = 8 / 2 - 1 = 3 (with remainder discarded) length = 2 result = str.substr(3, 2) = "it" Step 7
Assemble the if statement in C++.
Here’s the completed code segment. if (str.length() % 2 == 1) { position = str.length() / 2; length = 1; } else {
C++ for Everyone, Cay Horstmann, Copyright © 2009 John Wiley & Sons, Inc. All Rights Reserved.
sc_ch03_we1.fm Page 3 Friday, September 5, 2008 4:07 PM
Worked Example 3.1 • Extracting the Middle position = str.length() / 2 - 1; length = 2; } result = str.substr(position, length);
C++ for Everyone, Cay Horstmann, Copyright © 2009 John Wiley & Sons, Inc. All Rights Reserved.
3
Chapter Goals To learn abo ...
1 of 1
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
Chapter
Chapter Goals , , and loops • To learn about • To avoid infinite loops and off-by-one errors • To understand nested loops • To implement programs that read and process data sets • To use a computer for simulations This chapter presents the various iteration constructs that are available in C++. These constructs execute one or more statements repeatedly until a goal is reached. You will see how the techniques that you learn in this chapter can be applied to the processing of input data and the programming of simulations.
Copyright © 2009 John Wiley & Sons, Inc. All rights reserved.
2/1/2010 10:44 AM
The while Loop
1 of 5
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
In this section, you will learn how to repeatedly execute statements until a goal has been reached.
Because the interest earned also earns interest, a bank balance grows exponentially. iStockphoto.
Recall the investment problem from Chapter 1. You put $10,000 into a bank account that earns 5 percent interest per year. How many years does it take for the account balance to be double the original investment? In Chapter 1 we developed the following algorithm for this problem: Start with a year value of 0 and a balance of $10,000.
Repeat the following steps while the balance is less than $20,000 Add 1 to the year value Multiply the balance value by 1.05 (a 5 percent increase) Report the final year value as the answer You now know how to define and update the variables in C++. What you don't yet know is how to carry out “Repeat steps while the balance is less than $20,000”.
In a particle accelerator, subatomic particles traverse a loop-shaped tunnel multiple times, gaining the speed required for physical experiments. Similarly, in computer science, statements in a loop are executed while a condition is true. Fermi National Accelerator Laboratory/Photo Researchers, Inc.
In C++, the
statement implements such a repetition (see Syntax 4.1). The code
condition
2/1/2010 10:45 AM
The while Loop
2 of 5
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
statements keeps executing the statements while the condition is true. In our case, we want to increment the year counter and add interest while the balance is less than the target balance of $20,000:
Loops execute a block of code repeatedly while a condition remains true. A statement is an example of a loop. If you draw a flowchart, the flow of execution loops again to the point where the condition is tested (see Figure 1).
Figure 1 Flowchart of a
Loop
Here is the program that solves the investment problem. Figure 2 illustrates the program's execution.
2/1/2010 10:45 AM
The while Loop
3 of 5
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
Figure 2 Execution of the
Loop
ch04/doublinv.cpp
2/1/2010 10:45 AM
PRODUCTIVITY HINT 4.1 Hand-Tracing Loops
1 of 3
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
Productivity Hint 4.1
PRODUCTIVITY HINT 4.1 Hand-Tracing Loops
In Productivity Hint 3.2, you learned about the method of hand tracing. This method is particularly effective for understanding how a loop works. Consider this example. What value is printed?
There are three variables:
, and
.
The first two variables are initialized with 1729 and 0 before the loop is entered.
Now enter the loop. The variable is set to 9 (the remainder of dividing 1729 by 10). The variable is set to 0 + 9 = 9. Finally, becomes 172. (Recall that the remainder in the division 1729 / 10 is discarded because both arguments are integers.). Cross out the old values and write the new ones under the old ones.
2/1/2010 10:47 AM
PRODUCTIVITY HINT 4.1 Hand-Tracing Loops
2 of 3
Since
Because
, we repeat the loop. Now
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
becomes 2,
is still not zero, we repeat the loop, setting
is set to 9 + 2 = 11, and
to 7,
is set to 17.
to 11 + 7 = 18, and
to 1.
We enter the loop for one last time. Now is set to 1, to 19, and becomes zero. The condition is now false, and we continue with the output statement after the loop. The value that is output is 19.
Of course, you can get the same answer by just running the code. The hope is that by hand-tracing, you gain an insight. Consider again what happens in each iteration: • We extract the last digit of • We add that digit to • We strip the digit off In other words, the loop forms the sum of the digits in . You now know what the loop does for any value of , not just the one in the example. Why would anyone want to form the sum of the digits? Operations of this kind are useful for checking the validity
2/1/2010 10:47 AM
PRODUCTIVITY HINT 4.1 Hand-Tracing Loops
3 of 3
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
of credit card numbers and other forms of ID numbers—see Exercise P4.2.
Copyright © 2009 John Wiley & Sons, Inc. All rights reserved.
2/1/2010 10:47 AM
COMMON ERROR 4.1 Infinite Loops
1 of 2
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
Common Error 4.1
COMMON ERROR 4.1 Infinite Loops
A very annoying loop error is an infinite loop: a loop that runs forever and can be stopped only by killing the program or restarting the computer. If there are output statements in the program, then reams and reams of output flash by on the screen. Otherwise, the program just sits there and hangs, seeming to do nothing. On some systems, you can kill a hanging program by hitting Ctrl + C. On others, you can close the window in which the program runs. A common reason for infinite loops is forgetting to update the variable that controls the loop:
Here the programmer forgot to add a loop never comes to an end.
command in the loop. As a result, the year always stays at 1, and the
Another common reason for an infinite loop is accidentally incrementing a counter that should be decremented (or vice versa). Consider this example:
The variable really should have bezen decremented, not incremented. This is a common error because incrementing counters is so much more common than decrementing that your fingers may type the ++ on autopilot. As a consequence, is always larger than 0, and the loop never ends. (Actually, may eventually exceed the largest representable positive integer and wrap around to a negative number. Then the loop ends—of course, with a completely wrong result.)
2/1/2010 10:48 AM
COMMON ERROR 4.1 Infinite Loops
2 of 2
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
In this famous engraving by M.C. Escher, the hooded figures traverse an infinite loop, a loop that never ends. M.C. Escher's “Ascending and Descending” © 2008 The M.C. Escher Company-Holland. All rights reserved. www.mcescher.com.
Copyright © 2009 John Wiley & Sons, Inc. All rights reserved.
2/1/2010 10:48 AM
COMMON ERROR 4.2 Don't Think "Are We There Yet?"
1 of 1
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
Common Error 4.2
COMMON ERROR 4.2 Don't Think “Are We There Yet?”
When doing something repetitive, most of us want to know when we are done. For example, you may think, “I want to get at least $20,000,” and set the loop condition to
But the
loop thinks the opposite: How long am I allowed to keep going? The correct loop condition is
In other words: “Keep at it while the balance is less than the target”.
When writing a loop condition, don't ask, “Are we there yet?” The condition determines how long the loop will keep going. Karen Town/iStockphoto.
Copyright © 2009 John Wiley & Sons, Inc. All rights reserved.
2/1/2010 10:48 AM
COMMON ERROR 4.3 Off-by-One Errors
1 of 2
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
Common Error 4.3
COMMON ERROR 4.3 Off-by-One Errors
Consider our computation of the number of years that are required to double an investment:
Should start at 0 or at 1? Should you test for easy to be off by one in these expressions.
or for
It is
Some people try to solve off-by-one errors by randomly inserting or until the program seems to work—a terrible strategy. It can take a long time to compile and test all the various possibilities. Expending a small amount of mental effort is a real time saver. Fortunately, off-by-one errors are easy to avoid, simply by thinking through a couple of test cases and using the information from the test cases to come up with a rationale for your decisions. An off-by-one error is a common error when programming loops. Think through simple test cases to avoid this type of error.
Should start at 0 or at 1? Look at a scenario with simple values: an initial balance of $100 and an interest rate of 50 percent. After year 1, the balance is $150, and after year 2 it is $225, or over $200. So the investment doubled after 2 years. The loop executed two times, incrementing each time. Hence must start at 0, not at 1.
In other words, the variable denotes the balance after the end of the year. At the outset, the variable contains the balance after year 0 and not after year 1. Next, should you use a or comparison in the test? This is harder to figure out, because it is rare for the balance to be exactly twice the initial balance. There is one case when this happens, namely when the interest is 100 percent. The loop executes once. Now is 1, and is exactly equal to . Has the investment doubled after one year? It has. Therefore, the loop should not execute again. If the test condition is , the loop stops, as it should. If the test condition had been , the
2/1/2010 10:48 AM
COMMON ERROR 4.3 Off-by-One Errors
2 of 2
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
loop would have executed once more. In other words, you keep adding interest while the balance has not yet doubled.
Copyright © 2009 John Wiley & Sons, Inc. All rights reserved.
2/1/2010 10:48 AM
RANDOM FACT 4.1 The First Bug
1 of 1
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
Random Fact 4.1
RANDOM FACT 4.1 The First Bug
According to legend, the first bug was found in the Mark II, a huge electromechanical computer at Harvard University. It really was caused by a bug—a moth was trapped in a relay switch. Actually, from the note that the operator left in the log book next to the moth (see Figure 3), it appears as if the term “bug” had already been in active use at the time.
Figure 3 The First Bug
Naval Surface Weapons Center, Dahlgren, VA. The pioneering computer scientist Maurice Wilkes wrote: “Somehow, at the Moore School and afterwards, one had always assumed there would be no particular difficulty in getting programs right. I can remember the exact instant in time at which it dawned on me that a great part of my future life would be spent finding mistakes in my own programs.”
Copyright © 2009 John Wiley & Sons, Inc. All rights reserved.
2/1/2010 10:49 AM
The for Loop
1 of 6
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
The for loop is used when a value runs from a starting point to an ending point with a constant increment or decrement.
It often happens that you want to execute a sequence of statements a given number of times. You can use a controlled by a counter, as in the following example:
loop that is
Initialize the counter Check the counter
Update the counter Because this loop type is so common, there is a special form for it, called the
loop (see Syntax 4.2).
In general, the for loop: initialization
condition
update
statements has exactly the same effect as the
loop:
initialization condition statements update
2/1/2010 10:49 AM
The for Loop
2 of 6
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
You can visualize the for loop as an orderly sequence of steps. Enrico Fianchini/iStockphoto.
When a loop is controlled by a counter, the loop looks neater than a loop because it groups the initialization, condition, and update expressions together. However, it is important to realize that these expressions are not executed together (see Figure 4). • The initialization is executed once, before the loop is entered. • The condition is checked before each iteration. • The update is executed after each iteration.
2/1/2010 10:49 AM
The for Loop
3 of 6
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
Figure 4 Execution of a
A
Loop
loop can count down instead of up:
The increment or decrement need not be in steps of 1:
See Table 2 on page 150 for additional variations. Table 2 Loop
Loop Examples
Values of
Comment
012345
Note that the loop is executed 6 times. (See Quality Tip 4.3 on page 151.)
543210
Use
02468
Use
0 2 4 6 8 10 12 14 … (infinite loop)
You can use < or i in the word. Swap the letters at positions j and i. } Print the word. To swap the letters, construct substrings as follows:
Then replace the string with
Exercise P4.8. Write a program that reads a word and prints each character of the word on a separate line. For example, if the user provides the input , the program prints
Exercise P4.9. Write a program that reads a word and prints the word in reverse. For example, if the user provides the input “ program prints
”, the
Exercise P4.10. Write a program that reads a word and prints the number of vowels in the word. For this exercise, assume that are vowels. For example, if the user provides the input “ ”, the program prints . Exercise P4.11. Write a program that reads a word and prints the number of syllables in the word. For this exercise, assume that syllables are determined as follows: Each sequence of vowels , except for the last in a word, is a vowel. However, if that algorithm yields a count of 0, change it to 1. For example,
Exercise P4.12.
2/1/2010 10:52 AM
Programming Exercises
3 of 7
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
Write a program that reads a word and prints all substrings, sorted by length. For example, if the user provides the input “ ”, the program prints
Exercise P4.13. Write a program that prints all powers of 2 from 20 up to 220. Exercise P4.14. Write a program that reads a number and prints all of its binary digits: Print the remainder , then replace the number with . Keep going until the number is 0. For example, if the user provides the input 13, the output should be
Exercise P4.15. Mean and standard deviation. Write a program that reads a set of floating-point data values. Choose an appropriate mechanism for prompting for the end of the data set. When all values have been read, print out the count of the values, the , where is average, and the standard deviation. The average of a data set {x1, …, xn} is the sum of the input values. The standard deviation is
However, this formula is not suitable for the task. By the time the program has computed , the individual xi are long gone. Until you know how to save these values, use the numerically less stable formula
You can compute this quantity by keeping track of the count, the sum, and the sum of squares as you process the input values. Exercise P4.16. The Fibonacci numbers are defined by the sequence
Reformulate that as
After that, discard , which is no longer needed, and set appropriate number of times.
to
and
to
. Repeat
an
Implement a program that computes the Fibonacci numbers in that way.
2/1/2010 10:52 AM
Programming Exercises
4 of 7
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
Exercise P4.17. Factoring of integers. Write a program that asks the user for an integer and then prints out all its factors. For example, when the user enters 150, the program should print
Exercise P4.18. Prime numbers. Write a program that prompts the user for an integer and then prints out all prime numbers up to that integer. For example, when the user enters 20, the program should print
Recall that a number is a prime number if it is not divisible by any number except 1 and itself. Exercise P4.19. Write a program that prints a multiplication table, like this:
Exercise P4.20. Write a program that reads an integer and displays, using asterisks, a filled and hollow square, placed next to each other. For example if the side length is 5, the program should display
Exercise P4.21. Write a program that reads an integer and displays, using asterisks, a filled diamond of the given side length. For example, if the side length is 4, the program should display
Exercise P4.22. Projectile flight. Suppose a cannonball is propelled straight into the air with a starting velocity v0. Any calculus book will state that the position of the ball after t seconds is
, where g = 9.81 m/sec2 is the gravitational force
2/1/2010 10:52 AM
Programming Exercises
5 of 7
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
of the earth. No calculus book ever mentions why someone would want to carry out such an obviously dangerous experiment, so we will do it in the safety of the computer. In fact, we will confirm the theorem from calculus by a simulation. In our simulation, we will consider how the ball moves in very short time intervals Δt. In a short time interval the velocity v is nearly constant, and we can compute the distance the ball moves as Δs = vΔt. In our program, we will simply set
and update the position by
The velocity changes constantly—in fact, it is reduced by the gravitational force of the earth. In a short time interval, Δv = -gΔt, we must keep the velocity updated as
In the next iteration the new velocity is used to update the distance. Now run the simulation until the cannonball falls back to the earth. Get the initial velocity as an input (100 m/sec is a good value). Update the position and velocity 100 times per second, but print out the position only every full second. Also print out the values from the exact formula for comparison. What is the benefit of this kind of simulation when an exact formula is available? Well, the formula from the calculus book is not exact. Actually, the gravitational force diminishes the further the cannonball is away from the surface of the earth. This complicates the algebra sufficiently that it is not possible to give an exact formula for the actual motion, but the computer simulation can simply be extended to apply a variable gravitational force. For cannonballs, the calculus-book formula is actually good enough, but computers are necessary to compute accurate trajectories for higher-flying objects such as ballistic missiles. Exercise P4.23. The game of Nim. This is a well-known game with a number of variants. The following variant has an interesting winning strategy. Two players alternately take marbles from a pile. In each move, a player chooses how many marbles to take. The player must take at least one but at most half of the marbles. Then the other player takes a turn. The player who takes the last marble loses. You will write a program in which the computer plays against a human opponent. Generate a random integer between 10 and 100 to denote the initial size of the pile. Generate a random integer between 0 and 1 to decide whether the computer or the human takes the first turn. Generate a random integer between 0 and 1 to decide whether the computer plays smart or stupid. In stupid mode the computer simply takes a random legal value (between 1 and n/2) from the pile whenever it has a turn. In smart mode the computer takes off enough marbles to make the size of the pile a power of two minus 1—that is, 3, 7, 15, 31, or 63. That is always a legal move, except when the size of the pile is currently one less than a power of two. In that case, the computer makes a random legal move. You will note that the computer cannot be beaten in smart mode when it has the first move, unless the pile size happens to be 15, 31, or 63. Of course, a human player who has the first turn and knows the winning strategy can win against the computer. Exercise P4.24. The Drunkard's Walk. A drunkard in a grid of streets randomly picks one of four directions and stumbles to the next intersection, then again randomly picks one of four directions, and so on. You might think that on average the drunkard doesn't move very far because the choices cancel each other out, but that is actually not the case. Represent locations as integer pairs (x, y). Implement the drunkard's walk over 100 intersections and print the beginning and ending location. Exercise P4.25. The Monty Hall Paradox. Marilyn vos Savant described the following problem (loosely based on a game show hosted by Monty Hall) in a popular magazine: “Suppose you're on a game show, and you're given the choice of three doors: Behind one door is a car; behind the others, goats. You pick a door, say No. 1, and the host, who knows what's behind the doors,
2/1/2010 10:52 AM
Programming Exercises
6 of 7
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
opens another door, say No. 3, which has a goat. He then says to you, “Do you want to pick door No. 2?” Is it to your advantage to switch your choice?” Ms. vos Savant proved that it is to your advantage, but many of her readers, including some mathematics professors, disagreed, arguing that the probability would not change because another door was opened. Your task is to simulate this game show. In each iteration, randomly pick a door number between 1 and 3 for placing the car. Randomly have the player pick a door. Randomly have the game show host pick one of the two doors having a goat. Now increment a counter for strategy 1 if the player wins by switching to the third door, and increment a counter for strategy 2 if the player wins by sticking with the original choice. Run 1,000 iterations and print both counters. Exercise P4.26. The Buffon Needle Experiment. The following experiment was devised by Comte Georges-Louis Leclerc de Buffon (1707–1788), a French naturalist. A needle of length 1 inch is dropped onto paper that is ruled with lines 2 inches apart. If the needle drops onto a line, we count it as a hit. (See Figure 7.) Buffon conjectured that the quotient tries/hits approximates π.
Figure 7 The Buffon Needle Experiment
For the Buffon needle experiment, you must generate two random numbers: one to describe the starting position and one to describe the angle of the needle with the x-axis. Then you need to test whether the needle touches a grid line. Generate the lower point of the needle. Its x-coordinate is irrelevant, and you may assume its y-coordinate ylow to be any random number between 0 and 2. The angle α between the needle and the x-axis can be any value between 0 degrees and 180 degrees (π radians). The upper end of the needle has y-coordinate The needle is a hit if yhigh is at least 2, as shown in Figure 8.
Figure 8 A Hit in the Buffon Needle Experiment
Stop after 10,000 tries and print the quotient tries/hits. (This program is not suitable for computing the value of π. You need π in the computation of the angle.)
2/1/2010 10:52 AM
Programming Exercises
7 of 7
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
Copyright © 2009 John Wiley & Sons, Inc. All rights reserved.
2/1/2010 10:52 AM
Answers to Self-Check Questions
1 of 3
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
1. 23 years. 2. 7 years. 3. Add a statement
as the last statement in the
loop.
4. The program prints the same output. This is because the balance after 14 years is slightly below $20,000, and after 15 years, it is slightly above $20,000. 5. Note that the value 128 is printed even though it is larger than 100. 6.
7. 11 numbers: 8.
9.
10. However, it is best not to use a loop in this case because the loop condition does not relate to the loop would be a better choice.
variable. A
11.
12.
2/1/2010 10:53 AM
Answers to Self-Check Questions
2 of 3
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
Here, the variable value had to be initialized with an artificial value to ensure that the loop is entered at least once. 13. Yes. The do loop body
condition
is equivalent to this while loop: condition
body
14.
15.
16. All values in the inner loop should be displayed on the same line. 17. Change lines 14, 19, and 31 to
. Change
to 5.
18. 60: The outer loop is executed 10 times, and the inner loop 6 times. 19.
20.
21. 22. The first check ends the loop after the sentinel has been read. The second check ensures that the sentinel is not processed as an input value. loop would never be entered. The user would never be prompted for input. Since 23. The would then print “ ”.
stays 0, the program
2/1/2010 10:53 AM
Answers to Self-Check Questions
3 of 3
http://edugen.wiley.com/edugen/courses/crs2656/horstmann3292/horstma...
24. The stream also fails. A more accurate prompt would have been: “Enter values, a key other than a digit to quit.” But that might be more confusing to the program user who would need now ponder which key to choose. 25. You don't know whether the input fails until after you try reading input. 26. Compute
, and use 0 for heads, 1 for tails, or the other way around.
and associate the numbers 0 … 3 with the four suits. Then compute 27. Compute associate the numbers 0 … 12 with Jack, Ace, 2 … 10, Queen, and King 28. It is required for calling the
and
function.
29. The call will produce a value between 2 and 12, but all values have the same probability. When throwing a pair of dice, the number 7 is six times as likely as the number 2. The correct formula is
30.
Copyright © 2009 John Wiley & Sons, Inc. All rights reserved.
2/1/2010 10:53 AM
sc_ch04_we1.fm Page 1 Friday, September 5, 2008 11:36 AM
Worked Example 4.1 • Credit Card Processing
1
W O R K E D E X A M P L E 4.1 Credit Card Processing One of the minor annoyances of online shopping is that many web sites require you to enter a credit card without spaces or dashes, which makes double-checking the number rather tedious. How hard can it be to remove dashes or spaces from a string? Not hard at all, as this worked example shows.
Your task is to remove all spaces or dashes from a string credit_card_number. For example, if credit_card_number is "4123-5678-9012-3450", then you should set it to "4123567890123450" Step 1
Decide what work must be done inside the loop.
In the loop, we visit each character in turn. You can get the ith character as string ch = credit_card_number.substr(i, 1);
If it is not a dash or space, we move on to the next character. If it is a dash or space, we remove the offending character. Loop { ch = the ith character of credit_card_number If ch is a space or dash { Remove the character from credit_card_number. } Else { Increment i. } } You may wonder how to remove a character from a string in C++. Here is the procedure for removing the character at position i: Take the substrings that end before i and start after i, and concatenate them. 4
1
2
3
-
5
6
7
8
-
9
0
1
2
-
3
4
5
0
i before
after
C++ for Everyone, Cay Horstmann, Copyright © 2009 John Wiley & Sons, Inc. All Rights Reserved.
sc_ch04_we1.fm Page 2 Friday, September 5, 2008 11:36 AM
2
C++ for Everyone •
CHAPTER
4
string before = credit_card_number.substr(0, i); string after = credit_card_number.substr(i + 1); credit_card_number = before + after;
Note that we do not increment i after removing a character. For example, in the figure above, i was 4, and we removed the dash at position 4. The next time we enter the loop, we want to reexamine position 4 which now contains the character 5. Step 2
Specify the loop condition.
We stay in the loop while the index i is a valid position. That is, i < credit_card_number.length()
Step 3
Find out how often the loop is repeated, and choose the loop type.
We don’t know at the outset how often the loop is repeated. It depends on the number of dashes and spaces that we find. Therefore, we will choose a while loop. Why not a do loop? If we are given an empty string (because the user has not provided any credit card number at all), we do not want to enter the loop at all. Step 4
Process the result after the loop has finished.
In this case, the result is simply the string. Step 5
Trace the loop with typical examples.
The complete loop is i=0 While i < credit_card_number.length() { ch = the ith character of credit_card_number. If ch is a space or dash { Remove the character from credit_card_number. } Else { Increment i. } } It is a bit tedious to trace a string with 20 characters, so we will use a shorter example:
credit_card_number 4-56-7 4-56-7 456-7 456-7 456-7 4567
i 0 1 1 2 3 3
ch 4 5 6 7
C++ for Everyone, Cay Horstmann, Copyright © 2009 John Wiley & Sons, Inc. All Rights Reserved.
sc_ch04_we1.fm Page 3 Friday, September 5, 2008 11:36 AM
Worked Example 4.1 • Credit Card Processing Step 6
Implement the loop in C++.
Here’s the complete program, ch04/ccnumber.cpp. #include #include <string> using namespace std; int main() { string credit_card_number = "4123-5678-9012-3450"; int i = 0; while (i < credit_card_number.length()) { string ch = credit_card_number.substr(i, 1); if (ch == " " || ch == "-") { string before = credit_card_number.substr(0, i); string after = credit_card_number.substr(i + 1); credit_card_number = before + after; } else { i++; } } cout = 100) { name = digit_name(part / 100) + " hundred"; part = part % 100; }
Now you have seen all the important building blocks for the int_name function. Here is the complete program.
ch05/intname.cpp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
#include #include <string> using namespace std; /** Turns a digit into its English name. @param digit an integer between 1 and 9 @return the name of digit ("one" . . . "nine") */ string digit_name(int digit) { if (digit == 1) return "one"; if (digit == 2) return "two"; if (digit == 3) return "three"; if (digit == 4) return "four"; if (digit == 5) return "five"; if (digit == 6) return "six"; if (digit == 7) return "seven"; if (digit == 8) return "eight"; if (digit == 9) return "nine"; return ""; } /** Turns a number between 10 and 19 into its English name. @param number an integer between 10 and 19 @return the name of the given number ("ten" . . . "nineteen") */ string teen_name(int number)
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
{ if (number if (number if (number if (number if (number if (number if (number if (number if (number if (number return "";
== == == == == == == == == ==
10) 11) 12) 13) 14) 15) 16) 17) 18) 19)
return return return return return return return return return return
"ten"; "eleven"; "twelve"; "thirteen"; "fourteen"; "fifteen"; "sixteen"; "seventeen"; "eighteen"; "nineteen";
} /** Gives the name of the tens part of a number between 20 and 99. @param number an integer between 20 and 99 @return the name of the tens part of the number ("twenty" . . . "ninety") */ string tens_name(int number) { if (number >= 90) return "ninety"; if (number >= 80) return "eighty"; if (number >= 70) return "seventy"; if (number >= 60) return "sixty"; if (number >= 50) return "fifty"; if (number >= 40) return "forty"; if (number >= 30) return "thirty"; if (number >= 20) return "twenty"; return ""; } /** Turns a number into its English name. @param number a positive integer < 1,000 @return the name of the number (e.g. "two hundred seventy four") */ string int_name(int number) { int part = number; // The part that still needs to be converted string name; // The return value if (part >= 100) { name = digit_name(part / 100) + " hundred"; part = part % 100; } if (part >= 20) { name = name + part = part % } else if (part >= { name = name +
" " + tens_name(part); 10; 10) " " + teen_name(part);
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
part = 0; } if (part > 0) { name = name + " " + digit_name(part); } return name; } int main() { cout > input; cout = 10. teens_name(16) is sixteen, so the variables now have the values
Now it becomes clear why you need to set part to 0. Otherwise, you would enter the next branch and the result would be "four hundred sixteen six". Tracing the code is an effective way to understand the subtle aspects of a function.
Productivity Hint 5.4 PRODUCTIVITY HINT 5.4 Stubs
When writing a larger program, it is not always feasible to implement and test all functions at once. You often need to test a function that calls another, but the other function hasn't yet been implemented. Then you can temporarily replace the missing function with a stub. A stub is a function that returns a simple value that is sufficient for testing another function. Here are examples of stub functions. /** Turns a digit into its English name. @param digit an integer between 1 and 9 @return the name of digit ("one" . . . "nine") */ string digit_name(int digit) { return "mumble"; } /** Gives the name of the tens part of a number between 20 and 99. @param number an integer between 20 and 99 @return the tens name of the number ("twenty" . . . "ninety") */ string tens_name(int number) { return "mumblety"; }
If you combine these stubs with the int_name function and test it with a parameter value of 274, you will get a result of "mumble hundred mumblety mumble", which indicates that the basic logic of the int_name function is working correctly.
Worked Example 5.2 WORKED EXAMPLE 5.2 Calculating a Course Grade
Students in this course take four exams and earn a letter grade (A+, A, A-, B+, B, B-, C+, C, C-, D+, D, D-, or F) for each of them. The course grade is determined by dropping the lowest grade and averaging the three remaining grades. To average grades, first convert them to number grades, using the usual scheme A+ = 4.3, A = 4.0, A- = 3.7, B+ = 3.3, …, D- = 0.7, F = 0. Then compute their average and convert it back to the closest letter grade. For example, an average of 3.51 would be an A-. Your task is to read inputs of the form: letter_grade1 letter_grade2 letter_grade3 letter_grade4
For example, A- B+ C A
For each input line, your output should be letter_grade
where the letter grade is the grade earned in the course, as just described. For example, A-
The end of inputs will be indicated by a letter_grade1 field of Q. Step 1 Carry out stepwise refinement. We will use the process of stepwise refinement. To process the inputs, we can process each line individually. Therefore, we define a task process line . To process a line, we read the first grade and bail out if it is a Q. Otherwise, we read the four grades. Since we need them in their numeric form, we identify a task convert letter grade to number . We then have four numbers and need to find the smallest one. That is another task, find smallest of four numbers . To average the remaining ones, we compute the sum of all values, subtract the smallest, and divide by three. Let's say that is not worth making into a subtask. Next, we need to convert the result back into a letter grade. That is yet another subtask convert number grade to letter . Finally, we print the letter grade. That is again so simple that it requires no subtask. Step 2 Convert letter grade to number. How do we convert a letter grade to a number? Take the first character, and convert A to 4, B to 3, C to 2, D to 1, and F to 0. If there is a + suffix, add 0.3, and if there is a - suffix, subtract 0.3. Here is a function for that task. /** Converts a letter grade to a number. @param grade a letter grade (A+, A, A-, . . ., D-,
F) @return the equivalent number grade */ double grade_to_number(string grade) { double result = 0; string first = grade.substr(0, 1); if (first == "A") { result = 4; } else if (first == "B") { result = 3; } else if (first == "C") { result = 2; } else if (first == "D") { result = 1; } if (grade.length() > 1) { if (grade.substr(1, 1) == "+") { result = result + 0.3; } else { result = result - 0.3; } } return result; }
Step 3 Convert number grade to letter. How do we do the opposite conversion? Here, the challenge is that we need to convert to the nearest letter grade. For example, if x is the number grade, then we have: 2.5 x < 2.85: B2.85 x < 3.15: B 3.15 x < 3.5: B+ We can make a function with 13 branches, one for each valid letter grade. /** Converts a number to the nearest letter grade. @param x a number between 0 and 4.3 @return the nearest letter grade */ string number_to_grade(double x) { if (x >= 4.15) { return "A+"; } if (x >= 3.85) { return "A"; } if (x >= 3.5) { return "A-"; } if (x >= 3.15) { return "B+"; } if (x >= 2.85) { return "B"; } if (x >= 2.5) { return "B-"; } if (x >= 2.15) { return "C+"; } if (x >= 1.85) { return "C"; } if (x >= 1.5) { return "C-"; } if (x >= 1.15) { return "D+"; } if (x >= 0.85) { return "D"; } if (x >= 0.5) { return "D-"; } return "F"; }
Step 4 Find the minimum of four numbers. Finally, how do we find the smallest of four numbers? Let's suppose we can find the smallest of two numbers, with a function min(x, y). Then the smallest of four numbers is min(min(x1, x2), min(x3, x4)). Finding the smallest of two numbers is easy. /** Returns the smaller of two numbers. @param x a number @param y a number @return the smaller of x and y */ double min(double x, double y) { if (x < y) { return x; } else { return y; } }
Step 5 Process a line. As previously described, to process a line, we read in the four input strings, convert grades to numbers, and compute the average after dropping the lowest grade. Then we print the grade corresponding to that average. However, if we read the first input string and find a Q, we need to signal to the caller that we have reached the end of the input set and that no further calls should be made. Our function will return a bool value, true if it was successful, false if it encountered the sentinel. /** Processes one line of input. @return true if the sentinel was not encountered */ bool process_line() { cout > g1; if (g1 == "Q") { return false; } string g2; string g3; string g4; cin >> g2 >> g3 >> g4; double x1 = grade_to_number(g1); double x2 = grade_to_number(g2); double x3 = grade_to_number(g3); double x4 = grade_to_number(g4); double xlow = min(min(x1, x2), min(x3, x4)); double avg = (x1 + x2 + x3 + x4 - xlow) / 3;
cout = amount) { balance = balance - amount; } else { balance = balance - PENALTY; } } int main() { double harrys_account = 1000; double sallys_account = 500; withdraw(harrys_account, 100); // Now harrys_account is 900 withdraw(harrys_account, 1000); // Insufficient funds // Now harrys_account is 890 withdraw(sallys_account, 150); cout