C++ for Everyone 2nd Edition

This book is an introduction to C++ and computer programming that focuses on the essentials—and on effective learning.


Cay Horstmannn


562 Pages

72100 Reads

60 Downloads

English

PDF Format

27.1 MB

C, C++ Programming

Download PDF format


  • Cay Horstmannn   
  • 562 Pages   
  • 03 Mar 2015
  • Page - 1

    read more..

  • Page - 2

    This page intentionally left blank read more..

  • Page - 3

    C++ for Ev E ryon E cfe2_fm_pi_xxvi.indd 1 10/28/10 5:08 PM read more..

  • Page - 4

    This page intentionally left blank read more..

  • Page - 5

    C++ for Ev E ryon E Second e dition cay Horstmann San Jose State University John Wiley & Sons, Inc. cfe2_fm_pi_xxvi.indd 3 10/28/10 5:08 PM read more..

  • Page - 6

    VICE PRESIDENT AND EXECUTIVE PUBLISHER Don Fowley EXECUTIVE EDITOR Beth Lang Golub EDITORIAL PROGRAM ASSISTANT Michael Berlin PRODUCTION SERVICES MANAGER Dorothy Sinclair SENIOR PRODUCTION EDITOR Janet Foxman EXECUTIVE MARKETING MANAGER Christopher Ruel MARKETING ASSISTANT Diana Smith CREATIVE DIRECTOR Harry Nolan SENIOR PHOTO EDITOR Lisa Gee SENIOR DESIGNER Madelyn Lesure EXECUTIVE MEDIA read more..

  • Page - 7

    Pr E fa CE v This book is an introduction to C++ and computer programming that focuses on the essentials—and on effective learning. The book is designed to serve a wide range of student interests and abilities and is suitable for a first course in programming for computer scientists, engineers, and students in other disciplines. No prior program- ming experience is required, read more..

  • Page - 8

    vi Preface new to This Edition Problem Solving Strategies This edition adds practical, step-by-step illustrations of techniques that can help stu- dents devise and evaluate solutions to programming problems. Introduced where they are most relevant, these strategies address barriers to success for many students. Strategies included are: • Algorithm Design (with pseudocode) • First Do read more..

  • Page - 9

    Preface vii File processing is the subject of Chapter 8. Section 8.1 can be covered sooner for an intro duction to reading and writing text files. The remainder of the chapter gives addi tional material for practical applications. Chapters 9 and 10 introduce the object-oriented features of C++. Chapter 9 introduces class design and implementation. Chapter 10 covers inheritance and read more..

  • Page - 10

    viii Walkthrough a Walkthrough of the Learning aids 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 fea- tures, such as chapter objectives and a wealth of exercises, each chapter contains read more..

  • Page - 11

    Walkthrough ix 6.5 Problem Solving: Discovering Algorithms by Manipulating Physical Objects 277 Now how does that help us with our problem, switching the first and the second half of the array? Let’s put the first coin into place, by swapping it with the fifth coin. However, as C++ programmers, we will say that we swap the coins in positions 0 and 4: read more..

  • Page - 12

    x Walkthrough • Figure 3 Parameter Passing 1 Function call result1 = side_length = 2 Initializing function parameter variable result1 = side_length = 2 3 About to return to the caller result1 = side_length = volume = 8 2 4 After function call result1 = 8 double result1 = cube_volume(2); double volume = side_length * side_length * side_length; return volume; double result1 = cube_volume(2); read more..

  • Page - 13

    Walkthrough xi Hand-Tracing A very useful technique for understanding whether a program works correctly is called hand-tracing. You simulate the pro- gram’s activity on a sheet of paper. You can use this method with pseudocode or C++ code. Get an index card, a cocktail napkin, or whatever sheet of paper is within reach. Make a column for each variable. Have the program read more..

  • Page - 14

    xii Preface appendices Appendix A contains a programming style guide. Using a style guide for program- ming assignments benefits students by directing them toward good habits and reduc- ing gratuitous choice. The style guide is available in electronic form so that instruc- tors can modify it to reflect their preferred style. Appendices B and C summarize C++ reserved words and read more..

  • Page - 15

    acknowledgments xiii acknowledgments Many thanks to Beth Golub, Tom Kulesa, Andre Legaspi, Elizabeth Mills, Michael Berlin, and Lisa Gee at John Wiley & Sons, and to the team at Publishing Services for their hard work and sup port for this book project. An especially deep acknowledg- ment and thanks to Cindy Johnson, who, through enormous patience and attention to detail, made read more..

  • Page - 16

    xiv acknowledgments Lorrie Lehman, University of North Carolina, Charlotte Cynthia Lester, Tuskegee University Yanjun Li, Fordham University W. James MacLean, University of Toronto LindaLee Massoud, Mott Community College Charles W. Mellard, DeVry Institute of Technology, Irving Ethan V. Munson, University of Wisconsin, Milwaukee Philip Regalbuto, Trident Technical College Don Retzlaff, University of read more..

  • Page - 17

    C onTE n TS xv PrEfaCE v SPECIaL fEaTurES xx InTroDuCTIon 1 1.1 What is Programming 2 1.2 The anatomy of a Computer 3 1.3 Machine Code and Programming Languages 6 1.4 Becoming familiar with your Programming Environment 7 1.5 analyzing your first Program 11 1.6 Errors 15 1.7 Problem Solving: algorithm Design 17 funDaMEnTaL DaTa TyPES 29 2.1 variables read more..

  • Page - 18

    xvi Contents 4.6 Problem Solving: Storyboards 154 4.7 Common Loop algorithms 157 4.8 nested Loops 165 4.9 random numbers and Simulations 168 funCTIonS 193 5.1 functions as Black Boxes 194 5.2 Implementing functions 196 5.3 Parameter Passing 199 5.4 return values 202 5.5 functions Without return values 206 5.6 Problem Solving: reusable functions 208 read more..

  • Page - 19

    Contents xvii Available online actionURI(www.wiley.com/college/horstmann):at www.wiley.com/college/horstmann. 8.3 Writing Text output 361 8.4 String Streams 363 8.5 Command Line arguments 365 8.6 random access and Binary files 372 CLaSSES 389 9.1 object-oriented Programming 390 9.2 Specifying the Public Interface of a Class 392 9.3 Data Members 395 9.4 Member functions read more..

  • Page - 20

    xviii Contents Available online actionURI(www.wiley.com/college/horstmann):at www.wiley.com/college/horstmann. LISTS, STaCkS, anD QuEuES (WEB onLy) 13.1 using Linked Lists 13.2 Implementing Linked Lists 13.3 The Efficiency of List, array, and vector operations 13.4 Stacks and Queues SETS, MaPS, anD PrIorITy QuEuES (WEB onLy) 14.1 Sets 14.2 Binary Search Trees read more..

  • Page - 21

    Contents xix SynTax BoxES assignment 34 C++ Program 12 Class Definition 393 Comparisons 83 Constructor with Base-Class Initializer 451 Defining an array 251 Defining a vector 285 Derived-Class Definition 448 Dynamic Memory allocation 325 for Statement 144 function Definition 197 if Statement 78 Input Statement 48 Member function Definition read more..

  • Page - 22

    xx Special features CHaPTEr Available online actionURI(www.wiley.com/college/horstmann):at www.wiley.com/college/horstmann. Programming Tips Special Topics random facts Backup Copies 11 Escape Sequences 14 The EnIaC and the Dawn of Computing 5 Standards organizations 7 Choose Descriptive variable names 38 Do not use Magic numbers 39 Spaces in Expressions 46 numeric Types in C++ 38 numeric ranges and read more..

  • Page - 23

    Special Features xxi   Available online at actionURI(www.wiley.com/college/horstmann):www.wiley.com/college/horstmann . Programming Tips Special Topics Random Facts Backup Copies 11 Escape Sequences 14 The ENIAC and the Dawn of Computing 5 Standards Organizations 7 Choose Descriptive Variable Names 38 Do Not Use Magic Numbers 39 Spaces in Expressions 46 Numeric Types in C++ 38 Numeric Ranges and read more..

  • Page - 24

    xxii Special features CHaPTEr Available online actionURI(www.wiley.com/college/horstmann):at www.wiley.com/college/horstmann. Programming Tips Special Topics random facts use arrays for Sequences of related values 255 Prefer vectors over arrays 289 Sorting with the C++ Library 263 a Sorting algorithm 263 Binary Search 264 Constant array Parameters 269 an Early Internet Worm 255 The first Programmer 290 read more..

  • Page - 25

    Special Features xxiii   Available online at actionURI(www.wiley.com/college/horstmann):www.wiley.com/college/horstmann . Programming Tips Special Topics Random Facts Use Arrays for Sequences of Related Values 255 Prefer Vectors over Arrays 289 Sorting with the C++ Library 263 A Sorting Algorithm 263 Binary Search 264 Constant Array Parameters 269 An Early Internet Worm 255 The First Programmer 290 read more..

  • Page - 26

    xxiv Special features CHaPTEr Available online actionURI(www.wiley.com/college/horstmann):at www.wiley.com/college/horstmann. Programming Tips Special Topics random facts Library functions for Sorting and Binary Search The Quicksort algorithm Defining an ordering for Sorting objects Cataloging your necktie Collection reverse Polish notation Defining an ordering for Container Elements Constant Iterators read more..

  • Page - 27

    Special Features xxv   Available online at actionURI(www.wiley.com/college/horstmann):www.wiley.com/college/horstmann . Programming Tips Special Topics Random Facts Library Functions for Sorting and Binary Search The Quicksort Algorithm Defining an Ordering for Sorting Objects Cataloging Your Necktie Collection Reverse Polish Notation Defining an Ordering for Container Elements Constant Iterators read more..

  • Page - 28

    This page intentionally left blank read more..

  • Page - 29

    1 Chapter 1 Introdu C t I on 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 compile-time and run-time errors to describe an algorithm with pseudocode to understand the activity of programming Chapter Goals Chapter Contents read more..

  • Page - 30

    2 Just as you gather tools, study a project, and make a plan for tackling it, in this chapter you will gather up the basics you need to start learning to program. after a brief introduction to computer hardware, software, and programming in general, you will learn how to write and run your first C++ program. You will also learn how to diagnose and fix programming read more..

  • Page - 31

    1.2 the anatomy of a Computer 3 make small changes in a program that lead to immediate improvements, and to see the computer become an extension of your mental powers. 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 read more..

  • Page - 32

    4 Chapter 1 Introduction figure 2  a hard disk Programs and data are typically stored on the hard disk and loaded into memory when the program starts. The program then updates the data in memory and writes the modified data back to the hard disk. To interact with a human user, a computer requires peripheral devices. The com- puter transmits infor mation (called read more..

  • Page - 33

    1.2 the anatomy of a Computer 5 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 an optical disk such as a DVD, or elsewhere on the network. When a program is started, it is brought into memory, where the CPU can read it. The read more..

  • Page - 34

    6 Chapter 1 Introduction 1.3 Machine Code and programming languages On the most basic level, computer instructions are extremely primitive. The proces- sor 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 read more..

  • Page - 35

    1.4 Becoming Familiar with Your programming environment 7 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? 8.  What are the most important uses for C++? Practice It  Now you can try these exercises at the end of the chapter: R1.5. 1.4 Becoming Familiar with Your read more..

  • Page - 36

    8 Chapter 1 Introduction #include <iostream> using namespace std; int main() { cout << "Hello, World!" << endl; return 0; } We will examine this program in the next section. No matter which programming environment you use, you begin your activity by typing the pro gram statements into an editor window. Create a new file and call it hello.cpp read more..

  • Page - 37

    1.4 Becoming Familiar with Your programming environment 9 figure 6  Compiling and running the hello program in a Console Window It is useful to know what goes on behind the scenes when your program gets built. First, the compiler translates the C++ source code (that is, the statements that you wrote) into machine instructions. The machine code contains only read more..

  • Page - 38

    10 Chapter 1 Introduction figure 8  a Folder hierarchy However, you should create folders for organizing your work. It is a good idea to make a separate folder for your programming class. Inside that folder, make a sepa- rate folder for each assignment. Some programming environments place your programs into a default location if you don’t specify a folder yourself. read more..

  • Page - 39

    1.5 analyzing Your First program 11 Backup Copies Backing up files on a memory stick is an easy and convenient stor- age 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 read more..

  • Page - 40

    12 Chapter 1 Introduction syntax 1.1 C++ program #include <iostream> using namespace std; int main() { cout << "Hello, World!" << endl; return 0; } Every program includes one or more headers for required services such as input/output. Every program that uses standard services requires this directive. Every program has a main function. Replace this read more..

  • Page - 41

    1.5 analyzing Your First program 13 syntax 1.2 output statement cout << "The answer is" << 6 * 7 << endl; Sending endl to cout starts a new line. Data sent to cout is displayed in a console window. You can send strings and numbers to cout . Add a << symbol before each item to be displayed. Strings are enclosed in quotation marks. * read more..

  • Page - 42

    14 Chapter 1 Introduction 15.  What does the following statement print? cout << 2 * 2 << 2; 16.  What does the following statement print? cout << "Hello" << endl << endl << "World"; Practice It  Now you can try these exercises at the end of the chapter: R1.7, P1.1, P1.2. omitting semicolons In C++ every statement must end in a read more..

  • Page - 43

    1.6 errors 15 Finally, the escape sequence \n denotes a newline character that starts a new line on the screen. The command cout << "Hello, World! \n"; has exactly the same effect as cout << "Hello, World!" << endl; 1.6 errors Programming languages follow very strict conven- tions. When you talk to another person, and you scramble or omit a word read more..

  • Page - 44

    16 Chapter 1 Introduction output. Because run-time errors are caused by logical flaws in the program, they are often called logic errors. Some kinds of run-time errors are so severe that they gener- ate an exception: a signal from the processor that aborts the program with an error message. For example, if your program includes the statement cout << 1 / 0; your read more..

  • Page - 45

    1.7 problem solving: algorithm design 17 1.7 problem solving: algorithm design You will soon learn how to program calculations and decision making in C++. But before we look at the mechanics of implementing computations in the next chapter, let’s consider the planning process that pre cedes implementation. You may have run across advertisements that encourage you to pay for read more..

  • Page - 46

    18 Chapter 1 Introduction Repeat the following steps while the balance is less than $20,000 Add 1 to the year value. Compute the interest as balance x 0.05 (i.e., 5 percent interest) Add the interest to the balance. year interest balance 0 10000 1 500.00 10500.00 14 942.82 19799.32 15 989.96 20789.28 Report the final year value as the answer. Of course, read more..

  • Page - 47

    1.7 problem solving: algorithm design 19 figure 9  the software development process A method is unambiguous when there are precise instructions for what to do at each step and where to go next. There is no room for guesswork or cre- ativity. A method is executable when each step can be carried out in practice. Had we asked to use the actual interest rate that read more..

  • Page - 48

    20 Chapter 1 Introduction 23.  Suppose each photo in Self Check 22 had a price tag. Give an algorithm for find- ing the most expen sive photo. 24.  Suppose you have a random sequence of black and white marbles and want to rearrange it so that the black and white marbles are grouped together. Consider this algorithm: Repeat until sorted Locate the first black read more..

  • Page - 49

    Chapter summary 21 23.  Suppose each photo in Self Check 22 had a price tag. Give an algorithm for find- ing the most expen sive photo. 24.  Suppose you have a random sequence of black and white marbles and want to rearrange it so that the black and white marbles are grouped together. Consider this algorithm: Repeat until sorted Locate the first black marble that is read more..

  • Page - 50

    22 Chapter 1 Introduction describe the process of translating high-level languages to machine code. • Computer programs are stored as machine instructions in a code that depends on the processor type. • C++ is a general-purpose language that is in widespread use for systems and embedded programming. • High-level programming languages are independent of the processor. read more..

  • Page - 51

    review exercises 23 r1.1  Explain the difference between using a computer program and programming a computer. r1.2  Which parts of a computer can store program code? Which can store user data? r1.3  Which parts of a computer serve to give information to the user? Which parts take user input? r1.4  A toaster is a single-function device, but a computer can be programmed to read more..

  • Page - 52

    24 Chapter 1 Introduction r1.12  Write an algorithm to settle the following question: A bank account starts out with $10,000. Interest is compounded monthly at 6 percent per year (0.5 percent per month). Every month, $500 is withdrawn to meet college expenses. After how many years is the account depleted? r1.13  Consider the question in Exercise R1.12. Suppose the numbers read more..

  • Page - 53

    programming exercises 25 engineering r1.21  Suppose you know how long it takes a car to accelerate from 0 to 60 miles per hour. Develop an algorithm for computing the time required to travel a given distance (for example 5 miles), assuming that the car is initially at rest, accelerates to a given speed (for example 25 miles per hour), and drives at that speed until read more..

  • Page - 54

    26 Chapter 1 Introduction P1.4  Write a program that prints the sum of the first ten positive integers, 1 + 2 + … + 10. P1.5  Write a program that prints the product of the first ten positive integers, 1 × 2 × … × 10. (Use * for multiplication in C++.) P1.6  Write a program that prints the balance of an account that earns 5 percent read more..

  • Page - 55

    answers to self-Check Questions 27 engineering P1.16  The atmospheres of the gas giant planets (Jupiter, Saturn, Uranus, and Neptune) are mostly comprised of hydrogen (H2) followed by helium (He). The atmospheres of the terrestrial planets are mostly comprised of carbon dioxide (CO2) followed by nitrogen (N2) for Venus and Mars, and for Earth, mostly Nitrogen (N2) followed by read more..

  • Page - 56

    28 Chapter 1 Introduction 20.  4 years: 0 10,000 1 12,000 2 14,400 3 17,280 4 20,736 21.  Is the number of minutes at most 300? a.  If so, the answer is $29.95 × 1.125 = $33.70. b.  If not, 1. Compute the difference: (number of minutes) – 300. 2. Multiply that difference by 0.45. 3. Add $29.95. 4. Multiply the total by 1.125. That is the answer. 22.  read more..

  • Page - 57

    2 Chapter 29 Fundamental d ata t ypes to be able to define and initialize variables and constants to understand the properties and limitations of integer and floating-point numbers to write arithmetic expressions and assignment statements in C++ to appreciate the importance of comments and good code layout to create programs that read and process input, and display the read more..

  • Page - 58

    30 numbers and character strings (such as the ones on this display board) are important data types in any C++ program. In this chapter, you will learn how to work with numbers and text, and how to write simple programs that perform useful tasks with them. 2.1 Variables When your program carries out computations, you will want to store values so that you can use them read more..

  • Page - 59

    2.1 Variables 31 syntax 2.1 Variable definition int cans_per_pack = 6; A variable definition ends with a semicolon. Types introduced in this chapter are the number types int and double (page 32) and the string type (page 57). Supplying an initial value is optional, but it is usually a good idea. See page 37. See page 33 for rules and examples of read more..

  • Page - 60

    32 Chapter 2 Fundamental data types When a fractional part is required (such as in the number 0.355), we use floating- point numbers. The most commonly used type for floating-point numbers in C++ is called double . (If you want to know the reason, read Special Topic 2.1 on page 38.) Here is the definition of a floating-point variable: double can_volume = 0.355; When read more..

  • Page - 61

    2.1 Variables 33 When a fractional part is required (such as in the number 0.355), we use floating- point numbers. The most commonly used type for floating-point numbers in C++ is called double . (If you want to know the reason, read Special Topic 2.1 on page 38.) Here is the definition of a floating-point variable: double can_volume = 0.355; When a value such as 6 read more..

  • Page - 62

    34 Chapter 2 Fundamental data types 2.1.4 the assignment statement You use the assignment statement to place a new value into a variable. Here is an example: cans_per_pack = 8; The left-hand side of an assignment statement consists of a variable. The right-hand side is an expression that has a value. That value is stored in the variable, overwriting its previous read more..

  • Page - 63

    2.1 Variables 35 2.1.5 Figure 1  executing the assignment total_volume = total_volume + 2 1 total_volume = total_volume + 2 2.13 2 total_volume = 4.13 4.13 total_volume + 2 Constants When a variable is defined with the reserved word const , its value can never change. Constants are com monly written using capital letters to distinguish them visually from regular variables: const read more..

  • Page - 64

    36 Chapter 2 Fundamental data types You use the // syntax for single-line comments. If you have a comment that spans multiple lines, enclose it between /* and */ delimiters. The compiler ignores these delimiters and everything in between. Here is a typical example, a long comment at the beginning of a program, to explain the program’s pur pose: /* This read more..

  • Page - 65

    2.1 Variables 37 3.  Define and initialize two variables, unit_price and quantity , to contain the unit price of a single bottle and the number of bottles purchased. Use reasonable initial values. 4.  Use the variables defined in Self Check 3 to display the total purchase price. 5.  Some drinks are sold in four-packs instead of six-packs. How would you change the read more..

  • Page - 66

    38 Chapter 2 Fundamental data types choose descriptive Variable names We could have saved ourselves a lot of typing by using shorter variable names, as in double cv = 0.355; Compare this definition with the one that we actually used, though. Which one is easier to read? There is no compar ison. Just reading can_volume is a lot less trouble than reading cv and read more..

  • Page - 67

    2.1 Variables 39 In addition to the int type, C++ has integer types short , long , and long long . For each integer type, there is an unsigned equivalent. For example, the short type typically has a range from –32,768 to 32,767, whereas unsigned short has a range from 0 to 65,535. These strange-looking limits are the result of the use of binary numbers read more..

  • Page - 68

    40 Chapter 2 Fundamental data types 2.2 arithmetic In the following sections, you will learn how to carry out arithmetic and mathemati- cal calculations in C++. 2.2.1 arithmetic operators C++ supports the same four basic arithmetic operations as a calculator—addition, subtraction, multi plication, and division—but it uses different symbols for multipli- cation and division. You read more..

  • Page - 69

    2.2 arithmetic 41 If you are interested in the remainder only, use the % operator: 7 % 4 is 3, the remainder of the integer division of 7 by 4. The % symbol has no analog in algebra. It was chosen because it looks similar to / , and the remainder operation is related to division. The operator is called modulus. (Some people call it modulo or mod.) It read more..

  • Page - 70

    42 Chapter 2 Fundamental data types Figure 2  analyzing an expression b * pow(1 + r / 100, n) r 100 r 1 + 100 r n     1 + 100 b r n ×+     1 100 To use the sqrt and pow functions, you must place the line #include <cmath> at the top of your program file. The header file <cmath> is a standard C++ header that read more..

  • Page - 71

    2.2 arithmetic 43 table 6 other mathematical Functions Function description sin(x) sine of x (x in radians) cos(x) cosine of x tan(x) tangent of x log10(x) decimallog () () > log, 10 0 xx abs(x) absolute value x Table 6 shows additional functions that are declared in the <cmath> header. Inputs and outputs are float ing-point numbers. 10.  A bank account earns read more..

  • Page - 72

    44 Chapter 2 Fundamental data types int s3; cin >> s1 >> s2 >> s3; double average = (s1 + s2 + s3) / 3; // Error cout << "Your average score is " << average << endl; What could be wrong with that? Of course, the average of s1 , s2 , and s3 is s1 s2 s3 ++ 3 Here, however, the / does not mean division in the mathematical read more..

  • Page - 73

    2.2 arithmetic 45 Forgetting header Files Every program that carries out input or output needs the <iostream> header. If you use mathemat- ical functions such as sqrt , you need to include <cmath> . If you forget to include the appropriate header file, the compiler will not know sym bols such as cout or sqrt . If the compiler complains about an undefined read more..

  • Page - 74

    46 Chapter 2 Fundamental data types int main() { double price = 4.35; int cents = 100 * price; // Should be 100 * 4.35 = 435 cout << cents << endl; // Prints 434 ! return 0; } Of course, one hundred times 4 .35 is 435, but the program prints 434 . Most computers represent numbers in the binary system. In the binary system, read more..

  • Page - 75

    2.2 arithmetic 47 combining assignment and arithmetic In C++, you can combine arithmetic and assignment. For example, the instruction total += cans * CAN_VOLUME; is a shortcut for total = total + cans * CAN_VOLUME; Similarly, total *= 2; is another way of writing total = total * 2; Many programmers find this a convenient shortcut. If you like it, go ahead and use it in read more..

  • Page - 76

    48 Chapter 2 Fundamental data types 2.3 Input and output 2.3.1 Input In this section, you will see how to place user input into a variable. Consider for example the volume1.cpp program on page 36. Rather than assuming that the price for the two-liter bottle and the six-pack of cans are identical, we can ask the program user for the prices. When a program asks read more..

  • Page - 77

    2.3 Input and output 49 2.3.2 Formatted output When you print the result of a computation, you often want some control over its appearance. For exam ple, when you print an amount in dollars and cents, you usually want it to be rounded to two significant digits. That is, you want the output to look like Price per ounce: 0.04 instead of Price per ounce: 0.0409722 The read more..

  • Page - 78

    50 Chapter 2 Fundamental data types This command prints the value price_per_ounce in a field of width 8, for example 0 . 0 4 (where each represents a space). There is a notable difference between the setprecision and setw manipulators. Once you set the preci sion, that value is used for all floating-point numbers. But the width affects only the next value. read more..

  • Page - 79

    2.3 Input and output 51 15.  table 7 Formatting output output statement output Comment cout << 12.345678; 12.3457 By default, a number is printed with 6 significant digits. cout << fixed << setprecision(2) << 12.3; 12.30 Use the fixed and setprecision manipulators to control the number of digits after the decimal point. cout << read more..

  • Page - 80

    52 Chapter 2 Fundamental data types 2.4 problem solving: First do It By hand A very important step for developing an algorithm is to first carry out the computa- tions by hand. If you can’t compute a solution yourself, it’s unlikely that you’ll be able to write a program that automates the computation. To illustrate the use of hand calculations, consider the read more..

  • Page - 81

    2.4 problem solving: First do It By hand 53 20.  Translate the pseudocode for computing the number of tiles and the gap width into C++. 21.  Suppose the architect specifies a pattern with black, gray, and white tiles, like this: Again, the first and last tile should be black. How do you need to modify the algorithm? 22.  A robot needs to tile a floor with read more..

  • Page - 82

    54 Chapter 2 Fundamental data types step 1  Understand the problem: What are the inputs? What are the desired outputs? In this problem, there are two inputs: • The denomination of the bill that the customer inserts • The price of the purchased item There are two desired outputs: • The number of dollar coins that the machine returns • The number of quarters read more..

  • Page - 83

    2.4 problem solving: First do It By hand 55 step 1  Understand the problem: What are the inputs? What are the desired outputs? In this problem, there are two inputs: • The denomination of the bill that the customer inserts • The price of the purchased item There are two desired outputs: • The number of dollar coins that the machine returns • The number of read more..

  • Page - 84

    56 Chapter 2 Fundamental data types Here is the complete program, ch02/vending.cpp : #include <iostream> #include <iomanip> using namespace std; int main() { const int PENNIES_PER_DOLLAR = 100; const int PENNIES_PER_QUARTER = 25; cout << "Enter bill value (1 = $1 bill, 5 = $5 bill, etc.): "; int bill_value; cin >> bill_value; read more..

  • Page - 85

    2.5 strings 57 Here is the complete program, ch02/vending.cpp : #include <iostream> #include <iomanip> using namespace std; int main() { const int PENNIES_PER_DOLLAR = 100; const int PENNIES_PER_QUARTER = 25; cout << "Enter bill value (1 = $1 bill, 5 = $5 bill, etc.): "; int bill_value; cin >> bill_value; cout << read more..

  • Page - 86

    58 Chapter 2 Fundamental data types When a string is read with the >> operator, only one word is placed into the string variable. For example, suppose the user types Harry Morgan as the response to the prompt. This input consists of two words. After the call cin >> name , the string "Harry" is placed into the variable name . Use another input read more..

  • Page - 87

    2.5 strings 59 If you omit the length, you get all characters from the given position to the end of the string. For exam ple, greeting.substr(7) is the string "World!" (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. It then prints out your initials. read more..

  • Page - 88

    60 Chapter 2 Fundamental data types 25.  table 8 string operations statement result Comment string str = "C"; str = str + "++"; str is set to "C++" When applied to strings, + denotes concatenation. string str = "C" + "++"; error error: You cannot concatenate two string literals. cout << "Enter name: "; cin >> name; read more..

  • Page - 89

    2.5 strings 61 Hebrew, Arabic, and English the situation is much more dra matic in languages that use the Chi nese script: the Chinese dialects, Japanese, and korean. the Chinese script is not alphabetic but ideo- graphic. a character represents an idea or thing. most words are made up of one, two, or three of these ideo graphic characters. (over 50,000 ideo graphs are read more..

  • Page - 90

    62 Chapter 2 Fundamental data types Write variable definitions in c++. • A variable is a storage location with a name. • When defining a variable, you usually specify an initial value. • When defining a variable, you also specify the type of its values. • Use the int type for numbers that cannot have a fractional part. • Use the double type for read more..

  • Page - 91

    review exercises 63 • A member function is invoked using the dot notation. • Use the substr member function to extract a substring of a string r2.1  What is the value of mystery after this sequence of statements? int mystery = 1; mystery = 1 - 2 * mystery; mystery = mystery + 1; r2.2  What is wrong with the following sequence of statements? int mystery = 1; read more..

  • Page - 92

    64 Chapter 2 Fundamental data types a. s.length() + t.length() b. s.substr(1, 2) c. s.substr(s.length() / 2, 1) d. s + t e. t + s r2.7  Find at least five compile-time errors in the following program. #include iostream int main(); { cout << "Please enter two numbers:" cin << x, y; cout << "The sum of << x << "and" read more..

  • Page - 93

    review exercises 65 r2.13  Write pseudocode for a program that computes the first and last digit of a number. For example, if the input is 23456 , the program should print out 2 and 6 . Hint: % , log10 . r2.14  Modify the pseudocode for the program in How To 2.1 so that the pro gram gives change in quarters, dimes, and nickels. You can assume that the price read more..

  • Page - 94

    66 Chapter 2 Fundamental data types r2.19  Run the following program, and explain the output you get. #include <iostream> using namespace std; int main() { int total; cout << "Please enter a number: "; double x1; cin >> x1; total = total + x1; cout << "total: " << total << endl; cout << read more..

  • Page - 95

    programming exercises 67 • The product • The average p2.5  Write a program that prompts the user for two integers and then prints • The distance (absolute value of the difference) • The maximum (the larger of the two) • The minimum (the smaller of the two) Hint: The max and min functions are defined in the <algorithm> header. p2.6  Write a program that read more..

  • Page - 96

    68 Chapter 2 Fundamental data types p2.12  The following pseudocode describes how to turn a string containing a ten-digit phone number (such as "4155551212" ) into a more readable string with parentheses and dashes, like this: "(415) 555-1212" . Take the substring consisting of the first three characters and surround it with "(" and ")". This is read more..

  • Page - 97

    programming exercises 69 p2.19  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 cout << "+--+--+--+"; You should do it the smart way, though. Define string variables to hold read more..

  • Page - 98

    70 Chapter 2 Fundamental data types p2.23  Write a program that transforms numbers 1 , 2 , 3 , …, 12 into the corresponding month names January , February , March , …, December . Hint: Make a very long string "January February March ..." , in which you add spaces such that each month name has the same length. Then use substr to extract the month read more..

  • Page - 99

    programming exercises 71 where R is the resistance (in Ω) at the temperature T (in °K), and R 0 is the resistance (in Ω) at the temperature T 0 (in °K). β is a constant that depends on the material used to make the thermistor. Thermistors are specified by providing values for R0, T0, and β. The thermistors used to make the pipe clip temperature sensors have R0 = read more..

  • Page - 100

    72 Chapter 2 Fundamental data types then prints a message giving the corresponding value of Vs, using the values for P, R, and Vt shown in the figure above. engineering p2.28  Consider the following tuning circuit connected to an antenna, where C is a variable capacitor whose capacitance ranges from Cmin to Cmax. LC Antenna The tuning circuit selects the frequency read more..

  • Page - 101

    answers to self-Check Questions 73 1.  One possible answer is int bottles_per_case = 8; You may choose a different variable name or a different initialization value, but your variable should have type int . 2.  There are three errors: •  You cannot have spaces in variable names. •  The variable type should be double because it holds a fractional value. •  There is a read more..

  • Page - 102

    74 Chapter 2 Fundamental data types 20.  int pairs = (total_width - tile_width) / (2 * tile_width); int tiles = 1 + 2 * pairs; double gap = (total_width - tiles * tile_width) / 2; Be sure that pairs is declared as an int . 21.  Now there are groups of four tiles (gray/white/gray/black) following the initial black tile. Therefore, the algorithm is now number read more..

  • Page - 103

    3 Chapter 75 De C isions to be able to implement decisions using if statements to learn how to compare integers, floating-point numbers, and strings to understand the Boolean data type to develop strategies for validating user input Chapter Goals Chapter Contents 3.1  The if STaTemenT  76 Syntax 3.1: if statement 78 Programming Tip 3.1: Brace layout 79 Programming Tip read more..

  • Page - 104

    76 one of the essential features of computer programs is their ability to make decisions. like a train that changes tracks depending on how the switches are set, a program can take different actions, depending on inputs and other circumstances. in this chapter, you will learn how to program simple and complex decisions. You will apply what you learn to the task of read more..

  • Page - 105

    3.1 the if statement 77 figure 1  Flowchart for if statement floor > 13 ? True False actual_floor = floor - 1 actual_floor = floor Condition figure 2  Flowchart for if statement with no else Branch floor > 13 ? True False actual_floor-- No else branch there is nothing to do in the else branch of the statement. In that case, you can omit it entirely, such as read more..

  • Page - 106

    78 Chapter 3 Decisions 1.  In some Asian countries, the number 14 is considered unlucky. Some building owners play it safe and skip both the thirteenth and the fourteenth floor. How would you modify the sample program to handle such a building? 2.  Consider the following if statement to compute a discounted price: if (original_price > 100) { discounted_price read more..

  • Page - 107

    3.1 the if statement 79 1.  In some Asian countries, the number 14 is considered unlucky. Some building owners play it safe and skip both the thirteenth and the fourteenth floor. How would you modify the sample program to handle such a building? 2.  Consider the following if statement to compute a discounted price: if (original_price > 100) { discounted_price read more..

  • Page - 108

    80 Chapter 3 Decisions Tabs Block-structured code has the property that nested statements are indented by one or more levels: int main() { | int floor; | ... | if (floor > 13) | { | | floor--; | } | | ... | return 0; } | | 0 1 2 Indentation level How do you move the cursor from the leftmost column to read more..

  • Page - 109

    3.1 the if statement 81 Tabs Block-structured code has the property that nested statements are indented by one or more levels: int main() { | int floor; | ... | if (floor > 13) | { | | floor--; | } | | ... | return 0; } | | 0 1 2 Indentation level How do you move the cursor from the leftmost column to read more..

  • Page - 110

    82 Chapter 3 Decisions avoid duplication in branches Look to see whether you duplicate code in each branch. If so, move it out of the if statement. Here is an example of such duplication: if (floor > 13) { actual_floor = floor - 1; cout << "Actual floor: " << actual_floor << endl; } else { actual_floor = floor; cout << read more..

  • Page - 111

    3.2 Comparing numbers and strings 83 table 1 relational operators C++ Math notation Description > > Greater than >= ≥ Greater than or equal < < Less than <= ≤ Less than or equal == = Equal != ≠ Not equal The == operator denotes equality testing: floor = 13; // Assign 13 to floor if (floor == 13) // Test whether floor equals read more..

  • Page - 112

    84 Chapter 3 Decisions 10.  How do you test that a string str is not the empty string? practice it  Now you can try these exercises at the end of the chapter: R3.2, R3.5, P3.14. Confusing = and == The rule for the correct usage of = and == is very simple: In tests, always use == and never use = . If it is so simple, why can’t the compiler be read more..

  • Page - 113

    3.2 Comparing numbers and strings 85 10.  How do you test that a string str is not the empty string? practice it  Now you can try these exercises at the end of the chapter: R3.2, R3.5, P3.14. Confusing = and == The rule for the correct usage of = and == is very simple: In tests, always use == and never use = . If it is so simple, why can’t the read more..

  • Page - 114

    86 Chapter 3 Decisions • The space character comes before all printable characters. • Numbers come before letters. • For the ordering of punctuation marks, see Appendix D. When comparing two strings, you compare the first letters of each word, then the sec ond letters, and so on, until one of the strings ends or you find the first letter pair that doesn’t read more..

  • Page - 115

    3.2 Comparing numbers and strings 87 • The space character comes before all printable characters. • Numbers come before letters. • For the ordering of punctuation marks, see Appendix D. When comparing two strings, you compare the first letters of each word, then the sec ond letters, and so on, until one of the strings ends or you find the first letter pair that read more..

  • Page - 116

    88 Chapter 3 Decisions and fill it in, as shown in Syntax 3.1 on page 78. Omit the else branch if it is not needed. In our example, the completed statement is if (original_price < 128) { discount_rate = 0.92; } else { discount_rate = 0.84; } discounted_price = discount_rate * original_price; WorkeD exaMple 3.1 extracting the middle This Worked Example read more..

  • Page - 117

    3.2 Comparing numbers and strings 89 and fill it in, as shown in Syntax 3.1 on page 78. Omit the else branch if it is not needed. In our example, the completed statement is if (original_price < 128) { discount_rate = 0.92; } else { discount_rate = 0.84; } discounted_price = discount_rate * original_price; WorkeD exaMple 3.1 extracting the middle This Worked read more..

  • Page - 118

    90 Chapter 3 Decisions 3.3 Multiple alternatives In Section 3.1, you saw how to program a two-way branch with an if statement. In many situations, there are more than two cases. In this section, you will see how to implement a decision with multiple alterna tives. For example, consider a program that displays the effect of an earthquake, as measured by the Rich read more..

  • Page - 119

    3.3 Multiple alternatives 91 figure 3  Multiple alternatives richter ≥ 8.0? richter ≥ 7.0? richter ≥ 6.0? richter ≥ 4.5? No destruction of buildings False False False False True True True True Most structures fall Many buildings destroyed Many buildings considerably damaged, some collapse Damage to poorly constructed buildings Here you must sort the conditions and test read more..

  • Page - 120

    92 Chapter 3 Decisions The switch Statement A sequence of if statements that compares a single integer value against several constant alter- natives can be imple mented as a switch statement. For example, int digit; ... switch (digit) { case 1: digit_name = "one"; break; case 2: digit_name = "two"; break; case 3: digit_name = read more..

  • Page - 121

    3.3 Multiple alternatives 93 The switch Statement A sequence of if statements that compares a single integer value against several constant alter- natives can be imple mented as a switch statement. For example, int digit; ... switch (digit) { case 1: digit_name = "one"; break; case 2: digit_name = "two"; break; case 3: digit_name = read more..

  • Page - 122

    94 Chapter 3 Decisions 3.4 nested Branches It is often necessary to include an if statement inside another. Such an arrangement is called a nested set of statements. Here is a typical example. In the United States, different tax rates are used depending on the taxpayer’s mari- tal status. There are different tax sched ules for single and for married taxpayers. Mar- read more..

  • Page - 123

    3.4 nested Branches 95 figure 4  income tax Computation 10% bracket 25% bracket Single income ≤ 32,000 10% bracket 25% bracket income ≤ 64,000 False True True False True False In theory, nesting can go deeper than two levels. A three-level decision process (first by state, then by filing status, then by income level) requires three nesting levels. ch03/tax.cpp 1 #include read more..

  • Page - 124

    96 Chapter 3 Decisions hand-Tracing A very useful technique for understanding whether a program works correctly is called hand-tracing. You simulate the pro- gram’s activity on a sheet of paper. You can use this method with pseudocode or C++ code. Get an index card, a cocktail napkin, or whatever sheet of paper is within reach. Make a column for each variable. Have read more..

  • Page - 125

    3.4 nested Branches 97 hand-Tracing A very useful technique for understanding whether a program works correctly is called hand-tracing. You simulate the pro- gram’s activity on a sheet of paper. You can use this method with pseudocode or C++ code. Get an index card, a cocktail napkin, or whatever sheet of paper is within reach. Make a column for each variable. Have the read more..

  • Page - 126

    98 Chapter 3 Decisions 3.5 problem solving: Flowcharts You have seen examples of flowcharts earlier in this chapter. A flowchart shows the structure of decisions and tasks that are required to solve a problem. When you have to solve a complex problem, it is a good idea to draw a flowchart to visualize the flow of control. The basic flowchart elements are shown in read more..

  • Page - 127

    3.5 problem solving: Flowcharts 99 3.5 problem solving: Flowcharts You have seen examples of flowcharts earlier in this chapter. A flowchart shows the structure of decisions and tasks that are required to solve a problem. When you have to solve a complex problem, it is a good idea to draw a flowchart to visualize the flow of control. The basic flowchart elements are read more..

  • Page - 128

    100 Chapter 3 Decisions There is one issue that you need to be aware of when drawing flow charts. Unconstrained branching and merging can lead to “spaghetti code”, a messy net- work of possible pathways through a program. There is a simple rule for avoiding spaghetti code: Never point an arrow inside another branch. To understand the rule, consider this example: read more..

  • Page - 129

    3.5 problem solving: Flowcharts 101 Don’t do that! The red arrow points inside a different branch. Instead, add another task that sets the ship ping cost to $10, like this: False True Shipping cost = $10 Inside US? True False Continental US? Shipping cost = $10 Shipping cost = $5 Not only do you avoid spaghetti code, but it is also a better design. In the future it read more..

  • Page - 130

    102 Chapter 3 Decisions make a Schedule and make Time for unexpected problems Commercial software is notorious for being delivered later than promised. For example, Microsoft originally prom ised that its Windows Vista operating system would be available late in 2003, then in 2005, then in March 2006; it finally was released in January 2007. Some of the early promises read more..

  • Page - 131

    3.7 Boolean Variables and operators 103 make a Schedule and make Time for unexpected problems Commercial software is notorious for being delivered later than promised. For example, Microsoft originally prom ised that its Windows Vista operating system would be available late in 2003, then in 2005, then in March 2006; it finally was released in January 2007. Some of the read more..

  • Page - 132

    104 Chapter 3 Decisions Conversely, let’s test whether water is not liquid at a given temperature. That is the case when the tem perature is at most 0 or at least 100. Use the || (or) operator to combine the expressions: if (temp <= 0 || temp >= 100) { cout << "Not liquid"; } Figure 9 shows flowcharts for these examples. Sometimes you need to read more..

  • Page - 133

    3.7 Boolean Variables and operators 105 table 5 selected operators and their precedence operator Description ++ -- + (unary) – (unary) ! Increment, decrement, positive, negative, Boolean not * / % Multiplication, division, remainder + - Addition, subtraction < <= > >= Comparisons == != Equal, not equal && Boolean and || Boolean or Conversely, let’s test whether read more..

  • Page - 134

    106 Chapter 3 Decisions Combining multiple relational operators Consider the expression if (0 <= temp <= 100) // Error This looks just like the mathematical test 0 ≤ temp ≤ 100. Unfortunately, it is not. Let us dissect the expression 0 <= temp <= 100 . The first half, 0 <= temp , is a test with out- come true or false , depending on the value of read more..

  • Page - 135

    3.7 Boolean Variables and operators 107 Combining multiple relational operators Consider the expression if (0 <= temp <= 100) // Error This looks just like the mathematical test 0 ≤ temp ≤ 100. Unfortunately, it is not. Let us dissect the expression 0 <= temp <= 100 . The first half, 0 <= temp , is a test with out- come true or false , depending on read more..

  • Page - 136

    108 Chapter 3 Decisions Short-Circuit evaluation of boolean operators When the && and || operators are computed, evaluation stops as soon as the truth value is determined. When an && is evaluated and the first condition is false, the second condition is not evaluated, because it does not matter what the outcome of the second test is. For example, read more..

  • Page - 137

    3.8 application: input Validation 109 That is, of course, the same as state != "AK" && state != "HI" Now apply the law to our shipping charge computation: !(country == "USA" && state != "AK" && state != "HI") is equivalent to !(country == "USA") || !(state != "AK") || !(state != read more..

  • Page - 138

    110 Chapter 3 Decisions Here is how you ensure that the user doesn’t enter a number outside the valid range: if (floor <= 0 || floor > 20) { cout << "Error: The floor must be between 1 and 20." << endl; return 1; } However, dealing with an input that is not a valid integer is a more serious problem. When the statement cin >> read more..

  • Page - 139

    3.8 application: input Validation 111 26 } 27 28 // Now we know that the input is valid 29 int actual_floor; 30 if (floor > 13) 31 { 32 actual_floor = floor - 1; 33 } 34 else 35 { 36 actual_floor = floor; 37 } 38 39 cout << "The read more..

  • Page - 140

    112 Chapter 3 Decisions use the if statement to implement a decision. • The if statement allows a program to carry out dif ferent actions depending on the nature of the data to be processed. implement comparisons of numbers and objects. • Relational operators (< <= > >= == != ) are used to compare numbers and strings. • Lexicographic order is used to read more..

  • Page - 141

    Chapter summary 113 use the if statement to implement a decision. • The if statement allows a program to carry out dif ferent actions depending on the nature of the data to be processed. implement comparisons of numbers and objects. • Relational operators (< <= > >= == != ) are used to compare numbers and strings. • Lexicographic order is used to compare read more..

  • Page - 142

    114 Chapter 3 Decisions implement decisions whose branches require further decisions. • When a decision statement is contained inside the branch of another decision statement, the statements are nested. • Nested decisions are required for problems that have two levels of decision mak ing. draw flowcharts for visualizing the control flow of a program. • Flow charts are made read more..

  • Page - 143

    review exercises 115 c. double x = 0; double y = 1; if (fabs(x - y) < 1) { cout << x; } else { cout << y; } d. double x = sqrt(2); double y = 2; if (x * x == y) { cout << x; } else { cout << y; } r3.3  Suppose x and y are variables of type double . Write a code fragment that sets y to x if x is positive and to 0 otherwise. read more..

  • Page - 144

    116 Chapter 3 Decisions r3.9  In a scheduling program, we want to check whether two appointments overlap. For simplicity, appointments start at a full hour, and we use military time (with hours 0–23). The following pseudocode describes an algorithm that determines whether the appointment with start time start1 and end time end1 overlaps with the appoint- ment with read more..

  • Page - 145

    review exercises 117 d. "car manufacturer", "carburetor" e. "Harry", "hairy" f.  "C++", " Car" g. "Tom", "Tom" h. "Car", "Carl" i.  "car", "bar" r3.19  Explain the difference between a sequence of else if clauses and nested if state- ments. Give an example for each. r3.20  Give an example of read more..

  • Page - 146

    118 Chapter 3 Decisions r3.28  Simplify the following expressions. Here, b is a variable of type bool . a. b == true b. b == false c. b != true d. b != false r3.29  Simplify the following statements. Here, b is a variable of type bool and n is a vari able of type int . a. if (n == 0) { b = true; } else { b = false; } (Hint: What is read more..

  • Page - 147

    programming exercises 119 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. p3.3  Write a program that reads in three floating-point numbers and prints the largest of the three inputs. For example: Please read more..

  • Page - 148

    120 Chapter 3 Decisions Your program should print the full description of the card. For example, Enter the card notation: QS Queen of Spades p3.12  When two points in time are compared, each given as hours (in military time, rang ing from 0 and 23) and minutes, the following pseudocode determines which comes first. If hour1 < hour2 time1 comes first. Else if hour1 read more..

  • Page - 149

    programming exercises 121 p3.16  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. Any overtime work (over 40 hours per week) is paid at 150 percent of the regular wage. Compute the pay. Print read more..

  • Page - 150

    122 Chapter 3 Decisions p3.21  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: read more..

  • Page - 151

    programming exercises 123 p3.24  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 Do not use a separate if/else branch for each month. Use Boolean operators. p3.25  A year with 366 days is called a read more..

  • Page - 152

    124 Chapter 3 Decisions Your task is to simulate a portion of the control software for the vehicle. The input is a sequence of values for the switches and the gear shift, in the following order: • Dashboard switches for left and right sliding door, child lock, and master unlock (0 for off or 1 for activated) • Inside and outside handles on the left and read more..

  • Page - 153

    programming exercises 125 Suppose the voltmeter voltage is constrained to the range Vmin = 12 volts ≤ Vm ≤ Vmax = 18 volts. Write a program that accepts a value of Vm and checks that it’s between 12 and 18. The program should return the gas temperature in degrees Celsius when Vm is between 12 and 18 and an error message when it isn’t. read more..

  • Page - 154

    126 Chapter 3 Decisions engineering p3.36  The average person can jump off the ground with a velocity of 7 mph without fear of leaving the planet. However, if an astronaut jumps with this velocity while standing on Halley’s Comet, will the astronaut ever come back down? Create a program that allows the user to input a launch velocity (in mph) from the surface of read more..

  • Page - 155

    answers to self-Check Questions 127 } else { cout << "Game tied"; } 12.  if (x > 0) { s = 1; } else if (x < 0) { s = -1; } else { s = 0; } 13.  You could first set s to one of the three values: s = 0; if (x > 0) { s = 1; } else if (x < 0) { s = -1; } 14.  The if (price <= 100) can be read more..

  • Page - 156

    128 Chapter 3 Decisions 23.  The “True” arrow from the first decision points into the “True” branch of the sec- ond decision, creating spaghetti code. 24.  Here is one solution. In Section 3.7, you will see how you can combine the condi- tions for a more elegant solution. True False Input < 0? Status = “Error” True False Input > 100? Status = “OK” Status = read more..

  • Page - 157

    answers to self-Check Questions 129 26.  27.  Test Case Expected Output Comment 12 12 Below 13th floor 14 13 Above 13th floor 13 ? The specification is not clear— See Section 3.8 for a version of this program with error handling 28.  A boundary test case is a price of $128. A 16 percent discount should apply because the problem statement states that the larger discount read more..

  • Page - 158

    130 Chapter 3 Decisions Step 1  Decide on 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 read more..

  • Page - 159

    4 Chapter 131 Loops to implement while, for, and do loops 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 Chapter Goa L s Chapter Contents 4.1  The while loop  132 Syntax 4.1: while statement 133 Common Error 4.1: Infinite Loops 136 Common Error 4.2: Don’t read more..

  • Page - 160

    132 In a loop, a part of a program is repeated over and over, until a specific goal is reached. Loops are important for calculations that require repeated steps and for processing input consisting of many data items. In this chapter you will learn about loop statements in C++, as well as techniques for writing programs that process input and simulate activities in the read more..

  • Page - 161

    4.1 the while Loop 133 figure 1  Flowchart of a while Loop False True Add interest to balance Increment year balance< TARGET ? In C++, the while statement implements such a repetition (see Syntax 4.1). The code while ( condition) { statements } keeps executing the statements while the condition is true. In our case, we want to increment the year counter and add read more..

  • Page - 162

    134 Chapter 4 Loops When you define a variable inside the loop body, the variable is created for each iteration of the loop and removed after the end of each iteration. For example, con- sider the interest variable in this loop: while (balance < TARGET) { year++; double interest = balance * RATE / 100; balance = balance + interest; } // read more..

  • Page - 163

    4.1 the while Loop 135 Here is the program that solves the investment problem. Figure 2 illustrates the program’s execution. ch04/doublinv.cpp 1 #include <iostream> 2 3 using namespace std; 4 5 int main() 6 { 7 const double RATE = 5; 8 const double INITIAL_BALANCE = 10000; 9 const double TARGET = 2 * INITIAL_BALANCE; 10 read more..

  • Page - 164

    136 Chapter 4 Loops table 1 while Loop examples Loop output explanation i = 5; while (i > 0) { cout << i << " "; i--; } 5 4 3 2 1 When i is 0, the loop condition is false, and the loop ends. i = 5; while (i > 0) { cout << i << " "; i++; } 5 6 7 8 9 10 11 ... The i++ statement is read more..

  • Page - 165

    4.1 the while Loop 137 balance = balance * (1 + RATE / 100); } Here the programmer forgot to add a year++ command in the loop. As a result, the year always stays at 1, and the loop never comes to an end. Another common reason for an infinite loop is accidentally incrementing a counter that should be decremented (or vice versa). Consider this example: read more..

  • Page - 166

    138 Chapter 4 Loops Should year start at 0 or at 1? Should you test for balance < TARGET or for balance <= TARGET ? It is easy to be off by one in these expressions. Some people try to solve off-by-one errors by randomly inserting +1 or -1 until the pro- gram seems to work—a terrible strategy. It can take a long time to compile and test all read more..

  • Page - 167

    4.2 problem solving: hand-tracing 139 4.2 problem solving: hand-tracing In Programming Tip 3.6, you learned about the method of hand-tracing. When you hand-trace code or pseudocode, you write the names of the variables on a sheet of paper, mentally execute each step of the code and update the variables. It is best to have the code written or printed on a sheet of read more..

  • Page - 168

    140 Chapter 4 Loops Finally, n becomes 172. (Recall that the remainder in the division 1729 / 10 is dis- carded because both argu ments are integers.) Cross out the old values and write the new ones under the old ones. int n = 1729; int sum = 0; while (n > 0) { int digit = n % 10; sum = sum + digit; n = n / 10; } cout << read more..

  • Page - 169

    4.2 problem solving: hand-tracing 141 int n = 1729; int sum = 0; while (n > 0) Because n equals zero, this condition is not true. { int digit = n % 10; sum = sum + digit; n = n / 10; } cout << sum << endl; The condition n > 0 is now false. Continue with the statement after the loop. int n = 1729; int sum = 0; while read more..

  • Page - 170

    142 Chapter 4 Loops 7.  Hand-trace the following code, showing the value of n and the output. What potential error do you notice? int n = 1; while (n <= 3) { cout << n << ", "; n++; } 8.  Hand-trace the following code, assuming that a is 2 and n is 4. Then explain what the code does for arbitrary values of a and n. int read more..

  • Page - 171

    4.3 the for Loop 143 for (counter = 1; counter <= 10; counter++) { cout << counter << endl; } Some people call this loop count-controlled. In contrast, the while loop of the preceding section can be called an event-controlled loop because it executes until an event occurs (for example, when the balance reaches the target). Another commonly-used term for a read more..

  • Page - 172

    144 Chapter 4 Loops syntax 4.2 for statement for (int i = 5; i <= 10; i++) { sum = sum + i; } This loop executes 6 times. See page 147. These three expressions should be related. See page 147. This initialization happens once before the loop starts. The loop is executed while this condition is true. This update read more..

  • Page - 173

    4.3 the for Loop 145 for (int year = 1; year <= nyears; year++) { Update balance. Print year and balance. } Here is the complete program. Figure 4 shows the corresponding flowchart. figure 4  Flowchart of a for Loop ch04/invtable.cpp 1 #include <iostream> 2 #include <iomanip> 3 4 using namespace std; 5 6 int main() 7 { 8 const double read more..

  • Page - 174

    146 Chapter 4 Loops program run Enter number of years: 10 1 10500.00 2 11025.00 3 11576.25 4 12155.06 5 12762.82 6 13400.96 7 14071.00 8 14774.55 9 15513.28 10 16288.95 11.  Write the for loop of the invtable.cpp program as a while loop. table 2 for Loop examples Loop Values read more..

  • Page - 175

    4.3 the for Loop 147 use for loops for Their intended purpose only A for loop is an idiom for a loop of a particular form. A value runs from the start to the end, with a constant incre ment or decrement. The compiler won’t check whether the initialization, condition, and update expressions are related. For example, the following loop is legal: // read more..

  • Page - 176

    148 Chapter 4 Loops For example, for (int i = 0; i <= 10; i++) runs 11 times. Maybe that is what you want; if not, start at 1 or use < 10 . One way to visualize this “+1” error is by looking at a fence. Each section has one fence post to the left, and there is a final post on the right of the last section. Forgetting to count the last value is often read more..

  • Page - 177

    4.4 the do Loop 149 figure 5  Flowchart of a do Loop 16.  Suppose that we want to check for inputs that are at least 0 and at most 100. Modify the do loop for this check. 17.  Rewrite the input check, using a while loop. What is the disadvantage of your solution? 18.  Suppose C++ didn’t have a do loop. Could you rewrite any do loop as a while read more..

  • Page - 178

    150 Chapter 4 Loops 4.5 processing Input In this section, you will learn how to read and pro- cess a sequence of input values. Whenever you read a sequence of inputs, you need to have some method of indicating the end of the sequence. Sometimes you are lucky and no input value can be zero. Then you can prompt the user to keep entering numbers, or 0 to read more..

  • Page - 179

    4.5 processing Input 151 The following program reads inputs until the user enters the sentinel, and then com- putes and prints the average. ch04/sentinel.cpp 1 #include <iostream> 2 3 using namespace std; 4 5 int main() 6 { 7 double sum = 0; 8 int count = 0; 9 double salary = 0; 10 cout << "Enter read more..

  • Page - 180

    152 Chapter 4 Loops We now encounter an additional complexity. You only know that input failed after you have entered the loop and attempted to read it. To remember the failure, use a Boolean variable: cout << "Enter values, Q to quit: "; bool more = true; while (more) { cin >> value; if (cin.fail()) { more = false; } read more..

  • Page - 181

    4.5 processing Input 153 practice it  Now you can try these exercises at the end of the chapter: R4.10, P4.6, P4.7. clearing the failure State When an input operation has failed, all further input operations also fail. If you want to read two number sequences and use a letter as a sentinel, you need to clear the failure state after reading the first sentinel. Call read more..

  • Page - 182

    154 Chapter 4 Loops redirection of input and output Consider the sentinel program that computes the average value of an input sequence. If you use such a program, then it is quite likely that you already have the values in a file, and it seems a shame that you have to type them all in again. The command line interface of your operating system provides a way read more..

  • Page - 183

    4.6 problem solving: storyboards 155 figure 6  storyboard for the Design of a Web application What if there is more than one quantity? A user may have a whole table of centimeter values that should be converted into inches. What if the user enters units that our program doesn’t know how to handle, such as angstrom? What if the user asks for impossible read more..

  • Page - 184

    156 Chapter 4 Loops when the user enters a wrong unit? Let’s make another storyboard to demonstrate error handling. What unit do you want to convert from? cm What unit do you want to convert to? inches Sorry, unknown unit. What unit do you want to convert to? inch Sorry, unknown unit. What unit do you want to convert to? grrr Handling Unknown Units (needs read more..

  • Page - 185

    4.7 Common Loop algorithms 157 27.  Google has a simple interface for converting units. You just type the question, and you get the answer. Make storyboards for an equivalent interface in a C++ program. Show the “happy day” scenario in which all goes well, and show the handling of two kinds of errors. 28.  Consider a modification of the program in Self Check read more..

  • Page - 186

    158 Chapter 4 Loops To compute an average, count how many values you have, and divide by the count. Be sure to check that the count is not zero. double total = 0; int count = 0; double input; while (cin >> input) { total = total + input; count++; } double average = 0; if (count > 0) { average = total / count; } 4.7.2 Counting Matches You read more..

  • Page - 187

    4.7 Common Loop algorithms 159 4.7.3 Finding the First Match When you count the values that fulfill a con- dition, you need to look at all values. How- ever, if your task is to find a match, then you can stop as soon as the condition is fulfilled. Here is a loop that finds the first space in a string. Because we do not visit all elements in the string, read more..

  • Page - 188

    160 Chapter 4 Loops To find the height of the tallest bus rider, remember the largest value so far, and update it whenever you see a taller one. To compute the smallest value, simply reverse the comparison: double smallest; cin >> smallest; double input; while (cin >> input) { if (input < smallest) { smallest = input; } } 4.7.5 read more..

  • Page - 189

    4.7 Common Loop algorithms 161 When comparing adjacent values, store the previous value in a variable. One problem remains. When the loop is entered for the first time, previous has not yet been set. You can solve this problem with an initial input operation outside the loop: double input; double previous; cin >> previous; while (cin >> input) { if (input == read more..

  • Page - 190

    162 Chapter 4 Loops Step 1  Decide what work must be done inside the loop. Every loop needs to do some kind of repetitive work, such as • Reading another item. • Updating a value (such as a bank balance or total). • Incrementing a counter. If you can’t figure out what needs to go inside the loop, start by writing down the steps that you would take read more..

  • Page - 191

    4.7 Common Loop algorithms 163 Step 1  Decide what work must be done inside the loop. Every loop needs to do some kind of repetitive work, such as • Reading another item. • Updating a value (such as a bank balance or total). • Incrementing a counter. If you can’t figure out what needs to go inside the loop, start by writing down the steps that you would read more..

  • Page - 192

    164 Chapter 4 Loops Here is our complete loop: Read first value; store as highest value. highest month = 1 for (current month = 2; current month <= 12; current month++) Read next value. If value is higher than the highest value, set highest value to that value, highest month to current month. Step 6  Trace the loop with typical examples. Hand-trace your loop code, read more..

  • Page - 193

    4.8 nested Loops 165 Here is our complete loop: Read first value; store as highest value. highest month = 1 for (current month = 2; current month <= 12; current month++) Read next value. If value is higher than the highest value, set highest value to that value, highest month to current month. Step 6  Trace the loop with typical examples. Hand-trace your loop code, read more..

  • Page - 194

    166 Chapter 4 Loops There are 10 rows in the outer loop. For each x, the program prints four columns in the inner loop. Thus, a total of 10 × 4 = 40 values are printed. Following is the complete program. Note that we also use loops to print the table header. However, those loops are not nested. ch04/powtable.cpp 1 #include <iostream> 2 #include read more..

  • Page - 195

    4.8 nested Loops 167 program run 1 2 3 4 x x x x 1 1 1 1 2 4 8 16 read more..

  • Page - 196

    168 Chapter 4 Loops 38.  Why is there a statement cout << endl in the outer loop but not in the inner loop? 39.  How would you change the program so that all powers from x0 to x5 are displayed? 40.  If you make the change in Self Check 39, how many values are displayed? 41.  What do the following nested loops display? for (int i = 0; i < 3; read more..

  • Page - 197

    4.9 random numbers and simulations 169 5 6 int main() 7 { 8 for (int i = 1; i <= 10; i++) 9 { 10 int r = rand(); 11 cout << r << endl; 12 } 13 return 0; 14 } program run 1804289383 846930886 1681692777 1714636915 1957747793 424238335 719885386 1649760492 596516649 118964142 Actually, the read more..

  • Page - 198

    170 Chapter 4 Loops Here is a program that simulates the throw of a pair of dice. ch04/dice.cpp 1 #include <iostream> 2 #include <string> 3 #include <cstdlib> 4 #include <ctime> 5 6 using namespace std; 7 8 int main() 9 { 10 srand(time(0)); 11 12 for (int i = 1; i <= 10; i++) 13 { 14 read more..

  • Page - 199

    4.9 random numbers and simulations 171 If the generated point lies inside the circle, we count it as a hit. That is the case when x2 + y2 ≤ 1. Because our shots are entirely random, we expect that the ratio of hits ̸ tries is approximately equal to the ratio of the areas of the circle and the square, that is, p ̸ 4. Therefore, our estimate read more..

  • Page - 200

    172 Chapter 4 Loops 43.  How do you simulate a coin toss with the rand function? 44.  How do you simulate the picking of a random playing card? 45.  Why does the dice.cpp file include the <ctime> header? 46.  In many games, you throw a pair of dice to get a value between 2 and 12. What is wrong with this simulated throw of a pair of dice? int read more..

  • Page - 201

    Chapter summary 173 explain the flow of execution in a loop. • Loops execute a block of code repeatedly while a condition remains true. • An off-by-one error is a common error when programming loops. Think through simple test cases to avoid this type of error. use the technique of hand-tracing to analyze the behavior of a pro gram. • Hand-tracing is a simulation of read more..

  • Page - 202

    174 Chapter 4 Loops know the most common loop algorithms. • To compute an average, keep a total and a count of all values. • To count values that fulfill a condition, check all values and increment a counter for each match. • If your goal is to find a match, exit the loop when the match is found. • To find the largest value, update the largest value read more..

  • Page - 203

    review exercises 175 r4.5  Write a program trace for the pseudocode in Exercise P4.9, assuming the input val ues are 4 7 –2 –5 0. r4.6  Is the following code legal? for (int i = 0; i < 10; i++) { for (int i = 0; i < 10; i++) { cout << i << " "; } cout << endl; } What does it print? Is it good read more..

  • Page - 204

    176 Chapter 4 Loops r4.11  Rewrite the following for loop into a while loop. int s = 0; for (int i = 1; i <= 10; i++) { s = s + i; } r4.12  Rewrite the following do /while loop into a while loop. int n; cin >> n; double x = 0; double s; do { s = 1.0 / (1 + n * n); n++; x = x + s; } while (s > 0.01); read more..

  • Page - 205

    review exercises 177 } cout << s << " " << n; r4.15  What do the following program segments print? Find the answers by tracing the code, not by using the computer. a. int n = 1; for (int i = 2; i < 5; i++) { n = n + i; } cout << n; b. int i; double n = 1 / 2; for (i = 2; i <= 5; i++) { n = n + 1.0 / i; } cout read more..

  • Page - 206

    178 Chapter 4 Loops r4.23  The nested loops for (int i = 1; i <= height; i++) { for (int j = 1; j <= width; j++) { cout << "*"; } cout << endl; } display a rectangle of a given width and height, such as **** **** **** Write a single for loop that displays the same rectangle. r4.24  Suppose you design an educational game to teach read more..

  • Page - 207

    programming exercises 179 p4.4  Complete the program in How To 4.1 on page 162. Your program should read twelve temperature values and print the month with the highest temperature. p4.5  Credit Card Number Check. The last digit of a credit card number is the check digit, which protects against transcription errors such as an error in a single digit or switching two read more..

  • Page - 208

    180 Chapter 4 Loops p4.9  Translate the following pseudocode for finding the minimum value from a set of inputs into a C++ program. Set a Boolean variable "first" to true. While another value has been read successfully If first is true Set the minimum to the value. Set first to false. Else if the value is less than the minimum Set the minimum to read more..

  • Page - 209

    programming exercises 181 p4.15  Write a program that reads a word and prints all substrings, sorted by length. For example, if the user provides the input "rum" , the program prints r u m ru um rum p4.16  Write a program that reads a number and prints all of its binary digits: Print the remainder number % 2 , then replace the number with number / 2 . Keep read more..

  • Page - 210

    182 Chapter 4 Loops p4.19  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 2 3 5 5 p4.20  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 read more..

  • Page - 211

    programming exercises 183 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 read more..

  • Page - 212

    184 Chapter 4 Loops figure 9  a hit in the Buffon needle experiment 2 0 yhigh yy ylow yy α 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 read more..

  • Page - 213

    programming exercises 185 time interval the velocity v is nearly con stant, and we can compute the distance the ball moves as Δs = v Δt. In our program, we will simply set const double DELTA_T = 0.01; and update the position by s = s + v * DELTA_T; The velocity changes constantly—in fact, it is reduced by the gravitational force of the earth. In a short time interval, Δv = read more..

  • Page - 214

    186 Chapter 4 Loops (Note: There are two values of y for each x and z because the hull is symmetric from starboard to port.) The cross-sectional area at a point x is called the “section” in nautical parlance. To compute it, let z go from 0 to –T in n increments, each of size Tn. For each value of z, compute the value for y. Then sum read more..

  • Page - 215

    answers to self-Check Questions 187 Write a C++ program that models the circuit shown and varies the turns ratio from 0.01 to 2 in 0.01 increments, then determines the value of the turns ratio that maxi- mizes the power delivered to the speakers. 1.  23 years. 2.  7 years. 3.  Add a statement cout << balance << endl; as the last statement in the while loop. read more..

  • Page - 216

    188 Chapter 4 Loops This yields the correct answer. The number 123 has 3 digits. count n 1 100 2 10 This yields the wrong answer. The number 100 also has 3 digits. The loop condition should have been while (temp >= 10) 11.  int year = 1; while (year <= nyears) { balance = balance * (1 + RATE / 100); read more..

  • Page - 217

    answers to self-Check Questions 189 cin >> x; sum = sum + x; } while (x != 0); 20.  int x = 0; int previous; do { previous = x; cin >> x; sum = sum + x; } while (previous != x); 21.  No data 22.  The first check ends the loop after the sentinel has been read. The second check ensures that the sentinel is not read more..

  • Page - 218

    190 Chapter 4 Loops 28.  One score is not enough 29.  It would not be possible to implement this interface using the C++ features we have covered up to this point. There is no way for the program to know when the first set of inputs ends. (When you read numbers with cin >> value , it is your choice whether to put them on a single line or multiple read more..

  • Page - 219

    answers to self-Check Questions 191 39.  Change lines 14, 19, and 31 to for (int n = 0; n <= NMAX; n++) . Change NMAX to 5. 40.  60: The outer loop is executed 10 times, and the inner loop 6 times. 41.  0123 1234 2345 42.  for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 4; j++) { cout << "[]"; read more..

  • Page - 220

    This page intentionally left blank read more..

  • Page - 221

    5 Chapter 193 Fun C tions to be able to implement functions to become familiar with the concept of parameter passing to appreciate the importance of function comments to develop strategies for decomposing complex tasks into simpler ones to be able to determine the scope of a variable to recognize when to use value and reference parameters Chapter Goals Chapter Contents 5.1  read more..

  • Page - 222

    194 Functions are a fundamental building block of C++ programs. a function packages a computation into a form that can be easily understood and reused. (the person in the image to the left is executing the function “make two cups of espresso”.) in this chapter, you will learn how to design and implement your own functions. using the process of stepwise refinement, you read more..

  • Page - 223

    5.1 Functions as Black Boxes 195 Figure 2  the pow Function as a Black Box 2, 3 8 pow Inputs Output When another function calls the pow function, it provides “inputs”, such as the expressions 2 and 3 in the call pow(2, 3) . These expressions are called arguments. This terminology avoids confusion with other inputs, such as those pro vided by a human user. read more..

  • Page - 224

    196 Chapter 5 Functions 1.  Consider the function call pow(3, 2) . What are the arguments and return value? 2.  What is the return value of the function call pow(pow(2, 2), 2) ? 3.  The ceil function in the C++ standard library takes a single argument x and returns the smallest inte ger ≥ x. What is the return value of ceil(2.3) ? 4.  It is possible read more..

  • Page - 225

    5.2 implementing Functions 197 The return statement gives the function’s result to the caller. Let’s put this function to use. We’ll supply a main function that calls the cube_volume function twice. int main() { double result1 = cube_volume(2); double result2 = cube_volume(10); cout << "A cube with side length 2 has volume " << result1 << read more..

  • Page - 226

    198 Chapter 5 Functions Here is the com plete program. Note the comment that describes the behavior of the function. (Programming Tip 5.1 on page 199 describes the format of the comment.) ch05/cube.cpp 1 #include <iostream> 2 3 using namespace std; 4 5 /** 6 Computes the volume of a cube. 7 @param side_length the side length of the cube 8 read more..

  • Page - 227

    5.3 parameter passing 199 Function comments Whenever you write a function, you should comment its behavior. Comments are for human readers, not compilers, and there is no universal standard for the layout of a function com- ment. In this book, we will use the following lay out: /** Computes the volume of a cube. @param side_length the side length of the read more..

  • Page - 228

    200 Chapter 5 Functions • Figure 3  parameter passing 1 Function call result1 = side_length = 2 Initializing function parameter variable result1 = side_length = 2 3 About to return to the caller result1 = side_length = volume = 8 2 4 After function call result1 = 8 double result1 = cube_volume(2); double volume = side_length * side_length * side_length; return volume; double result1 read more..

  • Page - 229

    5.3 parameter passing 201 return z; } int main() { int a = 4; int b = 7; cout << mystery(a, b) << endl; } 11.  What does this program print? Use a diagram like Figure 3 to find the answer. int mystery(int x) { int y = x * x; return y; } int main() { int a = 4; cout << mystery(a + 1) << read more..

  • Page - 230

    202 Chapter 5 Functions 5.4 return Values You use the return statement to specify the result of a function. When the return state- ment is processed, the function exits immediately. This behavior is convenient for handling exceptional cases at the begin ning: double cube_volume(double side_length) { if (side_length < 0) { return 0; } double volume = read more..

  • Page - 231

    5.4 return Values 203 flag this as an error, or the function might return a random value. Protect against this problem by returning some safe value: double cube_volume(double side_length) { if (side_length >= 0) { return side_length * side_length * side_length; } return 0; } The last statement of every function ought to be a return read more..

  • Page - 232

    204 Chapter 5 Functions Here is an alternate organization of the cube.cpp file: #include <iostream> using namespace std; // Declaration of cube_volume double cube_volume(double side_length); int main() { double result1 = cube_volume(2); // Use of cube_volume double result2 = cube_volume(10); cout << "A cube with side length 2 has volume " << read more..

  • Page - 233

    5.4 return Values 205 Here is an alternate organization of the cube.cpp file: #include <iostream> using namespace std; // Declaration of cube_volume double cube_volume(double side_length); int main() { double result1 = cube_volume(2); // Use of cube_volume double result2 = cube_volume(10); cout << "A cube with side length 2 has volume " << result1 read more..

  • Page - 234

    206 Chapter 5 Functions 5.5 Functions Without return Values Sometimes, you need to carry out a sequence of instructions that does not yield a value. If that instruction sequence occurs multiple times, you will want to package it into a function. In C++, you use the return type void to indicate the absence of a return value. Here is a typical example. Your task read more..

  • Page - 235

    5.5 Functions Without return Values 207 5.5 Functions Without return Values Sometimes, you need to carry out a sequence of instructions that does not yield a value. If that instruction sequence occurs multiple times, you will want to package it into a function. In C++, you use the return type void to indicate the absence of a return value. Here is a typical example. read more..

  • Page - 236

    208 Chapter 5 Functions 5.6 problem solving: reusable Functions You have used many functions from the C++ standard library. These functions have been provided as a part of standard C++ so that programmers need not recreate them. Of course, the C++ library doesn’t cover every conceivable need. You will often be able to save yourself time by designing your own func read more..

  • Page - 237

    5.6 problem solving: reusable Functions 209 When carrying out the same task multiple times, use a function. Here is a better alterna tive: /** Prompts a user to enter a value within a given range until the user provides a valid input. @param low the smallest allowable input @param high the largest allowable input @return the value read more..

  • Page - 238

    210 Chapter 5 Functions 20.  Consider the following function that computes compound interest for an account with an initial bal ance of $10,000 and an interest rate of 5 percent: double balance(int years) { return 10000 * pow(1.05, years); } How can you make this function more reusable? 21.  The comment explains what the following loop does. Use a function instead. // read more..

  • Page - 239

    5.7 problem solving: stepwise refinement 211 Figure 5  Flowchart of Coffee-Making solution Yes No Get coffee Ask for coffee Can you ask someone ? Make coffee Yes No Do you have instant coffee? Brew coffee Add coffee beans to grinder Put cup in micro- wave Bring to a boil Fill cup with water Fill kettle with water Heat 3 min. Grind 60 sec. Add water to coffee maker Add filter to coffee read more..

  • Page - 240

    212 Chapter 5 Functions How can this function do its job? Let’s look at a simple case first. If the number is between 1 and 9, we need to compute "one" … "nine" . In fact, we need the same computation again for the hundreds (two hun dred ). Using the stepwise decomposition process, we design another function for this simpler task. Again, read more..

  • Page - 241

    5.7 problem solving: stepwise refinement 213 If (part > 0) Append digit_name(part) to name. This pseudocode has a number of important improvements over the verbal descrip- tion. It shows how to arrange the tests, starting with the comparisons against the larger numbers, and it shows how the smaller number is subsequently processed in further if statements. On the other read more..

  • Page - 242

    214 Chapter 5 Functions 13 if (digit == 1) return "one"; 14 if (digit == 2) return "two"; 15 if (digit == 3) return "three"; 16 if (digit == 4) return "four"; 17 if (digit == 5) return "five"; 18 if (digit == 6) return "six"; 19 if (digit read more..

  • Page - 243

    5.7 problem solving: stepwise refinement 215 73 if (part >= 100 ) 74 { 75 name = digit_name(part / 100) + " hundred"; 76 part = part % 100; 77 } 78 79 if (part >= 20) 80 { 81 name = name + " " + tens_name(part); 82 part = part % read more..

  • Page - 244

    216 Chapter 5 Functions practice it  Now you can try these exercises at the end of the chapter: R5.12, P5.16, P5.19. keep Functions short  There is a certain cost for writing a function. You need to design, code, and test the function. The function needs to be documented. You need to spend some effort to make the function reusable rather than tied to a specific read more..

  • Page - 245

    5.7 problem solving: stepwise refinement 217 Now you enter the branch part >= 10 . teen_name(16) is sixteen , so the variables now have the values int_name(number = 416) part name 416 "" 16 "four hundred" 0 "four hundred sixteen" Now it becomes clear why you need to set part to 0 in line 87. Otherwise, you would enter the next read more..

  • Page - 246

    218 Chapter 5 Functions 5.8 Variable scope and Global Variables It is possible to define the same variable name more than once in a program. When the variable name is used, you need to know to which definition it belongs. In this sec- tion, we discuss the rules for dealing with multiple definitions of the same name. A variable that is defined within a function read more..

  • Page - 247

    5.8 Variable scope and Global Variables 219 5.8 Variable scope and Global Variables It is possible to define the same variable name more than once in a program. When the variable name is used, you need to know to which definition it belongs. In this sec- tion, we discuss the rules for dealing with multiple definitions of the same name. A variable that is defined read more..

  • Page - 248

    220 Chapter 5 Functions Consider this sample program: 1  int x; 2  int mystery(int x) 3  { 4  int s = 0; 5  for (int i = 0; i < x; i++) 6  { 7  int x = i + 1; 8  s = s + x; 9  } 10  return x; 11  } 12  int main() 13  { 14  x = 4; 15  int s = read more..

  • Page - 249

    5.9 reference parameters 221 Here is a first attempt: void withdraw(double balance, double amount) // Does not work { const double PENALTY = 10; if (balance >= amount) { balance = balance - amount; } else { balance = balance - PENALTY; } } But this doesn’t work. Let’s walk through the function read more..

  • Page - 250

    222 Chapter 5 Functions Figure 7  reference and Value parameters harrys_account = balance = amount = 100 900 Reference parameter Value parameter main function withdraw function The parameter variable balance is called a value parameter, because it is initialized with the value of the supplied argument. All functions that we have written so far use value parameters. In this read more..

  • Page - 251

    5.9 reference parameters 223 Figure 8  When balance is a reference parameter 1 Function call harrys_account = balance = amount = 1000 2 Initializing function parameters harrys_account = balance = amount = 100 1000 3 About to return to the caller harrys_account = balance = amount = 100 900 4 After function call harrys_account = 900 withdraw(harrys_account, 100); withdraw(harrys_account, 100); read more..

  • Page - 252

    224 Chapter 5 Functions 5 /** 6 Withdraws the amount from the given balance, or withdraws 7 a penalty if the balance is insufficient. 8 @param balance the balance from which to make the withdrawal 9 @param amount the amount to withdraw 10 */ 11 void withdraw(double& balance, double amount) 12 { 13 const double PENALTY read more..

  • Page - 253

    5.9 reference parameters 225 36.  Write a function minmax so that the call minmax(x, y, a, b) sets a to the smaller of x and y and b to the larger of x and y . 37.  What does this program print? void mystery(int& a, int& b) { a = a - b; b = b + a; a = b - a; } int main() { int x = 4; int y read more..

  • Page - 254

    226 Chapter 5 Functions 5.10 recursive Functions (optional) A recursive function is a function that calls itself. This is not as unusual as it sounds at first. Suppose you face the arduous task of cleaning up an entire house. You may well say to yourself, “I’ll pick a room and clean it, and then I’ll clean the other rooms.” In other words, the cleanup read more..

  • Page - 255

    5.10 recursive Functions (optional) 227 } cout << endl; } Look at the print_triangle function one more time and notice how utterly reasonable it is. If the side length is 0, nothing needs to be printed. The next part is just as reason- able. Print the smaller triangle and don’t think about why that works. Then print a row of [] . Clearly, the read more..

  • Page - 256

    228 Chapter 5 Functions 9 void print_triangle(int side_length) 10 { 11 if (side_length < 1 ) { return; } 12 print_triangle(side_length - 1); 13 for (int i = 0; i < side_length; i++) 14 { 15 cout << "[]" ; 16 } 17 cout << endl; 18 } 19 20 int main() 21 { 22 read more..

  • Page - 257

    5.10 recursive Functions (optional) 229 } cout << endl; print_triangle(side_length - 1); } What is the result of print_triangle(4) ? 39.  Consider this recursive function: int mystery(int n) { if (n <= 0) { return 0; } return n + mystery(n - 1); } What is mystery(4) ? 40.  Consider this recursive function: int mystery(int n) { if (n read more..

  • Page - 258

    230 Chapter 5 Functions step 2  Combine solutions with simpler inputs into a solution of the original problem. In your mind, consider the solutions for the simpler inputs that you have discovered in Step 1. Don’t worry how those solutions are obtained. Simply have faith that the solutions are readily available. Just say to yourself: These are simpler inputs, so read more..

  • Page - 259

    5.10 recursive Functions (optional) 231 A number with a single digit is its own digit sum, so you can stop the recursion when n < 10 , and return n in that case. Or, if you prefer, you can be even lazier. If n has a single digit, then digit_sum(n / 10) + n % 10 equals digit_sum(0) + n . You can simply terminate the recursion when n is zero. read more..

  • Page - 260

    232 Chapter 5 Functions understand the concepts of functions, arguments, and return values. • A function is a named sequence of instructions. • Arguments are supplied when a function is called. The return value is the result that the function computes. Be able to implement functions. • When defining a function, you provide a name for the func tion, a variable for read more..

  • Page - 261

    review exercises 233 determine the scope of variables in a program. • The scope of a variable is the part of the program in which it is visible. • A variable in a nested block shadows a variable with the same name in an outer block. • A local variable is defined inside a function. A global variable is defined outside a function. • Avoid global variables in read more..

  • Page - 262

    234 Chapter 5 Functions r5.4  True or false? a.  A function has exactly one return statement. b.  A function has at least one return statement. c.  A function has at most one return value. d.  A function with return value void never has a return statement. e.  When executing a return statement, the function exits immediately. f.  A function with return read more..

  • Page - 263

    review exercises 235 5  int n = 0; 6  a = c; 7  if (n < c) 8  { 9  n = a + b; 10  } 11  return n; 12  } 13  14  int g(int c) 15  { 16  int n = 0; 17  int a = c; 18  if (n < f(c)) 19  { 20  n = a + b; 21  } 22  return read more..

  • Page - 264

    236 Chapter 5 Functions r5.13  Consider the following function: int f(int n) { if (n <= 1) { return 1; } if (n % 2 == 0) // n is even { return f(n / 2); } else { return f(3 * n + 1); } } Perform traces of the computations f(1) , f(2) , f(3) , f(4) , f(5) , f(6) , f(7) , f(8) , f(9) , and f(10) . read more..

  • Page - 265

    programming exercises 237 int temp = a; a = b; b = temp; } int main() { int x = 3; int y = 4; false_swap2(x, y); cout << x << " " << y << endl; return 0; } Why doesn’t the function swap the contents of x and y ? How can you rewrite the function to work cor rectly? r5.18  The following read more..

  • Page - 266

    238 Chapter 5 Functions p5.4  Write the following functions: a. bool all_the_same(double x, double y, double z) , returning true if the arguments are all the same b. bool all_different(double x, double y, double z) , returning true if the arguments are all different c. bool sorted(double x, double y, double z) , returning true if the arguments are sorted, with the read more..

  • Page - 267

    programming exercises 239 double cylinder_volume(double r, double h) double cylinder_surface(double r, double h) double cone_volume(double r, double h) double cone_surface(double r, double h) that compute the volume and surface area of a sphere with radius r , a cylinder with a circular base with radius r and height h , and a cone with a circular base with radius r and height read more..

  • Page - 268

    240 Chapter 5 Functions p5.19  Write a program that prints a paycheck. Ask the program user for the name of the employee, the hourly rate, and the number of hours worked. If the number of hours exceeds 40, the employee is paid “time and a half”, that is, 150 percent of the hourly rate on the hours exceeding 40. Your check should look similar to that in read more..

  • Page - 269

    programming exercises 241 total = 0 While the roman number string is not empty If the first character has a larger value than the second, or the string has length 1 Add value(first character) to total. Remove the character. Else Add value(second character) - value(first character) to total. Remove both characters. p5.23  In Exercise P3.23 you were asked to read more..

  • Page - 270

    242 Chapter 5 Functions Each digit of the zip code, and the check digit, is encoded according to the following table where 0 denotes a half bar and 1 a full bar. The digit can be easily computed from the bar code using the column weights 7, 4, 2, 1, 0. For example, 01100 is 0 × 7 + 1 × 4 + 1 × 2 + 0 × 1 × 0 × read more..

  • Page - 271

    programming exercises 243 character at the end. For example, to reverse "flow" , first reverse "low" to "wol" , then add the "f" at the end. p5.28  Write a recursive function bool is_palindrome(string str) that returns true if str is a palindrome, that is, a word that is the same when reversed. Examples of palin drome are “deed”, read more..

  • Page - 272

    244 Chapter 5 Functions engineering p5.34  In a movie theater, the angle q at which a viewer sees the picture on the screen depends on the distance x of the viewer from the screen. For a movie theater with the dimensions shown in the picture below, write a function that computes the angle for a given distance. 24 ft. 6 ft. 8° θ θ x Next, provide a more read more..

  • Page - 273

    answers to self-Check Questions 245 The amount of power in watts required to overcome such drag force is P = FDv, and the equivalent horsepower required is Hp = P ̸ 746. Write a program that accepts a car’s velocity and computes the power in watts and in horsepower needed to over- come the resulting drag force. Note: 1 mph = 0.447 m̸s. 1.  The arguments read more..

  • Page - 274

    246 Chapter 5 Functions cout << "-"; } cout << endl; } void box_string(string str) { int n = str.length(); print_line(n + 2); cout << "!" << str << "!" << endl; print_line(n + 2); } 18.  int total_pennies = round_to_pennies(total); int total_tax_pennies = round_to_pennies(total * read more..

  • Page - 275

    answers to self-Check Questions 247 22.  It is very easy to replace the space with any character. /** @param str any string @param ch a string of length 1 @return the number of times that ch occurs in str */ int count(string str, string ch) { int count = 0; for (int i = 0; i < str.length(); i++) { if read more..

  • Page - 276

    248 Chapter 5 Functions 32.  The variables s defined in lines 4 and 15. 33.  Yes, but since the function does not modify the amount parameter variable, there is no need to do so. 34.  void transfer(double& balance1, double& balance2, double amount) 35.  bool withdraw(double& balance, double amount) { if (balance >= amount) { balance = read more..

  • Page - 277

    6 Chapter 249 a rrays and Ve C tors to become familiar with using arrays and vectors to collect values to learn about common algorithms for processing arrays and vectors to write functions that receive and return arrays and vectors to be able to use two-dimensional arrays Chapter Goals Chapter Contents 6.1  ArrAys  250 Syntax 6.1: defining an array 251 Common Error 6.1: read more..

  • Page - 278

    250 In many programs, you need to collect large numbers of values. In standard C++, you use arrays and vectors for this purpose. arrays are a fundamental structure of the C++ language. the standard C++ library provides the vector construct as a more convenient alternative when working with collections whose size is not fixed. In this chapter, you will learn about arrays, read more..

  • Page - 279

    6.1 arrays 251 syntax 6.1 defining an array double values[5] = { 32, 54, 67.5, 29, 34.5 }; Element type Optional list of initial values Size Name Size must be a constant. Ok to omit size if initial values are given. Use brackets to access an element. values[i] = 0; The index must be ≥ 0 and < the size of the array. read more..

  • Page - 280

    252 Chapter 6 arrays and Vectors 6.1.2 accessing array elements The values stored in an array are called its elements. Each element has a position number, called an index. To access a value in the values array, you must specify which index you want to use. That is done with the [] operator: values[4] = 34.5; Now the element with index 4 is filled with read more..

  • Page - 281

    6.1 arrays 253 The most common bounds error is the following: double values[10]; cout << values[10]; There is no values[10] in an array with ten elements—the legal index values range from 0 to 9. To visit all elements of an array, use a variable for the index. Suppose values has ten elements and the integer variable i takes values 0, 1, 2, and so on, up read more..

  • Page - 282

    254 Chapter 6 arrays and Vectors } } At the end of this loop, current_size contains the actual number of elements in the array. Note that you have to stop accepting inputs if the size of the array reaches the capacity. To process the gathered array elements, you again use the companion variable, not the capacity. This loop prints the partially filled read more..

  • Page - 283

    6.1 arrays 255 program act unpredictably, and it can even cause the program to terminate. These are serious errors that can be difficult to detect. use Arrays for sequences of related values Arrays are intended for storing sequences of values with the same meaning. For example, an array of test scores makes perfect sense: int scores[NUMBER_OF_SCORES]; But an array double read more..

  • Page - 284

    256 Chapter 6 arrays and Vectors 6.2 Common array algorithms In the following sections, we discuss some of the most common algorithms for processing sequences of values. We present the algorithms so that you can use them with fully and partially filled arrays as well as vectors (which we will introduce in Section 6.7). When we use the expression size of values, you read more..

  • Page - 285

    6.2 Common array algorithms 257 6.2.3 sum and average Value You have already encountered this algorithm in Section 4.7.1. Here is the code for computing the sum of all elements in an array: double total = 0; for (int i = 0; i < size of values; i++) { total = total + values[i]; } To obtain the average, divide by the number of elements: double average = read more..

  • Page - 286

    258 Chapter 6 arrays and Vectors 6.2.6 linear search You often need to search for the position of an element so that you can replace or remove it. Visit all elements until you have found a match or you have come to the end of the array. Here we search for the position of the first element equal to 100. int pos = 0; bool found = false; while (pos < read more..

  • Page - 287

    6.2 Common array algorithms 259 6.2.8 Inserting an element If the order of the elements does not matter, you can simply insert new elements at the end, incrementing the variable tracking the size. (See Figure 8.) For a partially filled array: if (current_size < CAPACITY) { current_size++; values[current_size - 1] = new_element; } It is more work to insert an read more..

  • Page - 288

    260 Chapter 6 arrays and Vectors Figure 10  swapping array elements values = [0] [1] [2] [3] [4] [i] [j] 34.5 29 67.5 54 32 1 values = [i] [j] 34.5 29 67.5 54 32 2 temp = 54 values = [i] [j] 34.5 29 67.5 29 32 3 temp = 54 values = [i] [j] 34.5 54 67.5 29 32 4 temp = 54 Values to be swapped Consider the task of swapping the elements at posi- tions i and j read more..

  • Page - 289

    6.2 Common array algorithms 261 However, this technique does not work if you need to read an arbitrary number of inputs. In that case, add the values to an array until the end of the input has been reached. double values[CAPACITY]; int current_size = 0; double input; while (cin >> input) { if (current_size < CAPACITY) { values[current_size] read more..

  • Page - 290

    262 Chapter 6 arrays and Vectors 36 cout << " <== largest value"; 37 } 38 cout << endl; 39 } 40 41 return 0; 42 } Program run Please enter values, Q to quit: 34.5 80 115 44.5 Q 34.5 80 115 <== largest value 44.5 8.  What is the output of the largest.cpp program with the read more..

  • Page - 291

    6.2 Common array algorithms 263 for (int i = pos; i < size of values - 1; i++) { values[i + 1] = values[i]; } Practice it  Now you can try these exercises at the end of the chapter: R6.10, R6.13, P6.6, P6.16. sorting with the C++ library You often want to sort the elements of an array or vector. Special Topic 6.2 shows you a sort- ing algorithm read more..

  • Page - 292

    264 Chapter 6 arrays and Vectors Now the unsorted region is only two elements long; keep to the same successful strategy. The minimum element is 12. Swap it with the first value, 17: 5 9 11 12 17 That leaves you with an unprocessed region of length 1, but of course a region of length 1 is always sorted. You are done. Here is the C++ code: for (int unsorted read more..

  • Page - 293

    6.3 arrays and Functions 265 We still don’t have a match because 15 ≠ 17, and we cannot divide the subsequence further. If we wanted to insert 15 into the sequence, we would need to insert it just before values[5] . This search process is called a binary search, because we cut the size of the search in half in each step. That cutting in half works only read more..

  • Page - 294

    266 Chapter 6 arrays and Vectors Array parameters are always reference parameters. (You will see the reason in Chapter 7.) Functions can modify array arguments, and those modifications affect the array that was passed into the function. For example, the following multiply func- tion updates all elements in the array: void multiply(double values[], int size, double factor) { read more..

  • Page - 295

    6.3 arrays and Functions 267 if (current_size < capacity) { inputs[current_size] = input; current_size++; } } } This function is called as append_inputs(values, MAXIMUM_NUMBER_OF_VALUES, current_size); After the call, the current_size variable contains the new size. The following example program reads read more..

  • Page - 296

    268 Chapter 6 arrays and Vectors 37 @param factor the value with which each element is multiplied 38 */ 39 void multiply(double values[], int size, double factor) 40 { 41 for (int i = 0; i < size; i++) 42 { 43 values[i] = values[i] * factor; 44 } 45 } 46 47 /** 48 Prints the read more..

  • Page - 297

    6.4 problem solving: adapting algorithms 269 Practice it  Now you can try these exercises at the end of the chapter: R6.14, P6.8, P6.12. Constant Array Parameters When a function doesn’t modify an array parameter, it is considered good style to add the const reserved word, like this: double sum(const double values[], int size) The const reserved word helps the reader read more..

  • Page - 298

    270 Chapter 6 arrays and Vectors We need to fix our plan of attack: Find the minimum value. Find its position. Remove that position from the array. Calculate the sum. Will it work? Let’s continue with our example. We found a minimum value of 4. Linear search tells us that the value 4 occurs at position 5. 8 [0] 7 [1] 8.5 [2] 9.5 [3] 7 [4] 4 [5] 10 [6] We remove read more..

  • Page - 299

    6.4 problem solving: adapting algorithms 271 The next section shows you a technique for discovering a new algorithm when none of the fundamen tal algorithms can be adapted to a task. 20.  Section 6.2.7 has two algorithms for removing an element. Which of the two should be used to solve the task described in this section? 21.  It isn’t actually necessary to remove read more..

  • Page - 300

    272 Chapter 6 arrays and Vectors The preceding section showed you how to decompose Compute the final score into fundamen- tal algorithms: Find the position of the minimum. Remove it from the array. Calculate the sum. step 2  Determine functions, arguments, and return values for each step. Even though it may be possible to put all steps into the main function, this is read more..

  • Page - 301

    6.4 problem solving: adapting algorithms 273 } We discussed the algorithm for min_position in the preceding section: /** Gets the position of the minimum value from an array. @param values a partially filled array @param size the number of elements in values @return the position of the smallest element in values */ int min_position(double values[], read more..

  • Page - 302

    274 Chapter 6 arrays and Vectors This main function completes the solution (see ch06/scores.cpp ). int main() { const int CAPACITY = 1000; double scores[CAPACITY]; int current_size = read_inputs(scores, CAPACITY); if (current_size == 0) { cout << "At least one score is required." << endl; } else { read more..

  • Page - 303

    6.5 problem solving: discovering algorithms by Manipulating physical objects 275 This main function completes the solution (see ch06/scores.cpp ). int main() { const int CAPACITY = 1000; double scores[CAPACITY]; int current_size = read_inputs(scores, CAPACITY); if (current_size == 0) { cout << "At least one score is required." read more..

  • Page - 304

    276 Chapter 6 arrays and Vectors Now how does that help us with our problem, switching the first and the second half of the array? Let’s put the first coin into place, by swapping it with the fifth coin. However, as C++ programmers, we will say that we swap the coins in positions 0 and 4: Next, we swap the coins in positions 1 and 5: Two more swaps, read more..

  • Page - 305

    6.5 problem solving: discovering algorithms by Manipulating physical objects 277 And how many iterations do we make? We need to swap all coins in the first half. That is, we need to swap size / 2 coins. The pseudocode is i = 0 j = size / 2 while (i < size / 2) swap elements at positions i and j i++ j++ It is a good idea to make a walkthrough of the read more..

  • Page - 306

    278 Chapter 6 arrays and Vectors 6.6 two-dimensional arrays It often happens that you want to store collections of values that have a two-dimensional layout. Such data sets commonly occur in financial and scientific applications. An arrangement consisting of rows and columns of values is called a two-dimensional array, or a matrix. Let’s explore how to store the example read more..

  • Page - 307

    6.6 two-dimensional arrays 279 6.6.2 accessing elements To access a particular element in the two-dimensional array, you need to specify two subscripts in sepa rate brackets to select the row and column, respectively (see Syntax 6.2 and Figure 12): int value = counts[3][1]; To access all values in a two-dimensional array, you use two nested loops. For exam- ple, the following read more..

  • Page - 308

    280 Chapter 6 arrays and Vectors 6.6.3 Computing row and Column totals A common task is to compute row or column totals. In our example, the row totals give us the total num ber of medals won by a particular country. Finding the right index values is a bit tricky, and it is a good idea to make a quick sketch. To compute the total of row i , we need to read more..

  • Page - 309

    6.6 two-dimensional arrays 281 6.6.4 two-dimensional array parameters When passing a two-dimensional array to a function, you must specify the number of columns as a con stant with the parameter type. For example, this function computes the total of a given row: const int COLUMNS = 3; int row_total(int table[][COLUMNS], int row) { int total = 0; for (int j read more..

  • Page - 310

    282 Chapter 6 arrays and Vectors The row_total function did not need to know the number of rows of the array. If the number of rows is required, pass it as a variable, as in this example: int column_total(int table[][COLUMNS], int rows, int column) { int total = 0; for (int i = 0; i < rows; i++) { total = total + read more..

  • Page - 311

    6.6 two-dimensional arrays 283 43 { 1, 0, 1 }, 44 { 1, 1, 0 }, 45 { 0, 0, 1 }, 46 { 1, 0, 0 }, 47 { 0, 1, 1 }, 48 { 0, 1, 1 }, 49 { 1, 1, 0 } 50 }; 51 52 cout << " Country read more..

  • Page - 312

    284 Chapter 6 arrays and Vectors 34.  Which elements are on the diagonal joining the upper-left and the lower-right corners of the tic-tac-toe board? Practice it  Now you can try these exercises at the end of the chapter: R6.23, P6.19, P6.20. omitting the Column size of a two-dimensional Array Parameter When passing a one-dimensional array to a function, you specify the read more..

  • Page - 313

    6.7 Vectors 285 34.  Which elements are on the diagonal joining the upper-left and the lower-right corners of the tic-tac-toe board? Practice it  Now you can try these exercises at the end of the chapter: R6.23, P6.19, P6.20. omitting the Column size of a two-dimensional Array Parameter When passing a one-dimensional array to a function, you specify the size of the array read more..

  • Page - 314

    286 Chapter 6 arrays and Vectors You access the vector elements as values[i] , just as you do with arrays. The size member function returns the current size of a vector. In a loop that visits all vector elements, use the size member function like this: for (int i = 0; i < values.size(); i++) { cout << values[i] << endl; } 6.7.2 Growing and read more..

  • Page - 315

    6.7 Vectors 287 6.7.3 Figure 15  removing an element with pop_back 2 After pop_back values = 2 1 Before pop_back values = 3 37.5 54 32 This element to be removed 32 54 Size decreased Vectors and Functions You can use vectors as function arguments in exactly the same way as any other val- ues. For example, the following function computes the sum of a vector of floating- read more..

  • Page - 316

    288 Chapter 6 arrays and Vectors As you can see, it is easy to use vectors with functions—there are no special rules to keep in mind. 6.7.4 Vector algorithms Most of the algorithms in Section 6.2 apply without change to vectors—simply replace size of values with values.size() . In this section, we discuss which of the algo- rithms are different for vectors. read more..

  • Page - 317

    6.7 Vectors 289 When you insert an element in the middle, you still want to call push_back so that the size of the vector is increased. Use the following code: int last_pos = values.size() - 1; values.push_back(values[last_pos]); for (int i = last_pos; i > pos; i--) { values[i] = values[i - 1]; } values[pos] = new_element; 35.  Define a vector of integers that read more..

  • Page - 318

    290 Chapter 6 arrays and Vectors use arrays for collecting values. • Use an array to collect a sequence of values of the same type. • Individual elements in an array values are accessed by an integer index i , using the notation values[i]. Before pocket calcu- lators and personal computers existed, navigators and engineers used mechanical adding machines, slide read more..

  • Page - 319

    Chapter summary 291 • An array element can be used like any variable. • An array index must be at least zero and less than the size of the array. • A bounds error, which occurs if you supply an invalid array index, can corrupt data or cause your program to terminate. • With a partially filled array, keep a companion variable for the cur rent size. read more..

  • Page - 320

    292 Chapter 6 arrays and Vectors use vectors for managing collections whose size can change. • A vector stores a sequence of values whose size can change. • Use the size member function to obtain the current size of a vector. • Use the push_back member function to add more elements to a vector. Use pop_back to reduce the size. • Vectors can occur as read more..

  • Page - 321

    review exercises 293 What are the contents of the array a after the following loops complete? a. for (int i = 1; i < 10; i++) { a[i] = a[i - 1]; } b. for (int i = 9; i > 0; i--) { a[i] = a[i - 1]; } c. for (int i = 0; i < 9; i++) { a[i] = a[i + 1]; } d. for (int i = 8; i >= 0; i--) { a[i] = a[i + 1]; } e. for (int i = 1; i < 10; read more..

  • Page - 322

    294 Chapter 6 arrays and Vectors r6.15  You are given two arrays denoting x- and y-coordinates of a set of points in the plane. For plotting the point set, we need to know the x- and y-coordinates of the smallest rectangle containing the points. y x How can you obtain these values from the fundamental algorithms in Section 6.2? r6.16  Solve the problem described in read more..

  • Page - 323

    programming exercises 295 c.  Two-dimensional arrays always have the same number of rows and columns. d.  Elements of different columns in a two-dimensional array can have different types. e.  A function cannot return a two-dimensional array. f.  All array parameters are reference parameters. g.  A function cannot change the dimensions of a two-dimensional array that is passed as read more..

  • Page - 324

    296 Chapter 6 arrays and Vectors h.  Return true if the array is currently sorted in increasing order. i.  Return true if the array contains two adjacent duplicate values. j.  Return true if the array contains duplicate values (which need not be adjacent). For each function, provide a test program. P6.3  Modify the largest.cpp program to mark both the smallest and read more..

  • Page - 325

    programming exercises 297 and 11 1 4 9 16 9 7 4 9 would be considered identical, but 1 4 9 16 9 7 4 9 11 and 11 11 7 9 16 4 1 4 9 would not. You will probably need one or more helper functions. P6.12  Write a function that removes duplicates from an array. For example, if remove_ duplicates is called with an array containing 1 4 9 16 9 7 4 9 11 then read more..

  • Page - 326

    298 Chapter 6 arrays and Vectors generating random values until you have a value that is not yet in the array. But that is inefficient. Instead, follow this algorithm: Make a second array and fill it with the numbers 1 to 10. Repeat 10 times Pick a random element from the second array. Remove it and append it to the permutation array. P6.17  It is a read more..

  • Page - 327

    programming exercises 299 Set row = n - 1, column = n / 2. For k = 1 ... n Place k at [row][column]. Increment row and column. If the row or column is n, replace it with 0. If the element at [row][column] has already been filled Set row and column to their previous value. Decrement row. Here is the 5 × 5 square that you get if you read more..

  • Page - 328

    300 Chapter 6 arrays and Vectors Write a program that prompts users to pick either a seat or a price. Mark sold seats by changing the price to 0. When a user specifies a seat, make sure it is available. When a user specifies a price, find any seat with that price. P6.25  Write a program that plays tic-tac-toe. The tic-tac-toe game is played on a 3 × 3 read more..

  • Page - 329

    programming exercises 301 4 7 9 9 11 then merge_sorted returns the vector 1 4 4 7 9 9 9 11 16 P6.29  Modify the ch06/image.cpp program in the book’s companion code to generate the image of a checkerboard. P6.30  Modify the ch06/animation.cpp program in the book’s companion code to show a rectangle that travels from the left of the image to the right and then read more..

  • Page - 330

    302 Chapter 6 arrays and Vectors Then write a program that reads one hundred terrain height values and shows how the terrain gets flooded when the water level increases in ten steps from the lowest point in the terrain to the highest. engineering P6.34  Modify the ch06/image.cpp program in the book’s companion code to generate the image of a sine wave. Draw a read more..

  • Page - 331

    answers to self-Check Questions 303 1.  int primes[] = { 2, 3, 5, 7, 11 }; 2.  2, 3, 5, 3, 2 3.  3, 4, 6, 8, 12 4.  values[0] = 0; values[CAPACITY - 1] = 0; 5.  for (int i = SIZE - 1; i >= 0; i--) { cout << values[i] << endl; } 6.  string words[10]; 7.  string words[] = { "Yes", "No" } ; 8.  20 <== read more..

  • Page - 332

    304 Chapter 6 arrays and Vectors } } return -1; } Note that the loop is simpler than that in Section 6.2.6 since we can simply return the position when a match is found. 18.  void read_inputs(double inputs[], int capacity, int& size) { size = 0; double input; while (cin >> input) { if read more..

  • Page - 333

    answers to self-Check Questions 305 25.  The paperclip for i assumes positions 0, 1, 2, 3. When i is incremented to 4, the con dition i < size / 2 becomes false, and the loop ends. Similarly, the paperclip for j assumes positions 4, 5, 6, 7, which are the valid positions for the second half of the array. 26.  It reverses the elements in the array. 27.  read more..

  • Page - 334

    306 Chapter 6 arrays and Vectors 34.  board[0][0], board[1][1], board[2][2] 35.  vector<int> primes; primes.push_back(2); primes.push_back(3); primes.push_back(5); primes.push_back(7); primes.push_back(11); 36.  vector<int> primes(5); primes[0] = 2; primes[1] = 3; primes[2] = 5; primes[3] = 7; primes[4] = 11; 37.  Ann, Cal 38.  The problem doesn’t state how many measurements read more..

  • Page - 335

    7 Chapter 307 p ointers to be able to declare, initialize, and use pointers to understand the relationship between arrays and pointers to be able to convert between string objects and character pointers to become familiar with dynamic memory allocation and deallocation Chapter Goals Chapter Contents 7.1  Defining anD Using Pointers  308 Syntax 7.1: pointer syntax 310 Common read more..

  • Page - 336

    308 in the game on the left, the spinner’s pointer moves to an item. a player follows the pointer and handles the item to which it points—by taking the ball or following the instructions written in the space. C++ also has pointers that can point to different values throughout a program run. pointers let you work with data whose locations change or whose size is read more..

  • Page - 337

    7.1 Defining and Using pointers 309 figure 1  pointers and Values in Memory 2 1 harrys_account = account_pointer = 20300 0 20300 harrys_account = account_pointer = joint_account = 0 20312 0 20300 20312 Point to memory at given address Point to memory at new address double* account_pointer = &harrys_account account_pointer = &joint_account The type double* , or “pointer to double ”, read more..

  • Page - 338

    310 Chapter 7 pointers figure 2  pointer Variables Can be on either side of an assignment 2 1 joint_account = account_pointer = 20312 1000 20312 balance = 1000 Update memory at given address Read from memory *account_pointer = 1000 balance = *account_pointer joint_account = account_pointer = 20312 1000 20312 An expression such as *account_pointer can be on the left or the right of read more..

  • Page - 339

    7.1 Defining and Using pointers 311 7.1.3 table 1 pointer syntax examples Assume the following declarations: int m = 10; // Assumed to be at address 20300 int n = 20; // Assumed to be at address 20304 int* p = &m; expression Value Comment p 20300 The address of m . *p 10 The value stored at that address. &n 20304 The address of n . p read more..

  • Page - 340

    312 Chapter 7 pointers There is a special value, NULL , that you should use to indicate a pointer that doesn’t point anywhere. If you define a pointer variable and are not ready to initialize it quite yet, set it to NULL . double* account_pointer = NULL; // Will set later You can later test whether the pointer is still NULL . If it is, don’t use it. if read more..

  • Page - 341

    7.1 Defining and Using pointers 313 int* p = &a; int* q = &b; *p = *q; cout << a << " " << b << endl; 3.  Consider this set of statements. What is printed? int a = 15; int* p = &a; int* q = &a; cout << *p + *q << endl; 4.  Consider this set of statements. What is printed? int a = 15; int* p = &a; int* q = read more..

  • Page - 342

    314 Chapter 7 pointers Pointers and references In Section 5.9, you saw how reference parameters enable a function to modify variables that are passed as arguments. Here is an example of a function with a reference parameter: void withdraw(double& balance, double amount) { if (balance >= amount) { balance = balance - amount; } } If you call read more..

  • Page - 343

    7.2 arrays and pointers 315 7.2.2 figure 3  pointers into an array a = 0 1 4 9 16 25 36 49 64 81 a + 3 = p = 20300 20300 20308 20316 20324 20332 20340 20348 20356 20364 20372 pointer arithmetic Pointers into arrays support pointer arithmetic. You can add an integer offset to the pointer to point to another array location. For example, suppose p points to the beginning of read more..

  • Page - 344

    316 Chapter 7 pointers 7.2.3 array parameter Variables are pointers Once you understand the connection between arrays and pointers, it becomes clear why array parameter variables are different from other parameter types. As an exam- ple, consider this function that computes the sum of all values in an array: double sum(double a[], int size) { double total = 0; read more..

  • Page - 345

    7.2 arrays and pointers 317 table 2 arrays and pointers expression Value Comment a 20300 The starting address of the array, here assumed to be 20300. *a 0 The value stored at that address. (The array contains values 0, 1, 4, 9, ....) a + 1 20308 The address of the next double value in the array. A double occupies 8 bytes. a + 3 20324 The address of the element read more..

  • Page - 346

    318 Chapter 7 pointers p++; q--; *p = *q; 9.  What do the following statements print? int a[] = { 2, 3, 5 }; cout << *a + 2 << " "; cout << *(a + 2) << endl; 10.  In Chapter 6, we defined a function void squares(int n, int result[]) Declare the parameter variable using pointer notation. Practice it  Now you can try these exercises at the read more..

  • Page - 347

    7.2 arrays and pointers 319 Program Clearly, not Cleverly Some programmers take great pride in minimizing the number of instructions, even if the resulting code is hard to understand. For example, here is a legal implementation of the sum function: double sum(double* a, int size) { double total = 0; while (size-- > 0) // Loop size times { read more..

  • Page - 348

    320 Chapter 7 pointers Constant Pointers The following definition specifies a constant pointer: const double* p = &balance; You cannot modify the value to which p points. That is, the following statement is illegal: *p = 0; // Error Of course, you can read the value: cout << *p; // OK A constant array parameter variable is equivalent to a constant pointer. For read more..

  • Page - 349

    7.3 C and C++ strings 321 figure 6  a Character array [0] [1] [2] [3] [4] [5] 'H' 'a' 'r' 'r' 'y' '\0' Points to 'H' char_pointer = The string is declared as const because you are not supposed to modify a literal string. (See Special Topic 7.3 on page 320 for more information on constant pointers.) A C string is terminated by a special character, called a null read more..

  • Page - 350

    322 Chapter 7 pointers The char_array variable is an array of 6 characters, initialized with 'H' , 'a' , 'r' , 'r' , 'y' , and a null termi nator. The compiler counts the characters in the string that is used for initializing the array, including the null terminator. You can modify the characters in the array: char_array[0] = 'L'; 7.3.4 Converting Between C read more..

  • Page - 351

    7.3 C and C++ strings 323 /** Makes an uppercase version of a string. @param str a string @return a string with the characters in str converted to uppercase */ string uppercase(string str) { string result = str; // Make a copy of str for (int i = 0; i < result.length(); i++) { result[i] = toupper(result[i]); // read more..

  • Page - 352

    324 Chapter 7 pointers H a r r y NAME_SIZE Last name and null terminator length Space ... This array can hold strings with a length of at most 39, because one character is required for the null terminator. Now copy the first name, using strncpy : strncpy(name, first, NAME_SIZE - 1); You must be careful not to overrun the target array. It is unlikely that a first read more..

  • Page - 353

    7.4 Dynamic Memory allocation 325 7.4 Dynamic Memory allocation In many programming situations, you do not know beforehand how many values you need. To solve this problem, you can use dynamic allocation and ask the C++ run-time system to create new values when ever you need them. The run-time system keeps a large storage area, called the heap, that can allocate val read more..

  • Page - 354

    326 Chapter 7 pointers After you delete a memory block, you can no longer use it. The storage space may already be used elsewhere. delete[] account_array; account_array[0] = 1000; // NO! You no longer own the memory of account_array Heap arrays have one significant advantage over array variables. If you declare an array variable, you must specify a fixed array size when read more..

  • Page - 355

    7.4 Dynamic Memory allocation 327 16. table 5 Common Memory allocation errors statements error int* p; *p = 5; delete p; There is no call to new int . int* p = new int; *p = 5; p = new int; The first allocated memory block was never deleted. int* p = new int[10]; *p = 5; delete p; The delete[] operator should have been used. int* p = new int[10]; int* q = p; read more..

  • Page - 356

    328 Chapter 7 pointers int primes[] = { 2, 3, 5, 7, 11 }; int* p = grow(primes, 5); 20.  Consider the grow function of Self Check 19. What must its caller remember to do? Practice it  Now you can try these exercises at the end of the chapter: R7.19, R7.21, P7.10. Dangling Pointers A very common pointer error is to use a pointer that points to memory that read more..

  • Page - 357

    7.5 arrays and Vectors of pointers 329 7.5 arrays and Vectors of pointers When you have a sequence of pointers, you can place them into an array or vector. An array and a vector of ten int* pointers are defined as int* pointer_array[10]; vector<int*> pointer_vector(10); The expression pointer_array[i] or pointer_vector[i] denotes the pointer with index i in the sequence. read more..

  • Page - 358

    330 Chapter 7 pointers figure 10  Movement of a Ball in the Galton Board array row i row i + 1 column j column j + 1 The following statements initialize the triangular array: int* counts[10]; for (int i = 0; i < 10; i++) { counts[i] = new int[i + 1]; } Note that the first element counts[0] contains a pointer to an array of length 1, and the last read more..

  • Page - 359

    7.5 arrays and Vectors of pointers 331 17 counts[i] = new int[i + 1]; 18 for (int j = 0; j <= i; j++) 19 { 20 counts[i][j] = 0; 21 } 22 } 23 24 const int RUNS = 1000; 25 26 // Simulate 1,000 balls 27 for (int run = 0; run < read more..

  • Page - 360

    332 Chapter 7 pointers 21.  Why didn’t we initialize the triangular array with the following loop? for (int i = 0; i < 10; i++) { counts[i] = new int[i]; } 22.  Suppose a program initializes a triangular array as we did in this section, and then accesses a non-exis tent element with the statement counts[1][2]++ Will the program compile? If so, what happens read more..

  • Page - 361

    7.6 problem solving: Draw a picture 333 Microphone TX-10\0 Smith, Diane\0 Lee, Tim\0 Tape recorder\0 Mini DVI cable\0 … items Finally, there is a parallel array checked_out_to of pointers to user names. Sometimes, items can be checked out to the same user. Other items aren’t checked out at all—the user name pointer is NULL . When you draw a diagram, try to read more..

  • Page - 362

    334 Chapter 7 pointers 30.  Suppose you want to sort the names of the items in the media center. There is no need to move the strings. All you need to do is rearrange the string pointers. Draw a picture that shows the result. Practice it  Now you can try these exercises at the end of the chapter: R7.25, R7.26, R7.27. step 1  Draw a picture. As described read more..

  • Page - 363

    7.6 problem solving: Draw a picture 335 30.  Suppose you want to sort the names of the items in the media center. There is no need to move the strings. All you need to do is rearrange the string pointers. Draw a picture that shows the result. Practice it  Now you can try these exercises at the end of the chapter: R7.25, R7.26, R7.27. step 1  Draw a read more..

  • Page - 364

    336 Chapter 7 pointers 7.7 structures and pointers (optional) 7.7.1 structures In C++, you use a structure to aggregate items of arbitrary types into a single value. For example, a street address is com posed of a house number and a street name. A structure named StreetAddress can be defined to combine these two values into a sin- gle entity. In C++, we define a read more..

  • Page - 365

    7.7 structures and pointers (optional) 337 7.7.2 pointers to structures It is common to allocate structure values dynamically, using the new operator: StreetAddress* address_pointer = new StreetAddress; Suppose you want to set the house number of the structure to which address_pointer points: *address_pointer.house_number = 1600; // Error Unfortunately, that is a syntax error. The dot read more..

  • Page - 366

    338 Chapter 7 pointers Employee sally; sally.name = "Lee, Sally"; sally.office = &accounting; Figure 12 shows how these structures are related. This sharing of information has an important benefit. Suppose the accounting office moves across the street: accounting.house_number = 1720; Now both Harry’s and Sally’s office addresses are automatically updated. 31.  figure 12  read more..

  • Page - 367

    Chapter summary 339 Define and use pointer variables. • A pointer denotes the location of a variable in memory. • The type T* denotes a pointer to a variable of type T . • The & operator yields the location of a variable. • The * operator accesses the variable to which a pointer points. • It is an error to use an uninitialized pointer. • The NULL read more..

  • Page - 368

    340 Chapter 7 pointers work with arrays and vectors of pointers. Draw diagrams for visualizing pointers and the data to which they point. • Draw the data that is being processed, then draw the pointer variables. When drawing the pointer arrows, illustrate a typical situation. Use structures to aggregate data items and work with pointers to structures. • A structure read more..

  • Page - 369

    review exercises 341 6  int* r = NULL; 7  *r = 3000; r7.5  Suppose that a system allows the use of any string as a password, even the empty string. However, when a user connects to the system for the first time, no password has been assigned. Describe how you can use a string* variable and the NULL pointer to distinguish unassigned passwords from empty ones. read more..

  • Page - 370

    342 Chapter 7 pointers r7.12  Implement a function firstlast that obtains the first and last values in an array of integers and stores the result in an array argument. r7.13  Explain the meanings of the following expressions: a. "Harry" + 1 b. *("Harry" + 2) c. "Harry"[3] d. [4]"Harry" r7.14  What is the difference between the following two read more..

  • Page - 371

    review exercises 343 r = q; 8 r = s; 9 s = p; 10 s = q; 11 s = r; 12 } r7.19 What happens if you forget to delete an object that you obtained from the heap? What happens if you delete it twice? r7.20 Write a program that accesses a deleted pointer, an uninitialized pointer, and a NULL pointer. What happens when you read more..

  • Page - 372

    344 Chapter 7 pointers P7.1  Write a function void sort2(double* p, double* p) that receives two pointers and sorts the values to which they point. If you call sort2(&x, &y) then x <= y after the call. P7.2  Write a function double replace_if_greater(double* p, double x) that replaces the value to which p points with x if x is greater. Return the old read more..

  • Page - 373

    programming exercises 345 array should have exactly size elements. Of course, you won’t know at the outset how many elements the user will enter. Start with an array of 10 elements, and double the size whenever the array fills up. At the end, allocate an array of the correct size and copy all inputs into it. Be sure to delete any intermediate arrays. P7.11  Enhance read more..

  • Page - 374

    346 Chapter 7 pointers P7.16  Modify Exercise P7.13 so that you first print the lines in the order that they were entered, then print them in sorted order. When you sort the lines, only rearrange the pointers in the lines array. P7.17  When you read a long document, there is a good chance that many words occur multiple times. Instead of storing each word, it read more..

  • Page - 375

    answers to self­Check Questions 347 and a train indicator that is 0 (empty), +1 (train moving clockwise), or –1 (train moving counterclockwise). Populate the system with four trains at random seg- ments, two in each direction. Display the tracks and trains in each step, like this: +-------------->--+ | x x x x x | | ----------<---- | | | read more..

  • Page - 376

    348 Chapter 7 pointers 21.  Then the first row would have had 0 elements and the last row would have had 9 elements. 22.  The program will compile. counts[1] is an int* pointer, and it is legal to apply [2] . counts[1][2] will access the memory address counts[1] + 2 , which unfortunately points to some other memory. That memory will be overwritten, and it read more..

  • Page - 377

    answers to self­Check Questions 349 28.  29.  30.  31.  StreetAddress state_dept; state_dept.house_number = 2201; state_dept.street_name = "C Street NW"; 32.  StreetAddress* state_dept = new StreetAddress; state_dept->house_number = 2201; state_dept->street_name = "C Street NW"; 33.  struct Date { string month; // It is also OK to define month as an int int read more..

  • Page - 378

    This page intentionally left blank read more..

  • Page - 379

    8 Chapter 351 Stream S to be able to read and write files to convert between strings and numbers using string streams to process command line arguments to understand the concepts of sequential and random access Chapter Goal S Chapter Content S 8.1  Reading and WRiting  text Files  352 Syntax 8.1: Working with File Streams 354 8.2  Reading text input  358 8.3  read more..

  • Page - 380

    352 In this chapter, you will learn how to read and write files using the C++ stream library—a very useful skill for processing real world data. as an application, you will learn how to encrypt data. (the enigma machine shown at left is an encryption device used by Germany in World War II. pioneering British computer scientists broke the code and were able to read more..

  • Page - 381

    8.1 reading and Writing text Files 353 File names can contain directory path information, such as ~/homework/input.dat (UNIX) c:\homework\input.dat (Windows) When you specify the file name as a string literal, and the name contains backslash characters (as in a Win dows filename), you must supply each backslash twice: in_file.open("c:\\homework\\input.dat"); Recall that a single read more..

  • Page - 382

    354 Chapter 8 Streams Syntax 8.1 Working with File Streams #include <fstream> ifstream in_file; in_file.open(filename.c_str()); in_file >> name >> value; ofstream out_file; out_file.open("c:\\output.txt"); out_file << name << " " << value << endl; Use ifstream for input, ofstream for output, fstream for both input and output. Include this header when you read more..

  • Page - 383

    8.1 reading and Writing text Files 355 shows that the 10th most common boy’s name was Joseph, with 260,365 births, or 1.2681 percent of all births during that period. The 10th most common girl’s name was Megan. Why are there many more Josephs than Megans? Parents seem to use a wider set of girl’s names, making each one of them less fre quent. Let us test read more..

  • Page - 384

    356 Chapter 8 Streams Note that the in_file parameter variable of the process_name function in the code below is a reference parameter. Reading or writing modifies a stream variable. The stream variable monitors how many characters have been read or written so far. Any read or write operation changes that data. For that reason, you must always make stream parameter read more..

  • Page - 385

    8.1 reading and Writing text Files 357 44 cout << endl; 45 } 46 47 return 0; 48 } program Run 1 Michael Jessica 2 Christopher Ashley 3 Matthew Emily 4 Joshua Sarah 5 Jacob Samantha 6 Nicholas Amanda 7 Andrew Brittany 8 Daniel Elizabeth 9 Tyler Taylor 10 Joseph Megan ... 68 Dustin Gabrielle 69 Noah Katie 70 Caitlin 71 Lindsey read more..

  • Page - 386

    358 Chapter 8 Streams 8.2 reading text Input In the following sections, you will learn how to process text with complex contents such as that which often occurs in real-life situations. 8.2.1 reading Words You already know how to read the next word from a stream, using the >> operator. string word; in_file >> word; Here is precisely what happens when that read more..

  • Page - 387

    8.2 reading text Input 359 If you read a character from a stream and you don’t like what you get, you can unget it. The isdigit function is one of several useful functions that categorize characters—see Table 1. All return true or false as to whether the argument passes the test. You must include the <cctype> header to use these functions. 8.2.3 read more..

  • Page - 388

    360 Chapter 8 Streams Here is a typical example of processing lines in a file. A file with population data from the CIA World Factbook site actionURI(https://www.cia.gov/library/publications/theworld-factbook/index.html):(https://www.cia.gov/library/publications/the- actionURI(https://www.cia.gov/library/publications/theworld-factbook/index.html):world-factbook/index.html read more..

  • Page - 389

    8.3 Writing text output 361 9.  What is the effect of the following loop? char ch; while (in_file.get(ch) && isspace(ch)) { } in_file.unget(); 10.  Why can’t you simply read the population data file with the following loop? while (in_file >> country_name >> population) { Process country name and population. } practice it  Now you can try these exercises at the read more..

  • Page - 390

    362 Chapter 8 Streams The numbers line up to the right. That alignment works well for numbers, but not for strings. Usually, you want strings to line up at the left. You use the left and right manipulators to set the alignment. The following example uses left alignment for a string and then switches back to right alignment for a number: out_file << left read more..

  • Page - 391

    8.4 String Streams 363 Table 2 summarizes the stream manipulators. Note that all manipulators set the state of the stream object for all subsequent operations, with the exception of setw . After each output operation, the field width is reset to 0. To use any of these manipulators, include the <iomanip> header. 11.  What is the output of the following statement? read more..

  • Page - 392

    364 Chapter 8 Streams Next, simply use the >> operator to read the month name, the day, the comma separa- tor, and the year: string month; int day; string comma; int year; strm >> month >> day >> comma >> year; Now month is "January" , day is 24 , and year is 1973 . Note that this input statement yields day and yea r as inte read more..

  • Page - 393

    8.5 Command line arguments 365 16.  What is the value of n after these statements? istrstream strm; strm.str("123,456"); int n; int m; char ch; strm >> n >> ch >> m; n = 1000 * n + m; 17.  What does string_to_int("123,456") return? 18.  What does string_to_int("$123") return? 19.  What is the value of strm.str() after these statements? read more..

  • Page - 394

    366 Chapter 8 Streams Figure 2  Caesar Cipher M e e t m e a t t h e P h h w p h d w w k h Plain text Encrypted text ### # Let’s write a program that encrypts a file—that is, scrambles it so that it is unread- able except to those who know the decryption method. Ignoring 2,000 years of prog- ress in the field of encryption, we will use a method read more..

  • Page - 395

    8.5 Command line arguments 367 23 int main(int argc, char* argv[]) 24 { 25 int key = 3; 26 int file_count = 0; // The number of files specified 27 ifstream in_file; 28 ofstream out_file; 29 30 for (int i = 1; i < argc; i++) // Process all command-line arguments 31 { 32 string arg = read more..

  • Page - 396

    368 Chapter 8 Streams the exercises at the end of this chapter give a few algorithms to encrypt text. Don’t actually use any of those meth- ods to send secret messages to your lover. any skilled cryptographer can break these schemes in a very short time—that is, reconstruct the origi- nal text without knowing the secret key word. In 1978 ron rivest, adi Shamir, read more..

  • Page - 397

    8.5 Command line arguments 369 step 1  Understand the processing task. As always, you need to have a clear understanding of the task before designing a solution. Can you carry out the task by hand (perhaps with smaller input files)? If not, get more information about the problem. The following pseudocode describes our processing task: While there are more lines to be read more..

  • Page - 398

    370 Chapter 8 Streams When gathering data that can be distributed over several lines, then it makes more sense to read words. Keep in mind that you lose all white space when you read words. Reading characters is mostly useful for tasks that require access to individual characters. Examples include ana lyzing character frequencies, changing tabs to spaces, or encryption. read more..

  • Page - 399

    8.5 Command line arguments 371 20 stream >> x; 21 return x; 22 } 23 24 /** 25 Extracts the country and associated value from an input line. 26 @param line a line containing a country name, followed by a number 27 @param country the string for holding the country name 28 @param value the variable for holding read more..

  • Page - 400

    372 Chapter 8 Streams 8.6 random access and Binary Files In the following sections, you will learn how to read and write data at arbitrary posi- tions in a file, and how to edit image files. 8.6.1 random access So far, you’ve read from a file an item at a time and written to a file an item at a time, without skipping forward or backward. That access read more..

  • Page - 401

    8.6 random access and Binary Files 373 8.6 random access and Binary Files In the following sections, you will learn how to read and write data at arbitrary posi- tions in a file, and how to edit image files. 8.6.1 random access So far, you’ve read from a file an item at a time and written to a file an item at a time, without skipping forward or backward. read more..

  • Page - 402

    374 Chapter 8 Streams Figure 5  the Bmp File Format for 24-bit true Color Images 02 10 18 22 file size offset width height ... ... ... Padding Scan line Scan line The image is stored as a sequence of pixel rows, starting with the pixels of the bot- tommost row of the image. Each pixel row contains a sequence of blue/green/red triplets. The end of the row is padded read more..

  • Page - 403

    8.6 random access and Binary Files 375 To try out this program, take one of your favorite images, use an image editor to convert to BMP format (or use queen-mary.bmp from the code files for this book), then run the program and view the transformed file in an image editor. Exercises P8.21 and P8.22 ask you to produce more interesting effects. ch08/imagemod.cpp 1 read more..

  • Page - 404

    376 Chapter 8 Streams 53 54 // Scan lines must occupy multiples of four bytes 55 int scanline_size = width * 3; 56 int padding = 0; 57 if (scanline_size % 4 != 0) 58 { 59 padding = 4 - scanline_size % 4; 60 } 61 62 if (file_size != start + (scanline_size + padding) * read more..

  • Page - 405

    Chapter Summary 377 develop programs that read and write files. • To read or write files, you use variables of type fstream , ifstream , or ofstream . • When opening a file stream, you supply the name of the file stored on disk. • Read from a file stream with the same operations that you use with cin . • Write to a file stream with the same operations that read more..

  • Page - 406

    378 Chapter 8 Streams Be able to process text in files. • When reading a string with the >> operator, the white space between words is consumed. • You can get individual characters from a stream and unget the last one. • You can read a line of input with the getline function and then process it further. Write programs that neatly format their output. read more..

  • Page - 407

    programming exercises 379 R8.6  Why are the in and out parameter variables of the encrypt_file function in Section 8.5 refer ence parameters and not value parameters? R8.7  Give an output statement to write a date and time in ISO 8601 format, such as 2011-03-01 09:35 Assume that the date and time are given in five integer variables year, month, day, hour, minute. read more..

  • Page - 408

    380 Chapter 8 Streams p8.3  Repeat Exercise P8.2, but allow the user to specify the file name on the command- line. If the user doesn’t specify any file name, then prompt the user for the name. p8.4  Write a program that reads a file containing two columns of floating-point num bers. Prompt the user for the file name. Print the average of each column. p8.5  read more..

  • Page - 409

    programming exercises 381 If the line was successfully read pos2 = current get position Set put position to pos1. Write the reversed line. Set get position to pos2. p8.9  Write a program that reads each line in a file, reverses its lines, and writes them to another file. Suppose the user specifies input.txt and output.txt when prompted for the file read more..

  • Page - 410

    382 Chapter 8 Streams makes a long file book.txt that contains the contents of the files chapter1.txt , chapter2. txt , and chapter3.txt . The target file is always the last file specified on the command line. p8.17  Random monoalphabet cipher. The Caesar cipher, which shifts all letters by a fixed amount, is far too easy to crack. Here is a better idea. As the read more..

  • Page - 411

    programming exercises 383 the input document. Choose a keyword, for example TIGER . Then encode the first letter of the input text like this: A B C D E F G H I J K L M N O T U V W X Y Z A B C D E F G H P I Q J R K S L T M U N V O W P X Q Y R Z S The encoded alphabet is just the regular alphabet shifted to start at T , the first letter of read more..

  • Page - 412

    384 Chapter 8 Streams p8.22  Write a program that edits an image file, turning it into grayscale. Replace each pixel with a pixel that has the same grayness level for the blue, green, and red component. The grayness level is computed by adding 30 percent of the red level, 59 percent of the green level, and 11 percent of the blue level. (The color- sensing cone read more..

  • Page - 413

    programming exercises 385 For each class, there is a file with student ID numbers and grades: csc2.txt 11234 A- 12547 B 16753 B+ 21886 C ... Write a program that asks for a student ID and prints out a grade report for that student, by searching all class files. Here is a sample report Student ID 16753 CSC2 B+ MTH121 C+ CHN1 A PHY50 A- engineering p8.26  After the switch read more..

  • Page - 414

    386 Chapter 8 Streams 1.  The stream will be in a failed state because there is no file with an empty name. 2.  The stream variable is declared as an input stream. It should have been an ofstream . 3.  The stream parameter variable in should be a reference parameter. 4.  Initialize boy_total and girl_total with 10. 5.  Add the following code to the read more..

  • Page - 415

    answers to Self-Check Questions 387 1.  The stream will be in a failed state because there is no file with an empty name. 2.  The stream variable is declared as an input stream. It should have been an ofstream . 3.  The stream parameter variable in should be a reference parameter. 4.  Initialize boy_total and girl_total with 10. 5.  Add the following code to the read more..

  • Page - 416

    388 Chapter 8 Streams 22.  key file_count i arg 3 0 1 -d -3 1 2 encrypt.txt 3 Then the program prints the message Usage: caesar [-d] infile outfile and exits. 23.  FDHVDU 24.  It turns them into # characters. The ASCII code for a space is 32, and the # character has code 35. 25.  It replaces the initial byte of a file with 0. 26.  Change read more..

  • Page - 417

    9 Chapter 389 Classes to understand the concept of encapsulation to master the separation of interface and implementation to be able to implement your own classes to understand how constructors and member functions act on objects to discover appropriate classes for solving programming problems to distribute a program over multiple source files Chapter Goals Chapter Contents 9.1  read more..

  • Page - 418

    390 this chapter introduces you to object-oriented program- ming, an important technique for writing complex programs. In an object-oriented program, you don’t simply manipulate numbers and strings, but you work with objects that are meaningful for your application. objects with the same behavior (such as the windmills to the left) are grouped into classes. a programmer provides read more..

  • Page - 419

    9.1 object-oriented programming 391 You can drive a car by operating the steering wheel and pedals, without know ing how the engine works. Similarly, you use an object through its member func tions. The implementation is hidden. When you develop an object-oriented program, you create your own classes that describe what is important in your application. For example, read more..

  • Page - 420

    392 Chapter 9 Classes In this chapter, you will learn how to design and implement your own classes in C++, and how to structure your programs in an object-oriented way, using the prin- ciple of encapsulation. 1.  In C++, is cin an object or a class? Is string an object or a class? 2.  When using a string object, you do not know how it stores its read more..

  • Page - 421

    9.2 specifying the public Interface of a Class 393 Here is the C++ syntax for the CashRegister class definition: class CashRegister { public: void clear(); void add_item(double price); double get_total() const; int get_count() const; private: data members—see Section 9.3 }; The member functions are declared in the public section of the class. Any read more..

  • Page - 422

    394 Chapter 9 Classes figure 1  the Interface of the CashRegister Class get_total get_count CashRegister Private data add_item clear Mutators Accessors has two mutators: clear and add_item . After you call either of these functions, the total amount and item count are changed. Accessors just query the object for some information without changing it. The CashRegister class has read more..

  • Page - 423

    9.3 Data Members 395 forgetting a Semicolon Braces { } are common in C++ code, and usually you do not place a semicolon after the closing brace. However, class definitions always end in }; . A common error is to forget that semicolon: class CashRegister { public: ... private: ... } // Forgot semicolon int main() { // Many compilers report the read more..

  • Page - 424

    396 Chapter 9 Classes The add_item function receives a price as an argument, and it must record the price. If the CashRegister object stores an array of entered prices, then the add_item function appends the price. On the other hand, if we decide to store just the item total and count, then the add_item function updates these two variables. Finally, the clear read more..

  • Page - 425

    9.4 Member Functions 397 10.  These clocks have common behavior, but each of them has a different state. Similarly, objects of a class can have their data members set to different values. What is the value of register1.item_count , register1.total_price , register2.item_ count , and register2.total_price after these statements? CashRegister register1; register1.clear(); read more..

  • Page - 426

    398 Chapter 9 Classes 9.4.1 Implementing Member Functions Here is the implementation of the add_item function of the CashRegister class. void CashRegister::add_item(double price) { item_count++; total_price = total_price + price; } The CashRegister:: prefix makes it clear that we are defining the add_item function of the CashRegister class. In C++ it is perfectly read more..

  • Page - 427

    9.4 Member Functions 399 figure 3  Implicit and explicit parameters 2 After the member function call register1.add_item(1.95) . 1 Before the member function call. register1 = item_count = CashRegister total_price = 1 1.95 register1 = item_count = CashRegister total_price = 0 0 The implicit parameter references this object. The explicit parameter is set to this argument. When a member function read more..

  • Page - 428

    400 Chapter 9 Classes for (int i = 1; i <= quantity; i++) { add_item(price); } } Here, the add_item member function is invoked on the implicit parameter. for (int i = 1; i <= quantity; i++) { implicit parameter.add_item(price); } That is the object on which the add_items function is invoked. For example, in the call read more..

  • Page - 429

    9.4 Member Functions 401 17 18 /** 19 Adds an item to this cash register. 20 @param price the price of this item 21 */ 22 void add_item(double price); 23 24 /** 25 @return the total amount of the current sale 26 */ 27 double get_total() const; 28 29 /** 30 read more..

  • Page - 430

    402 Chapter 9 Classes 77 register1.add_item(0.95); 78 display(register1); 79 register1.add_item(2.50); 80 display(register1); 81 return 0; 82 } Program run 1 $1.95 2 $2.90 3 $5.40 15.  What is wrong with this implementation of the get_total member function? int get_total() { return total_price; } 16.  Implement the add_items member read more..

  • Page - 431

    9.5 Constructors 403 }; When you compile your code, no error is reported. But now suppose that another program- mer uses your CashRegis ter class in a function void display_all(const CashRegister registers[]) { for (int i = 0; i < NREGISTERS; i++) { registers[i].display(); } } That programmer is conscientious and declares the registers parameter variable as const . But read more..

  • Page - 432

    404 Chapter 9 Classes A constructor is like a set of assembly instructions for an object. The constructor that you just saw has no arguments. Such a constructor is called a default construc tor. It is used whenever you define an object and do not specify any parameters for the construction. For example, if you define CashRegister register1; then the default read more..

  • Page - 433

    9.5 Constructors 405 public: Item(); // Additional member functions omitted private: string description; double price; }; In the Item constructor, you need to set price to 0, but you need not initialize the description data member. It is automatically initialized to the empty string. If you do not supply any constructor for a class, the compiler read more..

  • Page - 434

    406 Chapter 9 Classes public: Item(string item_description, double item_price); // No other constructors ... }; This Order class has a data member of type Item : class Order { public: Order(string customer_name, string item_description, double item_price); ... private: Item article; string customer; }; The Order constructor must call the Item read more..

  • Page - 435

    9.6 problem solving: tracing objects 407 9.6 problem solving: tracing objects You have seen how the technique of hand tracing is useful for understanding how a program works. When your program contains objects, it is useful to adapt the tech- nique so that you gain a better under standing about object data and encapsulation. Use an index card or a sticky note for each read more..

  • Page - 436

    408 Chapter 9 Classes item_count total_price 0 0 1 19.95 2 14.90 item_count total_price 0 0 1 19.95 These diagrams are also useful when you design a class. Suppose you are asked to enhance the CashRegister class to compute the sales tax. Add a function get_sales_tax to the front of the card. Now turn the card over, look over the data members, and ask yourself whether the read more..

  • Page - 437

    9.6 problem solving: tracing objects 409 26.  Trace the following member function calls: Car my_car(25); my_car.add_gas(20); my_car.drive(100); my_car.drive(200); my_car.add_gas(5); 27.  Suppose you are asked to simulate the odometer of the car, by adding a mem ber function get_miles_ driven . Add a data member to the object’s card that is suitable for computing this member function. read more..

  • Page - 438

    410 Chapter 9 Classes this step simpler if they write out member function calls that are applied to a sample object, like this: Menu main_menu; main_menu.add_option("Open new account"); // Add more options int input = main_menu.get_input(); Now we have a specific list of member functions. • void add_option(string option) • int get_input() const What about displaying the read more..

  • Page - 439

    9.6 problem solving: tracing objects 411 private: ... }; Step 4  Determine data members. Ask yourself what information an object needs to store to do its job. Remember, the member functions can be called in any order! The object needs to have enough internal memory to be able to process every member function using just its data members and the member function read more..

  • Page - 440

    412 Chapter 9 Classes } The Menu constructor is a bit odd. We need to construct a menu with no options. A vector is a class, and it has a default constructor. That constructor does exactly what we want, namely to construct an empty vector. Nothing else needs to be done: Menu::Menu() { } If you find that you have trouble with the implementation of some of your read more..

  • Page - 441

    9.6 problem solving: tracing objects 413 int input = main_menu.get_input(); cout << "Input: " << input << endl; return 0; } Program run 1) Open new account 2) Log into existing account 3) Help 4) Quit 5 1) Open new account 2) Log into existing account 3) Help 4) Quit 3 Input: 3 WorkeD exaMple 9.1 implementing a bank account class This read more..

  • Page - 442

    414 Chapter 9 Classes 9.7 problem solving: Discovering Classes When you solve a problem using objects and classes, you need to determine the classes required for the implementation. You may be able to reuse existing classes, or you may need to implement new ones. One simple approach for discovering classes and member functions is to look for the nouns and verbs in the read more..

  • Page - 443

    9.7 problem solving: Discovering Classes 415 figure 4  Class Diagram Quiz Question The aggregation relationship states that objects of one class contain objects of another class. Consider a quiz that is made up of questions. Since each quiz has one or more questions, we say that the class Quiz aggregates the class Question . There is a stan- dard notation, called a UML read more..

  • Page - 444

    416 Chapter 9 Classes 29.  What is the rule of thumb for finding classes? 30.  Your job is to write a program that plays chess. Might ChessBoard be an appropri- ate class? How about MovePiece ? 31.  In an e-mail system, messages are stored in a mailbox. Draw a UML diagram that shows the appro priate aggregation relationship. 32.  You are implementing a system read more..

  • Page - 445

    9.8 separate Compilation 417 figure 6  eliminating parallel Vectors Parallel vectors A vector of objects You can now eliminate the parallel vectors and replace them with a single vector: vector<Item> items; Each slot in the resulting vector corresponds to a slice in the set of parallel vectors (see Figure 6). 9.8 separate Compilation When you write and compile small read more..

  • Page - 446

    418 Chapter 9 Classes The source file contains • Definitions of member functions. • Definitions of nonmember functions. For the CashRegister class, you create a pair of files, cashregister.h and cashregister.cpp , that contain the interface and the implementation, respectively. The header file contains the class definition: ch09/cashregister.h 1 #ifndef CASHREGISTER_H 2 #define read more..

  • Page - 447

    9.8 separate Compilation 419 Note the set of directives that bracket the header file: #ifndef CASHREGISTER_H #define CASHREGISTER_H ... #endif Suppose a file includes two header files: cashregister.h , and another header file that itself includes cashregister.h . The effect of the directives is to skip the file when it is encountered the second time. If we did not have that read more..

  • Page - 448

    420 Chapter 9 Classes Here is a simple test program that puts the CashRegister class to use. Its source file includes the cashreg ister.h header file. ch09/registertest2.cpp 1 #include <iostream> 2 #include <iomanip> 3 #include "cashregister.h" 4 5 using namespace std; 6 7 /** 8 Displays the item count and total price of a cash read more..

  • Page - 449

    9.8 separate Compilation 421 You have just seen the simplest and most common case for designing header and source files. There are a few additional technical details that you should know. • A header file should include all headers that are necessary for defining the class. For example, if a class uses the string class, include the <string> header as well. read more..

  • Page - 450

    422 Chapter 9 Classes 9.9 pointers to objects The following sections discuss how to work with pointers to objects. As you will see in the next chapter, pointers to objects are important when you work with multiple objects from related classes. 9.9.1 Dynamically allocating objects It is common to allocate objects on the heap. As discussed in Section 7.4, you use the new read more..

  • Page - 451

    9.9 pointers to objects 423 The parentheses are necessary because in C++ the dot operator takes precedence over the * operator. The expression without the parentheses would be a compile-time error: *register_pointer.add_item(1.95); // Error—you can’t apply . to a pointer Because the dot operator has higher precedence than * , the dot would be applied to a pointer, not read more..

  • Page - 452

    424 Chapter 9 Classes destructors and resource management A destructor is a special member function that is automatically executed under two circumstances: • At the end of the block in which an object variable is defined • When a heap object is deleted To understand the need for destructors, consider an implementation of a string class, similar to that of the C++ read more..

  • Page - 453

    9.9 pointers to objects 425 figure 9  the Destructor Deallocates heap Memory 1 name = Heap H a r r y String char_array = 2 name = Heap H a r r y String char_array = Removed when object went out of scope Deleted by destructor In addition, one must also supply a “copy constructor” for making safe copies, for example, when passing an object as a function argument. The read more..

  • Page - 454

    426 Chapter 9 Classes understand the concepts of objects and classes. • A class describes a set of objects with the same behavior. • Every class has a public interface: a collection of mem ber functions through which the objects of the class can be manipulated. • Encapsulation is the act of providing a public interface and hiding implementation details. • read more..

  • Page - 455

    Chapter summary 427 formulate the public interface of a class in c++. • A mutator member function changes the object on which it operates. • An accessor member function does not change the object on which it operates. Use const with accessors. choose data members to represent the state of an object. • An object holds data members that are accessed by member functions. read more..

  • Page - 456

    428 Chapter 9 Classes Separate the interface and implementation of a class in header and source files. • The code of complex programs is distributed over multiple files. • Header files contain the definitions of classes and declarations of nonmember functions. • Source files contain function implementations. use pointers to objects and manage dynamically allocated objects. • read more..

  • Page - 457

    review exercises 429 r9.7  What is a member function, and how does it differ from a nonmember function? r9.8  What is a mutator function? What is an accessor function? r9.9  What happens if you forget the const in an accessor function? What happens if you accidentally supply a const in a mutator function? r9.10  What is an implicit parameter? How does it differ from read more..

  • Page - 458

    430 Chapter 9 Classes r9.24  Consider the following problem description: Employees receive their biweekly paychecks. They are paid their hourly rates for each hour worked; however, if they worked more than 40 hours per week, they are paid overtime at 150 percent of their regular wage. What classes should you use to implement it? r9.25  Consider the following problem read more..

  • Page - 459

    programming exercises 431 P9.3  Reimplement the CashRegister class so that it keeps track of the price of each added item in a vector<double> . Remove the item_count and total_price data members. Reim plement the clear , add_item , get_total , and get_count member functions. Add a mem ber function display_all that displays the prices of all items in the current read more..

  • Page - 460

    432 Chapter 9 Classes elements of a class Grade . Supply a constructor that constructs a grade from a string, such as "B+" . You will also need a function that translates grades into their numeric values (for example, "B+" becomes 3.3). P9.13  Define a class Country that stores the name of the country, its population, and its area. Using that read more..

  • Page - 461

    programming exercises 433 blank line sender name Also supply a main function that prints this letter. Dear John: I am sorry we must part. I wish you all the best. Sincerely, Mary Construct an object of the Letter class and call add_line twice. P9.18  Write a class Bug that models a bug moving along a horizontal line. The bug moves either to the right or left. read more..

  • Page - 462

    434 Chapter 9 Classes P9.22  Reimplement the Menu class from How To 9.1 to support submenus similar to the ones in a graphical user interface. A menu contains a sequence of menu items. Each menu item has a name and, option- ally, a submenu. Implement classes Menu and MenuItem . Supply a function to display a menu and get user input. Simply num ber the read more..

  • Page - 463

    programming exercises 435 private: ... }; engineering P9.24  Implement a class Car with the following properties. A car has a certain fuel effi- ciency (measured in miles̸gallon) and a certain amount of fuel in the gas tank. The efficiency is specified in the constructor, and the initial fuel level is 0. Supply a member function drive that simulates driving the car for a certain read more..

  • Page - 464

    436 Chapter 9 Classes Write a C++ program that represents a resistor as a class. Provide a single construc- tor that accepts values for the nominal resistance and tolerance and then determines the actual value randomly. The class should provide public member functions to get the nominal resistance, tolerance, and the actual resistance. Write a main function for the C++ read more..

  • Page - 465

    answers to self-Check Questions 437 For example (using the values from the table as a key), a resistor with red, violet, green, and gold bands (left to right) will have 2 as the first digit, 7 as the second digit, a multiplier of 105, and a tolerance of ±5%, for a resistance of 2,700 k Ω, plus or minus 5%. engineering P9.29  The figure below shows a frequently used electric read more..

  • Page - 466

    438 Chapter 9 Classes 9.  A mutator. Getting a character removes it from the stream, thereby modifying it. Not convinced? Consider what happens if you call the get function twice. You will usually get two different characters. But if you call an accessor twice on an object (without a mutation between the two calls), you are sure to get the same result. 10.  2 read more..

  • Page - 467

    answers to self-Check Questions 439 25.  Car my_car Car(mpg) add_gas(amount) drive(distance) get_gas_left gas_left miles_per_gallon 0 25 front back 26.  gas_left miles_per_gallon 0 20 16 8 13 25 27.  gas_left miles_per_gallon 0 25 total_miles 0 28.  gas_left miles_per_gallon 0 20 16 8 13 25 total_miles 0 100 200 29.  Look for nouns in the problem description. 30.  Yes (ChessBoard) and no (MovePiece). read more..

  • Page - 468

    440 Chapter 9 Classes who had checked out a particular book (perhaps to notify the patron to return it because it was requested by someone else), then you can argue that the aggregation should go the other way around. 33.  There would be no relationship. 34.  The header file that defines the BankAccount class, probably named bankaccount.h . 35.  None. The read more..

  • Page - 469

    10 Chapter 441 Inher I ta n C e to understand the concepts of inheritance and polymorphism to learn how to inherit and override member functions to be able to implement constructors for derived classes to be able to design and use virtual functions Chapter Goals Chapter Contents 10.1  InherItance hIerarchIes  442 10.2  ImplementIng DerIveD  classes  446 Syntax 10.1: read more..

  • Page - 470

    442 objects from related classes usually share common behavior. For example, shovels, rakes, and clippers all perform gardening tasks. In this chapter, you will learn how the notion of inheritance expresses the relationship between specialized and general classes. By using inheritance, you will be able to share code between classes and provide services that can be used by multiple read more..

  • Page - 471

    10.1 Inheritance hierarchies 443 Figure 2  the Inheritance hierarchy of stream Classes istringstream ifstream iostream fstream istream ostream ofstream ostringstream The inheritance relationship can give rise to hierarchies where classes get ever more specialized, as shown in Figure 1. The C++ stream classes, shown in Figure 2, are another example of such a hierarchy. Figure 2 uses the read more..

  • Page - 472

    444 Chapter 10 Inheritance Figure 3  Inheritance hierarchy of Question types Choice Question FillIn Question Numeric Question FreeResponse Question MultiChoice Question Question At the root of this hierarchy is the Question type. A question can dis play its text, and it can check whether a given response is a correct answer: class Question { public: Question(); void read more..

  • Page - 473

    10.1 Inheritance hierarchies 445 4 5 using namespace std; 6 7 class Question 8 { 9 public: 10 /** 11 Constructs a question with empty text and answer. 12 */ 13 Question(); 14 15 /** 16 @param question_text the text of this question 17 */ 18 void set_text(string question_text); 19 read more..

  • Page - 474

    446 Chapter 10 Inheritance 64 65 int main() 66 { 67 string response; 68 cout << boolalpha; // Show Boolean values as true, false 69 70 Question q1; 71 q1.set_text("Who was the inventor of C++?"); 72 q1.set_answer("Bjarne Stroustrup"); 73 74 q1.display(); 75 cout << "Your answer: "; 76 read more..

  • Page - 475

    10.2 Implementing Derived Classes 447 Like the manufacturer of a stretch limo, who starts with a regular car and modifies it, a programmer makes a derived class by modifying another class. The : symbol denotes inheritance. The reserved word public is required for a techni- cal reason (see Common Error 10.1 on page 449). A ChoiceQuestion object differs from a read more..

  • Page - 476

    448 Chapter 10 Inheritance syntax 10.1 Derived-Class Definition class ChoiceQuestion : public Question { public: ChoiceQuestion(); void add_choice(string choice, bool correct); void display() const; private: vector<string> choices; }; Derived class Base class The : symbol denotes inheritance. Declare functions that are added to the derived class. Define data members read more..

  • Page - 477

    10.2 Implementing Derived Classes 449 a member function on the implicit parameter, you don’t specify the parameter but just write the member function name: set_answer(num_str); The compiler interprets this call as implicit parameter.set_answer(num_str); 6.  Suppose q is an object of the class Question and cq an object of the class Choice­ Question . Which of the following read more..

  • Page - 478

    450 Chapter 10 Inheritance ChoiceQuestion q; ... cout << q.check_answer(response); // Error } This private inheritance is rarely useful. In fact, it violates the spirit of using inheritance in the first place—namely, to create objects that are usable just like the base-class objects. You should always use public inheritance and remember to supply the read more..

  • Page - 479

    10.3 overriding Member Functions 451 other cars when it comes to driving and refueling. They just have a better fuel efficiency. A single Car class with a data member double miles_per_gallon; is entirely sufficient. However, if you write a program that shows how to repair different kinds of vehicles, then it makes sense to have a separate class HybridCar . When it read more..

  • Page - 480

    452 Chapter 10 Inheritance Consider the display function of the ChoiceQuestion class. It needs to override the base-class display function in order to show the choices for the answer. Specifically, the derived-class function needs to • Display the question text. • Display the answer choices. The second part is easy because the answer choices are a data member of read more..

  • Page - 481

    10.3 overriding Member Functions 453 ch10/quiz2/test.cpp  1 #include <iostream> 2 #include <sstream> 3 #include <vector> 4 #include "question.h" 5 6 class ChoiceQuestion : public Question 7 { 8 public: 9 /** 10 Constructs a choice question with no choices. 11 */ 12 ChoiceQuestion(); 13 14 /** 15 read more..

  • Page - 482

    454 Chapter 10 Inheritance 59 // Ask a basic question 60 61 Question q1; 62 q1.set_text("Who was the inventor of C++?"); 63 q1.set_answer("Bjarne Stroustrup"); 64 65 q1.display(); 66 cout << "Your answer: "; 67 getline(cin, response); 68 cout << q1.check_answer(response) << endl; 69 read more..

  • Page - 483

    10.4 Virtual Functions and polymorphism 455 cout << i + 1 << ": " << choices[i] << endl; } } 13.  Look again at the implementation of the add_choice function that calls the set_answer function of the base class. Why don’t you need to call Question:: set_answer ? 14.  In the Manager class of Self Check 9, override read more..

  • Page - 484

    456 Chapter 10 Inheritance 10.4.1 the slicing problem In this section, we will discuss a problem that commonly arises when you work with a collection of objects that belong to different classes in a class hierarchy. If you look into the main function of quiz2/test.cpp , you will find that there was some repetitive code to display each question and check the read more..

  • Page - 485

    10.4 Virtual Functions and polymorphism 457 Instead, you need to store the actual objects elsewhere and collect their locations in an array by storing pointers. We will discuss the use of pointers in the next section. 10.4.2 pointers to Base and Derived Classes To access objects from different classes in a class hierarchy, use pointers. Pointers to the various objects all read more..

  • Page - 486

    458 Chapter 10 Inheritance 10.4.3 Virtual Functions When you collect objects of different classes in a class hierarchy, and then invoke a member function, you want the appropriate member function to be applied. For example, when you call the display member function on a Question* pointer that hap- pens to point to a ChoiceQuestion , you want the choices to be dis read more..

  • Page - 487

    10.4 Virtual Functions and polymorphism 459 10.4.4 In the same way that vehicles can differ in their method of locomotion, polymorphic objects carry out tasks in different ways. polymorphism The quiz array collects a mixture of both kinds of questions. Such a collection is called polymorphic (liter ally, “of multiple shapes”). Objects in a polymorphic collection read more..

  • Page - 488

    460 Chapter 10 Inheritance 16 /** 17 @param question_text the text of this question 18 */ 19 void set_text(string question_text); 20 21 /** 22 @param correct_response the answer for this question 23 */ 24 void set_answer(string correct_response); 25 26 /** 27 @param read more..

  • Page - 489

    10.4 Virtual Functions and polymorphism 461 ch10/quiz3/test.cpp 1 #include <iostream> 2 #include "question.h" 3 #include "choicequestion.h" 4 5 int main() 6 { 7 string response; 8 cout << boolalpha; 9 10 // Make a quiz with two questions 11 const int QUIZZES = 2; 12 Question* quiz[QUIZZES]; 13 read more..

  • Page - 490

    462 Chapter 10 Inheritance 19.  What is displayed as the result of the following statements? ChoiceQuestion* p = new ChoiceQuestion; p­>set_text("What is the answer?"); p­>add_choice("42", true); p­>add_choice("Something else", false); Question q = *p; q.display(); 20.  Suppose check_answer was not declared virtual in question.h . How would the behavior of read more..

  • Page - 491

    10.4 Virtual Functions and polymorphism 463 q.display(); cout << "Your answer: "; getline(cin, response); cout << q.check_answer(response) << endl; } If you call this function with a ChoiceQuestion object, then the parameter variable q is initialized with a copy of that object. But q is a Question object; the derived-class information read more..

  • Page - 492

    464 Chapter 10 Inheritance step 1  List the classes that are part of the hierarchy. In our case, the problem description yields two classes: SavingsAccount and Checking Account . To express the common ality between them, we will introduce a class BankAccount . step 2  Organize the classes into an inheritance hierarchy. Draw a UML diagram that shows base and derived read more..

  • Page - 493

    10.4 Virtual Functions and polymorphism 465 step 1  List the classes that are part of the hierarchy. In our case, the problem description yields two classes: SavingsAccount and Checking Account . To express the common ality between them, we will introduce a class BankAccount . step 2  Organize the classes into an inheritance hierarchy. Draw a UML diagram that shows base read more..

  • Page - 494

    466 Chapter 10 Inheritance public: /** Constructs a checking account with a zero balance. */ CheckingAccount(); virtual void withdraw(double amount); virtual void month_end(); private: ... }; step 6  Identify data members. List the data members for each class. If you find a data member that is common to all classes, be sure read more..

  • Page - 495

    10.4 Virtual Functions and polymorphism 467 double BankAccount::get_balance() const { return balance; } At the level of the BankAccount base class, we can say nothing about end of month processing. We choose to make that function do nothing: void BankAccount::month_end() { } In the withdraw member function of the SavingsAccount class, the minimum balance is updated. Note read more..

  • Page - 496

    468 Chapter 10 Inheritance In our sample program, we allocate 5 checking accounts and 5 savings accounts and store their addresses in an array of bank account pointers. Then we accept user commands and exe- cute deposits, withdrawals, and monthly processing. int main() { cout << fixed << setprecision(2); // Create accounts const int ACCOUNTS_SIZE = read more..

  • Page - 497

    10.4 Virtual Functions and polymorphism 469 WorkeD exaMple 10.1 Implementing an employee  hierarchy for payroll processing This Worked Example shows how to implement payroll pro cessing that works for different kinds of employees. have you ever won- dered how your instr uc tor or grader makes sure your programming homework is correct? In all likelihood, they look at your read more..

  • Page - 498

    470 Chapter 10 Inheritance explain the notions of inheritance, base class, and derived class. • A derived class inherits data and behavior from a base class. • You can always use a derived-class object in place of a base-class object. When K gets the answer from H that R halts when applied to itself, it is programmed to enter an infinite loop. otherwise K read more..

  • Page - 499

    review exercises 471 Implement derived classes in c++. • A derived class can override a base-class function by providing a new implementation. • The derived class inherits all data members and all functions that it does not override. • Unless specified otherwise, the base-class data members are initialized with the default construc tor. • The constructor of a derived class read more..

  • Page - 500

    472 Chapter 10 Inheritance r10.2  An object-oriented traffic simulation system has the following classes: Vehicle PickupTruck Car SportUtilityVehicle Truck Minivan Sedan Bicycle Coupe Motorcycle Draw a UML diagram that shows the inheritance relationships between these classes. r10.3  What inheritance relationships would you establish among the following classes? Student Professor Employee read more..

  • Page - 501

    review exercises 473 r10.12  What does the following program print? class B { public: void print(int n) const; }; void B::print(int n) const { cout << n << endl; } class D : public B { public: void print(int n) const; }; void D::print(int n) const { if (n <= 1) { B::print(n); } else if (n % 2 == 0) { print(n / 2); } else read more..

  • Page - 502

    474 Chapter 10 Inheritance d. x = new Sub(); e. *x = *y; f.  *y = *x; r10.15  What does the program print? Explain your answers by tracing the flow of each call. class B { public: B(); virtual void p() const; void q() const; }; B::B() {} void B::p() const { cout << "B::p\n"; } void B::q() const { cout << "B::q\n"; } class read more..

  • Page - 503

    programming exercises 475 p10.1  Add a class NumericQuestion to the question hierarchy of Section 10.1. If the response and the expected answer differ by no more than 0.01, then accept it as correct. p10.2  Add a class FillInQuestion to the question hierarchy of Section 10.1. Such a question is constructed with a string that contains the answer, surrounded by _ _ , read more..

  • Page - 504

    476 Chapter 10 Inheritance p10.12  Implement a base class Appointment and derived classes Onetime , Daily , Weekly , and Monthly . An appointment has a description (for example, “see the dentist”) and a date and time. Write a virtual function occurs_on(int year, int month, int day) that checks whether the appointment occurs on that date. For example, for a monthly read more..

  • Page - 505

    programming exercises 477 the inverting amplifier is given by g R R =− 2 1 . Similarly the gains of the noninverting amplifier and voltage divider amplifier are given by g R R =+ 1 2 1 and g R RR = + 2 12 , respectively. – + – + – + R 2 R 1 R 1 vi R 2 R 1 R 2 vo vo vi vi vo vo vi (a) Amplifier (b) Inverting amplifier (c) Noninverting amplifier (d) Voltage divider read more..

  • Page - 506

    478 Chapter 10 Inheritance Two simple resonant circuits are shown in the figure below. The circuit in (a) is called a parallel resonant circuit. The circuit in (b) is called a series resonant circuit. Both resonant circuits consist of a resistor having resistance R, a capacitor having capacitance C, and an inductor having inductance L. RL C C L R (a) Parallel resonant read more..

  • Page - 507

    answers to self-Check Questions 479 1.  Because every manager is an employee but not the other way around, the Manager class is more specialized. It is the derived class, and Employee is the base class. 2.  CheckingAccount and SavingsAccount both inherit from the more general class BankAc count . 3.  istream , istringstream , ifstream , iostream , fstream 4.  Vehicle , read more..

  • Page - 508

    This page intentionally left blank read more..

  • Page - 509

    A A P P E N D I X 481 C + + L A N g u A g E C o D I N g g u I D E L I N E s Introduction This coding style guide is a simplified version of one that has been used with good success both in industrial practice and for college courses. It lays down rules that you must follow for your programming assignments. A style guide is a set read more..

  • Page - 510

    482 Appendix A C++ Language Coding guidelines source Files Each program is a collection of one or more files or modules. The executable pro gram is obtained by compiling and linking these files. Organize the material in each file as follows: • Header comments • #include statements • Constants • Classes • Functions It is common to start each file with read more..

  • Page - 511

    Appendix A C++ Language Coding guidelines 483 Functions Supply a comment of the following form for every function. /** Explanation. @param parameter variable1 explanation @param parameter variable2 explanation ... @return explanation */ The introductory explanation is required for all functions except main . It should start with an uppercase read more..

  • Page - 512

    484 Appendix A C++ Language Coding guidelines Local Variables Do not define all local variables at the beginning of a block. Define each variable just before it is used for the first time. Every variable must be either explicitly initialized when defined or set in the immediately following statement (for example, through a >> instruction). int pennies = 0; or int read more..

  • Page - 513

    Appendix A C++ Language Coding guidelines 485 Make a constant const int DAYS_PER_YEAR = 365; so that you can easily produce a Martian version without trying to find all the 365’s, 364’s, 366’s, 367’s, and so on in your code. Classes Lay out the items of a class as follows: class ClassName { public: constructors mutators accessors private: read more..

  • Page - 514

    486 Appendix A C++ Language Coding guidelines Nonlinear Control Flow Don’t use the switch statement. Use if /else instead. Do not use the break , continue , or goto statement. Use a bool variable to control the execution flow. Lexical Issues Naming Conventions The following rules specify when to use upper­ and lowercase letters in identifier names. 1. All variable read more..

  • Page - 515

    Appendix A C++ Language Coding guidelines 487 Braces Opening and closing braces must line up, either horizontally or vertically. while (i < n) { cout << a[i] << endl; i++; } // OK while (i < n) { cout << a[i] << endl; i++; } // OK Some programmers don’t line up vertical braces but place the { behind the while : while (i < n) read more..

  • Page - 516

    This page intentionally left blank read more..

  • Page - 517

    B A P P E N D I X 489 R E s E Rv E D W o R D s u m m A Ry Reserved Word Description Reference Location bool The Boolean type Section 3.7 break Break out of a loop or switch Special Topic 3.3, 4.2 case A label in a switch statement Special Topic 3.3 char The character type Section 7.3 class Definition of a class Section 9.2 const Definition of a constant read more..

  • Page - 518

    490 Appendix B Reserved Word summary The following reserved words are not covered in this book: Reserved Word Description Reference Location public Features of a class that can be accessed by all functions Section 9.2 return Returns a value from a function Section 5.4 short A modifier for the int type that indicates that the type may have fewer bytes Special Topic 2.1 read more..

  • Page - 519

    C A P P E N D I X 491 O P E r At O r S u m m A ry The operators are listed in groups of decreasing precedence in the table below. The horizontal lines in the table indicate a change in operator prece dence. For example, z = x - y; means z = (x - y); because = has a lower precedence than - . The prefix unary operators and the read more..

  • Page - 520

    492 Appendix C Operator Summary Operator Description reference Location .* Access pointer to member not covered ->* Dereference and access pointer to member not covered * Multiplication Section 2.2.1 / Division or integer division Section 2.2.1, Section 2.2.3 % Integer remainder Section 2.2.3 + Addition Section 2.2.1 - Subtraction Section 2.2.1 << Output Section 1.5, Section 2.3.2, read more..

  • Page - 521

    D A P P E N D I X 493 C h A r A C t E r C o D E s These escape sequences can occur in strings (for example, "\n") and characters (for example, '\''). Escape sequence Description \n Newline \r Carriage return \t Tab \v Vertical tab \b Backspace \f Form feed \a Alert \\ Backslash \" Double quote \' Single quote \? Question mark \xh1h2 Code specified in read more..

  • Page - 522

    494 Appendix D Character Codes table 1 AsCII Code table Dec. Code hex Code Char- acter Dec. Code hex Code Char- acter Dec. Code hex Code Char- acter Dec. Code hex Code Char- acter 0 00 \0 32 20 Space 64 40 @ 96 60 ‘ 1 01 33 21 ! 65 41 A 97 61 a 2 02 34 22 " 66 42 B 98 62 b 3 03 35 23 # 67 43 C 99 63 c 4 04 36 24 $ 68 44 D 100 64 d 5 05 37 25 % 69 45 E 101 65 e 6 read more..

  • Page - 523

    E A P P E N D I X 495 C + + L I b r A ry S u m m A ry Standard Code Libraries <cmath> • double sqrt(double x) Function:Squareroot, x • double pow(double x, double y) Function:Power,xy.Ifx>0,ycanbeanyvalue.Ifxis0,ymustbe>0. Ifx<0,ymustbeaninteger. • double sin(double x) Function:Sine,sinx(xinradians) • double cos(double x) Function:Cosine,cosx(xinradians) • double read more..

  • Page - 524

    496 Appendix E C++ Library Summary • char isalnum(char c) Function:Testwhethercisaletteroranumber. • bool isdigit(char c) Function:Testswhethercisadigit. • bool isspace(char c) Function:Testswhetherciswhitespace. • bool islower(char c) Function:Testswhethercislowercase. • bool isupper(char c) Function:Testswhethercisuppercase. • char tolower(char c) Function:Returnsthelowercaseofc. • char toupper(char c) read more..

  • Page - 525

    Appendix E C++ Library Summary 497 • left, right Manipulator:Left-orright-justifiesvaluesiftheyareshorterthanthefieldwidth. • scientific Manipulator:Selectsscientificfloating-pointformat,suchas1.729000e+03. • setfill(char c) Manipulator:Setsthefillcharactertothecharacterc. • setprecision(int n) Manipulator:Setstheprecisionoffloating-pointvaluestondigitsafterthe decimalpointinfixedandscientificformats. • setw(int n) read more..

  • Page - 526

    498 Appendix E C++ Library Summary Class fstream • void fstream::open(const char n[]) Function:Opensafilewithnamenforreadingandwriting. Class fstreambase • void fstreambase::close() Function:Closesthefilestream. Notes: • fstreambase isthecommonbaseclassofifstream,ofstream,andfstream. • Toopenabinaryfilebothforinputandoutput,usef.open(n, ios::in | ios::out | ios::binary) <strstream> Class istringstream read more..

  • Page - 527

    499 Glossary Accessor function  A function that accesses an object but does not change it. Address  A value that specifies the location of a variable in memory. Aggregation relationship The “has-a” relationship between classes. Algorithm   An unambiguous, executable, and terminating specification to solve a  problem. ANSI/ISO C++ Standard   read more..

  • Page - 528

    500   Glossary break statement  A statement that terminates a loop or switch statement. Byte  A number between 0 and 255 (eight bits). Essentially all currently manufactured  computers use a byte as the smallest unit of storage in memory. Capacity   The number of values that a data structure such as an array can potentially  read more..

  • Page - 529

     Glossary  501 delete operator   The operator that recycles memory to the heap. Derived class  A class that modifies a base class by adding data members, adding  member functions, or redefining member functions. Directory  A structure on a disk that can hold files or other directories; also called a  folder. Dot notation   read more..

  • Page - 530

    502   Glossary IDE (Integrated Development Environment)  A programming environment that  includes an editor, compiler, and debugger. Implicit parameter The object on which a member function is called. For example,  in the call x.f(y), the object x is the implicit parameter of f. #include directive   An instruction to the preprocessor to include a header file. Index   read more..

  • Page - 531

     Glossary  503 Memory leak   Memory that is dynamically allocated but never returned to the heap  manager. A succession of memory leaks can cause the heap manager to run out of  memory. Modulus operator   The % operator that yields the remainder of an integer division. Mutator function  A member function that changes the state of an object. Nested block read more..

  • Page - 532

    504   Glossary Random access   The ability to access any value directly without having to read the  values preceding it. Recursive function  A  function  that  can  call  itself  with  simpler  values.  It  must  han dle the simplest values without calling itself.  Reference parameter  A parameter that is bound to a variable supplied in the call.  read more..

  • Page - 533

     Glossary  505 Syntax error   An instruction that does not follow the programming language rules  and is rejected by the compiler. Tab character   The '\t' character, which advances the next character on the line to  the next one of a set of fixed screen positions known as tab stops. Test coverage   read more..

  • Page - 534

    This page intentionally left blank read more..

  • Page - 535

    507 I n d e x Symbols ( ) (parentheses) order of arithmetic operations, 40 unbalanced, 42 & (ampersand) address operator, 309 reference parameter indicator, 222, 266 -> (arrow operator), 337, 422–423 * (asterisk) indirection operator, 309 multiplication operator, 40, 105t \ (backslash) displaying as a literal, 14 escape sequence, 14, 493t && (Boolean AND) confusing with read more..

  • Page - 536

    508   Index _ (underscore), in variable names, 33 [ ] operator accessing array elements, 252 accessing individual string characters, 322–323 ; (semicolon) in class definitions, 395 ending C++ statements, 13 in if statements, 80 omitting, 14 \0 , null terminator, 321 A \a (alert escape sequence), 493t abs function, 43t, 495 absolute path names, embedding, 482 absolute values, read more..

  • Page - 537

     Index  509 arithmetic, with loops averaging values, 157–158 comparing adjacent values, 160–161 counting items, 158 finding the first item, 159 maximum/minimum values, finding, 159–160 summing values, 157–158 arithmetic conversions casts, 46 floating-point to integer, 41 arithmetic operators absolute values, calculating, 43t addition, 40 cosines, calculating, 43t decimal log values, calculating, 43t read more..

  • Page - 538

    510   Index arrays, using with pointers (continued) pointer arithmetic, 315 returning a pointer to a local variable, 319 simulating a Galton board, 329–332 stepping through arrays, 318 arrow operator (->), 337, 422–423 artificial intelligence, 112–113 ASCII codes, 494t assignment = (equal sign), assignment operator, 34–35 combining with arithmetic, 47 asterisk (*) indirection operator, 309 read more..

  • Page - 539

     Index  511 style guide. See coding guidelines syntax, 12 C strings \0 , null terminator, 321 atoi function, 322 converting characters to integers, 322 converting to/from C++, 322 definition, 320–321 functions for, 323–324 length, determining, 321 manipulating directly, 323–324 strlen function, 321 terminating, 321 caesar.cpp (ch08), 366–367 calling constructors, 405 functions, 194, read more..

  • Page - 540

    512   Index code libraries, <ctime> time function, 496 code libraries, <fstream> close function, 498 fstream class, 498 fstreambase class, 498 ifstream class, 497 ofstream class, 497 open function, 497–498 code libraries, <iomanip> boolalpha manipulator, 496 fixed manipulator, 496 left manipulator, 497 right manipulator, 497 scientific manipulator, 497 setfill read more..

  • Page - 541

     Index  513 in source files, 482 companion variables, arrays, 253–254 comparisons adjacent values, with loops, 160–161 arithmetic. See arithmetic operators logical. See Boolean operations true/false. See Boolean operations comparisons, if statements case sensitivity, 86 floating-point numbers, 86 lexicographic order of strings, 86–87 numbers, 82–85 numbers vs. letters, 87 punctuation marks, read more..

  • Page - 542

    514   Index converting case, 322–323, 496 characters to integers, 322 numbers to words, 211–215 strings between C and C++, 322 copy constructors, 425 copy protection schemes, 172 copying arrays, 256 vectors, 288 cos function, 43t, 495 cosines, calculating, 43t counting items with loops, 158 loop iterations, 147–148 cout (<<) displaying to the screen, 12 ending displayed output, read more..

  • Page - 543

     Index  515 dereferencing operator. See indirection operator (*) derived classes : (colon), denoting inheritance, 447 defining, 446–449 definition, 442 inheriting from base classes, 451–455 overriding base classes, 448 overriding member functions, 451–455 private inheritance, 449–450 public reserved word, 447, 449–450 replicating base-class members, 450 syntax, 448 dice.cpp (ch04), 170 die read more..

  • Page - 544

    516   Index exponentiation. See powers, calculating extraction operator (>>) assigning values to variables, 48 reading input from a screen, 48 reading numbers from binary files, 373 reading strings from the console, 58 F \f (form feed escape sequence), 493t fabs function, 495 fail function description, 497 file stream input, 353–354 if statements, 110 failure state, clearing, read more..

  • Page - 545

     Index  517 flowcharts. See also storyboards common symbols, 99 debugging with, 99–101 do loops, 149 if statements, 77 loops, 149 for loops, 145 mapping multiple choices, 99 reusing tasks, 100–101 “spaghetti code,” avoiding, 100–101 while loops, 133, 149 folders, 9–10. See also directories for , reserved word, 489t for loops counting iterations, 147–148 description, read more..

  • Page - 546

    518   Index getline function, 359–361, 496 global variables, 219–220 goto statements, coding guidelines, 486 GPL (General Public License), 426 greater than (>), relational operator, 83t, 105t greater than or equal (>=), relational operator, 83t, 105t guidelines for coding. See coding guidelines H hand-tracing functions, 216–217 if statements, 97–98 while loops, 139–142 hanging read more..

  • Page - 547

     Index  519 defining, 446–449 definition, 442 inheriting from base classes, 451–455 overriding base classes, 448 overriding member functions, 451–455 private inheritance, 449–450 public reserved word, 447, 449–450 replicating base-class members, 450 syntax, 448 inheritance, hierarchies developing, 464–468 overview, 442–446 inheritance, virtual functions base classes, pointers to, 457 definition, read more..

  • Page - 548

    520   Index length C strings, determining, 321 strings, determining, 58–60 length function, 58–60, 496 less than (<), relational operator, 83t, 105t less than or equal (<=), relational operator, 83t, 105t lexical issues, coding guidelines. See coding guidelines, lexical issues libraries, integrated development environment, 9. See also code libraries licenses, software, 426 limits of read more..

  • Page - 549

     Index  521 minimum/maximum values, finding with loops, 159–160 minus sign (-) subtraction operator, 40, 105t unary negative operator, 105t unary operator, spaces in, 46 minus signs (--), decrement operator, 40, 105t missing break statements, 93 <cmath> header, 45 function return values, 203 header files, 45 main function, 16 modifying parameter variables, 201 strings, 321–322 read more..

  • Page - 550

    522   Index operators (continued) overloading, 406 OR operator (||) confusing with && (AND), 107 description, 105t inverting, 108 short-circuit evaluation, 108 order of class definitions, coding guidelines, 482 ostream class, 497 ostream variable, 352 ostringstream class, 363–365, 498 output. See also file streams; string streams definition, 4 displaying to the screen, 12, 15 read more..

  • Page - 551

     Index  523 pointers & , address operator, 309 to base classes from virtual functions, 457 dangling, 328 defining, 308–309 defining multiple variables, 313 definition, 308 to derived classes from virtual functions, 457 drawing pictures of, 332–335 initializing, 311–313 NULL , 312 simulating a Galton board, 329–332 syntax, 310 translating from reference parameters, 314 uninitialized, read more..

  • Page - 552

    524   Index public (continued) keys, 368 member functions, 402 public , reserved word, 490t public interface class definition syntax, 392–395 definition, 391 documenting, 410–411 specifying, 392–395, 409–410 public reserved word, derived classes, 447, 449–450 punctuation marks, if statement comparisons, 87 push_back function, 286, 288–289, 498 pyramids, volume calculation, 204–205 Q read more..

  • Page - 553

     Index  525 reusing functions, 208–210 variable names, 218–219 Richter scale, 90t Richter scale program, 90–92 right manipulator, 361, 497 Rivest, Ron, 368 roots, calculating, 41–43 rounding floating-point numbers, 41 roundoff errors, 45–46, 86 rows in two-dimensional arrays, summing, 280 RSA encryption, 368 S safe copies, 425 sample programs. See applications scientific manipulator, read more..

  • Page - 554

    526   Index string streams (continued) converting integers to strings, 364 converting strings to integers, 364 interface, adapting strings to, 363 istringstream class, 363–365 ostringstream class, 363–365 reading individual characters, 363 str function, 363–365 strings + (plus sign), concatenation operator, 57 case conversion, 322–323 char type, 320 character arrays, 321–322 comparing, read more..

  • Page - 555

     Index  527 troubleshooting. See debugging; error mes- sages; errors; exceptions true , reserved word, 103–106, 490t truncation, int number type, 39 truth tables, Boolean operations, 104 Turing, Alan, 469–470 Turing machines, 469–470 type tags vs. virtual functions, 462 U unbalanced parentheses, 42 “undefined symbol” message, 16 undefined variables, 37 underscore (_), in variable read more..

  • Page - 556

    528   Index viruses, 255 VisiCalc spreadsheets, 230–231 void , reserved word, 403, 490t void type, function return values, 206–207 volume calculations bottles, 30–51 cans, 30–51 cubes, 196–198, 204 pyramids, 204–205 soft drink containers, 30–51 volume1.cpp (ch02), 36 volume2.cpp (ch02), 50 volumes.h (ch09), 421 voting machines, electronic, 412–413 W while , reserved word, 490t read more..

  • Page - 557

    529 Credits text Credits Exercises P2.25, P5.32, P5.34: Adapted from MATLAB: An Introduction with Applications, Third Edition, Amos Gilat (John Wiley & Sons, Inc., 2008) Reprinted with per- mission of John Wiley & Sons, Inc. P4.28, P4.30: Adapted from Introduction to Engineering Programming: Solving Problems with Algorithms, James P. Holloway (John Wiley & Sons, Inc., 2004) Reprinted with read more..

  • Page - 558

    530 Credits Page 49, 62: Rich Koele/iStockphoto. Page 53: Courtesy NASA/JPL-Caltech. Page 54: Photos.com/Jupiter Images. Page 56, 62: jason walton/iStockphoto. Page 59, 63: Rich Legg/iStockphoto. Page 61 (left): Paul Vachier/iStockphoto. Page 61 (top right): Joel Carllet/iStockphoto. Page 61 (bottom right): iStockphoto. Page 65: Thomas Stange/iStockphoto. Page 67: iStockphoto. Page 68: Steve read more..

  • Page - 559

    Credits 531 Chapter4 Page 131, 132 (top): iStockphoto. Page 132 (middle): Jarek Szymanski/iStockphoto. Page 132 (bottom), 173: Maco Maccarini/iStockphoto. Page 137 (top): ohiophoto/iStockphoto. Page 137 (bottom): Karen Town/iStockphoto. Page 138: Naval Surface Weapons Center, Dahlgren, VA. Pages 139–141 (paperclip): Yvan Dubé/iStockphoto. Page 143, 173: Enrico Fianchini/iStockphoto. Page 148: read more..

  • Page - 560

    532 Credits Page 217: iStockphoto. Page 218 (top): paul kline/iStockphoto. Page 218 (collage), 233: Joan Champ/iStockphoto (Railway and Main); Steven Johnson/iStockphoto (Main and N. Putnam); Jeffrey Smith/iStockphoto (Main and South St.). Page 222: Winston Davidian/iStockphoto. Page 226: Janice Richard/iStockphoto. Page 227, 233: Nicolae Popovici/iStockphoto. Page 231: Reprint Courtesy of read more..

  • Page - 561

    Credits 533 Page 359, 378: Getty Images. Page 361, 378: iStockphoto. Page 363, 378: iStockphoto. Page 366, 378: iStockphoto. Page 368: Anna Khomulo/iStockphoto. Page 369: Oksana Perkins/iStockphoto. Page 373, 378: iStockphoto. Page 374: Cay Horstmann. Page 383, 384: Cay Horstmann. Page 386: Chris Dascher/iStockphoto. Chapter9 Page 389, 390 (top): Stephanie Strathdee/iStockphoto. Page 390 (bottom), read more..

  • Page - 562

    534 Credits Chapter 13 Chapter Opener: andrea laurita/iStockphoto. Stacks and Queues: Photodisc/Punchstock. Random Fact 13.1: Courtesy of Nigel Tout. Chapter 14 Chapter Opener: nicholas belton/iStockphoto. Icons Common Error icon: Scott Harms/iStockphoto. How To icon: Steve Simzer/iStockphoto. Paperclip: Yvan Dubé/iStockphoto. Programming Tip icon: Macdaddy/Dreamstime.com. Random Fact icon: read more..

Write Your Review