Starting Out With C Early Objects 9th Global
Edition Gaddis download
https://ebookbell.com/product/starting-out-with-c-early-
objects-9th-global-edition-gaddis-21355086
Explore and download more ebooks at ebookbell.com
Here are some recommended products that we believe you will be
interested in. You can click the link to download.
Starting Out With C Early Objects 7th Edition 7th Edition Tony Gaddis
https://ebookbell.com/product/starting-out-with-c-early-objects-7th-
edition-7th-edition-tony-gaddis-2451550
Starting Out With C Early Objects Formerly Alternate Edition 5th
Edition Tony Gaddis Godfrey Muganda Judy Walters
https://ebookbell.com/product/starting-out-with-c-early-objects-
formerly-alternate-edition-5th-edition-tony-gaddis-godfrey-muganda-
judy-walters-36151162
Starting Out With C Early Objects 8th Edition Tony Gaddis
https://ebookbell.com/product/starting-out-with-c-early-objects-8th-
edition-tony-gaddis-5033276
Starting Out With C Early Objects 10th Edition 10th Edition Tony
Gaddis
https://ebookbell.com/product/starting-out-with-c-early-objects-10th-
edition-10th-edition-tony-gaddis-11263868
Starting Out With C Early Objects 10e Tony Gaddis Judy Walters Godfrey
Muganda Gaddis
https://ebookbell.com/product/starting-out-with-c-early-
objects-10e-tony-gaddis-judy-walters-godfrey-muganda-gaddis-23503670
Starting Out With C Early Objects Tony Gaddis Judy Walters Godfrey
Muganda
https://ebookbell.com/product/starting-out-with-c-early-objects-tony-
gaddis-judy-walters-godfrey-muganda-32222180
Starting Out With C Early Objects 9e Tony Gaddis Judy Walters Godfrey
Muganda
https://ebookbell.com/product/starting-out-with-c-early-
objects-9e-tony-gaddis-judy-walters-godfrey-muganda-12078022
Starting Out With C From Control Structures Through Objects 8th
Edition Gaddis
https://ebookbell.com/product/starting-out-with-c-from-control-
structures-through-objects-8th-edition-gaddis-21347298
Starting Out With C From Control Structures Through Objects Brief
Version Gaddis
https://ebookbell.com/product/starting-out-with-c-from-control-
structures-through-objects-brief-version-gaddis-21973200
Global
edition
Starting Out With C++
Early Objects
ninTH edition
Tony Gaddis • Judy Walters • Godfrey Muganda
LOCATION OF VIDEONOTES IN THE TEXT
Chapter 1 Designing a Program with Pseudocode, p. 54
Designing the Account Balance Program, p. 59
Predicting the Output of Problem 30, p. 59
Solving the Candy Bar Sales Problem, p. 60
Chapter 2 Using cout to Display Output, p. 66
Assignment Statements, p. 93
Arithmetic Operators, p. 96
Solving the Restaurant Bill Problem, p. 108
Chapter 3 Using cin to Read Input, p. 111
Evaluating Mathematical Expressions, p. 118
Combined Assignment Operators, p. 136
Solving the Stadium Seating Problem, p. 182
Chapter 4 Using an if Statement, p. 195
Using an if/else Statement, p. 204
Using an if/else if Statement, p. 210
Using Logical Operators, p. 223
Solving the Time Calculator Problem, p. 272
Chapter 5 The while Loop, p. 278
The for Loop, p. 305
Nested Loops, p. 313
Solving the Ocean Levels Problem, p. 351
Chapter 6 Defining and Calling Functions, p. 358
Using Function Arguments, p. 367
Value-Returning Functions, p. 377
Solving the Markup Problem, p. 433
Chapter 7 Creating a Class, p. 446
Creating and Using Class Objects, p. 448
Creating and Using Structures, p. 488
Solving the Car Class Problem, p. 534
Chapter 8 Accessing Array Elements, p. 543
Passing an Array to a Function, p. 577
Two-Dimensional Arrays, p. 587
Solving the Chips and Salsa Problem, p. 627
Chapter 9 Performing a Binary Search, p. 640
Sorting a Set of Data, p. 647
Solving the Lottery Winners Problem, p. 675
(continued on next page)
VideoNote
LOCATION OF VIDEONOTES IN THE TEXT (continued)
Chapter 10 Pointer Variables, p. 681
Dynamically Allocating an Array, p. 705
Solving the Days in Current Month Problem, p. 736
Chapter 11 Operator Overloading, p. 764
Aggregation and Composition, p. 810
Overriding Base Class Functions, p. 831
Solving the Number of Days Worked Problem, p. 845
Chapter 12 Converting Strings to Numbers, p. 863
Writing a C-String Handling Function, p. 867
Solving the Case Manipulator Problem, p. 884
Chapter 13 The get Family of Member Functions, p. 903
Rewinding a File, p. 907
Solving the File Encryption Filter Problem, p. 946
Chapter 14 Recursive Binary Search, p. 961
QuickSort, p. 963
Solving the Recursive Multiplication Problem, p. 981
Chapter 15 Polymorphism, p. 989
Composition versus Inheritance, p. 1003
Solving the Sequence Sum Problem, p. 1019
Chapter 16 Throwing and Handling Exceptions, p. 1022
Writing a Function Template, p. 1034
Iterators, p. 1051
Solving the Arithmetic Exceptions Problem, p. 1068
Chapter 17 Adding an Element to a Linked List, p. 1079
Removing an Element from a Linked List, p. 1086
Solving the Member Insertion by Position Problem, p. 1117
Chapter 18 Storing Objects in an STL Stack, p. 1131
Storing Objects in an STL Queue, p. 1145
Solving the File Reverser Problem, p. 1157
Chapter 19 Inserting an Element into a Binary Tree, p. 1166
Removing an Element from a Binary Tree, p. 1170
Solving the Tree Size Problem, p. 1186
VideoNote
Ninth
Edition Starting Out with
C++
Early Objects
Tony Gaddis
Judy Walters
Godfrey Muganda
Global Edition
Boston  Columbus  Indianapolis  New York  San Francisco  Hoboken
Amsterdam  Cape Town  Dubai  London  Madrid  Milan  Munich  Paris  Montreal  Toronto
Delhi  Mexico City  Sao Paulo  Sydney  Hong Kong  Seoul  Singapore  Taipei  Tokyo
Vice President, Editorial Director, ECS: Marcia Horton
Acquisitions Editor: Matt Goldstein
Editorial Assistant: Kristy Alaura
Acquisitions Editor, Global Editions: Aditee Agarwal
Vice President of Marketing: Christy Lesko
Director of Field Marketing: Tim Galligan
Product Marketing Manager: Bram Van Kempen
Field Marketing Manager: Demetrius Hall
Marketing Assistant: Jon Bryant
Director of Product Management: Erin Gregg
Team Lead, Program and Project Management:
Scott Disanno
Program Manager: Carole Snyder
Project Editor, Global Editions: K.K. Neelakantan
Project Manager: RPK Editorial Services, Inc.
Senior Specialist, Program Planning and Support:
Maura Zaldivar-Garcia
Senior Manufacturing Controller, Global Editions:
Jerry Kataria
Cover Designer: Lumina Datamatics
Cover: Shutterstock
Manager, Rights and Permissions: Rachel Youdelman
Project Manager, Rights and Permissions: William Opaluch
Inventory Manager: Meredith Maresca
Media Project Manager: Renata Butera
Media Production Manager, Global Editions:
Vikram Kumar
Full-Service Project Management: Deepthi Mohan,
iEnergizer Aptara®
, Ltd.
Composition: Aptara®
Corporation
Microsoft and/or its respective suppliers make no representations about the suitability of the information contained in the
documents and related graphics published as part of the services for any purpose. All such documents and related graphics
are provided “as is” without warranty of any kind. Microsoft and/or its respective suppliers hereby disclaim all warranties
and conditions with regard to this information, including all warranties and conditions of merchantability, whether express,
implied or statutory, fitness for a particular purpose, title and non-infringement. In no event shall Microsoft and/or its
respective suppliers be liable for any special, indirect or consequential damages or any damages whatsoever resulting from
loss of use, data or profits, whether in an action of contract, negligence or other tortious action, arising out of or in connection
with the use or performance of information available from the services.
The documents and related graphics contained herein could include technical inaccuracies or typographical errors. Changes
are periodically added to the information herein. Microsoft and/or its respective suppliers may make improvements and/or
changes in the product(s) and/or the program(s) described herein at any time. Partial screen shots may be viewed in full
within the software version specified.
Microsoft®
Windows®
, and Microsoft Office®
are registered trademarks of the Microsoft corporation in the U.S.A. and
other countries. This book is not sponsored or endorsed by or affiliated with the Microsoft corporation.
The programs and applications presented in this book have been included for their instructional value. They have been tested
with care, but are not guaranteed for any particular purpose. The publisher does not offer any warranties or representations,
nor does it accept any liabilities with respect to the programs or applications.
Pearson Education Limited
Edinburgh Gate
Harlow
Essex CM20 2JE
England
and Associated Companies throughout the world
Visit us on the World Wide Web at:
www.pearsonglobaleditions.com
© Pearson Education Limited 2016
The rights of Tony Gaddis, Judy Walters, and Godfrey Muganda to be identified as the authors of this work have been as-
serted by them in accordance with the Copyright, Designs and Patents Act 1988.
Authorized adaptation from the United States edition, entitled Starting Out with C++: Early Objects, 9th Edition, ISBN
9780134400242, by Tony Gaddis, Judy Walters, and Godfrey Muganda published by Pearson Education © 2017.
All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or
by any means, electronic, mechanical, photocopying, recording or otherwise, without either the prior written permission of
the publisher or a license permitting restricted copying in the United Kingdom issued by the Copyright Licensing Agency Ltd,
Saffron House, 6–10 Kirby Street, London EC1N 8TS.
All trademarks used herein are the property of their respective owners. The use of any trademark in this text does not vest in
the author or publisher any trademark ownership rights in such trademarks, nor does the use of such trademarks imply any
affiliation with or endorsement of this book by such owners.
British Library Cataloguing-in-Publication Data
A catalogue record for this book is available from the British Library
10 9 8 7 6 5 4 3 2 1
ISBN 10: 1292157275
ISBN 13: 9781292157276
Typeset in 10/12.5 Sabon LT Pro by iEnergizer Aptara®
, Ltd.
Printed and bound in Malaysia
Last A-Head 5
Contents at a Glance
		 Preface 15
Chapter 1 Introduction to Computers and Programming 35
Chapter 2 Introduction to C++ 61
Chapter 3 Expressions and Interactivity 111
Chapter 4 Making Decisions 189
Chapter 5 Looping 277
Chapter 6 Functions 357
Chapter 7 Introduction to Classes and Objects 441
Chapter 8 Arrays 541
Chapter 9 Searching, Sorting, and Algorithm Analysis 637
Chapter 10 Pointers 679
Chapter 11 More about Classes and Object-Oriented Programming 737
Chapter 12 More on C-Strings and the string Class 849
Chapter 13 Advanced File and I/O Operations 887
Chapter 14 Recursion 949
Chapter 15 Polymorphism and Virtual Functions 983
Chapter 16 Exceptions, Templates, and the Standard Template Library (STL) 1021
Chapter 17 Linked Lists 1071
Chapter 18 Stacks and Queues 1119
Chapter 19 Binary Trees 1159
		 Appendix A: The ASCII Character Set 1189
		 Appendix B: Operator Precedence and Associativity 1193
		 Appendix C: Answers to Checkpoints 1195
		 Appendix D: Answers to Odd-Numbered Review Questions 1235
		 Index 1255
5
This page intentionally left blank
Contents
		 Preface 15
CHAPTER 1 Introduction to Computers and Programming 35
1.1 Why Program? 35
1.2 Computer Systems: Hardware and Software 37
1.3 Programs and Programming Languages 42
1.4 What Is a Program Made of? 47
1.5 Input, Processing, and Output 51
1.6 The Programming Process 52
1.7 Tying It All Together: Hi! It’s Me 57
CHAPTER 2 Introduction to C++ 61
2.1 The Parts of a C++ Program 61
2.2 The cout Object 65
2.3 The #include Directive 70
2.4 Variables and the Assignment Statement 71
2.5 Literals 73
2.6 Identifiers 75
2.7 Integer Data Types 77
2.8 Floating-Point Data Types 82
2.9 The char Data Type 86
2.10 The C++ string Class 90
2.11 The bool Data Type 91
2.12 Determining the Size of a Data Type 92
2.13 More on Variable Assignments and Initialization 93
2.14 Scope 95
2.15 Arithmetic Operators 96
2.16 Comments 100
2.17 Programming Style 101
2.18 Tying It All Together: Smile! 103
7
8 Contents
CHAPTER 3 Expressions and Interactivity 111
3.1 The cin Object 111
3.2 Mathematical Expressions 118
3.3 Data Type Conversion and Type Casting 126
3.4 Overflow and Underflow 132
3.5 Named Constants 133
3.6 Multiple and Combined Assignment 136
3.7 Formatting Output 140
3.8 Working with Characters and Strings 150
3.9 More Mathematical Library Functions 164
3.10 Random Numbers 166
3.11 Focus on Debugging: Hand Tracing a Program 170
3.12 Green Fields Landscaping Case Study—Part 1 172
3.13 Tying It All Together: Word Game 175
CHAPTER 4 Making Decisions 189
4.1 Relational Operators 189
4.2 The if Statement 195
4.3 The if/else Statement 204
4.4 The if/else  if Statement 209
4.5 Menu-Driven Programs 217
4.6 Nested if Statements 219
4.7 Logical Operators 223
4.8 Validating User Input 232
4.9 More about Blocks and Scope 234
4.10 More about Characters and Strings 237
4.11 The Conditional Operator 243
4.12 The switch Statement 247
4.13 Enumerated Data Types 256
4.14 Focus on Testing and Debugging: Validating Output Results 259
4.15 Green Fields Landscaping Case Study—Part 2 261
4.16 Tying It All Together: Fortune Teller 266
CHAPTER 5 Looping 277
5.1 Introduction to Loops: The while Loop 277
5.2 Using the while Loop for Input Validation 284
5.3 The Increment and Decrement Operators 287
5.4 Counters 292
5.5 Keeping a Running Total 294
5.6 Sentinels 297
5.7 The do-while Loop 299
Contents 9
5.8 The for Loop 305
5.9 Focus on Software Engineering: Deciding Which Loop to Use 311
5.10 Nested Loops 313
5.11 Breaking Out of a Loop 315
5.12 Using Files for Data Storage 319
5.13 Focus on Testing and Debugging: Creating Good Test Data 335
5.14 Central Mountain Credit Union Case Study 338
5.15 Tying It All Together: What a Colorful World 342
CHAPTER 6 Functions 357
6.1 Modular Programming 357
6.2 Defining and Calling Functions 358
6.3 Function Prototypes 366
6.4 Sending Data into a Function 367
6.5 Passing Data by Value 372
6.6 The return Statement 376
6.7 Returning a Value from a Function 377
6.8 Returning a Boolean Value 383
6.9 Using Functions in a Menu-Driven Program 385
6.10 Local and Global Variables 389
6.11 Static Local Variables 396
6.12 Default Arguments 398
6.13 Using Reference Variables as Parameters 402
6.14 Overloading Functions 412
6.15 The exit() Function 416
6.16 Stubs and Drivers 419
6.17 Little Lotto Case Study 421
6.18 Tying It All Together: Glowing Jack-o-lantern 426
CHAPTER 7 Introduction to Classes and Objects 441
7.1 Abstract Data Types 441
7.2 Object-Oriented Programming 443
7.3 Introduction to Classes 445
7.4 Creating and Using Objects 448
7.5 Defining Member Functions 450
7.6 Constructors 457
7.7 Destructors 463
7.8 Private Member Functions 466
7.9 Passing Objects to Functions 469
7.10 Object Composition 476
7.11 Focus on Software Engineering: Separating Class Specification, Implementation,
and Client Code 480
10 Contents
7.12 Structures 487
7.13 More about Enumerated Data Types 499
7.14 Home Software Company OOP Case Study 503
7.15 Introduction to Object-Oriented Analysis and
Design 510
7.16 Screen Control 520
7.17 Tying It All Together: Yoyo Animation 525
CHAPTER 8 Arrays 541
8.1 Arrays Hold Multiple Values 541
8.2 Accessing Array Elements 543
8.3 Inputting and Displaying Array Data 545
8.4 Array Initialization 552
8.5 The Range-Based for loop 559
8.6 Processing Array Contents 562
8.7 Using Parallel Arrays 573
8.8 The typedef Statement 577
8.9 Arrays as Function Arguments 577
8.10 Two-Dimensional Arrays 587
8.11 Arrays with Three or More Dimensions 594
8.12 Vectors 597
8.13 Arrays of Objects 609
8.14 National Commerce Bank Case Study 619
8.15 Tying It All Together: Rock, Paper, Scissors 621
CHAPTER 9 Searching, Sorting, and Algorithm Analysis 637
9.1 Introduction to Search Algorithms 637
9.2 Searching an Array of Objects 644
9.3 Introduction to Sorting Algorithms 647
9.4 Sorting an Array of Objects 655
9.5 Sorting and Searching Vectors 658
9.6 Introduction to Analysis of Algorithms 661
9.7 Case Studies 669
9.8 Tying It All Together: Secret Messages 669
CHAPTER 10 Pointers 679
10.1 Pointers and the Address Operator 679
10.2 Pointer Variables 681
10.3 The Relationship Between Arrays and
Pointers 685
Contents 11
10.4 Pointer Arithmetic 689
10.5 Initializing Pointers 690
10.6 Comparing Pointers 693
10.7 Pointers as Function Parameters 695
10.8 Pointers to Constants and Constant Pointers 699
10.9 Focus on Software Engineering: Dynamic Memory
Allocation 704
10.10 Focus on Software Engineering: Returning Pointers from
Functions 708
10.11 Pointers to Class Objects and Structures 714
10.12 Focus on Software Engineering: Selecting Members
of Objects 718
10.13 Smart Pointers 720
10.14 Tying It All Together: Pardon Me, Do You Have the Time? 728
CHAPTER 11 More about Classes and Object-Oriented Programming 737
11.1 The this Pointer and Constant Member Functions 737
11.2 Static Members 742
11.3 Friends of Classes 749
11.4 Memberwise Assignment 754
11.5 Copy Constructors 755
11.6 Operator Overloading 764
11.7 Rvalue References and Move Operations 785
11.8 Function Objects and Lambda Expressions 795
11.9 Type Conversion Operators 804
11.10 Convert Constructors 807
11.11 Aggregation and Composition 810
11.12 Inheritance 816
11.13 Protected Members and Class Access 821
11.14 Constructors, Destructors, and Inheritance 826
11.15 Overriding Base Class Functions 831
11.16 Tying It All Together: Putting Data on the World Wide Web 834
CHAPTER 12 More on C-Strings and the string Class 849
12.1 C-Strings 849
12.2 Library Functions for Working with C-Strings 854
12.3 Conversions Between Numbers and Strings 863
12.4 Writing Your Own C-String Handling Functions 867
12.5 More about the C++ string Class 873
12.6 Advanced Software Enterprises Case Study 876
12.7 Tying It All Together: Program Execution Environments 878
CHAPTER 13 Advanced File and I/O Operations 887
13.1 Input and Output Streams 887
13.2 More Detailed Error Testing 895
13.3 Member Functions for Reading and Writing Files 899
13.4 Binary Files 911
13.5 Creating Records with Structures 915
13.6 Random-Access Files 920
13.7 Opening a File for Both Input and Output 927
13.8 Online Friendship Connections Case Study: Object Serialization 932
13.9 Tying It All Together: File Merging and Color-Coded HTML 937
CHAPTER 14 Recursion 949
14.1 Introduction to Recursion 949
14.2 The Recursive Factorial Function 956
14.3 The Recursive gcd Function 958
14.4 Solving Recursively Defined Problems 959
14.5 A Recursive Binary Search Function 961
14.6 Focus on Problem Solving and Program Design: The QuickSort Algorithm 963
14.7 The Towers of Hanoi 967
14.8 Focus on Problem Solving: Exhaustive and Enumeration Algorithms 970
14.9 Focus on Software Engineering: Recursion versus Iteration 974
14.10 Tying It All Together: Infix and Prefix Expressions 975
CHAPTER 15 Polymorphism and Virtual Functions 983
15.1 Type Compatibility in Inheritance Hierarchies 983
15.2 Polymorphism and Virtual Member Functions 989
15.3 Abstract Base Classes and Pure Virtual Functions 997
15.4 Focus on Object-Oriented Programming: Composition versus Inheritance 1003
15.5 Secure Encryption Systems, Inc., Case Study 1007
15.6 Tying It All Together: Let’s Move It 1010
CHAPTER 16 Exceptions, Templates, and the Standard Template Library
(STL) 1021
16.1 Exceptions 1021
16.2 Function Templates 1033
16.3 Class Templates 1041
16.4 Class Templates and Inheritance 1046
16.5 Introduction to the Standard Template Library 1050
16.6 Tying It All Together: Word Transformers Game 1063
12 Contents
CHAPTER 17 Linked Lists 1071
17.1 Introduction to the Linked List ADT 1071
17.2 Linked List Operations 1077
17.3 A Linked List Template 1089
17.4 Recursive Linked List Operations 1093
17.5 Variations of the Linked List 1101
17.6 The STL list Container 1102
17.7 Reliable Software Systems, Inc., Case Study 1105
17.8 Tying It All Together: More on Graphics and Animation 1108
CHAPTER 18 Stacks and Queues 1119
18.1 Introduction to the Stack ADT 1119
18.2 Dynamic Stacks 1127
18.3 The STL stack Container 1131
18.4 Introduction to the Queue ADT 1133
18.5 Dynamic Queues 1140
18.6 The STL deque and queue Containers 1143
18.7 Focus on Problem Solving and Program Design: Eliminating Recursion 1146
18.8 Tying It All Together: Converting Postfix Expressions to Infix 1151
CHAPTER 19 Binary Trees 1159
19.1 Definition and Applications of Binary Trees 1159
19.2 Binary Search Tree Operations 1163
19.3 Template Considerations for Binary Search Trees 1179
19.4 Tying It All Together: Genealogy Trees 1179
Appendix A: The ASCII Character Set 1189
Appendix B: Operator Precedence and Associativity 1193
Appendix C: Answers to Checkpoints 1195
Appendix D: Answers to Odd-Numbered Review Questions 1235
Index 1255
Contents 13
Additional Appendices
The following appendices are located on the book’s companion web site.
Appendix E: A Brief Introduction to Object-Oriented Programming
Appendix F: Using UML in Class Design
Appendix G: Multi-Source File Programs
Appendix H: Multiple and Virtual Inheritance
Appendix I: Header File and Library Function Reference
Appendix J: Namespaces
Appendix K: C++ Casts and Run-Time Type Identification
Appendix L: Passing Command Line Arguments
Appendix M: Binary Numbers and Bitwise Operations
Appendix N: Introduction to Flowcharting
14 Contents
Preface
Welcome to Starting Out with C++: Early Objects, 9th Edition. This book is intended
for use in a two-term or three-term C++ programming sequence, or an accelerated
one-term course. Students new to programming, as well as those with prior course work
in other languages, will find this text beneficial. The fundamentals of programming
are covered for the novice, while the details, pitfalls, and nuances of the C++ language
are explored in-depth for both the beginner and more experienced student. The book
is written with clear, easy-to-understand language and it covers all the necessary
­
topics for an introductory programming course. This text is rich in example programs
that are concise, practical, and real world oriented, ensuring that the student not only
learns how to implement the features and constructs of C++, but why and when to
use them.
What’s New in the Ninth Edition
The New C++11 Standard
C++11 is the latest standard version of the C++ language. In previous years, while the
standard was being developed, it was known as C++0x. In August 2011, it was
approved by the International Standards Organization (ISO), and the name of the
standard was officially changed to C++11. Most of the popular C++ compilers now
support this standard.
The new C++11 standard was the primary motivation behind this edition, which
introduces many of the new language features. However, a C++11 compiler is not
strictly required to use the book. As you progress through the book, you will see
C++11 icons in the margins, next to the new features that are introduced. Programs
appearing in sections that are not marked with this icon will still compile using an
older compiler.
The C++11 Topics Introduced in This Edition
• The auto key word is introduced in Chapter 2 as a way to simplify complex
variable definitions. This key word causes the compiler to infer a variable’s data
type from its initialization value.
15
16 Preface
• Chapter 2 also introduces the new long long int and unsigned long long int
data types and the LL literal suffix.
• Chapter 5 shows how to pass a string object directly to a file stream object’s
open member function, without the need to call the c_str() member function.
A discussion of the c_str()function still exists for anyone using a legacy
compiler.
• The range-based for loop is introduced in Chapter 7. This new looping
mechanism automatically iterates over each element of an array, vector, or
other collection, without the need for a counter variable or a subscript.
• Chapter 7 also introduces strongly typed enums.
• Chapter 8 introduces new ways to initialize variables and shows how a vector
can now be initialized with an initialization list.
• Chapter 10 introduces smart pointers and provides examples of how and why to use
the new unique_ptr and shared_ptr pointers for safely allocating and working
with dynamic memory.
• Chapter 10 also introduces the move assignment operator, and the nullptr key
word, which is now the standard way of representing a null pointer.
• Chapter 11 discusses move constructors, provides more in depth coverage of
move assignment operators, and introduces lambda expressions.
• Chapter 12 introduces new functions in the C++11 string library and discusses
the new overloaded to_string functions for converting numeric values to string
objects.
• Chapter 15 introduces and demonstrates the use of the new override key word
that helps prevent subtle overriding errors and the new final key word that
prevents a virtual member function from being overridden.
• Chapter 16 introduces the new C++11 functions begin(c) and end(c) to specify
positions within a collection c where an operation should begin and end.
What Else is New
This book’s pedagogy and clear writing style remain the same as in the previous edition.
However, in addition to updating the book to introduce the new C++11 standard,
many improvements have been made to make it even more student-friendly.
• Updated Material
Material has been updated throughout the book to reflect changes in technology
and in software development environments, as well as to improve clarity and
incorporate best practices in teaching introductory programming. As a result,
new graphics and new or redesigned figures have been added throughout the
book where appropriate and new or improved sample programs have been
included in a number of chapters.
• New Material
New material has been added on a number of topics. In addition to introducing
and using new C++11 features, this new edition includes new sections on literals,
random numbers, and enumerated data types, as well as improved material on
designing classes.
Preface 17
• New Programming Challenges
New Programming Challenge problems have been added to every chapter.
• Reorganized Chapters
Several chapters have been redesigned to improve student learning. Chapter 5
(Looping) has been reorganized to give students more practice using the while
loop before introducing do-while and for loops. The Chapter 6 (Functions)
material on defining and calling functions has been reorganized to introduce
function prototypes earlier and allow main to always be the first function in
a client program.
Organization of the Text
This text teaches C++ in a step-by-step fashion. Each chapter covers a major set of
topics and builds knowledge as the student progresses through the book. Although
the chapters can be easily taught in their existing sequence, flexibility is provided.
The following dependency diagram (Figure P-1) suggests possible sequences of
instruction.
Chapter 1 covers fundamental hardware, software, and programming concepts. The
instructor may choose to skip this chapter if the class has already mastered those topics.
Chapters 2 through 6 cover basic C++ syntax, data types, expressions, selection
structures, repetition structures, and functions. Each of these chapters builds on the
previous chapter and should be covered in the order presented.
Chapter 7 introduces object-oriented programming. It can be covered any time after
Chapter 6, but before Chapter 11. Instructors who prefer to introduce arrays before
classes can cover Chapter 8 before Chapter 7. In this case it is only necessary to
postpone Section 8.13 (Arrays of Objects) until Chapter 7 has been covered.
As Figure P-1 illustrates, in the second half of the book Chapters 11, 12, 13, and 14
can be covered in any order. Chapters 11, 15, and 16, however, should be done in
sequence. Instructors who wish to introduce data structures at an earlier point in the
course, without having first covered advanced C++ and OOP features, can cover
Chapter 17 (Linked Lists), followed by Chapters 18 and 19 (Stacks & Queues and
Binary Trees), any time after Chapter 14 (Recursion). In this case it is necessary to
simply omit the sections in Chapters 17–19 that deal with templates and the Standard
Template Library.
18 Preface
Chapter 1
Introduction
Chapters 2–6
Basic
Language
Elements
Chapter 10
Pointers
Chapter 7
OOP Introduction
Chapter 8
Arrays
Chapter 11
More OOP
Chapter 12
Advanced
Strings
Chapter 13
Advanced Files
and I/O
Chapter 14
Recursion
Chapter 17
Linked Lists
Chapter 15
Adv. OOP
Chapter 16
Exceptions,
Templates,
and STL
Chapter 18
Stacks and
Queues
Chapter 19
Binary Trees
Chapter 9
Searching, Sorting,
and Algorithm Analysis
Figure P-1
Preface 19
Brief Overview of Each Chapter
Chapter 1: Introduction to Computers and Programming
This chapter provides an introduction to the field of computer science and covers
the fundamentals of hardware, software, operating systems, programming, problem
solving, and software engineering. The components of programs, such as key words,
variables, operators, and punctuation are covered. The tools of the trade, such as
hierarchy charts and pseudocode, are also presented. The Tying It All Together
section shows students how to use the cout statement to create a personalized
output message. Programming Challenges at the end of the chapter help students see
how the same basic input, processing, and output structure can be used to create
multiple programs.
Chapter 2: Introduction to C++
This chapter gets the student started in C++ by introducing the basic parts of a
C++ program, data types, the use of variables and literals, assignment statements,
simple arithmetic operations, program output, and comments. The C++ string
class is presented and string objects are used from this point on in the book as
the primary method of handling strings. Programming style conventions are
introduced, and good programming style is modeled here, as it is throughout the
text. The Tying It All Together section lets the student play with simple text-
based graphics.
Chapter 3: Expressions and Interactivity
In this chapter the student learns to write programs that input and handle numeric,
character, and string data. The use of arithmetic operators and the creation of
mathematical expressions are covered, with emphasis on operator precedence.
Debugging is introduced, with a section on hand tracing a program. Sections are also
included on using random numbers, on simple output formatting, on data type
conversion and type casting, and on using library functions that work with numbers.
The Tying It All Together section shows students how to create a simple interactive
word game.
Chapter 4: Making Decisions
Here the student learns about relational expressions and how to control the flow of a
program with if, if/else, and if/else  if statements. Logical operators, the
conditional operator, and the switch statement are also covered. Applications of these
constructs, such as menu-driven programs, are illustrated. This chapter also introduces
the concepts of blocks and scope and continues the theme of debugging with a section
on validating output results. The Tying It All Together section uses random numbers
and branching statements to create a fortune telling game.
Chapter 5: Looping
This chapter introduces, C++’s repetitive control mechanisms. The while loop, do-while
loop, and for loop are presented, along with a variety of methods to control them. These
include using counters, user input, end sentinels, and end-of-file testing. Applications
utilizing loops, such as keeping a running total and performing data validation, are also
covered. The chapter includes an extensive section on working with files and a section
on creating good test data, continuing the book’s emphasis on testing and debugging.
The Tying It All Together section introduces students to Windows commands to create
colorful output and uses a loop to create a multi-colored display.
Chapter 6: Functions
In this chapter the student learns how and why to modularize programs, using both
void and value-returning functions. Parameter passing is covered, with emphasis on
when arguments should be passed by value versus when they need to be passed by
reference. Scope of variables is covered and sections are provided on local versus global
variables and on static local variables. Overloaded functions are also introduced and
demonstrated. The Tying It All Together section includes a modular, menu-driven
program that emphasizes the versatility of functions, illustrating how their behavior
can be controlled by the arguments sent to them.
Chapter 7: Introduction to Classes and Objects
In this chapter the text begins to focus on the object-oriented paradigm. Students have used
provided C++ classes since the beginning of the text, but now they learn how to define their
own classes and to create and use objects of these classes. Careful attention is paid to
illustrating which functions belong in a class versus which functions belong in a client
program that uses the class. Good object-oriented practices are discussed and modeled, such
as protecting member data through carefully constructed accessor and mutator functions
and hiding class implementation details from client programs. Once students are comfortable
working with classes and objects, the chapter provides a brief introduction to the topic of
object-oriented analysis and design. The chapter also includes a section on enumerated data
types and a section on structures, which are used in the Tying It All Together section, where
students learn to use screen control techniques to create a yoyo animation.
Chapter 8: Arrays
In this chapter the student learns to create and work with single and multidimensional
arrays. Many examples of array processing are provided, including functions to compute
the sum, average, highest and lowest values in an array. Students also learn to create tables
usingtwo-dimensionalarrays,andtoanalyzearraydatabyroworbycolumn.Programming
techniques using parallel arrays are also demonstrated, and the student is shown how to
use a data file as an input source to populate an array. The range-based for loop is
introduced as an easy way to iterate through all the elements of an array, and STL vectors
are introduced and compared to arrays. A section on arrays of objects and structures is
located at the end of the chapter, so it can be covered now or saved for later if the instructor
wishes to cover this chapter before Chapter 7. The Tying It All Together section uses
arrays to create a game of Rock, Paper, Scissors between a human player and the computer.
20 Preface
Chapter 9: Searching, Sorting, and Algorithm Analysis
Here the student learns the basics of searching for information stored in arrays and of
sorting arrays, including arrays of objects. The chapter covers the Linear Search, Binary
Search, Bubble Sort, and Selection Sort algorithms and has an optional section on
sorting and searching STL vectors. A brief introduction to algorithm analysis is
included, and students are shown how to determine which of two algorithms is more
efficient. This chapter’s Tying It All Together section uses both a table lookup and a
searching algorithm to encode and decode secret messages.
Chapter 10: Pointers
This chapter explains how to use pointers. Topics include pointer arithmetic,
initialization of pointers, comparison of pointers, pointers and arrays, pointers
and functions, dynamic memory allocation, the new nullptr key word, and
more. A new section introduces smart pointers and shows how they can be used
to avoid memory leaks. The Tying It All Together section demonstrates the use of
pointers to access library data structures and functions that return calendar and
wall clock time.
Chapter 11: More About Classes and Object-Oriented Programming
This chapter continues the study of classes and object-oriented programming, covering
more advanced topics such as inheritance and object aggregation and composition.
Other topics include constant member functions, static members, friends, memberwise
assignment, copy constructors, object type conversion operators, convert constructors,
operator overloading, move constructors, and move assignment operators. A new
section introduces function objects and the C++11 lambda expressions. The Tying It
All Together section brings together the concepts of inheritance and convert constructors
to build a program that formats the contents of an array to form an HTML table for
display on a Web site.
Chapter 12: More on C-Strings and the string Class
This chapter covers standard library functions for working with characters and
C-strings, as well as material on string class functions, functions in the new C++11
string library, and new overloaded to_string functions for converting numeric
values to string objects. The Tying It All Together section shows students how to
access string-based program environments to obtain information about the computer
and the network on which the program is running.
Chapter 13: Advanced File and I/O Operations
This chapter introduces more advanced topics for working with sequential access
text files and introduces random access and binary files. Various modes for open-
ing files are discussed, as well as the many methods for reading and writing their
contents. The Tying It All Together program applies many of the techniques
c­
overed in the chapter to merge two text files into an HTML document for display
on the Web, with different colors used to illustrate which file each piece of data
came from.
Preface 21
Chapter 14: Recursion
In this chapter recursion is defined and demonstrated. A visual trace of recursive calls
is provided, and recursive applications are discussed. Many recursive algorithms are
presented, including recursive functions for computing factorials, finding a greatest
common denominator (GCD), performing a binary search, sorting using QuickSort,
and solving the famous Towers of Hanoi problem. For students who need more
challenge, there is a section on exhaustive and enumeration algorithms. The Tying It
All Together section uses recursion to evaluate prefix expressions.
Chapter 15: Polymorphism and Virtual Functions
The study of classes and object-oriented programming continues in this chapter with
the introduction of more advanced concepts such as polymorphism and virtual
functions. Information is also presented on abstract base classes, pure virtual functions,
type compatibility within an inheritance hierarchy, and virtual inheritance. The Tying
It All Together section illustrates the use of inheritance and polymorphism to display
and animate graphical images.
Chapter 16: Exceptions, Templates, and the Standard Template
Library (STL)
Here the student learns to develop enhanced error trapping techniques using exceptions.
Discussion then turns to using function and class templates to create generic code.
Finally, the student is introduced to the containers, iterators, and algorithms offered by
the Standard Template Library (STL). The Tying It All Together section uses various
containers in the Standard Template Library to create an educational children’s game.
Chapter 17: Linked Lists
This chapter introduces concepts and techniques needed to work with lists. A linked list
ADT is developed, and the student learns how to create and destroy a list, as well as to write
functions to insert, append, and delete nodes, to traverse the list, and to search for a specific
node. A linked list class template is also demonstrated. The Tying It All Together section
brings together many of the most important concepts of OOP by using objects, inheritance,
and polymorphism in conjunction with the STL list class to animate a collection of images.
Chapter 18: Stacks and Queues
In this chapter the student learns to create and use static and dynamic stacks and queues.
The operations of stacks and queues are defined, and templates for each ADT are
demonstrated. The static array-based stack uses exception-handling to handle stack
overflow and underflow, providing a realistic and natural example of defining, throwing,
and catching exceptions. The Tying It All Together section discusses strategies for
evaluating postfix expressions and uses a stack to convert a postfix expression to infix.
Chapter 19: Binary Trees
This chapter covers the binary tree ADT and demonstrates many binary tree operations.
The student learns to traverse a tree, insert, delete, and replace elements, search for a
particular element, and destroy a tree. The Tying It All Together section introduces a
tree structure versatile enough to create genealogy trees.
22 Preface
Appendices in the Book
Appendix A: The ASCII Character Set A list of the ASCII and extended ASCII
characters and their codes.
Appendix B: Operator Precedence and Associativity A list of the C++ operators
with their precedence and associativity.
Appendix C: Answers to Checkpoints A tool students can use to assess their
understanding by comparing their answers to the Checkpoint exercises found
throughout the book. The answers to all Checkpoint exercises are included.
Appendix D: Answers to Odd-Numbered Review Questions Another tool students
can use to gauge their understanding and progress.
Additional Appendices on the Book’s Companion Website
Appendix E: A Brief Introduction to Object-Oriented Programming An
introduction to the concepts and terminology of object-oriented programming.
Appendix F: Using UML in Class Design A brief introduction to the Unified Modeling
Language (UML) class diagrams with examples of their use.
Appendix G: Multi-Source File Programs A tutorial on how to create, compile,
and link programs with multiple source files. Includes the use of function header files,
class specification files, and class implementation files.
Appendix H: Multiple and Virtual Inheritance A self-contained discussion of the
C++ concepts of multiple and virtual inheritance for anyone already familiar with
single inheritance.
Appendix I: Header File and Library Function Reference A reference for the C++
library functions and header files used in the book.
Appendix J: Namespaces An explanation of namespaces and their purpose, with
examples provided on how to define a namespace and access its members.
Appendix K: C++ Casts and Run-Time Type Identification An introduction to
different ways of doing type casting in C++ and to run-time type identification.
Appendix L: Passing Command Line Arguments An introduction to writing C++
programs that accept command-line arguments. This appendix will be useful to students
working in a command-line environment, such as UNIX or Linux.
Appendix M: Binary Numbers and Bitwise Operations A guide to the binary
number system and the C++ bitwise operators, as well as a tutorial on the internal storage
of integers.
Appendix N: Introduction to Flowcharting A tutorial that introduces flowcharting
and its symbols. It includes handling sequence, selection, case, repetition, and calls
to other modules. Sample flowcharts for several of the book’s example programs
are presented.
Preface 23
Features of the Text
Concept Statements	
Each major section of the text starts with a concept statement.
This statement summarizes the key idea of the section.
Example Programs 	
The text has over 350 complete example programs, each
designed to highlight the topic currently being studied. In
most cases, these are practical, real-world examples. Source
code for these programs is provided so that students can run
the programs themselves.
Program Output 	
After each example program there is a sample of its screen
output. This immediately shows the student how the program
should function.
Tying It All Together 	
This special section, found at the end of every chapter, shows
the student how to do something clever and fun with the
material covered in that chapter.
VideoNotes 	
A series of online videos, developed specifically for this book,
are available for viewing at www.pearsonglobaleditions.
com/gaddis. VideoNote icons appear throughout the text,
alerting the student to videos about specific topics.
Checkpoints 	
Checkpoints are questions placed throughout each chapter as
a selftest study aid. Answers for all Checkpoint questions are
provided in Appendix C at the back of the book so students
can check how well they have learned a new topic.
Notes 	
Notes appear at appropriate places throughout the text. They
are short explanations of interesting or often misunderstood
points relevant to the topic at hand.
Warnings 	
Warnings caution the student about certain C++ features,
programming techniques, or practices that can lead to
malfunctioning programs or lost data.
Case Studies 	
Case studies that simulate real-world applications appear in
many chapters throughout the text, with complete code provided
for each one. Additional case studies are provided on the book’s
companion website. These case studies are designed to highlight
the major topics of the chapter in which they appear.
Review Questions 	
Each chapter presents a thorough and diverse set of review
questions, such as fill-in-the-blank and short answer, that
check the student’s mastery of the basic material presented in
the chapter. These are followed by exercises requiring problem
solving and analysis, such as the Algorithm Workbench,
Predict the Output, and Find the Errors sections. Each chapter
ends with a Soft Skills exercise that focuses on communication
and group process skills. Answers to the odd numbered review
questions and review exercises are provided in Appendix D at
the back of the book.
and Exercises
VideoNote
24 Preface
Programming 	
Each chapter offers a pool of programming exercises designed
to solidify the student’s knowledge of the topics currently
being studied. In most cases the assignments present
real-world problems to be solved.
Group Projects 	
There are several group programming projects throughout
the text, intended to be constructed by a team of students.
One student might build the program’s user interface, while
another student writes the mathematical code, and another
designs and implements a class the program uses. This process
is similar to the way many professional programs are written
and encourages teamwork within the classroom.
C++ Quick	
For easy access, a quick reference guide to the C++ language
is printed on the inside back cover.
Supplements
Student Resources
The following items are available on the Gaddis Series resource page at
www.pearsonglobaleditions.com/gaddis:
• Complete source code for every program included in the book
• Additional case studies, complete with source code
• A full set of appendices (including several tutorials) that accompany the book
• Access to the book’s companion VideoNotes
• Links to download numerous programming environments and IDEs, including
Visual Studio Community Edition.
Instructor Resources
The following supplements are available to qualified instructors only.
• Answers to all Review Questions in the text
• Solutions for all Programming Challenges in the text
• PowerPoint presentation slides for every chapter
• A computerized test bank
• A collection of lab materials
• Source code files
Visit the Pearson Education Instructor Resource Center (http://www.pearsonglobaleditions.
com/gaddis) for information on how to access them.
Practice and Assessment with MyProgrammingLab
MyProgrammingLab helps students fully grasp the logic, semantics, and syntax of
programming. Through practice exercises and immediate, personalized feedback,
MyProgrammingLab improves the programming competence of beginning students
who often struggle with the basic concepts and paradigms of popular high-level
programming languages. A self-study and homework tool, MyProgrammingLab
consists of hundreds of small practice exercises organized around the structure of this
Challenges
Reference Guide
Preface 25
textbook. For students, the system automatically detects errors in the logic and syntax
of their code submissions and offers targeted hints that help them figure out what went
wrong. For instructors, a comprehensive gradebook tracks correct and incorrect
answers and stores the code input by students for review.
MyProgrammingLab is offered to users of this book in partnership with Turing’s Craft,
the makers of the CodeLab interactive programming exercise system. For a full
demonstration, to see feedback from instructors and students, or to get started using
MyProgrammingLab in your course, visit www.myprogramminglab.com.
Which Gaddis C++ book is right for you?
The Starting Out with C++ Series includes three books, one of which is sure to fit your
course:
• Starting Out with C++: Early Objects
• Starting Out with C++: From Control Structures through Objects
• Starting Out with C++: Brief Version
26 Preface
Acknowledgments
There have been many helping hands in the development and publication of this text.
We would like to thank the following faculty reviewers for their helpful suggestions
and expertise.
Reviewers of the Ninth Edition or Its Previous Versions
Ahmad Abuhejleh
University of Wisconsin, River Falls
David Akins
El Camino College
Steve Allan
Utah State University
Ijaz A. Awan
Savannah State University
John Bierbauer
North Central College
Don Biggerstaff
Fayetteville Technical Community
­College
Paul Bladek
Spokane Falls Community College
Chuck Boehm
Dean Foods, Inc.
Bill Brown
Pikes Peak Community College
Richard Cacace
Pensacola Junior College
Randy Campbell
Morningside College
Stephen P. Carl
Wright State University
Wayne Caruolo
Red Rocks Community College
Thomas Cheatham
Middle Tennessee State University
James Chegwidden
Tarrant County College
John Cigas
Rockhurst University
John Cross
Indiana University of Pennsylvania
Fred M. D’Angelo
Pima Community College
Joseph DeLibero
Arizona State University
Dennis Fairclough
Utah Valley State College
Larry Farrer
Guilford Technical Community College
James D. Fitzgerald
Golden West College
Richard Flint
North Central College
Sheila Foster
California State University Long Beach
David E. Fox
American River College
Cindy Fry
Baylor University
Peter Gacs
Boston University
Cristi Gale
Sterling College
James Gifford
University of Wisconsin, Stevens Point
Leon Gleiberman
Touro College
Simon Gray
Ashland University—Ohio
Margaret E. Guertin
Tufts University
Jamshid Haghighi
Guilford Technical Community College
Ranette H. Halverson
Midwestern State University,
Wichita Falls, TX
Preface 27
Dennis Heckman
Portland Community College
Ric Heishman
Northern Virginia Community College
Patricia Hines
Brookdale Community College
Mike Holland
Northern Virginia Community College
Lister Wayne Horn
Pensacola Junior College
Richard Hull
Lenoir-Rhyne College
Norman Jacobson
University of California, Irvine
Eric Jiang
San Diego State University
Yinping Jiao
South Texas College
Neven Jurkovic
Palo Alto College
David Kaeli
Northeastern University
Chris Kardaras
North Central College
Amitava Karmaker
University of Wisconsin—Stout
Eugene Katzen
Montgomery College—Rockville
Willard Keeling
Blue Ridge Community College
A. J. Krygeris
Houston Community College
Ray Larson
Inver Hills Community College
Stephen Leach
Florida State University
Parkay Louie
Houston Community College
Zhu-qu Lu
University of Maine, Presque Isle
Tucjer Maney
George Mason University
Bill Martin
Central Piedmont Community College
Svetlana Marzelli
Atlantic Cape Community College
Debbie Mathews
J. Sargeant Reynolds
Ron McCarty
Penn State Erie, The Behrend College
Robert McDonald
East Stroudsburg University
James McGuffee
Austin Community College
M. Dee Medley
Augusta State University
Barbara Meguro
University of Hawaii—Hilo
Cathi Chambley-Miller
Aiken Technical College
Sandeep Mitra
SUNY Brockport
Churairat O’Brien
Columbia Basin College
Frank Paiano
Southwestern Community College
Jennifer Parham-Mocello
Oregon State University
Theresa Park
Texas State Technical College
Mark Parker
Shoreline Community College
Robert Plantz
Sonoma State University
Tino Posillico
SUNY Farmingdale
Mahmoud K. Quweider
University of Texas at Brownsville
M. Padmaja Rao
Francis Marion University
Timothy Reeves
San Juan College
Nancy Ripplinger
North Idaho College
28 Preface
Ronald Robison
Arkansas Tech University
Caroline St. Clair
North Central College
Dolly Samson
Weber State University
Kate Sanders
Rhode Island College
Tim Scheemaker
Onondaga Community College
Lalchand Shimpi
Saint Augustine’s College
Sung Shin
South Dakota State University
Barbara A. Smith
University of Dayton
Garth Sorenson
Snow College
Donald Southwell
Delta College
Daniel Spiegel
Kutztown University
Ray Springston
University of Texas at Arlington
Kirk Stephens
Southwestern Community College
Cherie Stevens
South Florida Community College
Joe Struss
Des Moines Area Community College
Hong Sung
University of Central Oklahoma
Sam Y. Sung
South Texas College
Mark Swanson
Red Wing Technical College
Martha Tillman
College of San Mateo
Maya Tolappa
Waubonsee Community College
Delores Tull
Itawamba Community College
Rober Tureman
Paul D. Camp Community College
Jane Turk
LaSalle University
Sylvia Unwin
Bellevue Community College
Stewart Venit
California State University, Los Angeles
David Walter
Virginia State University
Ju Wang
Virginia State University
Doug White
University of Northern Colorado
Chris Wild
Old Dominion University
Catherine Wyman
DeVry Institute of Technology, Phoenix
Sherali Zeadally
University of the District of Columbia
Chaim Ziegler
Brooklyn College
The authors would like to thank their students at Haywood Community College and
North Central College for inspiring them to write student-friendly books. They would
also like to thank their families for their tremendous support throughout this project.
An especially big thanks goes to our terrific editorial, production, and marketing team
at Pearson. In particular we want to thank our editor Matt Goldstein and our
production program manager Carole Snyder, who have been instrumental in guiding
the production of this book. We also want to thank our project manager, Rose Kernan,
who helped everything run smoothly, and our meticulous and knowledgable copyeditor,
Shelly Gerger-Knechtl, who dedicated many hours to making this book the best book
it could be. You are great people to work with!
Preface 29
Credits
Chapter 1
Figure 1-1: PowerPoint 2013, Windows 7, Microsoft Corporation
Figure 1-2a:	
Digital webcam in a white background with reflection: Iko/Shutterstock
Figure 1-2b:	
Modern flight joystick isolated on white background: Nikita Rogul/
Shutterstock
Figure 1-2c: Scanner close up shot, business concept: Feng Yu/Shutterstock
Figure 1-2d:	
Black Wireless Computer Keyboard and Mouse Isolated on White:
Chiyacat/Shutterstock
Figure 1-2e: Compact photo camera: Eikostas/Shutterstock
Figure 1-2f: Computer drawing tablet with pen: Tkemot/Shutterstock
Figure 1-2g:	
Illustration of Hard disk drive HDD isolated on white background with
soft shadow: Vitaly Korovin/Shutterstock
Figure 1-2h:	
Small computer speakers isolated on a white background:
StockPhotosArt/Shutterstock
Figure 1-2i: Color Printer: Jocic/Shutterstock
Figure 1-2j: Four monitors. Vector: Art gallery/Shutterstock
Figure 1-2k:	
Stick of computer random access memory (RAM): Peter Guess/Shutterstock
Figure 1-2l: Chip processor radiator: Aquila/Shutterstock
Figure 1-7: Screenshot of Microsoft Visual Studio, Microsoft Corporation
Chapter 2
Figure 2-1: Screenshots of Microsoft DOS, Microsoft Corporation
Chapter 5
Figure 5-11: Windows 10, Microsoft Corporation
Figure 5-12: Windows 10, Microsoft Corporation
All other Figures and Tables by the Authors
About the Authors
Tony Gaddis is the principal author of the Starting Out With series of textbooks. He is
a highly acclaimed instructor with two decades of experience teaching computer science
courses, primarily at Haywood Community College. Tony was previously selected as
the North Carolina Community College “Teacher of the Year” and has received the
Teaching Excellence award from the National Institute for Staff and Organizational
Development. The Starting Out With series includes introductory textbooks covering
Programming Logic and Design, C++, Java™, Microsoft®
Visual Basic®
, Microsoft®
C#, Python, App Inventor, and Alice, all published by Pearson.
Judy Walters is an Associate Professor of Computer Science at North Central College
in Naperville, Illinois, where she teaches courses in both Computer Science and Media
Studies. She is also very involved with International Programs at her college and has
spent three semesters teaching in Costa Rica, where she hopes to retire some day.
Godfrey Muganda is a Professor of Computer Science at North Central College. He
teaches a wide variety of courses at both the undergraduate and graduate levels, including
courses in Algorithms, Computer Organization, Web Applications, and Web Services.
30 Preface
Preface 31
Acknowledgments for the Global Edition
Pearson would like to thank and acknowledge the following people for their contribu-
tions to the Global Edition.
Contributors
Reviewers
Moumita Mitra Manna
Bangabasi College
Chitra Dhawale
P.R. Pote College of Engineering and
Management
Ela Kashyap
Amity University
Muthuraj M.
Timothy Yap
Multimedia University
This page intentionally left blank
PROGRAMMING PRACTICE
With MyProgrammingLab, your students will gain first-hand programming
experience in an interactive online environment.
IMMEDIATE, PERSONALIZED FEEDBACK
MyProgrammingLab automatically detects errors in the logic and syntax of their
code submission and offers targeted hints that enables students to figure out what
went wrong and why.
GRADUATED COMPLEXITY
MyProgrammingLab breaks down programming
concepts into short, understandable sequences
of exercises. Within each sequence the level and
sophistication of the exercises increase gradually
but steadily.
PEARSON eTEXT
The Pearson eText gives students access to their textbook anytime, anywhere
DYNAMIC ROSTER
Students’ submissions are stored in a roster that indicates whether
the submission is correct, how many attempts were made, and the
actual code submissions from each attempt.
STEP-BY-STEP VIDEONOTE TUTORIALS
These step-by-step video tutorials enhance the programming concepts presented
in select Pearson textbooks.
Copyright © 2017 Pearson Education, Inc. or its affiliate(s). All rights reserved. HELO88173 • 11/15
For more information and titles available with MyProgrammingLab,
please visit www.myprogramminglab.com.
Through the power of practice and immediate personalized feedback,
MyProgrammingLab helps improve your students’ performance.
To improving results
This page intentionally left blank
TOPICS
1.1 Why Program?
1.2 Computer Systems: Hardware and
Software
1.3 Programs and Programming Languages
1.4 What Is a Program Made of?
1.5 Input, Processing, and Output
1.6 The Programming Process
1.7 Tying It All Together: Hi! It’s Me
Introduction to Computers
and Programming
1.1 Why Program?
CONCEPT: Computers can do many different jobs because they are programmable.
Think about some of the different ways that people use computers. In school, students
use computers for tasks such as writing papers, searching for articles, sending e-mail,
and participating in online classes. At work, people use computers to analyze data,
make presentations, conduct business transactions, communicate with customers and
coworkers, control machines in manufacturing facilities, and do many other things. At
home, people use computers for tasks such as paying bills, shopping online, social
­
networking, and playing games. And don’t forget that smart phones, iPods®
, car navi-
gation systems, and many other devices are computers as well. The uses of computers
are almost limitless in our everyday lives.
Computers can do such a wide variety of things because they can be programmed. This
means that computers are not designed to do just one job, but to do any job that their
programs tell them to do. A program is a set of instructions that a computer follows to
perform a task. For example, Figure 1-1 shows screens using Microsoft Word and
PowerPoint, two commonly used programs.
C
H
A
P
T
E
R
1
35
36 Chapter 1 Introduction to Computers and Programming
Programs are commonly referred to as software. Software is essential to a computer
because without software, a computer can do nothing. All of the software that we use
to make our computers useful is created by individuals known as programmers or
software developers. A programmer, or software developer, is a person with the
training and skills necessary to design, create, and test computer programs. Computer
programming is an exciting and rewarding career. Today you will find programmers
working in business, medicine, government, law enforcement, agriculture, academics,
entertainment, and almost every other field.
Computer programming is both an art and a science. It is an art because every aspect
of a program should be designed with care and judgment. Listed below are a few of the
things that must be designed for any real-world computer program:
• The logical flow of the instructions
• The mathematical procedures
• The appearance of the screens
• The way information is presented to the user
• The program’s “user-friendliness”
• Manuals and other forms of written documentation
There is also a scientific, or engineering side to programming. Because programs rarely
work right the first time they are written, a lot of experimentation, correction, and
redesigning is required. This demands patience and persistence of the programmer.
Writing software demands discipline as well. Programmers must learn special ­
languages
like C++ because computers do not understand English or other human languages.
Languages such as C++ have strict rules that must be carefully followed.
Both the artistic and scientific nature of programming makes writing computer ­
software
like designing a car. Both cars and programs should be functional, efficient, powerful,
easy to use, and pleasing to look at.
Figure 1-1 A Word Processing Program and a Presentation Program
1.2 Computer Systems: Hardware and Software 37
1.2 Computer Systems: Hardware and Software
CONCEPT: All computer systems consist of similar hardware devices and software
components. This section provides an overview of standard computer
hardware and software organization.
Hardware
Hardware refers to the physical components of a computer. A computer, as we gener-
ally think of it, is not an individual device but a system of devices. Like the instruments
in a symphony orchestra, each device plays its own part. A typical computer system
consists of the following major components:
• The central processing unit (CPU)
• Main memory (random-access memory, or RAM)
• Secondary storage devices
• Input devices
• Output devices
The organization of a computer system is depicted in Figure 1-2.
Input
Devices
Output
Devices
Secondary
Storage Devices
Central Processing
Unit
Main Memory
(RAM)
Figure 1-2
38 Chapter 1 Introduction to Computers and Programming
The CPU
When a computer is performing the tasks that a program tells it to do, we say that the
computer is running or executing the program. The central processing unit, or CPU, is
the part of a computer that actually runs programs. The CPU is the most important
component in a computer because without it the computer could not run software.
In the earliest computers, CPUs were huge devices made of electrical and mechanical
components such as vacuum tubes and switches. Today’s CPUs, known as micropro-
cessors, are tiny chips small enough to be held in the palm of your hand. In addition to
being much smaller than the old electromechanical CPUs in early computers, today’s
microprocessors are also much more powerful.
The CPU’s job is to fetch instructions, follow the instructions, and produce some result.
Internally, the central processing unit consists of two parts: the control unit and the
arithmetic and logic unit (ALU). The control unit coordinates all of the computer’s
operations. It is responsible for determining where to get the next instruction and for
regulating the other major components of the computer with control signals. The
­
arithmetic and logic unit, as its name suggests, is designed to perform mathematical
operations. The organization of the CPU is shown in ­
Figure 1-3.
Central processing unit
(CPU)
Instruction
input
Arithmetic and
logic unit
(ALU)
Control unit
Result
output
Figure 1-3
A program is a sequence of instructions stored in the computer’s memory. When a
computer is running a program, the CPU is engaged in a process known formally as the
fetch/decode/execute cycle. The steps in the fetch/decode/execute cycle are as follows:
Fetch	
The CPU’s control unit fetches, from main memory, the next instruction in
the sequence of program instructions.
Decode	
The instruction is encoded in the form of a number. The control unit
decodes the instruction and generates an electronic signal.
Execute	
The signal is routed to the appropriate component of the computer (such as
the ALU, a disk drive, or some other device). The signal causes the ­component
to perform an operation.
These steps are repeated as long as there are instructions to perform.
1.2 Computer Systems: Hardware and Software 39
Main Memory
You can think of main memory as the computer’s work area. This is where the
­
computer stores a program while the program is running, as well as the data that the
program is working with. For example, suppose you are using a word processing
­
program to write an essay for one of your classes. While you do this, both the word
processing program and the essay are stored in main memory.
Main memory is commonly known as random-access memory or RAM. It is called this
because the CPU is able to quickly access data stored at any random location in this
memory. RAM is usually a volatile type of memory that is used only for temporary
storage while a program is running. When the computer is turned off, the contents of
RAM are erased. Inside your computer, RAM is stored in small chips.
A computer’s memory is divided into tiny storage cells known as bytes. One byte is
enough memory to store just a single letter of the alphabet or a small number. In order
to do anything meaningful, a computer has to have lots of bytes. Most computers
today have millions, or even billions, of bytes of memory.
Each byte is divided into eight smaller storage locations known as bits. The term bit
stands for binary digit. Computer scientists usually think of bits as tiny switches that
can be either on or off. Bits aren’t actual “switches,” however, at least not in the con-
ventional sense. In most computer systems, bits are tiny electrical components that can
hold either a positive or a negative charge. Computer scientists think of a positive charge
as a switch in the on position and a negative charge as a switch in the off position.
Each byte is assigned a unique number known as an address. The addresses are
ordered from lowest to highest. A byte is identified by its address, in much the same
way a post office box is identified by an address, so that the data stored there can be
located. ­Figure 1-4 shows a group of memory cells with their addresses. The number
149 is stored in the cell at address 16, and the number 72 is stored at address 23.
0
10
20
1
11
21
2
12
22
3
13
23
4
14
24
5
15
25
6
16
26
7
17
27
8
18
28
9
19
29
149
72
Figure 1-4
Secondary Storage
Secondary storage is a type of memory that can hold data for long periods of time—
even when there is no power to the computer. Frequently used programs are stored in
secondary memory and loaded into main memory as needed. Important information,
such as word processing documents, payroll data, and inventory figures, is saved to
secondary storage as well.
The most common type of secondary storage device is the disk drive. A disk drive
stores data by magnetically encoding it onto a circular disk. Most computers have a
40 Chapter 1 Introduction to Computers and Programming
disk drive mounted inside their case. External disk drives, which connect to one of
the computer’s communication ports, are also available. External disk drives can be
used to create backup copies of important data or to move data to another ­computer.
In addition to external disk drives, many types of devices have been created for copying
data and for moving it to other computers. The most commonly used devices today are
USB flash drives. These are small devices that plug into the computer’s USB (universal serial
bus) port and appear to the system as a disk drive. These drives, which use flash memory to
store data, are inexpensive, reliable, and small enough to be carried in your pocket.
Optical devices such as the CD (compact disc) and the DVD (digital versatile disc) are
also popular for data storage. Data is not recorded magnetically on an optical disc, but
rather is encoded as a series of pits on the disc surface. CD and DVD drives use a laser
to detect the pits and thus read the encoded data. Optical discs hold large amounts of
data, and because recordable CD and DVD drives are now commonplace, they are
good media for creating backup copies of data.
Input Devices
Input is any information the computer collects from the outside world. The device that
collects the information and sends it to the computer is called an input device. Com-
mon input devices are the keyboard, mouse, touch screen, scanner, digital camera, and
microphone. Disk drives, CD/DVD drives, and USB flash drives can also be considered
input devices because programs and information can be retrieved from them and
loaded into the computer’s memory.
Output Devices
Output is any information the computer sends to the outside world. It might be a sales
report, a list of names, or a graphic image. The information is sent to an output device,
which formats and presents it. Common output devices are computer screens, printers,
and speakers. Disk drives, USB flash drives, and CD/DVD recorders can also be con-
sidered output devices because the CPU can send information to them to be saved.
Software
If a computer is to function, software is needed. Everything that a computer does, from
the time you turn the power switch on until you shut the system down, is under the
control of software. There are two general categories of software: system software and
application software. Most computer programs clearly fit into one of these two ­categories.
Let’s take a closer look at each.
System Software
The programs that control and manage the basic operations of a computer are gener-
ally referred to as system software. System software typically includes the following
types of programs:
1.2 Computer Systems: Hardware and Software 41
• Operating Systems
An operating system is the most fundamental set of programs on a computer. The
operating system controls the internal operations of the computer’s hardware,
manages all the devices connected to the computer, allows data to be saved to and
retrieved from storage devices, and allows other programs to run on the computer.
• Utility Programs
A utility program performs a specialized task that enhances the computer’s
­
operation or safeguards data. Examples of utility programs are virus scanners,
file-compression programs, and data-backup programs.
• Software Development Tools
The software tools that programmers use to create, modify, and test software are
referred to as software development tools. Compilers and integrated development
environments, which we discuss later in this chapter, are examples of programs
that fall into this category.
Application Software
Programs that make a computer useful for everyday tasks are known as application
software, or application programs. These are the programs that people normally spend
most of their time running on their computers. Figure 1-1, at the beginning of this
chapter, shows screens from two commonly used applications Microsoft Word, a word
processing program, and Microsoft PowerPoint, a presentation program. Some other
examples of application software are spreadsheet programs, e-mail programs, Web
browsers, and game programs.
Checkpoint
1.1 Why is the computer used by so many different people, in so many different
professions?
1.2 List the five major hardware components of a computer system.
1.3 Internally, the CPU consists of what two units?
1.4 Describe the steps in the fetch/decode/execute cycle.
1.5 What is a memory address? What is its purpose?
1.6 Explain why computers have both main memory and secondary storage.
1.7 What are the two general categories of software?
1.8 What fundamental set of programs controls the internal operations of the
­computer’s hardware?
1.9 What do you call a program that performs a specialized task, such as a virus
scanner, a file-compression program, or a data-backup program?
1.10 Word processing programs, spreadsheet programs, e-mail programs, Web
browsers, and game programs belong to what category of software?
42 Chapter 1 Introduction to Computers and Programming
1.3 Programs and Programming Languages
CONCEPT: A program is a set of instructions a computer follows in order to
perform a task. A programming language is a special language used to
write computer programs.
What Is a Program?
Computers are designed to follow instructions. A computer program is a set of instruc-
tions that tells the computer how to solve a problem or perform a task. For example,
suppose we want the computer to calculate someone’s gross pay. Here is a list of things
the computer might do:
1. Display a message on the screen asking “How many hours did you work?”
2. Wait for the user to enter the number of hours worked. Once the user enters a
number, store it in memory.
3. Display a message on the screen asking “How much do you get paid per hour?”
4. Wait for the user to enter an hourly pay rate. Once the user enters a number, store
it in memory.
5. Multiply the number of hours by the amount paid per hour, and store the result
in memory.
6. Display a message on the screen that tells the amount of money earned. The
­
message must include the result of the calculation performed in step 5.
Collectively, these instructions are called an algorithm. An algorithm is a set of well-
defined steps for performing a task or solving a problem. Notice these steps are ordered
sequentially. Step 1 should be performed before step 2, and so forth. It is important
that these instructions be performed in their proper sequence.
Although a person might easily understand the instructions in the pay-calculating algorithm,
it is not ready to be executed on a computer because a computer’s CPU can only process
instructions written in machine language. A machine language program consists of a
sequence of binary numbers (numbers consisting of only 1s and 0s), which the CPU interprets
as commands. Here is an example of what a machine language instruction might look like:
1011010000000101
As you can imagine, encoding an algorithm in machine language would be tedious and
difficult. In addition, each different type of CPU has its own machine language. So if
you wrote a machine language program for computer A and then wanted to run it on
a computer B that has a different type of CPU, you would have to rewrite the program
in computer B’s machine language.
Programming languages, which use words instead of numbers, were invented to ease the task
of programming. A program can be written in a programming language such as C++, which
is much easier to understand and write than machine language. Programmers can then save
their programs in text files and use special software to convert them to machine language.
Program 1-1 shows how the pay-calculating algorithm might be written in C++.
1.3 Programs and Programming Languages 43
NOTE: The line numbers shown in Program 1-1 are not part of the program. This
book shows line numbers in all program listings to help point out specific parts of
the program.
Program 1-1
1 // This program calculates the user's pay.
2 #include iostream
3 using namespace std;
4
5 int main()
6 {
7 double hours, rate, pay;
8
9 // Get the number of hours worked.
10 cout  How many hours did you work? ;
11 cin  hours;
12
13 // Get the hourly pay rate.
14 cout  How much do you get paid per hour? ;
15 cin  rate;
16
17 // Calculate the pay.
18 pay = hours * rate;
19
20 // Display the pay.
21 cout  You have earned $  pay  endl;
22 return 0;
23 }
Program Output with Example Input Shown in Bold
How many hours did you work? 10 [Enter]
How much do you get paid per hour? 15 [Enter]
You have earned $150
The “Program Output with Example Input Shown in Bold” shows what the program
will display on the screen when it is running. In the example, the user enters 10 for the
number of hours worked and 15 for the hourly pay. The program displays the earn-
ings, which are $150.
Programming Languages
In a broad sense, there are two categories of programming languages: low level and
high level. A low-level language is close to the level of the computer, which means it
resembles the numeric machine language of the computer more than the natural lan-
guage of humans. The easiest languages for people to learn are high-level languages.
They are called “high level” because they are closer to the level of human-readability
than computer-readability. Figure 1-5 illustrates the concept of language levels.
44 Chapter 1 Introduction to Computers and Programming
Low level (machine language)
10100010 11101011
High level (Easily understood by humans)
Figure 1-5
Many high-level languages have been created. Table 1-1 lists a few of the well-known ones.
Table 1-1 Well-Known High-Level Programming Languages
Language Description
BASIC	
Beginners All-purpose Symbolic Instruction Code. A general programming
language originally designed to be simple enough for beginners to learn.
C	
A structured, general-purpose language developed at Bell Laboratories. C offers
both high-level and low-level features.
C++	
Based on the C language, C++ offers object-oriented features not found in C. Also
invented at Bell Laboratories.
C#	
Pronounced “C sharp.” A language invented by Microsoft for developing
applications based on the Microsoft .NET platform.
COBOL	
Common Business-Oriented Language. A language designed for business applications.
FORTRAN	
Formula Translator. A language designed for programming complex mathematical
algorithms.
Java	
An object-oriented language invented at Sun Microsystems. Java may be used to
develop programs that run over the Internet in a Web browser.
JavaScript	
A language used to write small programs that run in Web pages. Despite its name,
JavaScript is not related to Java.
Pascal	
A structured, general-purpose language designed primarily for teaching programming.
Python	
A general-purpose language created in the early 1990s. It has become popular for
both business and academic applications.
1.3 Programs and Programming Languages 45
C++ is a widely used language because, in addition to the high-level features necessary
for writing applications such as payroll systems and inventory programs, it also has
many low-level features. C++ is based on the C language, which was invented for pur-
poses such as writing operating systems and compilers. Because C++ evolved from C, it
carries all of C’s low-level capabilities with it.
C++ is also popular because of its portability. This means that a C++ program can be
written on one type of computer and then run on many other types of systems. This
usually requires recompiling the program on each type of system, but the program
itself often needs little or no change.
Ruby	
A general-purpose language created in the 1990s. It is becoming increasingly
popular for programs that run on Web servers.
Visual Basic	
A Microsoft programming language and software development environment that
allows programmers to quickly create Windows-based applications.
NOTE: Programs written for specific graphical environments typically do require sig-
nificant changes when moved to a different type of system. Examples of such graphical
environments are Windows, the X-Window System, and the Mac OS operating system.
Source Code, Object Code, and Executable Code
When a C++ program is written, it must be typed into the computer and saved to a file.
A text editor, which is similar to a word processing program, is used for this task. The
statements written by the programmer are called source code, and the file they are
saved in is called the source file.
After the source code is saved to a file, the process of translating it to machine language
can begin. During the first phase of this process, a program called the preprocessor reads
the source code. The preprocessor searches for special lines that begin with the # symbol.
These lines contain commands, or directives, that cause the preprocessor to amend or
process the source code in some way. During the next phase the compiler steps through
the preprocessed source code, translating each source code instruction into the appropri-
ate machine language instruction. This process will uncover any syntax errors that may be
in the program. Syntax errors are illegal uses of key words, operators, punctuation, and
other language elements. If the program is free of syntax errors, the compiler stores the
translated machine language instructions, which are called object code, in an object file.
Although an object file contains machine language instructions, it is not a complete
program. Here is why. C++ is conveniently equipped with a library of prewritten code for
performing common operations or sometimes-difficult tasks. For example, the library
­
contains hardware-specific code for displaying messages on the screen and reading input
from the keyboard. It also provides routines for mathematical functions, such as calculating
the square root of a number. This collection of code, called the run-time library, is extensive.
Programs almost always use some part of it. When the compiler generates an object file,
however, it does not include machine code for any run-time library routines the programmer
might have used. During the last phase of the translation process, another program called
the linker combines the object file with the necessary library routines. Once the linker has
finished with this step, an executable file is created. The executable file contains machine
language instructions, or executable code, and is ready to run on the computer.
46 Chapter 1 Introduction to Computers and Programming
Figure 1-6 illustrates the process of translating a C++ source file into an executable file.
The entire process of invoking the preprocessor, compiler, and linker can be initiated
with a single action. For example, on a Linux system, the following command causes
the C++ program named hello.cpp to be preprocessed, compiled, and linked. The
executable code is stored in a file named hello.
g++ -o hello hello.cpp
Source code
hello.cpp
Preprocessor
Modified
source code
Compiler
Object code
hello.obj
Executable code
hello.exe
Linker
Source code is entered
with a text editor by
the programmer.
// hello.cpp
#include iostream
using namespace std;
int main( )
{
cout  Hello Worldn;
return 0;
}
Figure 1-6
Many development systems, particularly those on personal computers, have integrated
development environments (IDEs). These environments consist of a text editor, com-
piler, debugger, and other utilities integrated into a package with a single set of menus.
Preprocessing, compiling, linking, and even executing a program is done with a single
click of a button, or by selecting a single item from a menu. Figure 1-7 shows a screen
from the Microsoft Visual Studio 2013 IDE.
1.4 What Is a Program Made of? 47
Figure 1-7
Checkpoint
1.11 What is an algorithm?
1.12 Why were computer programming languages invented?
1.13 What is the difference between a high-level language and a low-level language?
1.14 What does portability mean?
1.15 Explain the operations carried out by the preprocessor, compiler, and linker.
1.16 Explain what is stored in a source file, an object file, and an executable file.
1.17 What is an integrated development environment?
1.4 What Is a Program Made of?
CONCEPT: There are certain elements that are common to all programming languages.
Language Elements
All programming languages have a few things in common. Table 1-2 lists the common
elements found in almost every language.
48 Chapter 1 Introduction to Computers and Programming
Let’s look at some specific parts of Program 1-1 (the pay-calculating program) to see exam-
ples of each element listed in the table above. For convenience, Program 1-1 is listed again.
Table 1-2 Programming Language Elements
Language Element Description
Key Words	
Words that have a special meaning. Key words may only be used for
their intended purpose. Key words are also known as reserved words.
Programmer-Defined Words or names defined by the programmer. They are symbolic names
Identifiers that refer to variables or programming routines.
Operators	
Operators perform operations on one or more operands. An operand is
usually a piece of data, like a number.
Punctuation	
Punctuation characters that mark the beginning or ending of a statement,
or separate items in a list.
Syntax	
Rules that must be followed when constructing a program. Syntax
dictates how key words and operators may be used, and where
punctuation symbols must appear.
Program 1-1
1 // This program calculates the user's pay.
2 #include iostream
3 using namespace std;
4
5 int main()
6 {
7 double hours, rate, pay;
8
9 // Get the number of hours worked.
10 cout  How many hours did you work? ;
11 cin  hours;
12
13 // Get the hourly pay rate.
14 cout  How much do you get paid per hour? ;
15 cin  rate;
16
17 // Calculate the pay.
18 pay = hours * rate;
19
20 // Display the pay.
21 cout  You have earned $  pay  endl;
22 return 0;
23 }
Key Words (reserved words)
Three of C++’s key words appear on lines 3 and 5: using, namespace, and int. The word
double, which appears on line 7, is also a C++ key word. These words, which are always
written in lowercase, each have a special meaning in C++ and can only be used for their
1.4 What Is a Program Made of? 49
intended purposes. As you will see, the programmer is allowed to make up his or her own
names for certain things in a program. Key words, however, are reserved and cannot be
used for anything other than their designated purposes. Part of learning a programming
language is learning what the key words are, what they mean, and how to use them.
NOTE: The #include iostream statement in line 2 is a preprocessor directive.
NOTE: In C++, key words are always written in all lowercase.
Programmer-Defined Identifiers
The words hours, rate, and pay that appear in the program on lines 7, 11, 15, 18, and
21 are programmer-defined identifiers. They are not part of the C++ language but
rather are names made up by the programmer. In this particular program, these are the
names of variables. As you will learn later in this chapter, variables are the names of
memory locations that may hold data.
Operators
On line 18 the following statement appears:
pay = hours * rate;
The = and * symbols are both operators. They perform operations on pieces of data, known
as operands. The * operator multiplies its two operands, which in this example are the
variables hours and rate. The = symbol is called the assignment operator. It takes the
value of the expression on the right and stores it in the variable whose name appears on the
left. In this example, the = operator stores in the pay variable the result of the hours vari-
able multiplied by the rate variable. In other words, the statement says, “Make the pay
variable equal to hours times rate” or “pay is assigned the value of hours times rate.”
Punctuation
Notice that many lines end with a semicolon. A semicolon in C++ is similar to a period in
English. It marks the end of a complete sentence (or statement, as it is called in program-
ming). Semicolons do not appear at the end of every line in a C++ program, however.
There are rules that govern where semicolons are required and where they are not. Part
of learning C++ is learning where to place semicolons and other punctuation symbols.
Lines and Statements
Often, the contents of a program are thought of in terms of lines and statements. A line is
just that—a single line as it appears in the body of a program. Program 1-1 is shown with
each of its lines numbered. Most of the lines contain something meaningful; however, some
of the lines are empty. The blank lines are only there to make the program more readable.
A statement is a complete instruction that causes the computer to perform some action.
Here is the statement that appears in line 10 of Program 1-1:
cout  How many hours did you work? ;
Other documents randomly have
different content
Thicken cream of corn soup a little more if necessary, or, add corn to
thin cream sauce, and serve on toast. Left-overs of all sorts of cream
soups may be utilized for toast: celery, asparagus, string bean,
oyster plant and spinach, also succotash and other stewed or
creamed vegetables.
Lentil and Other Legume Toasts
Use any lentil gravy or thickened lentil soup, cream of peas or peas
and tomato soup thickened, red kidney beans purée or thickened
soup, on moistened slices of zwieback.
Toast Royal
1 cup drawn butter sauce
3 eggs
1 cup minced trumese or nutmese or ½ cup chopped nuts
Add meat to hot sauce and pour all over beaten salted eggs;
cook as scrambled eggs. Serve immediately on moistened slices of
zwieback, with baked tomatoes when convenient.
The following toasts are of a different nature (though slices of
zwieback may be used instead of bread), but they are good
emergency dishes.
French Toast
Add ½ cup of milk with salt to 2 or 3 beaten eggs. Dip slices of stale
bread or moistened zwieback in the mixture and brown delicately on
both sides on moderately hot buttered griddle or in quick oven, or in
frying pan covered. Serve plain or with any suitable sauce.
Drain slices after dipping in egg mixture; crumb, bake, and serve
with honey, maple syrup or jelly for Breaded French Toast.
German Toast
Add grated or fine chopped onion to egg mixture and finish the
same as French toast.
Spanish Cakes
Batter—2 eggs, 2 tablespns. flour, 1 teaspn. of oil, milk for smooth
thin batter. Nut milk may be used and oil omitted.
Cut thin slices of bread into any desired shape (round with biscuit
cutter), spread each one of half the pieces with jelly, jam or
marmalade and press another on to it; dip in the batter, lay on oiled
baking pan, stand 15 m. or longer in a cold place. Bake in a quick
oven, serve with a bit of the preserve on top and half of a nut
pressed into each, or, dusted with powdered sugar.
Mamie’s Surprise Biscuit
Inclose small cakes of nicely seasoned mashed potato in pastry
crust; bake, serve with milk gravy, drawn butter or cream sauce, or
with celery only. This is the original recipe which leads to the
following variations:
Mix finely-sliced celery with the potato.
Use the mixture of black walnut and potato stuffing, or mashed
lentils or mashed peas for filling.
Serve peas biscuit with tomato or tomato cream sauce.
Serve lentil biscuit with cream, cream of tomato or mushroom
sauce.
Lentil biscuit with fresh mushroom or Boundary Castle sauce,
with or without celery, might constitute one course at a dinner.
Make a filling of minced trumese, salt, oil, chopped parsley, onion
and mushrooms into small cakes or balls, inclose them in universal
crust, and when light, steam 25–30 m. Serve with drawn butter,
flavored with onion and parsley, or as garnish for a meat dish. Make
balls quite small for garnish.
Yorkshire Pudding
½ cup flour
salt
1⅓ cup milk
2 eggs
1 teaspn. oil
Beat eggs, add milk and pour gradually into flour mixed with salt;
add oil, beat well, turn into well oiled, or oiled and crumbed gem
pans; bake in moderate (slow at first) oven.
Serve as garnish or accompaniment to ragout, or if baked in flat
cakes, with slices of broiled or à la mode meats laid on them, and
gravy poured around. The pudding may be baked in a flat pan and
cut into any desired shape for serving. Whites and yolks of eggs may
be beaten separately. A large onion chopped may be used in the
pudding.
Rice Border
Pack hot boiled rice into well oiled border mold and let stand in a
warm place (over kettle of hot water) for 10 m. Turn on to serving
dish carefully.
Or, parboil 1 cup of rice in salted water 5 m.; drain and cook in a
double boiler with 2½–3 cups of milk and salt, until the rice is
tender and the milk absorbed, then pack into the mold.
1 tablespn. of butter and the yolks of 2 eggs may be added to
the rice about 2 m. before it is taken from the double boiler.
Oyster Plant and Potato Omelet—without eggs
With nicely seasoned, not too moist, mashed potato, mix slices of
cooked oyster plant which have been simmered in cream or butter.
Spread in well oiled frying or omelet pan. When delicately browned
on the bottom, fold, omelet fashion, turn on to a hot platter, garnish.
Serve plain or with cream sauce or with thin drawn butter. Or, grind
oyster plant, cook in a small quantity of water, add cream or butter
and mix with plain potato. Finely-sliced raw celery or chopped raw
onion and parsley may be used in the potato sometimes.
Baked Potatoes and Milk
Wash potatoes well, scrubbing with vegetable brush. Cut out any
imperfect spots. Bake until just done. Break up, skins and all, into
nice rich milk and eat like bread and milk for supper. A favorite dish
of some of the early settlers in Michigan.
Bread and Milk with Sweet Fruits
Add nice ripe blueberries to bread and milk for supper, also ripe
black raspberries or baked sweet apples. They are all delicious.
★ Apples in Oil
Simmer finely-sliced onion in oil 5–10 m. without browning; add salt
and a little water, then apples which have been washed, quartered,
cored and sliced without paring. Sprinkle lightly with salt. Cover and
cook until apples are just tender, not broken. Serve for breakfast or
supper, or with a meat dish instead of a vegetable, for luncheon or
dinner.
The onion may be omitted. Use a little sugar when apples are
very sour.
Onion Apples
Simmer sliced onions in oil, with salt, in baking pan. Place apples,
pared and cored, on top of the onions; sprinkle with sugar and put
¼ teaspn. in each cavity. Cover, bake; uncover and brown. Serve for
luncheon, or as garnish for meat dish.
TRUE MEATS
“And God said, Behold I have given you every herb bearing seed,
which is upon the face of all the earth, and every tree, in the which
is the fruit of a tree yielding seed; to you it shall be for meat.” Gen.
1:29.
“The food which God gave Adam in his sinless state is the best
for man’s use as he seeks to regain that sinless state.
“The intelligence displayed by many dumb animals approaches so
closely to human intelligence that it is a mystery.
“The animals see and hear and love and fear and suffer.
“They manifest sympathy and tenderness toward their
companions in suffering.
“They form attachments for man which are not broken without
great suffering to them.
“Think of the cruelty to animals that meat eating involves and its
effect on those who inflict and those who behold it. How it destroys
the tenderness with which we should regard these creatures of
God!”
The high price of flesh foods, the knowledge of the waste matter
in the blood of even healthy animals which remains in their flesh
after death, and the well authenticated reports of the increasing
prevalence of most loathsome diseases among them, causes a
growing desire among thinking people to take their food at first
hand, before it has become a part of the body of some lower animal.
So, the great food question of the day is—“What shall we use in
the place of meat?”
Nuts, legumes (peas, beans, lentils and peanuts) and eggs
contain as do flesh meats, an excess of the proteid or muscle-
building elements (nuts and legumes a much larger proportion than
flesh), so we may combine these with fruits, vegetables and some of
the cereals (rice, for instance) and have a perfect proportion of food
elements.
It must be borne in mind, however, that proteid foods must be
used sparingly, since an excess of these foods causes some of the
most serious diseases.
The bulk of our foods should be made up of fruits and vegetables
and some of the less hearty cereals and breads.
NUTS
As nuts occupy the highest round of the true meat ladder, we give a
variety of recipes for their use, following with legumes and eggs in
their order.
With nuts, as with other foods, the simplest way to use them is
the best. There are greater objections to foods than that they are
difficult of digestion, and in the case of nuts, that objection is
overcome by thorough mastication; in fact, they are an aid to the
cultivation of that important function in eating.
For those who are not able to chew their food, nuts may be
ground into butter.
Another aid to the digestion of nuts is the use with them of an
abundance of acid fruits. Fruits and nuts seem to be each the
complement of the other, the nuts as well, preventing the unpleasant
effects felt by some in the free use of fruits.
“No investigations have been found on record which demonstrate
any actual improvement in the digestibility of nuts due to salt.”—
M. E. Jaffa, M. S., Professor of Nutrition, University of California.
Be sure that nuts are fresh. Rancid nuts are no better than rancid
butter. Shelled nuts do not keep as well as those in the shell.
Almonds stand at the head of the nut family. It is better to buy
them in the shell as shelled almonds are apt to have bitter ones
among them. Almonds should not be partaken of largely with the
brown covering on, but are better to be blanched.
To Blanch Almonds—Throw them into perfectly boiling water, let
them come to the boiling point again, drain, pour cold water over
them and slip the skins off with the thumb and finger. Drop the
meats on to a dry towel, and when they are all done, roll them in
the towel for a moment, then spread them on plates or trays to dry.
They must be dried slowly as they color easily, and the sweet
almond flavor is gone when a delicate color only, is developed. For
butter they must be very dry, really brittle.
Brazil Nuts—castanas—cream nuts, do not require blanching, as
their covering does not seem to be objectionable. They are rich in oil
and are most valuable nuts. Slice and dry them for grinding.
Filberts—hazelnuts—cobnuts—Barcelonas, also may be eaten
without blanching, though they may be heated in the oven (without
browning) or put into boiling water and much of the brown covering
removed. They are at their best unground, as they do not give an
especially agreeable flavor to cooked foods. They may be made into
butter.
Brazil nuts and filberts often agree with those who cannot use
English walnuts and peanuts.
English Walnuts—The covering of the English walnut is
irritating and would better be removed when practicable. This is
done by the hot water method, using a knife instead of the thumb
and finger. The unblanched nuts may however, be used in
moderation by nearly every one.
Butternuts and black walnuts blanch more easily than the English
walnut.
When whole halves of such nuts as hickory nuts, pecans or
English walnuts are required, throw the nuts into boiling water for
two or three minutes, or steam them for three or four minutes, or
wrap them in woolen cloths wrung out of boiling water. Crack, and
remove meats at once. Do not leave nuts in water long enough to
soak the meats.
Pinenuts come all ready blanched. When they require washing,
pour boiling water over them first, then cold water. Drain, dry in
towels, then on plates in warm oven.
Peanuts—ground nuts, because of their large proportion of oil,
and similarity in other respects to nuts are classed with them,
though they are truly legumes.
The Spanish peanut contains more oil than the Virginia, but the
flavor of the Virginia is finer and its large size makes it easier to
prepare. The “Jumbos” are the cheapest.
To blanch Spanish peanuts the usual way, heat for some time,
without browning, in a slow oven, stirring often. When cool rub
between the hands or in a bag to remove the skins. The best way to
blow the hulls away after they are removed is to turn the nuts from
one pan to another in the wind.
Spanish peanuts can be obtained all ready blanched from the nut
food factories.
The Virginias, not being so rich in oil must always be blanched
the same as almonds. Be sure to let them boil well before draining. I
prefer to blanch the Spanish ones that way, too, the results are so
much more satisfactory.
When peanuts are partly dried, break them apart and remove the
germ, which is disagreeable and unwholesome: then finish drying.
A FEW SUGGESTIVE COMBINATIONS
For Using Nuts in the Simplest Ways
Brazil nuts, filberts or blanched almonds with:—
Fresh apples, pears or peaches;
Dried, steamed or stewed figs, raisins, dates, prunes, apple
sauce, baked apples or baked quinces;
Celery, lettuce, cabbage, tender inside leaves of spinach, grated
raw carrot or turnip;
Breakfast cereals, parched or popped corn, well browned
granella, crackers, gems, zwieback, Boston brown and other
breads;
Stewed green peas, string beans, asparagus, corn, greens,
potatoes, squash, cauliflower, all vegetables;
Pies, cakes and different desserts when used.
Nut Butter
A good nut butter mill is an excellent thing to have, but butter can
be made with the food cutters found nowadays in almost every
home. If the machine has a nut butter attachment, so much the
better; otherwise the nuts will need to be ground repeatedly until
the desired fineness is reached.
For almond butter, blanch and dry the almonds according to
directions, adjust the nut butter cutter, not too tight, put two or
three nuts into the mill at a time, and grind. When the almonds are
thoroughly dried they will work nicely if the mill is not fed too fast.
Brazil nuts and filberts need to be very dry for butter.
Pine nuts are usually dry enough as they come to us.
All nuts grind better when first dried.
Raw peanut butter is a valuable adjunct to cookery. To make,
grind blanched dried nuts; pack in tins or jars and keep in a dry
place.
For steamed butter, put raw butter without water into a double
boiler or close covered tins and steam 3–5 hours. Use without
further cooking in recipes calling for raw nut butter.
Or, grind dried boiled nuts the same as raw nuts. For immediate
use, boiled nuts may be ground without drying.
When roasted nut butter is used, it should be in small quantities
only, for flavoring soups, sauces or desserts.
My experience is that the best way to roast nuts for butter is to
heat them, after they are blanched and dried, in a slow oven, stirring
often, until of a cream or delicate straw color. By this method they
are more evenly colored all through. Do not salt the butter, as salt
spoils it for use with sweet dried fruits as a confection, and many
prefer it without salt on their bread.
The objection to roasted nuts is the same as for browning any
oil. Raising the oil of the nuts to a temperature high enough to
brown it, decomposes it and develops a poisonous acid.
Hardly too much can be said of the evil effects of the free use of
roasted nut butter.
“There are many persons who find that roasted peanuts eaten in
any quantity are indigestible in the sense of bringing on pain and
distress.... Sometimes this distress seems to be due to eating
peanuts which are roasted until they are very brown.”
—Mary Hinman Abel, Farmers’ Bulletin, No. 121, U.S. Department
of Agriculture.
Nut Meal
Nut meal is made the same as nut butter except that the nuts are
ground fewer times through the finest cutter of the mill, or once only
through the nut butter cutter loosely adjusted. Either cooked or raw
peanuts may be used, but a cooked peanut meal is very desirable.
The nuts may be cooked, dried and ground, or cooked without
water, after grinding, the same as steamed nut butter.
When one has no mill, meal of many kinds of nuts may be made
in the following manner:
Pound a few at a time in a small strong muslin bag; sift them
through a wire strainer and return the coarse pieces to the bag
again with the next portion. Be sure that not the smallest particle of
shell is left with the meats.
A dear friend of mine used to keep jars of different nut meals
prepared in this way on hand long before any manufactured ones
were on the market.
One writer says: “The children enjoy cracking the nuts and
picking out the meats, and it is a short task to prepare a cupful.”
Cooked nuts and some raw ones may be rubbed through the
colander for meal.
Nut meals are used for shortening pie crust, crackers and sticks;
and all except peanut, are delightful sprinkled over stewed fruits or
breakfast foods.
Nut Butter for Bread
Nut butters (except raw peanut) may be used on bread as they are
ground; but are usually stirred up with water to an agreeable butter-
like consistency, and salt added.
Strained tomato may be used instead of water for a change. This
is especially nice for sandwiches. With peanut butter made from
boiled or steamed nuts it has a flavor similar to cheese.
Nut butter is more attractive for the table when pressed through
a pastry tube in roses on to individual dishes. Use a cloth (not
rubber) pastry bag.
While pure nut butter, if kept in a dry place, will keep almost
indefinitely, it will sour as quickly as milk after water is added to it.
Nut Cream and Milk
Add water to nut butter until of the desired consistency, for cream;
then still more, for milk.
Almond milk makes a delightful drink and can be used by many
who cannot take dairy milk. It may be heated and a trifle of salt
added.
Cocoanut Milk
If you have not a cocoanut scraper, grate fresh cocoanut, one with
milk in it, or grind it four or five times through the finest cutter of a
mill. Pour over it an equal bulk or twice its bulk, of boiling water,
according to the richness of the milk desired or the quality of the
cocoanut. Stir and mix well and strain through cheese cloth or a wire
strainer. Add a second quantity of hot water and strain again,
wringing or pressing very dry. Throw the fibre away.
Use cocoanut milk or cream for vegetable or pudding sauces or
in almost any way that dairy milk and cream are used. Stir before
using. To break the nut in halves, take it in the left hand and strike it
with a hammer in a straight line around the center. It may be sawed
in two if the cups are desired for use.
Cocoanut Butter
Place milk on ice for a few hours when the butter will rise to the top
and can be skimmed off.
Ground or Grated Cocoanut
Is delightful on breakfast cereals, or eaten with bread in place of
butter. The brown covering of the meat should first be taken off.
Shredded Cocoanut
Put any left-overs of prepared cocoanut on a plate and set in the sun
or near the stove to dry. Keep in glass jars in a dry place. This
unsweetened cocoanut can be used for shortening and in many
places where sweet is not desirable.
Milk and Rich Cream of Raw Peanuts
May be prepared the same as cocoanut milk, except that cold or
lukewarm water is used instead of hot.
To raw nut meal (not butter) add one half more of water than
you have of meal. Mix and beat well, strain through a thin cloth,
squeeze as dry as possible. Let milk stand in a cool place and a very
rich cream will rise which may be used for shortening pie crust,
crackers and sticks, or in place of dairy cream in other ways. The
skimmed milk will be suitable for soups, stews or gravies. It may be
cooked before using if more convenient. The pulp also may be used
in soups. It should be thoroughly cooked.
Nut Relish
Different nut butters and meals may be combined in varying
proportions. For instance, 2 parts Brazil nuts, 1 part each pine nuts
and almonds; or 1 part each Brazil nuts, almonds, pecans, and pine
nuts. Dry nuts well and grind all together or combine after grinding.
Press into tumblers or small tins and stand in cool place. Unmold to
serve. The relish may be used in combinations suggested for whole
nuts, and it is a great improvement over cheese, with apple pie.
Toasted Almonds
When blanched almonds are thoroughly dried, put them into a slow
oven and let them come gradually to a delicate cream color, not
brown. These may be served in place of salted almonds.
Sweetmeats of fruits and nuts will be found among confections.
COOKED NUT DISHES
Nut Croquettes
1 cup chopped nuts (not too fine), hickory, pecan, pine or
butternuts, or a mixture of two with some almonds if desired; 2 cups
boiled rice or hominy, 1½ tablespn. oil or melted butter, salt, sage.
Mix, shape into rolls about 1 in. in diameter and 2½ in. in length.
Egg and crumb; bake in quick oven until just heated through and
delicately browned, 8 to 10 m. Serve plain or with any desired sauce
or vegetable.
Nut Croquettes No. 2
1 cup chopped nuts, 1 cup cooked rice, any desired seasoning or
none, salt; mix.
Sauce—
2 tablespns. oil
½ cup flour
1–1¼ cup milk
1 egg or yolk only or no egg
salt
Heat but do not brown the oil, add half the flour, then the milk,
and when smooth, the salt and the remainder of the flour, and
combine with mixed nuts and rice. Cool, shape, egg, crumb, bake.
Crumb also before dipping in egg the same as Trumese croquettes, if
necessary. Bake only until beginning to crack. Serve at once.
Savory Nut Croquettes
1 cup stale, quite dry, bread crumbs, ½ cup (scant) milk or
consommé, ¼–½ level teaspn. powdered leaf sage or winter savory,
½ cup black walnut or butternut meats, salt. Mix, shape, egg,
crumb, bake.
1 cup chopped mixed nuts may be used and celery salt or no
flavoring. Hickory nut meats alone, require no flavoring.
Nut and Sweet Potato Cutlets
1 cup chopped nut meats
2 cups chopped boiled sweet potato
1 tablespn. butter
1 egg
salt
Mix while warm. Pack in brick-shaped tin until cold. Unmold, slice,
egg, crumb or flour. Brown in quick oven or on oiled griddle. Serve
plain or with sauce 16 or 17.
★ Baked Pine Nuts
After picking out the pieces of shell, pour boiling water over 2 lbs. of
pine nuts in a fine colander. Rinse in cold water and put into the
bean pot, with 2 large onions sliced fine, 1–1⅓ cup strained tomato
and 2–2½ teaspns. salt. Heat quite rapidly at first; boil gently for a
half hour, then simmer slowly in the oven 10–12 hours or longer.
Leave just juicy for serving.
Black Walnut and Potato Mound
Mix 1 qt. nicely seasoned, well beaten mashed potato, ½–1 cup
chopped black walnut meats and 2 or 3 tablespns. grated onion. Pile
in rocky mound on baking pan or plate. Sprinkle with crumbs or not.
Bake in quick oven until delicately browned. Garnish and serve with
sauce 6 or 16.
Nut and Rice Roast or Timbale
1–2 cups chopped nuts, one kind or mixed (no English walnuts
unless blanched), 2 cups boiled or steamed rice, 1½–3 tablespns. oil
or melted butter, salt.
Mix ingredients and put into well oiled timbale mold or individual
molds or brick shaped tin. Bake covered, in pan of water ¾–1½ hr.
according to size of mold. Uncover large mold a short time at the
last. Let stand a few minutes after removing from oven, unmold, and
serve with creamed celery or peas or with sauce 16 (cocoanut cream
if convenient) or 34.
Loaf may be flavored, and served with any suitable sauce.
Loaf of Nuts
2 tablespns. raw nut butter
⅓ cup whole peanuts cooked almost tender
½ cup each chopped or ground pecans, almonds and filberts (or
butternuts, hazelnuts, and hickory nuts)
2 cups stale bread crumbs pressed firmly into the cup
salt
¾–1 cup water or 1 of milk
The quantity of liquid will depend upon the crumbs and other
conditions. Put into oiled mold or can, cover, steam 3 hours. Or, have
peanuts cooked tender, form into oval loaf, bake on tin in oven,
basting occasionally with butter and water or salted water only.
Serve with sauce 9, 10, 57, 59, or 69. Loaf may be served cold in
slices, or dipped in egg, and crumbed, and baked as cutlets.
Other nuts may be substituted for peanuts.
One-half cup black walnuts and 1½ cup cooked peanuts,
chopped, make a good combination. A delicate flavoring of sage,
savory or onion is not out of place with these.
To Boil Peanuts
Put blanched, shelled peanuts into boiling water and boil
continuously, for from 3–5 hrs., or until tender. (When the altitude is
not great it takes Virginias 4 or 5 hours and Spanish about 3 to cook
tender).
Drain, saving the liquid for soup stock, and use when boiled
peanuts are called for.
Nut Soup Stock
Use the liquid, well diluted, poured off from boiled peanuts, for
soups. Large quantities may be boiled down to a jelly and kept for a
long time in a dry place. If paraffine is poured over the jelly, it will
keep still better. Use 1 tablespn. only of this jelly for each quart of
soup.
Peanuts with Green Peas
Boil 1 cup blanched peanuts 1–2 hrs., drain off the water and save
for soup. Put fresh water on to the peanuts, add salt and finish
cooking. Just before serving add 1 pt. of drained, canned peas. Heat
well. Add more salt if necessary, and serve. Or, 1 pt. of fresh green
peas may be cooked with the nuts at the last. Small new potatoes
would be a suitable addition also.
★ Peanuts Baked like Beans
1 lb. (¾ qt.) blanched peanuts
¼ cup strained tomato
½–1 tablespn. browned flour
1¼–1½ teaspn. salt
Mix browned flour, tomato and salt, put into bean pot with the
nuts and a large quantity of boiling water. Boil rapidly ½ hr., then
bake in a slow oven 8–14 hours. Add boiling water without stirring,
when necessary. When done the peanuts should be slightly juicy.
Small dumplings steamed separately, may be served with baked
peanuts sometimes.
Baked Peanuts—Lemon Apples
Pile peanuts in center of platter or chop tray. Surround with lemon
apples, garnish with grape leaves and tendrils or with foliage plant
leaves.
Peanuts with Noodles or Vermicelli
Cook peanuts in bouillon with bay leaf and onions. Just before
serving, add cooked noodles or vermicelli.
Nut Chinese Stew
Use boiled peanuts instead of nutmese and raw nut butter, and rice
(not too much) in place of potato, in Nut Irish Stew.
Peanut Gumbo
Simmer sliced or chopped onion in butter; add 1 pt. stewed okra;
simmer 5–10 m. Add 1 pt. strained tomato, then ¾–1 qt. of baked
or boiled peanuts. Turn into a double boiler and add ½ cup boiled
rice. Heat 15–20 m.
Hot Pot of Peanuts
Put layers of sliced onion, sliced potatoes and boiled peanuts into
baking dish with salt and a slight sprinkling of sage. Cover the top
with halved potatoes. Stir a little raw nut butter with water and pour
over all. Cover with a plate or close fitting cover and bake 2 hours.
Remove cover and brown.
Peanut Hashes
Cooked peanuts, chopped very little if any, may be used in place of
trumese with potatoes or rice for hash.
Bread, cracker or zwieback crumbs may be substituted for potato
or rice.
Peanut German Chowder
1 pt. cooked peanuts
1 large onion
2 tablespns. chopped parsley
½ medium sized bay leaf
⅛ level teaspn. thyme
1 small carrot
1 level tablespn. browned flour
2 level tablespns. white flour
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com

Starting Out With C Early Objects 9th Global Edition Gaddis

  • 1.
    Starting Out WithC Early Objects 9th Global Edition Gaddis download https://ebookbell.com/product/starting-out-with-c-early- objects-9th-global-edition-gaddis-21355086 Explore and download more ebooks at ebookbell.com
  • 2.
    Here are somerecommended products that we believe you will be interested in. You can click the link to download. Starting Out With C Early Objects 7th Edition 7th Edition Tony Gaddis https://ebookbell.com/product/starting-out-with-c-early-objects-7th- edition-7th-edition-tony-gaddis-2451550 Starting Out With C Early Objects Formerly Alternate Edition 5th Edition Tony Gaddis Godfrey Muganda Judy Walters https://ebookbell.com/product/starting-out-with-c-early-objects- formerly-alternate-edition-5th-edition-tony-gaddis-godfrey-muganda- judy-walters-36151162 Starting Out With C Early Objects 8th Edition Tony Gaddis https://ebookbell.com/product/starting-out-with-c-early-objects-8th- edition-tony-gaddis-5033276 Starting Out With C Early Objects 10th Edition 10th Edition Tony Gaddis https://ebookbell.com/product/starting-out-with-c-early-objects-10th- edition-10th-edition-tony-gaddis-11263868
  • 3.
    Starting Out WithC Early Objects 10e Tony Gaddis Judy Walters Godfrey Muganda Gaddis https://ebookbell.com/product/starting-out-with-c-early- objects-10e-tony-gaddis-judy-walters-godfrey-muganda-gaddis-23503670 Starting Out With C Early Objects Tony Gaddis Judy Walters Godfrey Muganda https://ebookbell.com/product/starting-out-with-c-early-objects-tony- gaddis-judy-walters-godfrey-muganda-32222180 Starting Out With C Early Objects 9e Tony Gaddis Judy Walters Godfrey Muganda https://ebookbell.com/product/starting-out-with-c-early- objects-9e-tony-gaddis-judy-walters-godfrey-muganda-12078022 Starting Out With C From Control Structures Through Objects 8th Edition Gaddis https://ebookbell.com/product/starting-out-with-c-from-control- structures-through-objects-8th-edition-gaddis-21347298 Starting Out With C From Control Structures Through Objects Brief Version Gaddis https://ebookbell.com/product/starting-out-with-c-from-control- structures-through-objects-brief-version-gaddis-21973200
  • 5.
    Global edition Starting Out WithC++ Early Objects ninTH edition Tony Gaddis • Judy Walters • Godfrey Muganda
  • 6.
    LOCATION OF VIDEONOTESIN THE TEXT Chapter 1 Designing a Program with Pseudocode, p. 54 Designing the Account Balance Program, p. 59 Predicting the Output of Problem 30, p. 59 Solving the Candy Bar Sales Problem, p. 60 Chapter 2 Using cout to Display Output, p. 66 Assignment Statements, p. 93 Arithmetic Operators, p. 96 Solving the Restaurant Bill Problem, p. 108 Chapter 3 Using cin to Read Input, p. 111 Evaluating Mathematical Expressions, p. 118 Combined Assignment Operators, p. 136 Solving the Stadium Seating Problem, p. 182 Chapter 4 Using an if Statement, p. 195 Using an if/else Statement, p. 204 Using an if/else if Statement, p. 210 Using Logical Operators, p. 223 Solving the Time Calculator Problem, p. 272 Chapter 5 The while Loop, p. 278 The for Loop, p. 305 Nested Loops, p. 313 Solving the Ocean Levels Problem, p. 351 Chapter 6 Defining and Calling Functions, p. 358 Using Function Arguments, p. 367 Value-Returning Functions, p. 377 Solving the Markup Problem, p. 433 Chapter 7 Creating a Class, p. 446 Creating and Using Class Objects, p. 448 Creating and Using Structures, p. 488 Solving the Car Class Problem, p. 534 Chapter 8 Accessing Array Elements, p. 543 Passing an Array to a Function, p. 577 Two-Dimensional Arrays, p. 587 Solving the Chips and Salsa Problem, p. 627 Chapter 9 Performing a Binary Search, p. 640 Sorting a Set of Data, p. 647 Solving the Lottery Winners Problem, p. 675 (continued on next page) VideoNote
  • 7.
    LOCATION OF VIDEONOTESIN THE TEXT (continued) Chapter 10 Pointer Variables, p. 681 Dynamically Allocating an Array, p. 705 Solving the Days in Current Month Problem, p. 736 Chapter 11 Operator Overloading, p. 764 Aggregation and Composition, p. 810 Overriding Base Class Functions, p. 831 Solving the Number of Days Worked Problem, p. 845 Chapter 12 Converting Strings to Numbers, p. 863 Writing a C-String Handling Function, p. 867 Solving the Case Manipulator Problem, p. 884 Chapter 13 The get Family of Member Functions, p. 903 Rewinding a File, p. 907 Solving the File Encryption Filter Problem, p. 946 Chapter 14 Recursive Binary Search, p. 961 QuickSort, p. 963 Solving the Recursive Multiplication Problem, p. 981 Chapter 15 Polymorphism, p. 989 Composition versus Inheritance, p. 1003 Solving the Sequence Sum Problem, p. 1019 Chapter 16 Throwing and Handling Exceptions, p. 1022 Writing a Function Template, p. 1034 Iterators, p. 1051 Solving the Arithmetic Exceptions Problem, p. 1068 Chapter 17 Adding an Element to a Linked List, p. 1079 Removing an Element from a Linked List, p. 1086 Solving the Member Insertion by Position Problem, p. 1117 Chapter 18 Storing Objects in an STL Stack, p. 1131 Storing Objects in an STL Queue, p. 1145 Solving the File Reverser Problem, p. 1157 Chapter 19 Inserting an Element into a Binary Tree, p. 1166 Removing an Element from a Binary Tree, p. 1170 Solving the Tree Size Problem, p. 1186 VideoNote
  • 8.
    Ninth Edition Starting Outwith C++ Early Objects Tony Gaddis Judy Walters Godfrey Muganda Global Edition Boston  Columbus  Indianapolis  New York  San Francisco  Hoboken Amsterdam  Cape Town  Dubai  London  Madrid  Milan  Munich  Paris  Montreal  Toronto Delhi  Mexico City  Sao Paulo  Sydney  Hong Kong  Seoul  Singapore  Taipei  Tokyo
  • 9.
    Vice President, EditorialDirector, ECS: Marcia Horton Acquisitions Editor: Matt Goldstein Editorial Assistant: Kristy Alaura Acquisitions Editor, Global Editions: Aditee Agarwal Vice President of Marketing: Christy Lesko Director of Field Marketing: Tim Galligan Product Marketing Manager: Bram Van Kempen Field Marketing Manager: Demetrius Hall Marketing Assistant: Jon Bryant Director of Product Management: Erin Gregg Team Lead, Program and Project Management: Scott Disanno Program Manager: Carole Snyder Project Editor, Global Editions: K.K. Neelakantan Project Manager: RPK Editorial Services, Inc. Senior Specialist, Program Planning and Support: Maura Zaldivar-Garcia Senior Manufacturing Controller, Global Editions: Jerry Kataria Cover Designer: Lumina Datamatics Cover: Shutterstock Manager, Rights and Permissions: Rachel Youdelman Project Manager, Rights and Permissions: William Opaluch Inventory Manager: Meredith Maresca Media Project Manager: Renata Butera Media Production Manager, Global Editions: Vikram Kumar Full-Service Project Management: Deepthi Mohan, iEnergizer Aptara® , Ltd. Composition: Aptara® Corporation Microsoft and/or its respective suppliers make no representations about the suitability of the information contained in the documents and related graphics published as part of the services for any purpose. All such documents and related graphics are provided “as is” without warranty of any kind. Microsoft and/or its respective suppliers hereby disclaim all warranties and conditions with regard to this information, including all warranties and conditions of merchantability, whether express, implied or statutory, fitness for a particular purpose, title and non-infringement. In no event shall Microsoft and/or its respective suppliers be liable for any special, indirect or consequential damages or any damages whatsoever resulting from loss of use, data or profits, whether in an action of contract, negligence or other tortious action, arising out of or in connection with the use or performance of information available from the services. The documents and related graphics contained herein could include technical inaccuracies or typographical errors. Changes are periodically added to the information herein. Microsoft and/or its respective suppliers may make improvements and/or changes in the product(s) and/or the program(s) described herein at any time. Partial screen shots may be viewed in full within the software version specified. Microsoft® Windows® , and Microsoft Office® are registered trademarks of the Microsoft corporation in the U.S.A. and other countries. This book is not sponsored or endorsed by or affiliated with the Microsoft corporation. The programs and applications presented in this book have been included for their instructional value. They have been tested with care, but are not guaranteed for any particular purpose. The publisher does not offer any warranties or representations, nor does it accept any liabilities with respect to the programs or applications. Pearson Education Limited Edinburgh Gate Harlow Essex CM20 2JE England and Associated Companies throughout the world Visit us on the World Wide Web at: www.pearsonglobaleditions.com © Pearson Education Limited 2016 The rights of Tony Gaddis, Judy Walters, and Godfrey Muganda to be identified as the authors of this work have been as- serted by them in accordance with the Copyright, Designs and Patents Act 1988. Authorized adaptation from the United States edition, entitled Starting Out with C++: Early Objects, 9th Edition, ISBN 9780134400242, by Tony Gaddis, Judy Walters, and Godfrey Muganda published by Pearson Education © 2017. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, without either the prior written permission of the publisher or a license permitting restricted copying in the United Kingdom issued by the Copyright Licensing Agency Ltd, Saffron House, 6–10 Kirby Street, London EC1N 8TS. All trademarks used herein are the property of their respective owners. The use of any trademark in this text does not vest in the author or publisher any trademark ownership rights in such trademarks, nor does the use of such trademarks imply any affiliation with or endorsement of this book by such owners. British Library Cataloguing-in-Publication Data A catalogue record for this book is available from the British Library 10 9 8 7 6 5 4 3 2 1 ISBN 10: 1292157275 ISBN 13: 9781292157276 Typeset in 10/12.5 Sabon LT Pro by iEnergizer Aptara® , Ltd. Printed and bound in Malaysia
  • 10.
    Last A-Head 5 Contentsat a Glance Preface 15 Chapter 1 Introduction to Computers and Programming 35 Chapter 2 Introduction to C++ 61 Chapter 3 Expressions and Interactivity 111 Chapter 4 Making Decisions 189 Chapter 5 Looping 277 Chapter 6 Functions 357 Chapter 7 Introduction to Classes and Objects 441 Chapter 8 Arrays 541 Chapter 9 Searching, Sorting, and Algorithm Analysis 637 Chapter 10 Pointers 679 Chapter 11 More about Classes and Object-Oriented Programming 737 Chapter 12 More on C-Strings and the string Class 849 Chapter 13 Advanced File and I/O Operations 887 Chapter 14 Recursion 949 Chapter 15 Polymorphism and Virtual Functions 983 Chapter 16 Exceptions, Templates, and the Standard Template Library (STL) 1021 Chapter 17 Linked Lists 1071 Chapter 18 Stacks and Queues 1119 Chapter 19 Binary Trees 1159 Appendix A: The ASCII Character Set 1189 Appendix B: Operator Precedence and Associativity 1193 Appendix C: Answers to Checkpoints 1195 Appendix D: Answers to Odd-Numbered Review Questions 1235 Index 1255 5
  • 11.
  • 12.
    Contents Preface 15 CHAPTER1 Introduction to Computers and Programming 35 1.1 Why Program? 35 1.2 Computer Systems: Hardware and Software 37 1.3 Programs and Programming Languages 42 1.4 What Is a Program Made of? 47 1.5 Input, Processing, and Output 51 1.6 The Programming Process 52 1.7 Tying It All Together: Hi! It’s Me 57 CHAPTER 2 Introduction to C++ 61 2.1 The Parts of a C++ Program 61 2.2 The cout Object 65 2.3 The #include Directive 70 2.4 Variables and the Assignment Statement 71 2.5 Literals 73 2.6 Identifiers 75 2.7 Integer Data Types 77 2.8 Floating-Point Data Types 82 2.9 The char Data Type 86 2.10 The C++ string Class 90 2.11 The bool Data Type 91 2.12 Determining the Size of a Data Type 92 2.13 More on Variable Assignments and Initialization 93 2.14 Scope 95 2.15 Arithmetic Operators 96 2.16 Comments 100 2.17 Programming Style 101 2.18 Tying It All Together: Smile! 103 7
  • 13.
    8 Contents CHAPTER 3Expressions and Interactivity 111 3.1 The cin Object 111 3.2 Mathematical Expressions 118 3.3 Data Type Conversion and Type Casting 126 3.4 Overflow and Underflow 132 3.5 Named Constants 133 3.6 Multiple and Combined Assignment 136 3.7 Formatting Output 140 3.8 Working with Characters and Strings 150 3.9 More Mathematical Library Functions 164 3.10 Random Numbers 166 3.11 Focus on Debugging: Hand Tracing a Program 170 3.12 Green Fields Landscaping Case Study—Part 1 172 3.13 Tying It All Together: Word Game 175 CHAPTER 4 Making Decisions 189 4.1 Relational Operators 189 4.2 The if Statement 195 4.3 The if/else Statement 204 4.4 The if/else  if Statement 209 4.5 Menu-Driven Programs 217 4.6 Nested if Statements 219 4.7 Logical Operators 223 4.8 Validating User Input 232 4.9 More about Blocks and Scope 234 4.10 More about Characters and Strings 237 4.11 The Conditional Operator 243 4.12 The switch Statement 247 4.13 Enumerated Data Types 256 4.14 Focus on Testing and Debugging: Validating Output Results 259 4.15 Green Fields Landscaping Case Study—Part 2 261 4.16 Tying It All Together: Fortune Teller 266 CHAPTER 5 Looping 277 5.1 Introduction to Loops: The while Loop 277 5.2 Using the while Loop for Input Validation 284 5.3 The Increment and Decrement Operators 287 5.4 Counters 292 5.5 Keeping a Running Total 294 5.6 Sentinels 297 5.7 The do-while Loop 299
  • 14.
    Contents 9 5.8 Thefor Loop 305 5.9 Focus on Software Engineering: Deciding Which Loop to Use 311 5.10 Nested Loops 313 5.11 Breaking Out of a Loop 315 5.12 Using Files for Data Storage 319 5.13 Focus on Testing and Debugging: Creating Good Test Data 335 5.14 Central Mountain Credit Union Case Study 338 5.15 Tying It All Together: What a Colorful World 342 CHAPTER 6 Functions 357 6.1 Modular Programming 357 6.2 Defining and Calling Functions 358 6.3 Function Prototypes 366 6.4 Sending Data into a Function 367 6.5 Passing Data by Value 372 6.6 The return Statement 376 6.7 Returning a Value from a Function 377 6.8 Returning a Boolean Value 383 6.9 Using Functions in a Menu-Driven Program 385 6.10 Local and Global Variables 389 6.11 Static Local Variables 396 6.12 Default Arguments 398 6.13 Using Reference Variables as Parameters 402 6.14 Overloading Functions 412 6.15 The exit() Function 416 6.16 Stubs and Drivers 419 6.17 Little Lotto Case Study 421 6.18 Tying It All Together: Glowing Jack-o-lantern 426 CHAPTER 7 Introduction to Classes and Objects 441 7.1 Abstract Data Types 441 7.2 Object-Oriented Programming 443 7.3 Introduction to Classes 445 7.4 Creating and Using Objects 448 7.5 Defining Member Functions 450 7.6 Constructors 457 7.7 Destructors 463 7.8 Private Member Functions 466 7.9 Passing Objects to Functions 469 7.10 Object Composition 476 7.11 Focus on Software Engineering: Separating Class Specification, Implementation, and Client Code 480
  • 15.
    10 Contents 7.12 Structures487 7.13 More about Enumerated Data Types 499 7.14 Home Software Company OOP Case Study 503 7.15 Introduction to Object-Oriented Analysis and Design 510 7.16 Screen Control 520 7.17 Tying It All Together: Yoyo Animation 525 CHAPTER 8 Arrays 541 8.1 Arrays Hold Multiple Values 541 8.2 Accessing Array Elements 543 8.3 Inputting and Displaying Array Data 545 8.4 Array Initialization 552 8.5 The Range-Based for loop 559 8.6 Processing Array Contents 562 8.7 Using Parallel Arrays 573 8.8 The typedef Statement 577 8.9 Arrays as Function Arguments 577 8.10 Two-Dimensional Arrays 587 8.11 Arrays with Three or More Dimensions 594 8.12 Vectors 597 8.13 Arrays of Objects 609 8.14 National Commerce Bank Case Study 619 8.15 Tying It All Together: Rock, Paper, Scissors 621 CHAPTER 9 Searching, Sorting, and Algorithm Analysis 637 9.1 Introduction to Search Algorithms 637 9.2 Searching an Array of Objects 644 9.3 Introduction to Sorting Algorithms 647 9.4 Sorting an Array of Objects 655 9.5 Sorting and Searching Vectors 658 9.6 Introduction to Analysis of Algorithms 661 9.7 Case Studies 669 9.8 Tying It All Together: Secret Messages 669 CHAPTER 10 Pointers 679 10.1 Pointers and the Address Operator 679 10.2 Pointer Variables 681 10.3 The Relationship Between Arrays and Pointers 685
  • 16.
    Contents 11 10.4 PointerArithmetic 689 10.5 Initializing Pointers 690 10.6 Comparing Pointers 693 10.7 Pointers as Function Parameters 695 10.8 Pointers to Constants and Constant Pointers 699 10.9 Focus on Software Engineering: Dynamic Memory Allocation 704 10.10 Focus on Software Engineering: Returning Pointers from Functions 708 10.11 Pointers to Class Objects and Structures 714 10.12 Focus on Software Engineering: Selecting Members of Objects 718 10.13 Smart Pointers 720 10.14 Tying It All Together: Pardon Me, Do You Have the Time? 728 CHAPTER 11 More about Classes and Object-Oriented Programming 737 11.1 The this Pointer and Constant Member Functions 737 11.2 Static Members 742 11.3 Friends of Classes 749 11.4 Memberwise Assignment 754 11.5 Copy Constructors 755 11.6 Operator Overloading 764 11.7 Rvalue References and Move Operations 785 11.8 Function Objects and Lambda Expressions 795 11.9 Type Conversion Operators 804 11.10 Convert Constructors 807 11.11 Aggregation and Composition 810 11.12 Inheritance 816 11.13 Protected Members and Class Access 821 11.14 Constructors, Destructors, and Inheritance 826 11.15 Overriding Base Class Functions 831 11.16 Tying It All Together: Putting Data on the World Wide Web 834 CHAPTER 12 More on C-Strings and the string Class 849 12.1 C-Strings 849 12.2 Library Functions for Working with C-Strings 854 12.3 Conversions Between Numbers and Strings 863 12.4 Writing Your Own C-String Handling Functions 867 12.5 More about the C++ string Class 873 12.6 Advanced Software Enterprises Case Study 876 12.7 Tying It All Together: Program Execution Environments 878
  • 17.
    CHAPTER 13 AdvancedFile and I/O Operations 887 13.1 Input and Output Streams 887 13.2 More Detailed Error Testing 895 13.3 Member Functions for Reading and Writing Files 899 13.4 Binary Files 911 13.5 Creating Records with Structures 915 13.6 Random-Access Files 920 13.7 Opening a File for Both Input and Output 927 13.8 Online Friendship Connections Case Study: Object Serialization 932 13.9 Tying It All Together: File Merging and Color-Coded HTML 937 CHAPTER 14 Recursion 949 14.1 Introduction to Recursion 949 14.2 The Recursive Factorial Function 956 14.3 The Recursive gcd Function 958 14.4 Solving Recursively Defined Problems 959 14.5 A Recursive Binary Search Function 961 14.6 Focus on Problem Solving and Program Design: The QuickSort Algorithm 963 14.7 The Towers of Hanoi 967 14.8 Focus on Problem Solving: Exhaustive and Enumeration Algorithms 970 14.9 Focus on Software Engineering: Recursion versus Iteration 974 14.10 Tying It All Together: Infix and Prefix Expressions 975 CHAPTER 15 Polymorphism and Virtual Functions 983 15.1 Type Compatibility in Inheritance Hierarchies 983 15.2 Polymorphism and Virtual Member Functions 989 15.3 Abstract Base Classes and Pure Virtual Functions 997 15.4 Focus on Object-Oriented Programming: Composition versus Inheritance 1003 15.5 Secure Encryption Systems, Inc., Case Study 1007 15.6 Tying It All Together: Let’s Move It 1010 CHAPTER 16 Exceptions, Templates, and the Standard Template Library (STL) 1021 16.1 Exceptions 1021 16.2 Function Templates 1033 16.3 Class Templates 1041 16.4 Class Templates and Inheritance 1046 16.5 Introduction to the Standard Template Library 1050 16.6 Tying It All Together: Word Transformers Game 1063 12 Contents
  • 18.
    CHAPTER 17 LinkedLists 1071 17.1 Introduction to the Linked List ADT 1071 17.2 Linked List Operations 1077 17.3 A Linked List Template 1089 17.4 Recursive Linked List Operations 1093 17.5 Variations of the Linked List 1101 17.6 The STL list Container 1102 17.7 Reliable Software Systems, Inc., Case Study 1105 17.8 Tying It All Together: More on Graphics and Animation 1108 CHAPTER 18 Stacks and Queues 1119 18.1 Introduction to the Stack ADT 1119 18.2 Dynamic Stacks 1127 18.3 The STL stack Container 1131 18.4 Introduction to the Queue ADT 1133 18.5 Dynamic Queues 1140 18.6 The STL deque and queue Containers 1143 18.7 Focus on Problem Solving and Program Design: Eliminating Recursion 1146 18.8 Tying It All Together: Converting Postfix Expressions to Infix 1151 CHAPTER 19 Binary Trees 1159 19.1 Definition and Applications of Binary Trees 1159 19.2 Binary Search Tree Operations 1163 19.3 Template Considerations for Binary Search Trees 1179 19.4 Tying It All Together: Genealogy Trees 1179 Appendix A: The ASCII Character Set 1189 Appendix B: Operator Precedence and Associativity 1193 Appendix C: Answers to Checkpoints 1195 Appendix D: Answers to Odd-Numbered Review Questions 1235 Index 1255 Contents 13
  • 19.
    Additional Appendices The followingappendices are located on the book’s companion web site. Appendix E: A Brief Introduction to Object-Oriented Programming Appendix F: Using UML in Class Design Appendix G: Multi-Source File Programs Appendix H: Multiple and Virtual Inheritance Appendix I: Header File and Library Function Reference Appendix J: Namespaces Appendix K: C++ Casts and Run-Time Type Identification Appendix L: Passing Command Line Arguments Appendix M: Binary Numbers and Bitwise Operations Appendix N: Introduction to Flowcharting 14 Contents
  • 20.
    Preface Welcome to StartingOut with C++: Early Objects, 9th Edition. This book is intended for use in a two-term or three-term C++ programming sequence, or an accelerated one-term course. Students new to programming, as well as those with prior course work in other languages, will find this text beneficial. The fundamentals of programming are covered for the novice, while the details, pitfalls, and nuances of the C++ language are explored in-depth for both the beginner and more experienced student. The book is written with clear, easy-to-understand language and it covers all the necessary ­ topics for an introductory programming course. This text is rich in example programs that are concise, practical, and real world oriented, ensuring that the student not only learns how to implement the features and constructs of C++, but why and when to use them. What’s New in the Ninth Edition The New C++11 Standard C++11 is the latest standard version of the C++ language. In previous years, while the standard was being developed, it was known as C++0x. In August 2011, it was approved by the International Standards Organization (ISO), and the name of the standard was officially changed to C++11. Most of the popular C++ compilers now support this standard. The new C++11 standard was the primary motivation behind this edition, which introduces many of the new language features. However, a C++11 compiler is not strictly required to use the book. As you progress through the book, you will see C++11 icons in the margins, next to the new features that are introduced. Programs appearing in sections that are not marked with this icon will still compile using an older compiler. The C++11 Topics Introduced in This Edition • The auto key word is introduced in Chapter 2 as a way to simplify complex variable definitions. This key word causes the compiler to infer a variable’s data type from its initialization value. 15
  • 21.
    16 Preface • Chapter2 also introduces the new long long int and unsigned long long int data types and the LL literal suffix. • Chapter 5 shows how to pass a string object directly to a file stream object’s open member function, without the need to call the c_str() member function. A discussion of the c_str()function still exists for anyone using a legacy compiler. • The range-based for loop is introduced in Chapter 7. This new looping mechanism automatically iterates over each element of an array, vector, or other collection, without the need for a counter variable or a subscript. • Chapter 7 also introduces strongly typed enums. • Chapter 8 introduces new ways to initialize variables and shows how a vector can now be initialized with an initialization list. • Chapter 10 introduces smart pointers and provides examples of how and why to use the new unique_ptr and shared_ptr pointers for safely allocating and working with dynamic memory. • Chapter 10 also introduces the move assignment operator, and the nullptr key word, which is now the standard way of representing a null pointer. • Chapter 11 discusses move constructors, provides more in depth coverage of move assignment operators, and introduces lambda expressions. • Chapter 12 introduces new functions in the C++11 string library and discusses the new overloaded to_string functions for converting numeric values to string objects. • Chapter 15 introduces and demonstrates the use of the new override key word that helps prevent subtle overriding errors and the new final key word that prevents a virtual member function from being overridden. • Chapter 16 introduces the new C++11 functions begin(c) and end(c) to specify positions within a collection c where an operation should begin and end. What Else is New This book’s pedagogy and clear writing style remain the same as in the previous edition. However, in addition to updating the book to introduce the new C++11 standard, many improvements have been made to make it even more student-friendly. • Updated Material Material has been updated throughout the book to reflect changes in technology and in software development environments, as well as to improve clarity and incorporate best practices in teaching introductory programming. As a result, new graphics and new or redesigned figures have been added throughout the book where appropriate and new or improved sample programs have been included in a number of chapters. • New Material New material has been added on a number of topics. In addition to introducing and using new C++11 features, this new edition includes new sections on literals, random numbers, and enumerated data types, as well as improved material on designing classes.
  • 22.
    Preface 17 • NewProgramming Challenges New Programming Challenge problems have been added to every chapter. • Reorganized Chapters Several chapters have been redesigned to improve student learning. Chapter 5 (Looping) has been reorganized to give students more practice using the while loop before introducing do-while and for loops. The Chapter 6 (Functions) material on defining and calling functions has been reorganized to introduce function prototypes earlier and allow main to always be the first function in a client program. Organization of the Text This text teaches C++ in a step-by-step fashion. Each chapter covers a major set of topics and builds knowledge as the student progresses through the book. Although the chapters can be easily taught in their existing sequence, flexibility is provided. The following dependency diagram (Figure P-1) suggests possible sequences of instruction. Chapter 1 covers fundamental hardware, software, and programming concepts. The instructor may choose to skip this chapter if the class has already mastered those topics. Chapters 2 through 6 cover basic C++ syntax, data types, expressions, selection structures, repetition structures, and functions. Each of these chapters builds on the previous chapter and should be covered in the order presented. Chapter 7 introduces object-oriented programming. It can be covered any time after Chapter 6, but before Chapter 11. Instructors who prefer to introduce arrays before classes can cover Chapter 8 before Chapter 7. In this case it is only necessary to postpone Section 8.13 (Arrays of Objects) until Chapter 7 has been covered. As Figure P-1 illustrates, in the second half of the book Chapters 11, 12, 13, and 14 can be covered in any order. Chapters 11, 15, and 16, however, should be done in sequence. Instructors who wish to introduce data structures at an earlier point in the course, without having first covered advanced C++ and OOP features, can cover Chapter 17 (Linked Lists), followed by Chapters 18 and 19 (Stacks & Queues and Binary Trees), any time after Chapter 14 (Recursion). In this case it is necessary to simply omit the sections in Chapters 17–19 that deal with templates and the Standard Template Library.
  • 23.
    18 Preface Chapter 1 Introduction Chapters2–6 Basic Language Elements Chapter 10 Pointers Chapter 7 OOP Introduction Chapter 8 Arrays Chapter 11 More OOP Chapter 12 Advanced Strings Chapter 13 Advanced Files and I/O Chapter 14 Recursion Chapter 17 Linked Lists Chapter 15 Adv. OOP Chapter 16 Exceptions, Templates, and STL Chapter 18 Stacks and Queues Chapter 19 Binary Trees Chapter 9 Searching, Sorting, and Algorithm Analysis Figure P-1
  • 24.
    Preface 19 Brief Overviewof Each Chapter Chapter 1: Introduction to Computers and Programming This chapter provides an introduction to the field of computer science and covers the fundamentals of hardware, software, operating systems, programming, problem solving, and software engineering. The components of programs, such as key words, variables, operators, and punctuation are covered. The tools of the trade, such as hierarchy charts and pseudocode, are also presented. The Tying It All Together section shows students how to use the cout statement to create a personalized output message. Programming Challenges at the end of the chapter help students see how the same basic input, processing, and output structure can be used to create multiple programs. Chapter 2: Introduction to C++ This chapter gets the student started in C++ by introducing the basic parts of a C++ program, data types, the use of variables and literals, assignment statements, simple arithmetic operations, program output, and comments. The C++ string class is presented and string objects are used from this point on in the book as the primary method of handling strings. Programming style conventions are introduced, and good programming style is modeled here, as it is throughout the text. The Tying It All Together section lets the student play with simple text- based graphics. Chapter 3: Expressions and Interactivity In this chapter the student learns to write programs that input and handle numeric, character, and string data. The use of arithmetic operators and the creation of mathematical expressions are covered, with emphasis on operator precedence. Debugging is introduced, with a section on hand tracing a program. Sections are also included on using random numbers, on simple output formatting, on data type conversion and type casting, and on using library functions that work with numbers. The Tying It All Together section shows students how to create a simple interactive word game. Chapter 4: Making Decisions Here the student learns about relational expressions and how to control the flow of a program with if, if/else, and if/else  if statements. Logical operators, the conditional operator, and the switch statement are also covered. Applications of these constructs, such as menu-driven programs, are illustrated. This chapter also introduces the concepts of blocks and scope and continues the theme of debugging with a section on validating output results. The Tying It All Together section uses random numbers and branching statements to create a fortune telling game.
  • 25.
    Chapter 5: Looping Thischapter introduces, C++’s repetitive control mechanisms. The while loop, do-while loop, and for loop are presented, along with a variety of methods to control them. These include using counters, user input, end sentinels, and end-of-file testing. Applications utilizing loops, such as keeping a running total and performing data validation, are also covered. The chapter includes an extensive section on working with files and a section on creating good test data, continuing the book’s emphasis on testing and debugging. The Tying It All Together section introduces students to Windows commands to create colorful output and uses a loop to create a multi-colored display. Chapter 6: Functions In this chapter the student learns how and why to modularize programs, using both void and value-returning functions. Parameter passing is covered, with emphasis on when arguments should be passed by value versus when they need to be passed by reference. Scope of variables is covered and sections are provided on local versus global variables and on static local variables. Overloaded functions are also introduced and demonstrated. The Tying It All Together section includes a modular, menu-driven program that emphasizes the versatility of functions, illustrating how their behavior can be controlled by the arguments sent to them. Chapter 7: Introduction to Classes and Objects In this chapter the text begins to focus on the object-oriented paradigm. Students have used provided C++ classes since the beginning of the text, but now they learn how to define their own classes and to create and use objects of these classes. Careful attention is paid to illustrating which functions belong in a class versus which functions belong in a client program that uses the class. Good object-oriented practices are discussed and modeled, such as protecting member data through carefully constructed accessor and mutator functions and hiding class implementation details from client programs. Once students are comfortable working with classes and objects, the chapter provides a brief introduction to the topic of object-oriented analysis and design. The chapter also includes a section on enumerated data types and a section on structures, which are used in the Tying It All Together section, where students learn to use screen control techniques to create a yoyo animation. Chapter 8: Arrays In this chapter the student learns to create and work with single and multidimensional arrays. Many examples of array processing are provided, including functions to compute the sum, average, highest and lowest values in an array. Students also learn to create tables usingtwo-dimensionalarrays,andtoanalyzearraydatabyroworbycolumn.Programming techniques using parallel arrays are also demonstrated, and the student is shown how to use a data file as an input source to populate an array. The range-based for loop is introduced as an easy way to iterate through all the elements of an array, and STL vectors are introduced and compared to arrays. A section on arrays of objects and structures is located at the end of the chapter, so it can be covered now or saved for later if the instructor wishes to cover this chapter before Chapter 7. The Tying It All Together section uses arrays to create a game of Rock, Paper, Scissors between a human player and the computer. 20 Preface
  • 26.
    Chapter 9: Searching,Sorting, and Algorithm Analysis Here the student learns the basics of searching for information stored in arrays and of sorting arrays, including arrays of objects. The chapter covers the Linear Search, Binary Search, Bubble Sort, and Selection Sort algorithms and has an optional section on sorting and searching STL vectors. A brief introduction to algorithm analysis is included, and students are shown how to determine which of two algorithms is more efficient. This chapter’s Tying It All Together section uses both a table lookup and a searching algorithm to encode and decode secret messages. Chapter 10: Pointers This chapter explains how to use pointers. Topics include pointer arithmetic, initialization of pointers, comparison of pointers, pointers and arrays, pointers and functions, dynamic memory allocation, the new nullptr key word, and more. A new section introduces smart pointers and shows how they can be used to avoid memory leaks. The Tying It All Together section demonstrates the use of pointers to access library data structures and functions that return calendar and wall clock time. Chapter 11: More About Classes and Object-Oriented Programming This chapter continues the study of classes and object-oriented programming, covering more advanced topics such as inheritance and object aggregation and composition. Other topics include constant member functions, static members, friends, memberwise assignment, copy constructors, object type conversion operators, convert constructors, operator overloading, move constructors, and move assignment operators. A new section introduces function objects and the C++11 lambda expressions. The Tying It All Together section brings together the concepts of inheritance and convert constructors to build a program that formats the contents of an array to form an HTML table for display on a Web site. Chapter 12: More on C-Strings and the string Class This chapter covers standard library functions for working with characters and C-strings, as well as material on string class functions, functions in the new C++11 string library, and new overloaded to_string functions for converting numeric values to string objects. The Tying It All Together section shows students how to access string-based program environments to obtain information about the computer and the network on which the program is running. Chapter 13: Advanced File and I/O Operations This chapter introduces more advanced topics for working with sequential access text files and introduces random access and binary files. Various modes for open- ing files are discussed, as well as the many methods for reading and writing their contents. The Tying It All Together program applies many of the techniques c­ overed in the chapter to merge two text files into an HTML document for display on the Web, with different colors used to illustrate which file each piece of data came from. Preface 21
  • 27.
    Chapter 14: Recursion Inthis chapter recursion is defined and demonstrated. A visual trace of recursive calls is provided, and recursive applications are discussed. Many recursive algorithms are presented, including recursive functions for computing factorials, finding a greatest common denominator (GCD), performing a binary search, sorting using QuickSort, and solving the famous Towers of Hanoi problem. For students who need more challenge, there is a section on exhaustive and enumeration algorithms. The Tying It All Together section uses recursion to evaluate prefix expressions. Chapter 15: Polymorphism and Virtual Functions The study of classes and object-oriented programming continues in this chapter with the introduction of more advanced concepts such as polymorphism and virtual functions. Information is also presented on abstract base classes, pure virtual functions, type compatibility within an inheritance hierarchy, and virtual inheritance. The Tying It All Together section illustrates the use of inheritance and polymorphism to display and animate graphical images. Chapter 16: Exceptions, Templates, and the Standard Template Library (STL) Here the student learns to develop enhanced error trapping techniques using exceptions. Discussion then turns to using function and class templates to create generic code. Finally, the student is introduced to the containers, iterators, and algorithms offered by the Standard Template Library (STL). The Tying It All Together section uses various containers in the Standard Template Library to create an educational children’s game. Chapter 17: Linked Lists This chapter introduces concepts and techniques needed to work with lists. A linked list ADT is developed, and the student learns how to create and destroy a list, as well as to write functions to insert, append, and delete nodes, to traverse the list, and to search for a specific node. A linked list class template is also demonstrated. The Tying It All Together section brings together many of the most important concepts of OOP by using objects, inheritance, and polymorphism in conjunction with the STL list class to animate a collection of images. Chapter 18: Stacks and Queues In this chapter the student learns to create and use static and dynamic stacks and queues. The operations of stacks and queues are defined, and templates for each ADT are demonstrated. The static array-based stack uses exception-handling to handle stack overflow and underflow, providing a realistic and natural example of defining, throwing, and catching exceptions. The Tying It All Together section discusses strategies for evaluating postfix expressions and uses a stack to convert a postfix expression to infix. Chapter 19: Binary Trees This chapter covers the binary tree ADT and demonstrates many binary tree operations. The student learns to traverse a tree, insert, delete, and replace elements, search for a particular element, and destroy a tree. The Tying It All Together section introduces a tree structure versatile enough to create genealogy trees. 22 Preface
  • 28.
    Appendices in theBook Appendix A: The ASCII Character Set A list of the ASCII and extended ASCII characters and their codes. Appendix B: Operator Precedence and Associativity A list of the C++ operators with their precedence and associativity. Appendix C: Answers to Checkpoints A tool students can use to assess their understanding by comparing their answers to the Checkpoint exercises found throughout the book. The answers to all Checkpoint exercises are included. Appendix D: Answers to Odd-Numbered Review Questions Another tool students can use to gauge their understanding and progress. Additional Appendices on the Book’s Companion Website Appendix E: A Brief Introduction to Object-Oriented Programming An introduction to the concepts and terminology of object-oriented programming. Appendix F: Using UML in Class Design A brief introduction to the Unified Modeling Language (UML) class diagrams with examples of their use. Appendix G: Multi-Source File Programs A tutorial on how to create, compile, and link programs with multiple source files. Includes the use of function header files, class specification files, and class implementation files. Appendix H: Multiple and Virtual Inheritance A self-contained discussion of the C++ concepts of multiple and virtual inheritance for anyone already familiar with single inheritance. Appendix I: Header File and Library Function Reference A reference for the C++ library functions and header files used in the book. Appendix J: Namespaces An explanation of namespaces and their purpose, with examples provided on how to define a namespace and access its members. Appendix K: C++ Casts and Run-Time Type Identification An introduction to different ways of doing type casting in C++ and to run-time type identification. Appendix L: Passing Command Line Arguments An introduction to writing C++ programs that accept command-line arguments. This appendix will be useful to students working in a command-line environment, such as UNIX or Linux. Appendix M: Binary Numbers and Bitwise Operations A guide to the binary number system and the C++ bitwise operators, as well as a tutorial on the internal storage of integers. Appendix N: Introduction to Flowcharting A tutorial that introduces flowcharting and its symbols. It includes handling sequence, selection, case, repetition, and calls to other modules. Sample flowcharts for several of the book’s example programs are presented. Preface 23
  • 29.
    Features of theText Concept Statements Each major section of the text starts with a concept statement. This statement summarizes the key idea of the section. Example Programs The text has over 350 complete example programs, each designed to highlight the topic currently being studied. In most cases, these are practical, real-world examples. Source code for these programs is provided so that students can run the programs themselves. Program Output After each example program there is a sample of its screen output. This immediately shows the student how the program should function. Tying It All Together This special section, found at the end of every chapter, shows the student how to do something clever and fun with the material covered in that chapter. VideoNotes A series of online videos, developed specifically for this book, are available for viewing at www.pearsonglobaleditions. com/gaddis. VideoNote icons appear throughout the text, alerting the student to videos about specific topics. Checkpoints Checkpoints are questions placed throughout each chapter as a selftest study aid. Answers for all Checkpoint questions are provided in Appendix C at the back of the book so students can check how well they have learned a new topic. Notes Notes appear at appropriate places throughout the text. They are short explanations of interesting or often misunderstood points relevant to the topic at hand. Warnings Warnings caution the student about certain C++ features, programming techniques, or practices that can lead to malfunctioning programs or lost data. Case Studies Case studies that simulate real-world applications appear in many chapters throughout the text, with complete code provided for each one. Additional case studies are provided on the book’s companion website. These case studies are designed to highlight the major topics of the chapter in which they appear. Review Questions Each chapter presents a thorough and diverse set of review questions, such as fill-in-the-blank and short answer, that check the student’s mastery of the basic material presented in the chapter. These are followed by exercises requiring problem solving and analysis, such as the Algorithm Workbench, Predict the Output, and Find the Errors sections. Each chapter ends with a Soft Skills exercise that focuses on communication and group process skills. Answers to the odd numbered review questions and review exercises are provided in Appendix D at the back of the book. and Exercises VideoNote 24 Preface
  • 30.
    Programming Each chapteroffers a pool of programming exercises designed to solidify the student’s knowledge of the topics currently being studied. In most cases the assignments present real-world problems to be solved. Group Projects There are several group programming projects throughout the text, intended to be constructed by a team of students. One student might build the program’s user interface, while another student writes the mathematical code, and another designs and implements a class the program uses. This process is similar to the way many professional programs are written and encourages teamwork within the classroom. C++ Quick For easy access, a quick reference guide to the C++ language is printed on the inside back cover. Supplements Student Resources The following items are available on the Gaddis Series resource page at www.pearsonglobaleditions.com/gaddis: • Complete source code for every program included in the book • Additional case studies, complete with source code • A full set of appendices (including several tutorials) that accompany the book • Access to the book’s companion VideoNotes • Links to download numerous programming environments and IDEs, including Visual Studio Community Edition. Instructor Resources The following supplements are available to qualified instructors only. • Answers to all Review Questions in the text • Solutions for all Programming Challenges in the text • PowerPoint presentation slides for every chapter • A computerized test bank • A collection of lab materials • Source code files Visit the Pearson Education Instructor Resource Center (http://www.pearsonglobaleditions. com/gaddis) for information on how to access them. Practice and Assessment with MyProgrammingLab MyProgrammingLab helps students fully grasp the logic, semantics, and syntax of programming. Through practice exercises and immediate, personalized feedback, MyProgrammingLab improves the programming competence of beginning students who often struggle with the basic concepts and paradigms of popular high-level programming languages. A self-study and homework tool, MyProgrammingLab consists of hundreds of small practice exercises organized around the structure of this Challenges Reference Guide Preface 25
  • 31.
    textbook. For students,the system automatically detects errors in the logic and syntax of their code submissions and offers targeted hints that help them figure out what went wrong. For instructors, a comprehensive gradebook tracks correct and incorrect answers and stores the code input by students for review. MyProgrammingLab is offered to users of this book in partnership with Turing’s Craft, the makers of the CodeLab interactive programming exercise system. For a full demonstration, to see feedback from instructors and students, or to get started using MyProgrammingLab in your course, visit www.myprogramminglab.com. Which Gaddis C++ book is right for you? The Starting Out with C++ Series includes three books, one of which is sure to fit your course: • Starting Out with C++: Early Objects • Starting Out with C++: From Control Structures through Objects • Starting Out with C++: Brief Version 26 Preface
  • 32.
    Acknowledgments There have beenmany helping hands in the development and publication of this text. We would like to thank the following faculty reviewers for their helpful suggestions and expertise. Reviewers of the Ninth Edition or Its Previous Versions Ahmad Abuhejleh University of Wisconsin, River Falls David Akins El Camino College Steve Allan Utah State University Ijaz A. Awan Savannah State University John Bierbauer North Central College Don Biggerstaff Fayetteville Technical Community ­College Paul Bladek Spokane Falls Community College Chuck Boehm Dean Foods, Inc. Bill Brown Pikes Peak Community College Richard Cacace Pensacola Junior College Randy Campbell Morningside College Stephen P. Carl Wright State University Wayne Caruolo Red Rocks Community College Thomas Cheatham Middle Tennessee State University James Chegwidden Tarrant County College John Cigas Rockhurst University John Cross Indiana University of Pennsylvania Fred M. D’Angelo Pima Community College Joseph DeLibero Arizona State University Dennis Fairclough Utah Valley State College Larry Farrer Guilford Technical Community College James D. Fitzgerald Golden West College Richard Flint North Central College Sheila Foster California State University Long Beach David E. Fox American River College Cindy Fry Baylor University Peter Gacs Boston University Cristi Gale Sterling College James Gifford University of Wisconsin, Stevens Point Leon Gleiberman Touro College Simon Gray Ashland University—Ohio Margaret E. Guertin Tufts University Jamshid Haghighi Guilford Technical Community College Ranette H. Halverson Midwestern State University, Wichita Falls, TX Preface 27
  • 33.
    Dennis Heckman Portland CommunityCollege Ric Heishman Northern Virginia Community College Patricia Hines Brookdale Community College Mike Holland Northern Virginia Community College Lister Wayne Horn Pensacola Junior College Richard Hull Lenoir-Rhyne College Norman Jacobson University of California, Irvine Eric Jiang San Diego State University Yinping Jiao South Texas College Neven Jurkovic Palo Alto College David Kaeli Northeastern University Chris Kardaras North Central College Amitava Karmaker University of Wisconsin—Stout Eugene Katzen Montgomery College—Rockville Willard Keeling Blue Ridge Community College A. J. Krygeris Houston Community College Ray Larson Inver Hills Community College Stephen Leach Florida State University Parkay Louie Houston Community College Zhu-qu Lu University of Maine, Presque Isle Tucjer Maney George Mason University Bill Martin Central Piedmont Community College Svetlana Marzelli Atlantic Cape Community College Debbie Mathews J. Sargeant Reynolds Ron McCarty Penn State Erie, The Behrend College Robert McDonald East Stroudsburg University James McGuffee Austin Community College M. Dee Medley Augusta State University Barbara Meguro University of Hawaii—Hilo Cathi Chambley-Miller Aiken Technical College Sandeep Mitra SUNY Brockport Churairat O’Brien Columbia Basin College Frank Paiano Southwestern Community College Jennifer Parham-Mocello Oregon State University Theresa Park Texas State Technical College Mark Parker Shoreline Community College Robert Plantz Sonoma State University Tino Posillico SUNY Farmingdale Mahmoud K. Quweider University of Texas at Brownsville M. Padmaja Rao Francis Marion University Timothy Reeves San Juan College Nancy Ripplinger North Idaho College 28 Preface
  • 34.
    Ronald Robison Arkansas TechUniversity Caroline St. Clair North Central College Dolly Samson Weber State University Kate Sanders Rhode Island College Tim Scheemaker Onondaga Community College Lalchand Shimpi Saint Augustine’s College Sung Shin South Dakota State University Barbara A. Smith University of Dayton Garth Sorenson Snow College Donald Southwell Delta College Daniel Spiegel Kutztown University Ray Springston University of Texas at Arlington Kirk Stephens Southwestern Community College Cherie Stevens South Florida Community College Joe Struss Des Moines Area Community College Hong Sung University of Central Oklahoma Sam Y. Sung South Texas College Mark Swanson Red Wing Technical College Martha Tillman College of San Mateo Maya Tolappa Waubonsee Community College Delores Tull Itawamba Community College Rober Tureman Paul D. Camp Community College Jane Turk LaSalle University Sylvia Unwin Bellevue Community College Stewart Venit California State University, Los Angeles David Walter Virginia State University Ju Wang Virginia State University Doug White University of Northern Colorado Chris Wild Old Dominion University Catherine Wyman DeVry Institute of Technology, Phoenix Sherali Zeadally University of the District of Columbia Chaim Ziegler Brooklyn College The authors would like to thank their students at Haywood Community College and North Central College for inspiring them to write student-friendly books. They would also like to thank their families for their tremendous support throughout this project. An especially big thanks goes to our terrific editorial, production, and marketing team at Pearson. In particular we want to thank our editor Matt Goldstein and our production program manager Carole Snyder, who have been instrumental in guiding the production of this book. We also want to thank our project manager, Rose Kernan, who helped everything run smoothly, and our meticulous and knowledgable copyeditor, Shelly Gerger-Knechtl, who dedicated many hours to making this book the best book it could be. You are great people to work with! Preface 29
  • 35.
    Credits Chapter 1 Figure 1-1:PowerPoint 2013, Windows 7, Microsoft Corporation Figure 1-2a: Digital webcam in a white background with reflection: Iko/Shutterstock Figure 1-2b: Modern flight joystick isolated on white background: Nikita Rogul/ Shutterstock Figure 1-2c: Scanner close up shot, business concept: Feng Yu/Shutterstock Figure 1-2d: Black Wireless Computer Keyboard and Mouse Isolated on White: Chiyacat/Shutterstock Figure 1-2e: Compact photo camera: Eikostas/Shutterstock Figure 1-2f: Computer drawing tablet with pen: Tkemot/Shutterstock Figure 1-2g: Illustration of Hard disk drive HDD isolated on white background with soft shadow: Vitaly Korovin/Shutterstock Figure 1-2h: Small computer speakers isolated on a white background: StockPhotosArt/Shutterstock Figure 1-2i: Color Printer: Jocic/Shutterstock Figure 1-2j: Four monitors. Vector: Art gallery/Shutterstock Figure 1-2k: Stick of computer random access memory (RAM): Peter Guess/Shutterstock Figure 1-2l: Chip processor radiator: Aquila/Shutterstock Figure 1-7: Screenshot of Microsoft Visual Studio, Microsoft Corporation Chapter 2 Figure 2-1: Screenshots of Microsoft DOS, Microsoft Corporation Chapter 5 Figure 5-11: Windows 10, Microsoft Corporation Figure 5-12: Windows 10, Microsoft Corporation All other Figures and Tables by the Authors About the Authors Tony Gaddis is the principal author of the Starting Out With series of textbooks. He is a highly acclaimed instructor with two decades of experience teaching computer science courses, primarily at Haywood Community College. Tony was previously selected as the North Carolina Community College “Teacher of the Year” and has received the Teaching Excellence award from the National Institute for Staff and Organizational Development. The Starting Out With series includes introductory textbooks covering Programming Logic and Design, C++, Java™, Microsoft® Visual Basic® , Microsoft® C#, Python, App Inventor, and Alice, all published by Pearson. Judy Walters is an Associate Professor of Computer Science at North Central College in Naperville, Illinois, where she teaches courses in both Computer Science and Media Studies. She is also very involved with International Programs at her college and has spent three semesters teaching in Costa Rica, where she hopes to retire some day. Godfrey Muganda is a Professor of Computer Science at North Central College. He teaches a wide variety of courses at both the undergraduate and graduate levels, including courses in Algorithms, Computer Organization, Web Applications, and Web Services. 30 Preface
  • 36.
    Preface 31 Acknowledgments forthe Global Edition Pearson would like to thank and acknowledge the following people for their contribu- tions to the Global Edition. Contributors Reviewers Moumita Mitra Manna Bangabasi College Chitra Dhawale P.R. Pote College of Engineering and Management Ela Kashyap Amity University Muthuraj M. Timothy Yap Multimedia University
  • 37.
  • 38.
    PROGRAMMING PRACTICE With MyProgrammingLab,your students will gain first-hand programming experience in an interactive online environment. IMMEDIATE, PERSONALIZED FEEDBACK MyProgrammingLab automatically detects errors in the logic and syntax of their code submission and offers targeted hints that enables students to figure out what went wrong and why. GRADUATED COMPLEXITY MyProgrammingLab breaks down programming concepts into short, understandable sequences of exercises. Within each sequence the level and sophistication of the exercises increase gradually but steadily. PEARSON eTEXT The Pearson eText gives students access to their textbook anytime, anywhere DYNAMIC ROSTER Students’ submissions are stored in a roster that indicates whether the submission is correct, how many attempts were made, and the actual code submissions from each attempt. STEP-BY-STEP VIDEONOTE TUTORIALS These step-by-step video tutorials enhance the programming concepts presented in select Pearson textbooks. Copyright © 2017 Pearson Education, Inc. or its affiliate(s). All rights reserved. HELO88173 • 11/15 For more information and titles available with MyProgrammingLab, please visit www.myprogramminglab.com. Through the power of practice and immediate personalized feedback, MyProgrammingLab helps improve your students’ performance. To improving results
  • 39.
  • 40.
    TOPICS 1.1 Why Program? 1.2Computer Systems: Hardware and Software 1.3 Programs and Programming Languages 1.4 What Is a Program Made of? 1.5 Input, Processing, and Output 1.6 The Programming Process 1.7 Tying It All Together: Hi! It’s Me Introduction to Computers and Programming 1.1 Why Program? CONCEPT: Computers can do many different jobs because they are programmable. Think about some of the different ways that people use computers. In school, students use computers for tasks such as writing papers, searching for articles, sending e-mail, and participating in online classes. At work, people use computers to analyze data, make presentations, conduct business transactions, communicate with customers and coworkers, control machines in manufacturing facilities, and do many other things. At home, people use computers for tasks such as paying bills, shopping online, social ­ networking, and playing games. And don’t forget that smart phones, iPods® , car navi- gation systems, and many other devices are computers as well. The uses of computers are almost limitless in our everyday lives. Computers can do such a wide variety of things because they can be programmed. This means that computers are not designed to do just one job, but to do any job that their programs tell them to do. A program is a set of instructions that a computer follows to perform a task. For example, Figure 1-1 shows screens using Microsoft Word and PowerPoint, two commonly used programs. C H A P T E R 1 35
  • 41.
    36 Chapter 1Introduction to Computers and Programming Programs are commonly referred to as software. Software is essential to a computer because without software, a computer can do nothing. All of the software that we use to make our computers useful is created by individuals known as programmers or software developers. A programmer, or software developer, is a person with the training and skills necessary to design, create, and test computer programs. Computer programming is an exciting and rewarding career. Today you will find programmers working in business, medicine, government, law enforcement, agriculture, academics, entertainment, and almost every other field. Computer programming is both an art and a science. It is an art because every aspect of a program should be designed with care and judgment. Listed below are a few of the things that must be designed for any real-world computer program: • The logical flow of the instructions • The mathematical procedures • The appearance of the screens • The way information is presented to the user • The program’s “user-friendliness” • Manuals and other forms of written documentation There is also a scientific, or engineering side to programming. Because programs rarely work right the first time they are written, a lot of experimentation, correction, and redesigning is required. This demands patience and persistence of the programmer. Writing software demands discipline as well. Programmers must learn special ­ languages like C++ because computers do not understand English or other human languages. Languages such as C++ have strict rules that must be carefully followed. Both the artistic and scientific nature of programming makes writing computer ­ software like designing a car. Both cars and programs should be functional, efficient, powerful, easy to use, and pleasing to look at. Figure 1-1 A Word Processing Program and a Presentation Program
  • 42.
    1.2 Computer Systems:Hardware and Software 37 1.2 Computer Systems: Hardware and Software CONCEPT: All computer systems consist of similar hardware devices and software components. This section provides an overview of standard computer hardware and software organization. Hardware Hardware refers to the physical components of a computer. A computer, as we gener- ally think of it, is not an individual device but a system of devices. Like the instruments in a symphony orchestra, each device plays its own part. A typical computer system consists of the following major components: • The central processing unit (CPU) • Main memory (random-access memory, or RAM) • Secondary storage devices • Input devices • Output devices The organization of a computer system is depicted in Figure 1-2. Input Devices Output Devices Secondary Storage Devices Central Processing Unit Main Memory (RAM) Figure 1-2
  • 43.
    38 Chapter 1Introduction to Computers and Programming The CPU When a computer is performing the tasks that a program tells it to do, we say that the computer is running or executing the program. The central processing unit, or CPU, is the part of a computer that actually runs programs. The CPU is the most important component in a computer because without it the computer could not run software. In the earliest computers, CPUs were huge devices made of electrical and mechanical components such as vacuum tubes and switches. Today’s CPUs, known as micropro- cessors, are tiny chips small enough to be held in the palm of your hand. In addition to being much smaller than the old electromechanical CPUs in early computers, today’s microprocessors are also much more powerful. The CPU’s job is to fetch instructions, follow the instructions, and produce some result. Internally, the central processing unit consists of two parts: the control unit and the arithmetic and logic unit (ALU). The control unit coordinates all of the computer’s operations. It is responsible for determining where to get the next instruction and for regulating the other major components of the computer with control signals. The ­ arithmetic and logic unit, as its name suggests, is designed to perform mathematical operations. The organization of the CPU is shown in ­ Figure 1-3. Central processing unit (CPU) Instruction input Arithmetic and logic unit (ALU) Control unit Result output Figure 1-3 A program is a sequence of instructions stored in the computer’s memory. When a computer is running a program, the CPU is engaged in a process known formally as the fetch/decode/execute cycle. The steps in the fetch/decode/execute cycle are as follows: Fetch The CPU’s control unit fetches, from main memory, the next instruction in the sequence of program instructions. Decode The instruction is encoded in the form of a number. The control unit decodes the instruction and generates an electronic signal. Execute The signal is routed to the appropriate component of the computer (such as the ALU, a disk drive, or some other device). The signal causes the ­component to perform an operation. These steps are repeated as long as there are instructions to perform.
  • 44.
    1.2 Computer Systems:Hardware and Software 39 Main Memory You can think of main memory as the computer’s work area. This is where the ­ computer stores a program while the program is running, as well as the data that the program is working with. For example, suppose you are using a word processing ­ program to write an essay for one of your classes. While you do this, both the word processing program and the essay are stored in main memory. Main memory is commonly known as random-access memory or RAM. It is called this because the CPU is able to quickly access data stored at any random location in this memory. RAM is usually a volatile type of memory that is used only for temporary storage while a program is running. When the computer is turned off, the contents of RAM are erased. Inside your computer, RAM is stored in small chips. A computer’s memory is divided into tiny storage cells known as bytes. One byte is enough memory to store just a single letter of the alphabet or a small number. In order to do anything meaningful, a computer has to have lots of bytes. Most computers today have millions, or even billions, of bytes of memory. Each byte is divided into eight smaller storage locations known as bits. The term bit stands for binary digit. Computer scientists usually think of bits as tiny switches that can be either on or off. Bits aren’t actual “switches,” however, at least not in the con- ventional sense. In most computer systems, bits are tiny electrical components that can hold either a positive or a negative charge. Computer scientists think of a positive charge as a switch in the on position and a negative charge as a switch in the off position. Each byte is assigned a unique number known as an address. The addresses are ordered from lowest to highest. A byte is identified by its address, in much the same way a post office box is identified by an address, so that the data stored there can be located. ­Figure 1-4 shows a group of memory cells with their addresses. The number 149 is stored in the cell at address 16, and the number 72 is stored at address 23. 0 10 20 1 11 21 2 12 22 3 13 23 4 14 24 5 15 25 6 16 26 7 17 27 8 18 28 9 19 29 149 72 Figure 1-4 Secondary Storage Secondary storage is a type of memory that can hold data for long periods of time— even when there is no power to the computer. Frequently used programs are stored in secondary memory and loaded into main memory as needed. Important information, such as word processing documents, payroll data, and inventory figures, is saved to secondary storage as well. The most common type of secondary storage device is the disk drive. A disk drive stores data by magnetically encoding it onto a circular disk. Most computers have a
  • 45.
    40 Chapter 1Introduction to Computers and Programming disk drive mounted inside their case. External disk drives, which connect to one of the computer’s communication ports, are also available. External disk drives can be used to create backup copies of important data or to move data to another ­computer. In addition to external disk drives, many types of devices have been created for copying data and for moving it to other computers. The most commonly used devices today are USB flash drives. These are small devices that plug into the computer’s USB (universal serial bus) port and appear to the system as a disk drive. These drives, which use flash memory to store data, are inexpensive, reliable, and small enough to be carried in your pocket. Optical devices such as the CD (compact disc) and the DVD (digital versatile disc) are also popular for data storage. Data is not recorded magnetically on an optical disc, but rather is encoded as a series of pits on the disc surface. CD and DVD drives use a laser to detect the pits and thus read the encoded data. Optical discs hold large amounts of data, and because recordable CD and DVD drives are now commonplace, they are good media for creating backup copies of data. Input Devices Input is any information the computer collects from the outside world. The device that collects the information and sends it to the computer is called an input device. Com- mon input devices are the keyboard, mouse, touch screen, scanner, digital camera, and microphone. Disk drives, CD/DVD drives, and USB flash drives can also be considered input devices because programs and information can be retrieved from them and loaded into the computer’s memory. Output Devices Output is any information the computer sends to the outside world. It might be a sales report, a list of names, or a graphic image. The information is sent to an output device, which formats and presents it. Common output devices are computer screens, printers, and speakers. Disk drives, USB flash drives, and CD/DVD recorders can also be con- sidered output devices because the CPU can send information to them to be saved. Software If a computer is to function, software is needed. Everything that a computer does, from the time you turn the power switch on until you shut the system down, is under the control of software. There are two general categories of software: system software and application software. Most computer programs clearly fit into one of these two ­categories. Let’s take a closer look at each. System Software The programs that control and manage the basic operations of a computer are gener- ally referred to as system software. System software typically includes the following types of programs:
  • 46.
    1.2 Computer Systems:Hardware and Software 41 • Operating Systems An operating system is the most fundamental set of programs on a computer. The operating system controls the internal operations of the computer’s hardware, manages all the devices connected to the computer, allows data to be saved to and retrieved from storage devices, and allows other programs to run on the computer. • Utility Programs A utility program performs a specialized task that enhances the computer’s ­ operation or safeguards data. Examples of utility programs are virus scanners, file-compression programs, and data-backup programs. • Software Development Tools The software tools that programmers use to create, modify, and test software are referred to as software development tools. Compilers and integrated development environments, which we discuss later in this chapter, are examples of programs that fall into this category. Application Software Programs that make a computer useful for everyday tasks are known as application software, or application programs. These are the programs that people normally spend most of their time running on their computers. Figure 1-1, at the beginning of this chapter, shows screens from two commonly used applications Microsoft Word, a word processing program, and Microsoft PowerPoint, a presentation program. Some other examples of application software are spreadsheet programs, e-mail programs, Web browsers, and game programs. Checkpoint 1.1 Why is the computer used by so many different people, in so many different professions? 1.2 List the five major hardware components of a computer system. 1.3 Internally, the CPU consists of what two units? 1.4 Describe the steps in the fetch/decode/execute cycle. 1.5 What is a memory address? What is its purpose? 1.6 Explain why computers have both main memory and secondary storage. 1.7 What are the two general categories of software? 1.8 What fundamental set of programs controls the internal operations of the ­computer’s hardware? 1.9 What do you call a program that performs a specialized task, such as a virus scanner, a file-compression program, or a data-backup program? 1.10 Word processing programs, spreadsheet programs, e-mail programs, Web browsers, and game programs belong to what category of software?
  • 47.
    42 Chapter 1Introduction to Computers and Programming 1.3 Programs and Programming Languages CONCEPT: A program is a set of instructions a computer follows in order to perform a task. A programming language is a special language used to write computer programs. What Is a Program? Computers are designed to follow instructions. A computer program is a set of instruc- tions that tells the computer how to solve a problem or perform a task. For example, suppose we want the computer to calculate someone’s gross pay. Here is a list of things the computer might do: 1. Display a message on the screen asking “How many hours did you work?” 2. Wait for the user to enter the number of hours worked. Once the user enters a number, store it in memory. 3. Display a message on the screen asking “How much do you get paid per hour?” 4. Wait for the user to enter an hourly pay rate. Once the user enters a number, store it in memory. 5. Multiply the number of hours by the amount paid per hour, and store the result in memory. 6. Display a message on the screen that tells the amount of money earned. The ­ message must include the result of the calculation performed in step 5. Collectively, these instructions are called an algorithm. An algorithm is a set of well- defined steps for performing a task or solving a problem. Notice these steps are ordered sequentially. Step 1 should be performed before step 2, and so forth. It is important that these instructions be performed in their proper sequence. Although a person might easily understand the instructions in the pay-calculating algorithm, it is not ready to be executed on a computer because a computer’s CPU can only process instructions written in machine language. A machine language program consists of a sequence of binary numbers (numbers consisting of only 1s and 0s), which the CPU interprets as commands. Here is an example of what a machine language instruction might look like: 1011010000000101 As you can imagine, encoding an algorithm in machine language would be tedious and difficult. In addition, each different type of CPU has its own machine language. So if you wrote a machine language program for computer A and then wanted to run it on a computer B that has a different type of CPU, you would have to rewrite the program in computer B’s machine language. Programming languages, which use words instead of numbers, were invented to ease the task of programming. A program can be written in a programming language such as C++, which is much easier to understand and write than machine language. Programmers can then save their programs in text files and use special software to convert them to machine language. Program 1-1 shows how the pay-calculating algorithm might be written in C++.
  • 48.
    1.3 Programs andProgramming Languages 43 NOTE: The line numbers shown in Program 1-1 are not part of the program. This book shows line numbers in all program listings to help point out specific parts of the program. Program 1-1 1 // This program calculates the user's pay. 2 #include iostream 3 using namespace std; 4 5 int main() 6 { 7 double hours, rate, pay; 8 9 // Get the number of hours worked. 10 cout How many hours did you work? ; 11 cin hours; 12 13 // Get the hourly pay rate. 14 cout How much do you get paid per hour? ; 15 cin rate; 16 17 // Calculate the pay. 18 pay = hours * rate; 19 20 // Display the pay. 21 cout You have earned $ pay endl; 22 return 0; 23 } Program Output with Example Input Shown in Bold How many hours did you work? 10 [Enter] How much do you get paid per hour? 15 [Enter] You have earned $150 The “Program Output with Example Input Shown in Bold” shows what the program will display on the screen when it is running. In the example, the user enters 10 for the number of hours worked and 15 for the hourly pay. The program displays the earn- ings, which are $150. Programming Languages In a broad sense, there are two categories of programming languages: low level and high level. A low-level language is close to the level of the computer, which means it resembles the numeric machine language of the computer more than the natural lan- guage of humans. The easiest languages for people to learn are high-level languages. They are called “high level” because they are closer to the level of human-readability than computer-readability. Figure 1-5 illustrates the concept of language levels.
  • 49.
    44 Chapter 1Introduction to Computers and Programming Low level (machine language) 10100010 11101011 High level (Easily understood by humans) Figure 1-5 Many high-level languages have been created. Table 1-1 lists a few of the well-known ones. Table 1-1 Well-Known High-Level Programming Languages Language Description BASIC Beginners All-purpose Symbolic Instruction Code. A general programming language originally designed to be simple enough for beginners to learn. C A structured, general-purpose language developed at Bell Laboratories. C offers both high-level and low-level features. C++ Based on the C language, C++ offers object-oriented features not found in C. Also invented at Bell Laboratories. C# Pronounced “C sharp.” A language invented by Microsoft for developing applications based on the Microsoft .NET platform. COBOL Common Business-Oriented Language. A language designed for business applications. FORTRAN Formula Translator. A language designed for programming complex mathematical algorithms. Java An object-oriented language invented at Sun Microsystems. Java may be used to develop programs that run over the Internet in a Web browser. JavaScript A language used to write small programs that run in Web pages. Despite its name, JavaScript is not related to Java. Pascal A structured, general-purpose language designed primarily for teaching programming. Python A general-purpose language created in the early 1990s. It has become popular for both business and academic applications.
  • 50.
    1.3 Programs andProgramming Languages 45 C++ is a widely used language because, in addition to the high-level features necessary for writing applications such as payroll systems and inventory programs, it also has many low-level features. C++ is based on the C language, which was invented for pur- poses such as writing operating systems and compilers. Because C++ evolved from C, it carries all of C’s low-level capabilities with it. C++ is also popular because of its portability. This means that a C++ program can be written on one type of computer and then run on many other types of systems. This usually requires recompiling the program on each type of system, but the program itself often needs little or no change. Ruby A general-purpose language created in the 1990s. It is becoming increasingly popular for programs that run on Web servers. Visual Basic A Microsoft programming language and software development environment that allows programmers to quickly create Windows-based applications. NOTE: Programs written for specific graphical environments typically do require sig- nificant changes when moved to a different type of system. Examples of such graphical environments are Windows, the X-Window System, and the Mac OS operating system. Source Code, Object Code, and Executable Code When a C++ program is written, it must be typed into the computer and saved to a file. A text editor, which is similar to a word processing program, is used for this task. The statements written by the programmer are called source code, and the file they are saved in is called the source file. After the source code is saved to a file, the process of translating it to machine language can begin. During the first phase of this process, a program called the preprocessor reads the source code. The preprocessor searches for special lines that begin with the # symbol. These lines contain commands, or directives, that cause the preprocessor to amend or process the source code in some way. During the next phase the compiler steps through the preprocessed source code, translating each source code instruction into the appropri- ate machine language instruction. This process will uncover any syntax errors that may be in the program. Syntax errors are illegal uses of key words, operators, punctuation, and other language elements. If the program is free of syntax errors, the compiler stores the translated machine language instructions, which are called object code, in an object file. Although an object file contains machine language instructions, it is not a complete program. Here is why. C++ is conveniently equipped with a library of prewritten code for performing common operations or sometimes-difficult tasks. For example, the library ­ contains hardware-specific code for displaying messages on the screen and reading input from the keyboard. It also provides routines for mathematical functions, such as calculating the square root of a number. This collection of code, called the run-time library, is extensive. Programs almost always use some part of it. When the compiler generates an object file, however, it does not include machine code for any run-time library routines the programmer might have used. During the last phase of the translation process, another program called the linker combines the object file with the necessary library routines. Once the linker has finished with this step, an executable file is created. The executable file contains machine language instructions, or executable code, and is ready to run on the computer.
  • 51.
    46 Chapter 1Introduction to Computers and Programming Figure 1-6 illustrates the process of translating a C++ source file into an executable file. The entire process of invoking the preprocessor, compiler, and linker can be initiated with a single action. For example, on a Linux system, the following command causes the C++ program named hello.cpp to be preprocessed, compiled, and linked. The executable code is stored in a file named hello. g++ -o hello hello.cpp Source code hello.cpp Preprocessor Modified source code Compiler Object code hello.obj Executable code hello.exe Linker Source code is entered with a text editor by the programmer. // hello.cpp #include iostream using namespace std; int main( ) { cout Hello Worldn; return 0; } Figure 1-6 Many development systems, particularly those on personal computers, have integrated development environments (IDEs). These environments consist of a text editor, com- piler, debugger, and other utilities integrated into a package with a single set of menus. Preprocessing, compiling, linking, and even executing a program is done with a single click of a button, or by selecting a single item from a menu. Figure 1-7 shows a screen from the Microsoft Visual Studio 2013 IDE.
  • 52.
    1.4 What Isa Program Made of? 47 Figure 1-7 Checkpoint 1.11 What is an algorithm? 1.12 Why were computer programming languages invented? 1.13 What is the difference between a high-level language and a low-level language? 1.14 What does portability mean? 1.15 Explain the operations carried out by the preprocessor, compiler, and linker. 1.16 Explain what is stored in a source file, an object file, and an executable file. 1.17 What is an integrated development environment? 1.4 What Is a Program Made of? CONCEPT: There are certain elements that are common to all programming languages. Language Elements All programming languages have a few things in common. Table 1-2 lists the common elements found in almost every language.
  • 53.
    48 Chapter 1Introduction to Computers and Programming Let’s look at some specific parts of Program 1-1 (the pay-calculating program) to see exam- ples of each element listed in the table above. For convenience, Program 1-1 is listed again. Table 1-2 Programming Language Elements Language Element Description Key Words Words that have a special meaning. Key words may only be used for their intended purpose. Key words are also known as reserved words. Programmer-Defined Words or names defined by the programmer. They are symbolic names Identifiers that refer to variables or programming routines. Operators Operators perform operations on one or more operands. An operand is usually a piece of data, like a number. Punctuation Punctuation characters that mark the beginning or ending of a statement, or separate items in a list. Syntax Rules that must be followed when constructing a program. Syntax dictates how key words and operators may be used, and where punctuation symbols must appear. Program 1-1 1 // This program calculates the user's pay. 2 #include iostream 3 using namespace std; 4 5 int main() 6 { 7 double hours, rate, pay; 8 9 // Get the number of hours worked. 10 cout How many hours did you work? ; 11 cin hours; 12 13 // Get the hourly pay rate. 14 cout How much do you get paid per hour? ; 15 cin rate; 16 17 // Calculate the pay. 18 pay = hours * rate; 19 20 // Display the pay. 21 cout You have earned $ pay endl; 22 return 0; 23 } Key Words (reserved words) Three of C++’s key words appear on lines 3 and 5: using, namespace, and int. The word double, which appears on line 7, is also a C++ key word. These words, which are always written in lowercase, each have a special meaning in C++ and can only be used for their
  • 54.
    1.4 What Isa Program Made of? 49 intended purposes. As you will see, the programmer is allowed to make up his or her own names for certain things in a program. Key words, however, are reserved and cannot be used for anything other than their designated purposes. Part of learning a programming language is learning what the key words are, what they mean, and how to use them. NOTE: The #include iostream statement in line 2 is a preprocessor directive. NOTE: In C++, key words are always written in all lowercase. Programmer-Defined Identifiers The words hours, rate, and pay that appear in the program on lines 7, 11, 15, 18, and 21 are programmer-defined identifiers. They are not part of the C++ language but rather are names made up by the programmer. In this particular program, these are the names of variables. As you will learn later in this chapter, variables are the names of memory locations that may hold data. Operators On line 18 the following statement appears: pay = hours * rate; The = and * symbols are both operators. They perform operations on pieces of data, known as operands. The * operator multiplies its two operands, which in this example are the variables hours and rate. The = symbol is called the assignment operator. It takes the value of the expression on the right and stores it in the variable whose name appears on the left. In this example, the = operator stores in the pay variable the result of the hours vari- able multiplied by the rate variable. In other words, the statement says, “Make the pay variable equal to hours times rate” or “pay is assigned the value of hours times rate.” Punctuation Notice that many lines end with a semicolon. A semicolon in C++ is similar to a period in English. It marks the end of a complete sentence (or statement, as it is called in program- ming). Semicolons do not appear at the end of every line in a C++ program, however. There are rules that govern where semicolons are required and where they are not. Part of learning C++ is learning where to place semicolons and other punctuation symbols. Lines and Statements Often, the contents of a program are thought of in terms of lines and statements. A line is just that—a single line as it appears in the body of a program. Program 1-1 is shown with each of its lines numbered. Most of the lines contain something meaningful; however, some of the lines are empty. The blank lines are only there to make the program more readable. A statement is a complete instruction that causes the computer to perform some action. Here is the statement that appears in line 10 of Program 1-1: cout How many hours did you work? ;
  • 55.
    Other documents randomlyhave different content
  • 56.
    Thicken cream ofcorn soup a little more if necessary, or, add corn to thin cream sauce, and serve on toast. Left-overs of all sorts of cream soups may be utilized for toast: celery, asparagus, string bean, oyster plant and spinach, also succotash and other stewed or creamed vegetables. Lentil and Other Legume Toasts Use any lentil gravy or thickened lentil soup, cream of peas or peas and tomato soup thickened, red kidney beans purée or thickened soup, on moistened slices of zwieback. Toast Royal 1 cup drawn butter sauce 3 eggs 1 cup minced trumese or nutmese or ½ cup chopped nuts Add meat to hot sauce and pour all over beaten salted eggs; cook as scrambled eggs. Serve immediately on moistened slices of zwieback, with baked tomatoes when convenient. The following toasts are of a different nature (though slices of zwieback may be used instead of bread), but they are good emergency dishes. French Toast Add ½ cup of milk with salt to 2 or 3 beaten eggs. Dip slices of stale bread or moistened zwieback in the mixture and brown delicately on
  • 57.
    both sides onmoderately hot buttered griddle or in quick oven, or in frying pan covered. Serve plain or with any suitable sauce. Drain slices after dipping in egg mixture; crumb, bake, and serve with honey, maple syrup or jelly for Breaded French Toast. German Toast Add grated or fine chopped onion to egg mixture and finish the same as French toast. Spanish Cakes Batter—2 eggs, 2 tablespns. flour, 1 teaspn. of oil, milk for smooth thin batter. Nut milk may be used and oil omitted. Cut thin slices of bread into any desired shape (round with biscuit cutter), spread each one of half the pieces with jelly, jam or marmalade and press another on to it; dip in the batter, lay on oiled baking pan, stand 15 m. or longer in a cold place. Bake in a quick oven, serve with a bit of the preserve on top and half of a nut pressed into each, or, dusted with powdered sugar. Mamie’s Surprise Biscuit Inclose small cakes of nicely seasoned mashed potato in pastry crust; bake, serve with milk gravy, drawn butter or cream sauce, or with celery only. This is the original recipe which leads to the following variations: Mix finely-sliced celery with the potato. Use the mixture of black walnut and potato stuffing, or mashed lentils or mashed peas for filling.
  • 58.
    Serve peas biscuitwith tomato or tomato cream sauce. Serve lentil biscuit with cream, cream of tomato or mushroom sauce. Lentil biscuit with fresh mushroom or Boundary Castle sauce, with or without celery, might constitute one course at a dinner. Make a filling of minced trumese, salt, oil, chopped parsley, onion and mushrooms into small cakes or balls, inclose them in universal crust, and when light, steam 25–30 m. Serve with drawn butter, flavored with onion and parsley, or as garnish for a meat dish. Make balls quite small for garnish. Yorkshire Pudding ½ cup flour salt 1⅓ cup milk 2 eggs 1 teaspn. oil Beat eggs, add milk and pour gradually into flour mixed with salt; add oil, beat well, turn into well oiled, or oiled and crumbed gem pans; bake in moderate (slow at first) oven. Serve as garnish or accompaniment to ragout, or if baked in flat cakes, with slices of broiled or à la mode meats laid on them, and gravy poured around. The pudding may be baked in a flat pan and cut into any desired shape for serving. Whites and yolks of eggs may be beaten separately. A large onion chopped may be used in the pudding.
  • 59.
    Rice Border Pack hotboiled rice into well oiled border mold and let stand in a warm place (over kettle of hot water) for 10 m. Turn on to serving dish carefully. Or, parboil 1 cup of rice in salted water 5 m.; drain and cook in a double boiler with 2½–3 cups of milk and salt, until the rice is tender and the milk absorbed, then pack into the mold. 1 tablespn. of butter and the yolks of 2 eggs may be added to the rice about 2 m. before it is taken from the double boiler. Oyster Plant and Potato Omelet—without eggs With nicely seasoned, not too moist, mashed potato, mix slices of cooked oyster plant which have been simmered in cream or butter. Spread in well oiled frying or omelet pan. When delicately browned on the bottom, fold, omelet fashion, turn on to a hot platter, garnish. Serve plain or with cream sauce or with thin drawn butter. Or, grind oyster plant, cook in a small quantity of water, add cream or butter and mix with plain potato. Finely-sliced raw celery or chopped raw onion and parsley may be used in the potato sometimes. Baked Potatoes and Milk Wash potatoes well, scrubbing with vegetable brush. Cut out any imperfect spots. Bake until just done. Break up, skins and all, into nice rich milk and eat like bread and milk for supper. A favorite dish of some of the early settlers in Michigan. Bread and Milk with Sweet Fruits
  • 60.
    Add nice ripeblueberries to bread and milk for supper, also ripe black raspberries or baked sweet apples. They are all delicious. ★ Apples in Oil Simmer finely-sliced onion in oil 5–10 m. without browning; add salt and a little water, then apples which have been washed, quartered, cored and sliced without paring. Sprinkle lightly with salt. Cover and cook until apples are just tender, not broken. Serve for breakfast or supper, or with a meat dish instead of a vegetable, for luncheon or dinner. The onion may be omitted. Use a little sugar when apples are very sour. Onion Apples Simmer sliced onions in oil, with salt, in baking pan. Place apples, pared and cored, on top of the onions; sprinkle with sugar and put ¼ teaspn. in each cavity. Cover, bake; uncover and brown. Serve for luncheon, or as garnish for meat dish.
  • 61.
    TRUE MEATS “And Godsaid, Behold I have given you every herb bearing seed, which is upon the face of all the earth, and every tree, in the which is the fruit of a tree yielding seed; to you it shall be for meat.” Gen. 1:29. “The food which God gave Adam in his sinless state is the best for man’s use as he seeks to regain that sinless state. “The intelligence displayed by many dumb animals approaches so closely to human intelligence that it is a mystery. “The animals see and hear and love and fear and suffer. “They manifest sympathy and tenderness toward their companions in suffering. “They form attachments for man which are not broken without great suffering to them. “Think of the cruelty to animals that meat eating involves and its effect on those who inflict and those who behold it. How it destroys the tenderness with which we should regard these creatures of God!” The high price of flesh foods, the knowledge of the waste matter in the blood of even healthy animals which remains in their flesh after death, and the well authenticated reports of the increasing prevalence of most loathsome diseases among them, causes a growing desire among thinking people to take their food at first hand, before it has become a part of the body of some lower animal. So, the great food question of the day is—“What shall we use in the place of meat?”
  • 62.
    Nuts, legumes (peas,beans, lentils and peanuts) and eggs contain as do flesh meats, an excess of the proteid or muscle- building elements (nuts and legumes a much larger proportion than flesh), so we may combine these with fruits, vegetables and some of the cereals (rice, for instance) and have a perfect proportion of food elements. It must be borne in mind, however, that proteid foods must be used sparingly, since an excess of these foods causes some of the most serious diseases. The bulk of our foods should be made up of fruits and vegetables and some of the less hearty cereals and breads. NUTS As nuts occupy the highest round of the true meat ladder, we give a variety of recipes for their use, following with legumes and eggs in their order. With nuts, as with other foods, the simplest way to use them is the best. There are greater objections to foods than that they are difficult of digestion, and in the case of nuts, that objection is overcome by thorough mastication; in fact, they are an aid to the cultivation of that important function in eating. For those who are not able to chew their food, nuts may be ground into butter. Another aid to the digestion of nuts is the use with them of an abundance of acid fruits. Fruits and nuts seem to be each the complement of the other, the nuts as well, preventing the unpleasant effects felt by some in the free use of fruits.
  • 63.
    “No investigations havebeen found on record which demonstrate any actual improvement in the digestibility of nuts due to salt.”— M. E. Jaffa, M. S., Professor of Nutrition, University of California. Be sure that nuts are fresh. Rancid nuts are no better than rancid butter. Shelled nuts do not keep as well as those in the shell. Almonds stand at the head of the nut family. It is better to buy them in the shell as shelled almonds are apt to have bitter ones among them. Almonds should not be partaken of largely with the brown covering on, but are better to be blanched. To Blanch Almonds—Throw them into perfectly boiling water, let them come to the boiling point again, drain, pour cold water over them and slip the skins off with the thumb and finger. Drop the meats on to a dry towel, and when they are all done, roll them in the towel for a moment, then spread them on plates or trays to dry. They must be dried slowly as they color easily, and the sweet almond flavor is gone when a delicate color only, is developed. For butter they must be very dry, really brittle. Brazil Nuts—castanas—cream nuts, do not require blanching, as their covering does not seem to be objectionable. They are rich in oil and are most valuable nuts. Slice and dry them for grinding. Filberts—hazelnuts—cobnuts—Barcelonas, also may be eaten without blanching, though they may be heated in the oven (without browning) or put into boiling water and much of the brown covering removed. They are at their best unground, as they do not give an especially agreeable flavor to cooked foods. They may be made into butter. Brazil nuts and filberts often agree with those who cannot use English walnuts and peanuts.
  • 64.
    English Walnuts—The coveringof the English walnut is irritating and would better be removed when practicable. This is done by the hot water method, using a knife instead of the thumb and finger. The unblanched nuts may however, be used in moderation by nearly every one. Butternuts and black walnuts blanch more easily than the English walnut. When whole halves of such nuts as hickory nuts, pecans or English walnuts are required, throw the nuts into boiling water for two or three minutes, or steam them for three or four minutes, or wrap them in woolen cloths wrung out of boiling water. Crack, and remove meats at once. Do not leave nuts in water long enough to soak the meats. Pinenuts come all ready blanched. When they require washing, pour boiling water over them first, then cold water. Drain, dry in towels, then on plates in warm oven. Peanuts—ground nuts, because of their large proportion of oil, and similarity in other respects to nuts are classed with them, though they are truly legumes. The Spanish peanut contains more oil than the Virginia, but the flavor of the Virginia is finer and its large size makes it easier to prepare. The “Jumbos” are the cheapest. To blanch Spanish peanuts the usual way, heat for some time, without browning, in a slow oven, stirring often. When cool rub between the hands or in a bag to remove the skins. The best way to blow the hulls away after they are removed is to turn the nuts from one pan to another in the wind.
  • 65.
    Spanish peanuts canbe obtained all ready blanched from the nut food factories. The Virginias, not being so rich in oil must always be blanched the same as almonds. Be sure to let them boil well before draining. I prefer to blanch the Spanish ones that way, too, the results are so much more satisfactory. When peanuts are partly dried, break them apart and remove the germ, which is disagreeable and unwholesome: then finish drying. A FEW SUGGESTIVE COMBINATIONS
  • 66.
    For Using Nutsin the Simplest Ways Brazil nuts, filberts or blanched almonds with:— Fresh apples, pears or peaches; Dried, steamed or stewed figs, raisins, dates, prunes, apple sauce, baked apples or baked quinces; Celery, lettuce, cabbage, tender inside leaves of spinach, grated raw carrot or turnip; Breakfast cereals, parched or popped corn, well browned granella, crackers, gems, zwieback, Boston brown and other breads; Stewed green peas, string beans, asparagus, corn, greens, potatoes, squash, cauliflower, all vegetables; Pies, cakes and different desserts when used. Nut Butter A good nut butter mill is an excellent thing to have, but butter can be made with the food cutters found nowadays in almost every home. If the machine has a nut butter attachment, so much the better; otherwise the nuts will need to be ground repeatedly until the desired fineness is reached. For almond butter, blanch and dry the almonds according to directions, adjust the nut butter cutter, not too tight, put two or three nuts into the mill at a time, and grind. When the almonds are thoroughly dried they will work nicely if the mill is not fed too fast. Brazil nuts and filberts need to be very dry for butter. Pine nuts are usually dry enough as they come to us. All nuts grind better when first dried.
  • 67.
    Raw peanut butteris a valuable adjunct to cookery. To make, grind blanched dried nuts; pack in tins or jars and keep in a dry place. For steamed butter, put raw butter without water into a double boiler or close covered tins and steam 3–5 hours. Use without further cooking in recipes calling for raw nut butter. Or, grind dried boiled nuts the same as raw nuts. For immediate use, boiled nuts may be ground without drying. When roasted nut butter is used, it should be in small quantities only, for flavoring soups, sauces or desserts. My experience is that the best way to roast nuts for butter is to heat them, after they are blanched and dried, in a slow oven, stirring often, until of a cream or delicate straw color. By this method they are more evenly colored all through. Do not salt the butter, as salt spoils it for use with sweet dried fruits as a confection, and many prefer it without salt on their bread. The objection to roasted nuts is the same as for browning any oil. Raising the oil of the nuts to a temperature high enough to brown it, decomposes it and develops a poisonous acid. Hardly too much can be said of the evil effects of the free use of roasted nut butter. “There are many persons who find that roasted peanuts eaten in any quantity are indigestible in the sense of bringing on pain and distress.... Sometimes this distress seems to be due to eating peanuts which are roasted until they are very brown.” —Mary Hinman Abel, Farmers’ Bulletin, No. 121, U.S. Department of Agriculture.
  • 68.
    Nut Meal Nut mealis made the same as nut butter except that the nuts are ground fewer times through the finest cutter of the mill, or once only through the nut butter cutter loosely adjusted. Either cooked or raw peanuts may be used, but a cooked peanut meal is very desirable. The nuts may be cooked, dried and ground, or cooked without water, after grinding, the same as steamed nut butter. When one has no mill, meal of many kinds of nuts may be made in the following manner: Pound a few at a time in a small strong muslin bag; sift them through a wire strainer and return the coarse pieces to the bag again with the next portion. Be sure that not the smallest particle of shell is left with the meats. A dear friend of mine used to keep jars of different nut meals prepared in this way on hand long before any manufactured ones were on the market. One writer says: “The children enjoy cracking the nuts and picking out the meats, and it is a short task to prepare a cupful.” Cooked nuts and some raw ones may be rubbed through the colander for meal. Nut meals are used for shortening pie crust, crackers and sticks; and all except peanut, are delightful sprinkled over stewed fruits or breakfast foods. Nut Butter for Bread Nut butters (except raw peanut) may be used on bread as they are ground; but are usually stirred up with water to an agreeable butter-
  • 69.
    like consistency, andsalt added. Strained tomato may be used instead of water for a change. This is especially nice for sandwiches. With peanut butter made from boiled or steamed nuts it has a flavor similar to cheese. Nut butter is more attractive for the table when pressed through a pastry tube in roses on to individual dishes. Use a cloth (not rubber) pastry bag. While pure nut butter, if kept in a dry place, will keep almost indefinitely, it will sour as quickly as milk after water is added to it. Nut Cream and Milk Add water to nut butter until of the desired consistency, for cream; then still more, for milk. Almond milk makes a delightful drink and can be used by many who cannot take dairy milk. It may be heated and a trifle of salt added. Cocoanut Milk If you have not a cocoanut scraper, grate fresh cocoanut, one with milk in it, or grind it four or five times through the finest cutter of a mill. Pour over it an equal bulk or twice its bulk, of boiling water, according to the richness of the milk desired or the quality of the cocoanut. Stir and mix well and strain through cheese cloth or a wire strainer. Add a second quantity of hot water and strain again, wringing or pressing very dry. Throw the fibre away. Use cocoanut milk or cream for vegetable or pudding sauces or in almost any way that dairy milk and cream are used. Stir before
  • 70.
    using. To breakthe nut in halves, take it in the left hand and strike it with a hammer in a straight line around the center. It may be sawed in two if the cups are desired for use. Cocoanut Butter Place milk on ice for a few hours when the butter will rise to the top and can be skimmed off. Ground or Grated Cocoanut Is delightful on breakfast cereals, or eaten with bread in place of butter. The brown covering of the meat should first be taken off. Shredded Cocoanut Put any left-overs of prepared cocoanut on a plate and set in the sun or near the stove to dry. Keep in glass jars in a dry place. This unsweetened cocoanut can be used for shortening and in many places where sweet is not desirable. Milk and Rich Cream of Raw Peanuts May be prepared the same as cocoanut milk, except that cold or lukewarm water is used instead of hot. To raw nut meal (not butter) add one half more of water than you have of meal. Mix and beat well, strain through a thin cloth, squeeze as dry as possible. Let milk stand in a cool place and a very rich cream will rise which may be used for shortening pie crust, crackers and sticks, or in place of dairy cream in other ways. The
  • 71.
    skimmed milk willbe suitable for soups, stews or gravies. It may be cooked before using if more convenient. The pulp also may be used in soups. It should be thoroughly cooked. Nut Relish Different nut butters and meals may be combined in varying proportions. For instance, 2 parts Brazil nuts, 1 part each pine nuts and almonds; or 1 part each Brazil nuts, almonds, pecans, and pine nuts. Dry nuts well and grind all together or combine after grinding. Press into tumblers or small tins and stand in cool place. Unmold to serve. The relish may be used in combinations suggested for whole nuts, and it is a great improvement over cheese, with apple pie. Toasted Almonds When blanched almonds are thoroughly dried, put them into a slow oven and let them come gradually to a delicate cream color, not brown. These may be served in place of salted almonds. Sweetmeats of fruits and nuts will be found among confections. COOKED NUT DISHES Nut Croquettes 1 cup chopped nuts (not too fine), hickory, pecan, pine or butternuts, or a mixture of two with some almonds if desired; 2 cups boiled rice or hominy, 1½ tablespn. oil or melted butter, salt, sage. Mix, shape into rolls about 1 in. in diameter and 2½ in. in length. Egg and crumb; bake in quick oven until just heated through and
  • 72.
    delicately browned, 8to 10 m. Serve plain or with any desired sauce or vegetable. Nut Croquettes No. 2 1 cup chopped nuts, 1 cup cooked rice, any desired seasoning or none, salt; mix. Sauce— 2 tablespns. oil ½ cup flour 1–1¼ cup milk 1 egg or yolk only or no egg salt Heat but do not brown the oil, add half the flour, then the milk, and when smooth, the salt and the remainder of the flour, and combine with mixed nuts and rice. Cool, shape, egg, crumb, bake. Crumb also before dipping in egg the same as Trumese croquettes, if necessary. Bake only until beginning to crack. Serve at once. Savory Nut Croquettes 1 cup stale, quite dry, bread crumbs, ½ cup (scant) milk or consommé, ¼–½ level teaspn. powdered leaf sage or winter savory, ½ cup black walnut or butternut meats, salt. Mix, shape, egg, crumb, bake. 1 cup chopped mixed nuts may be used and celery salt or no flavoring. Hickory nut meats alone, require no flavoring.
  • 73.
    Nut and SweetPotato Cutlets 1 cup chopped nut meats 2 cups chopped boiled sweet potato 1 tablespn. butter 1 egg salt Mix while warm. Pack in brick-shaped tin until cold. Unmold, slice, egg, crumb or flour. Brown in quick oven or on oiled griddle. Serve plain or with sauce 16 or 17. ★ Baked Pine Nuts After picking out the pieces of shell, pour boiling water over 2 lbs. of pine nuts in a fine colander. Rinse in cold water and put into the bean pot, with 2 large onions sliced fine, 1–1⅓ cup strained tomato and 2–2½ teaspns. salt. Heat quite rapidly at first; boil gently for a half hour, then simmer slowly in the oven 10–12 hours or longer. Leave just juicy for serving. Black Walnut and Potato Mound Mix 1 qt. nicely seasoned, well beaten mashed potato, ½–1 cup chopped black walnut meats and 2 or 3 tablespns. grated onion. Pile in rocky mound on baking pan or plate. Sprinkle with crumbs or not. Bake in quick oven until delicately browned. Garnish and serve with sauce 6 or 16. Nut and Rice Roast or Timbale
  • 74.
    1–2 cups choppednuts, one kind or mixed (no English walnuts unless blanched), 2 cups boiled or steamed rice, 1½–3 tablespns. oil or melted butter, salt. Mix ingredients and put into well oiled timbale mold or individual molds or brick shaped tin. Bake covered, in pan of water ¾–1½ hr. according to size of mold. Uncover large mold a short time at the last. Let stand a few minutes after removing from oven, unmold, and serve with creamed celery or peas or with sauce 16 (cocoanut cream if convenient) or 34. Loaf may be flavored, and served with any suitable sauce. Loaf of Nuts 2 tablespns. raw nut butter ⅓ cup whole peanuts cooked almost tender ½ cup each chopped or ground pecans, almonds and filberts (or butternuts, hazelnuts, and hickory nuts) 2 cups stale bread crumbs pressed firmly into the cup salt ¾–1 cup water or 1 of milk The quantity of liquid will depend upon the crumbs and other conditions. Put into oiled mold or can, cover, steam 3 hours. Or, have peanuts cooked tender, form into oval loaf, bake on tin in oven, basting occasionally with butter and water or salted water only. Serve with sauce 9, 10, 57, 59, or 69. Loaf may be served cold in slices, or dipped in egg, and crumbed, and baked as cutlets. Other nuts may be substituted for peanuts.
  • 75.
    One-half cup blackwalnuts and 1½ cup cooked peanuts, chopped, make a good combination. A delicate flavoring of sage, savory or onion is not out of place with these. To Boil Peanuts Put blanched, shelled peanuts into boiling water and boil continuously, for from 3–5 hrs., or until tender. (When the altitude is not great it takes Virginias 4 or 5 hours and Spanish about 3 to cook tender). Drain, saving the liquid for soup stock, and use when boiled peanuts are called for. Nut Soup Stock Use the liquid, well diluted, poured off from boiled peanuts, for soups. Large quantities may be boiled down to a jelly and kept for a long time in a dry place. If paraffine is poured over the jelly, it will keep still better. Use 1 tablespn. only of this jelly for each quart of soup. Peanuts with Green Peas Boil 1 cup blanched peanuts 1–2 hrs., drain off the water and save for soup. Put fresh water on to the peanuts, add salt and finish cooking. Just before serving add 1 pt. of drained, canned peas. Heat well. Add more salt if necessary, and serve. Or, 1 pt. of fresh green peas may be cooked with the nuts at the last. Small new potatoes would be a suitable addition also.
  • 76.
    ★ Peanuts Bakedlike Beans 1 lb. (¾ qt.) blanched peanuts ¼ cup strained tomato ½–1 tablespn. browned flour 1¼–1½ teaspn. salt Mix browned flour, tomato and salt, put into bean pot with the nuts and a large quantity of boiling water. Boil rapidly ½ hr., then bake in a slow oven 8–14 hours. Add boiling water without stirring, when necessary. When done the peanuts should be slightly juicy. Small dumplings steamed separately, may be served with baked peanuts sometimes. Baked Peanuts—Lemon Apples Pile peanuts in center of platter or chop tray. Surround with lemon apples, garnish with grape leaves and tendrils or with foliage plant leaves. Peanuts with Noodles or Vermicelli Cook peanuts in bouillon with bay leaf and onions. Just before serving, add cooked noodles or vermicelli. Nut Chinese Stew Use boiled peanuts instead of nutmese and raw nut butter, and rice (not too much) in place of potato, in Nut Irish Stew. Peanut Gumbo
  • 77.
    Simmer sliced orchopped onion in butter; add 1 pt. stewed okra; simmer 5–10 m. Add 1 pt. strained tomato, then ¾–1 qt. of baked or boiled peanuts. Turn into a double boiler and add ½ cup boiled rice. Heat 15–20 m. Hot Pot of Peanuts Put layers of sliced onion, sliced potatoes and boiled peanuts into baking dish with salt and a slight sprinkling of sage. Cover the top with halved potatoes. Stir a little raw nut butter with water and pour over all. Cover with a plate or close fitting cover and bake 2 hours. Remove cover and brown. Peanut Hashes Cooked peanuts, chopped very little if any, may be used in place of trumese with potatoes or rice for hash. Bread, cracker or zwieback crumbs may be substituted for potato or rice. Peanut German Chowder 1 pt. cooked peanuts 1 large onion 2 tablespns. chopped parsley ½ medium sized bay leaf ⅛ level teaspn. thyme 1 small carrot 1 level tablespn. browned flour 2 level tablespns. white flour
  • 78.
    Welcome to ourwebsite – the perfect destination for book lovers and knowledge seekers. We believe that every book holds a new world, offering opportunities for learning, discovery, and personal growth. That’s why we are dedicated to bringing you a diverse collection of books, ranging from classic literature and specialized publications to self-development guides and children's books. More than just a book-buying platform, we strive to be a bridge connecting you with timeless cultural and intellectual values. With an elegant, user-friendly interface and a smart search system, you can quickly find the books that best suit your interests. Additionally, our special promotions and home delivery services help you save time and fully enjoy the joy of reading. Join us on a journey of knowledge exploration, passion nurturing, and personal growth every day! ebookbell.com