Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
17 views72 pages

C For Business Programming 2nd Ed Edition Molluzzo PDF Download

The document provides a comprehensive overview of various C and C++ programming books available for download, including titles focused on business programming and specific applications like Arduino and game engine programming. It lists the authors, editions, and links to access these ebooks. Additionally, it includes a cataloging section for 'C++ for Business Programming' by John C. Molluzzo, detailing its contents and structure.

Uploaded by

zindiasanyo41
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views72 pages

C For Business Programming 2nd Ed Edition Molluzzo PDF Download

The document provides a comprehensive overview of various C and C++ programming books available for download, including titles focused on business programming and specific applications like Arduino and game engine programming. It lists the authors, editions, and links to access these ebooks. Additionally, it includes a cataloging section for 'C++ for Business Programming' by John C. Molluzzo, detailing its contents and structure.

Uploaded by

zindiasanyo41
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 72

C for business programming 2nd ed Edition

Molluzzo pdf download

https://ebookgate.com/product/c-for-business-programming-2nd-ed-
edition-molluzzo/

Get Instant Ebook Downloads – Browse at https://ebookgate.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Programming with ANSI C 2nd ed Edition Trivedi

https://ebookgate.com/product/programming-with-ansi-c-2nd-ed-edition-
trivedi/

ebookgate.com

Programming in C 2nd Edition Safari

https://ebookgate.com/product/programming-in-c-2nd-edition-safari/

ebookgate.com

C GUI Programming with Qt 4 2nd ed., Extensively rev. and


expanded Edition Jasmin Blanchette

https://ebookgate.com/product/c-gui-programming-with-qt-4-2nd-ed-
extensively-rev-and-expanded-edition-jasmin-blanchette/

ebookgate.com

C Programming for Arduino 1st Edition Julien Bayle

https://ebookgate.com/product/c-programming-for-arduino-1st-edition-
julien-bayle/

ebookgate.com
Programming Principles and Practices using C 2nd Edition
Bjarne Stroustrup

https://ebookgate.com/product/programming-principles-and-practices-
using-c-2nd-edition-bjarne-stroustrup/

ebookgate.com

C Programming for the Absolute Beginner 3rd Edition Keith


Davenport

https://ebookgate.com/product/c-programming-for-the-absolute-
beginner-3rd-edition-keith-davenport/

ebookgate.com

AI Game Engine Programming 2nd ed Edition Brian Schwab

https://ebookgate.com/product/ai-game-engine-programming-2nd-ed-
edition-brian-schwab/

ebookgate.com

Practice made perfect the discipline of business


management for financial advisers 1st ed Edition Mark C.
Tibergien
https://ebookgate.com/product/practice-made-perfect-the-discipline-of-
business-management-for-financial-advisers-1st-ed-edition-mark-c-
tibergien/
ebookgate.com

C 2013 for C Developers 2nd Edition Dean C. Wills

https://ebookgate.com/product/c-2013-for-c-developers-2nd-edition-
dean-c-wills/

ebookgate.com
C++ for Business
Programming
Second Edition

John C. Molluzzo
Pace University, New York

Upper Saddle River, New Jersey 07458


Library of Congress Cataloging-in-Publication Data
Molluzzo, John C.
C++ for business programming / John C. Molluzzo.-- 2nd ed.
p. cm.
Includes bibliographical references and index.
ISBN 0-13-046700-6
1. C++ (Computer program language) 2. Business--Computer programs.
I. Title.
HF5548.5.C125M65 2006
005.13'3--dc22 2005014365

Vice President and Editorial Director, ECS: Marcia J. Horton


Senior Acquisitions Editor: Tracy Dunkelberger
Editorial Assistant: Christianna Lee
Executive Managing Editor: Vince O’Brien
Managing Editor: Camille Trentacoste
Director of Creative Services: Paul Belfanti
Managing Editor, AV Management and Production: Patricia Burns
Art Editor: Gregory Dulles
Cover Design Director: Jayne Conte
Cover Designer: Kiwi Designs
Manufacturing Manager, ESM: Alexis Heydt-Long
Manufacturing Buyer: Lisa McDowell
Executive Marketing Manager: Pamela Shaffer
Marketing Assistant: Barrie Reinhold

© 2006 Pearson Education, Inc.


Pearson Prentice Hall
Pearson Education, Inc.
Upper Saddle River, NJ 07458

All rights reserved. No part of this book may be reproduced in any form or by any means, without
permission in writing from the publisher.
Pearson Prentice Hall® is a trademark of Pearson Education, Inc.

The author and publisher of this book have used their best efforts in preparing this book. These
efforts include the development, research, and testing of the theories and programs to determine
their effectiveness. The author and publisher make no warranty of any kind, expressed or implied,
with regard to these programs or the documentation contained in this book. The author and
publisher shall not be liable in any event for incidental or consequential damages in connection
with, or arising out of, the furnishing, performance, or use of these programs.

Printed in the United States of America

10 9 8 7 6 5 4 3 2 1

ISBN: 0-13-046700-6

Pearson Education Ltd., London Pearson Educación de Mexico, S.A. de C.V.


Pearson Education Australia Pty. Ltd., Sydney Pearson Education—Japan, Tokyo
Pearson Education Singapore, Pte. Ltd. Pearson Education Malaysia, Pte. Ltd.
Pearson Education North Asia Ltd., Hong Kong Pearson Education, Inc., Upper Saddle River, New Jersey
Pearson Education Canada, Inc., Toronto
Contents

PREFACE XV

PART I C++ Basics 1

1. INTRODUCTION TO C++ 1

Objectives 1
Why Study C++? 1
1.1 Our First C++ Program 3
1.1.1 The Program Development Cycle 3
1.1.2 Errors in the Cycle 7
1.1.3 Displaying a Two-Line Message: dem01-1.cpp 8
1.1.4 Comments 9
1.1.5 The Function main() 10
1.1.6 The Output Stream cout 11
1.1.7 The return Statement 13
1.1.8 The Preprocessor Directive #include 13
1.1.9 The using Directive 14
1.1.10 Execution of dem01-1.cpp 15
1.1.11 Keywords, Multiline Comments, and Escape Sequences 15
1.1.12 About the Exercises, Experiments, and Programming
Problems 16
1.2 Integers and Arithmetic 20
1.2.1 Identifiers 20
1.2.2 Variables 20
1.2.3 Using Integer Variables: dem01-2.cpp 22
1.2.4 Variable Declarations 23
1.2.5 Asking the User for Input: Prompts 24
1.2.6 The Input Stream cin 24
1.2.7 The Input Buffer 25
iii
iv Contents

1.2.8 The Assignment Operator and Integer Constants 25


1.2.9 The Arithmetic Operators 26
1.2.10 Operator Precedence Rules 28
1.2.11 The Object cout Revisited 30
1.3 Solving a Problem with Integers 32
1.3.1 Problem 1.1 32
1.3.2 The Program prb01-1.cpp 33
1.3.3 Header Files 34
1.3.4 Defined Constants 34
1.3.5 Declaration of Variables 35
1.3.6 The Prompts and Calculations 35
1.3.7 The Output: I/O Manipulators 35
1.4 Other Integer Data Types 36
1.4.1 Unsigned, Long, and Short Integers 36
1.4.2 Mixing Data Types 37
1.4.3 Using the Other Integer Types: Problem 1.2 38
Chapter Review 42
Terminology 42
Summary 43
Review Exercises 43

2. REAL NUMBERS 45
Objectives 45
2.1 Real Numbers 45
2.1.1 Real-Number Variables and Constants 45
2.1.2 Input and Output of Real Numbers 47
2.1.3 Outputting Decimal Numbers 47
2.1.4 Calculating Sales Tax—dem02-1.cpp 48
2.2 Solving Problems with Real Numbers 52
2.2.1 Simulating a Cash Register—Problem 2.1 52
2.2.2 Program Design 53
2.2.3 The Program prb02-1.cpp 53
2.2.4 Discussion of prb02-1.cpp 55
2.2.5 Averaging Quiz Grades—Problem 2.2 55
2.2.6 Program Design—Mixed Types and Type Casts 55
2.2.7 The Program prb02-2.cpp 57
2.2.8 Metric Conversion—Problem 2.3 58
2.2.9 Program Design 59
2.2.10 The Program prb02-3.cpp 61
2.3 More on Arithmetic 64
2.3.1 The Value of an Expression 64
2.3.2 Multiple Assignment Statements 65
2.3.3 The Compound Assignment Operators 66
2.3.4 Increment and Decrement Operators 69
Contents v

2.4 Three Difficulties When Displaying Decimal Numbers with cout 75


Chapter Review 78
Terminology 78
Summary 78
Review Exercises 79

3. ITERATION 80

Objectives 80
3.1 Relation Conditions 80
3.2 Indefinite Iteration: The while and do Statements 83
3.2.1 The while Statement 83
3.2.2 An Example of Indefinite Iteration: The char Data Type 85
3.2.3 Using cin.get() 87
3.2.4 The Program dem03-1.cpp 87
3.2.5 Embedded Assignment—Recoding dem03-1.cpp 90
3.2.6 The do-while Loop 91
3.3 Solving a Problem with Indefinite Iteration 96
3.3.1 Problem 3.1 96
3.3.2 Program Design 96
3.3.3 The Program prb03-1.cpp 98
3.3.4 More on Control-Expressions 102
3.4 Definite Iteration 105
3.4.1 The for Statement 105
3.4.2 An Example of Definite Iteration 109
3.4.3 Calculating Interest on a CD—Problem 3.2 111
3.5 Nested Loops 118
3.5.1 Nested while Loops 118
3.5.2 Nested for Loops 121
Chapter Review 126
Terminology 126
Summary 126
Review Exercises 127

4. DECISION MAKING 128

4.1 Basic Decision Making 128


4.1.1 The if Statement 128
4.1.2 Calculating a Payroll with Overtime—Problem 4.1 131
4.2 Compound Conditions—The Logical Operators 139
4.2.1 The not Operator, ! 139
4.2.2 The and Operator, && 139
4.2.3 Testing for a Digit—dem04-1.cpp 140
4.2.4 The or Operator, || 141
vi Contents

4.2.5 The Program dem04-2.cpp 141


4.2.6 Precedence Rules 142
4.3 Nested if Statements 146
4.3.1 Coding a Nested if Statement 146
4.3.2 Calculating a Payroll—Problem 4.2 150
4.3.3 Program Design 150
4.3.4 Character Input 151
4.3.5 The Program prb04-2.cpp 153
4.4 The switch Statement 161
4.4.1 Calculating Real Estate Commission—Problem 4.3 162
4.4.2 Program Design 162
4.4.3 The Program prb04-3.cpp 164
4.4.4 More on break 166
4.4.5 The continue Statement 168
Chapter Review 172
Terminology 172
Summary 172
Review Exercises 173

5. FUNCTIONS 174

Objectives 174
5.1 The Function Concept 175
5.1.1 How Functions Work 175
5.1.2 A Function with No Arguments and No Return Value 176
5.1.3 The Function Prototype and Definition 177
5.1.4 A Function with Arguments and No Return Value 181
5.1.5 Defining and Using a Function that Has Arguments 184
5.1.6 Passing Arguments by Value 186
5.2 User-Defined Functions that Return a Value 191
5.2.1 Calculating Grades Using a Function 191
5.2.2 Calculating Grades—The Program dem05-4.cpp 192
5.2.3 Variable Attributes 194
5.2.4 Scope 195
5.2.5 Duration—Storage Class 199
5.3 Programs that Use Functions 203
5.3.1 Problem 5.1—Moving Costs 203
5.3.2 Program Design 203
5.3.3 The Program prb05-1.cpp 204
5.3.4 Problem 5.2—Calculating Simple Interest 206
5.3.5 Program Design 207
5.3.6 The Program prb05-2.cpp: 208
5.3.7 Discussion of the Program 212
Contents vii

5.3.8 Testing the Program 212


5.3.9 Problem 5.3—Calculating Commissions: Data Validation 214
5.3.10 Program Design 215
5.3.11 The Program prb05-3.cpp 217
5.3.12 Discussion of the Program 222
5.4 The C++ Math Library Functions 227
5.4.1 The Library Function pow() 227
5.4.2 The Library Function sqrt() 228
Chapter Review 231
Terminology 231
Summary 231
Review Exercises 232

6. ARRAYS 234

Objectives 234
6.1 Basic Concepts 234
6.1.1 Definition of an Array 235
6.1.2 Declaring an Array 236
6.1.3 Referencing and Initializing Array Elements 236
6.1.4 Accessing Array Elements by Subscript 238
6.2 Processing an Array: for Loops 242
6.2.1 Using for Loops 242
6.2.2 Searching an Array 245
6.3 Sorting an Array 250
6.3.1 Sorting 250
6.3.2 A Sort Program—dem06-4.cpp 252
6.4 Multidimensional Arrays 256
6.4.1 Declaring Multidimensional Arrays 256
6.4.2 Processing a Two-Dimensional Array 258
6.4.3 Finding Student Averages—dem06-5.cpp 259
Chapter Review 264
Terminology 264
Summary 264
Review Exercises 265

7. POINTERS AND C-STRINGS 266

Objectives 266
7.1 Pointers 266
7.1.1 Declaring and Initializing Pointers 266
7.1.2 The Indirection Operator 270
7.1.3 Pointers and Arrays 272
viii Contents

7.2 C-Strings 277


7.2.1 Defining and Initializing a String 277
7.2.2 String Input and Output 278
7.2.3 String Constants as Pointers 280
7.2.4 Counting Characters in a String 281
7.2.5 Displaying a String in Reverse 282
7.2.6 Counting Words in a String 285
7.3 Arrays of Strings and Pointers 290
7.3.1 Defining an Array of Strings 290
7.3.2 Using an Array of Strings 291
7.3.3 Using an Array of Pointers to Store Strings 294
Chapter Review 297
Terminology 297
Summary 298
Review Exercises 298

8. POINTERS, ARRAYS, AND FUNCTIONS 299


Objectives 299
8.1 Pointers, Reference Variables, and Functions 299
8.1.1 Call By Address—Pointers as Function Arguments 300
8.1.2 Swapping Variable Values—An Example of Call
by Address 302
8.1.3 Reference Variables and Call by Reference 303
8.2 Arrays and Functions 309
8.2.1 Passing an Array to a Function 309
8.2.2 Sorting an Array 312
8.3 Strings and Functions 318
8.3.1 Using a Function to Count the Characters in a String 318
8.3.2 Using a Function to Reverse a String in Place 320
8.3.3 A Function that Returns a Pointer 321
8.4 The Standard Library String Functions 326
8.4.1 The Length of a String—The Function strlen() 326
8.4.2 String Assignment—The Function strcpy() 327
8.4.3 Comparing Strings—The Function strcmp() 329
8.4.4 Pasting Strings Together—The Function strcat() 331
8.4.5 Using the String Functions—dem08-9.cpp 332
8.5 Character Classification and Conversion Functions 336
8.5.1 The Character Classification Functions 336
8.5.2 The Character Conversion Functions 338
8.5.3 Putting the Functions to Work—Testing for a Palindrome 340
8.5.4 Numeric Conversion Functions and Numeric Validation 346
8.6 Dynamic Memory Allocation 351
8.6.1 The Heap 351
8.6.2 Static, Automatic, and Heap Memory 354
Contents ix

8.6.3 The Program dem08-15.cpp 355


8.6.4 A Second Example 356
Chapter Review 360
Terminology 360
Summary 361
Review Exercises 361

9. USER-DEFINED DATA TYPES AND TABLES 363

Objectives 363
9.1 The typedef and enum Statements 364
9.1.1 The typedef Statement 364
9.1.2 The enum Statement 366
9.1.3 An Example Using typedef and enum 367
9.2 Structures 371
9.2.1 Defining a Structure 371
9.2.2 Accessing Structure Members 372
9.2.3 Initializing a Structure Variable 375
9.2.4 More Complicated Structures 375
9.2.5 Assigning One Structure Variable to Another 377
9.3 Arrays of Structures: Tables 379
9.3.1 Defining a Table Using Structures 380
9.3.2 Loading Table Values 381
9.3.3 Sorting a Table 385
9.3.4 Searching a Table 390
9.3.5 Sequential Search 392
9.3.6 Binary Search 397
9.4 Structures, Functions, and Pointers 407
9.4.1 Functions and Structures 407
9.4.2 Pointers to Structures 413
9.4.3 Structure References 418
Chapter Review 424
Terminology 424
Summary 424
Review Exercises 425

PART II Object-Oriented Programming 426

10. THE string CLASS: AN INTRODUCTION TO CLASSES AND OBJECTS 426

Objectives 426
10.1 Objects, Classes, and Object-Oriented Systems 427
10.1.1 Familiar Classes and Objects 428
x Contents

10.2 Introduction to string Objects 430


10.2.1 Instantiating and Outputting string Objects 430
10.2.2 String Input 432
10.3 Operations on string Objects 438
10.3.1 String Assignment 438
10.3.2 Concatenation 438
10.3.3 Length of a String 439
10.3.4 Accessing Individual Characters in a String 441
10.4 Making Decisions with Strings 444
10.4.1 Equality 444
10.4.2 Inequality 444
10.5 Functions and string Objects 446
10.5.1 Testing for an Empty String 447
10.5.2 Functions that Use string Objects 447
10.6 Manipulating string Objects 451
10.6.1 Finding a String in a String 452
10.6.2 Searching for any Character from a Given List 453
10.6.3 Extracting a Substring from a String 453
10.6.4 Combining string Methods 453
10.6.5 Inserting and Removing Substrings 454
10.6.6 Program dem10-8.cpp 455
10.7 Putting Strings to Work 458
10.7.1 Problem 10.1—Removing and Printing Words
from a String 458
10.7.2 Discussion of prb10-1.cpp 460
10.7.3 Problem 10.2—The Palindrome Problem Revisited 461
10.7.4 Problem 10.3—Sorting a Table Revisited 464
10.8 Arrays of Strings 470
Chapter Review 473
Terminology 473
Summary 473
Review Exercises 474

11. PROGRAMMER-DEFINED CLASSES AND OBJECTS 476

Objectives 476
11.1 Declaring Objects and Classes 476
11.1.1 Defining a Class 477
11.1.2 Class Methods 479
11.1.3 The Class Constructor 480
11.1.4 Methods 482
11.1.5 The Program dem11-1.cpp 482
Contents xi

11.1.6 Discussion of dem11-1.cpp 484


11.1.7 The Relation between class and struct 485
11.2 A More Useful Class – Accessor and Mutator Methods 487
11.3 Constructor Overloading and Destructors 496
11.3.1 Constructor Overloading 496
11.3.2 Destructors 500
11.4 Default Arguments and Object Assignment 504
11.4.1 Default Arguments 504
11.4.2 Assigning One Object to Another 507
11.5 General Function Overloading and Function Templates 511
11.5.1 General Function Overloading 511
11.5.2 Function Templates 513
Chapter Review 517
Terminology 517
Summary 517
Review Exercises 518

12. MANIPULATING OBJECTS 519

Objectives 519
12.1 Using Arrays, Pointers, and Dynamic Memory Allocation 520
12.1.1 Array and Pointer Class Members 520
12.2 The Copy Constructor 528
12.2.1 The Copy Constructor: A Simple Example 528
12.2.2 A Copy Constructor For Savings_Account 533
12.3 Using const with Classes 540
12.3.1 Constant Objects and Methods 540
12.3.2 const in Pointer Declarations 543
12.3.3 Mixing Constant and Nonconstant Pointers 544
12.3.4 Constant Arguments in Functions 545
12.3.5 Constant Arguments and the Copy Constructor 547
12.3.6 Accessor Methods that Return Constant Pointers 547
12.4 Objects, Functions and Pointers 556
12.4.1 Functions that Return an Object 556
12.4.2 Passing an Object by Value 561
12.4.3 Pointers to Objects 568
12.4.4 Passing an Object by Pointer 570
12.4.5 References to Objects 574
12.4.6 Passing an Object by Reference 574
12.5 Dynamic Allocation of Objects 581
12.5.1 Using new and delete with Objects 581
xii Contents

12.6 Static Data Members and Functions 588


12.6.1 Static Data Members 588
12.6.2 Static Methods 590
Chapter Review 598
Terminology 598
Summary 598
Review Exercises 599

13. INHERITANCE 600

Objectives 600
13.1 Inheritance 601
13.1.1 Examples of Inheritance and Basic Terminology 601
13.1.2 Defining Derived Classes 604
13.1.3 Constructors in a Derived Class 607
13.1.4 The Destructor in a Derived Class 609
13.1.5 The Copy Constructor in a Derived Class 612
13.2 Functions in Class Hierarchies 618
13.2.1 Inheriting a Function 618
13.2.2 Method Overriding 620
13.2.3 Using the Scope Resolution Operator 623
13.3 Polymorphism 629
13.3.1 The Class Hierarchy 629
13.3.2 Defining the Classes 630
13.3.3 Pointers in a Class Hierarchy 631
13.3.4 Virtual Methods and Polymorphism 634
13.3.5 Virtual Destructors 636
13.3.6 Putting Polymorphism to Work 641
13.4 Abstract Base Classes 649
13.4.1 Pure virtual Methods and Abstract Base Classes 649
13.4.2 The Loan Class 651
Chapter Review 661
Terminology 661
Chapter Review 661
Review Exercises 662

14. FILES 664

Objectives 664
14.1 Input/Output Streams 665
14.1.1 The Standard I/O Streams: Revisiting cin,
cout, and cerr 665
14.1.2 Text Files 666
14.1.3 User-Declared Files 667
Contents xiii

14.1.4 Declaring the File Object 667


14.1.5 Opening the File 668
14.1.6 Processing the File 670
14.1.7 Closing the File 670
14.1.8 Checking for Errors When Opening a File 672
14.1.9 Creating a Text File of Records 674
14.1.10 File Input 677
14.1.11 Processing a Text File of Records 679
14.1.12 File Input/Output 681
14.2 Processing a File One Character at a Time 686
14.2.1 The get() and put() Methods 687
14.2.2 Output to the Printer 689
14.3 Random File Access 692
14.3.1 Text and Binary Files 692
14.3.2 Random-Access Member Functions 694
14.4 Binary Sequential File Processing 699
14.4.1 Creating a Binary Sequential File of Records 700
14.4.2 Reading a Sequential File of Records 705
14.5 Random Record Input/Output 709
14.5.1 Random-Access File Update 709
14.5.2 Creating the File 709
14.5.3 Designing the Update Program 710
14.5.4 Program Code 713
Chapter Review 727
Terminology 727
Summary 728
Review Exercises 729

15. SPECIAL TOPICS: FRIENDS, OPERATOR OVERLOADING, MACROS,


AND INLINE FUNCTIONS 730

Objectives 730
15.1 friend Functions 731
15.1.1 Defining a friend Function 731
15.1.2 Inheritance and friend Functions 736
15.2 Overloading Basic Arithmetic Operators 738
15.2.1 Adding Two Objects 738
15.2.2 Adding an Object and an Integer 740
15.2.3 Operator Overloading Rules 743
15.3 Overloading Assignment and the this Pointer 745
15.3.1 Overloading Assignment 745
15.3.2 The this Pointer 747
15.3.3 Inheritance and Overloaded Operators 752
xiv Contents

15.4 Overloading the Insertion and Extraction Operators 754


15.4.1 Overloading the Insertion Operator 754
15.4.2 Overloading the Extraction Operator 759
15.5 Overloading Compound Assignment Operators 763
15.5.1 Overloading += and –= 763
15.6 Overloading Relational Operators 768
15.6.1 Overloading == 768
15.7 Overloading Unary Operators 775
15.7.1 Overloading ++ 775
15.7.2 Overloading the Post-Increment ++ 775
15.8 Macros and Inline Functions 779
15.8.1 Symbolic Constants Using #define 779
15.8.2 Macro Definitions 780
15.8.3 An Example Using Macros—The Conditional Operator 782
15.8.4 Functions vs. Macros 785
15.8.5 Inline Functions 785
Chapter Review 788
Terminology 788
Summary 789
Review Exercises 790

APPENDIX A COMPUTERS AND DATA 791


APPENDIX B PROGRAM CONTROL 803
INDEX 819
Preface

C++ for Business Programming, Second Edition is an introduction to C++ program-


ming. The power of C++ lies in its object-oriented extensions of the C language. How-
ever, we believe that for beginning students it is best to learn the basics of
programming without the extra encumbrance of having to learn object-oriented con-
cepts. Therefore, the book is divided into two sections. Part I, “Basic C++,” covers the
procedural parts of C++. Part II, “Object-Oriented Programming,” covers all the es-
sential object-oriented ideas through inheritance and polymorphism.
Unlike most books on C++, which emphasize applications to computing or math-
ematics, this book emphasizes business applications. Therefore, the book is most ap-
propriate for business and information systems students. The entire book can be
covered in one semester in a class of students who have a good background in pro-
gramming in another language. In such a class, it is possible to quickly cover the essen-
tial programming constructs from Part I and then concentrate on object-oriented
concepts and programming in Part II. For students who have little programming expe-
rience, we suggest covering Part I in one semester and Part II in a second semester. The
material in Part I can be supplemented as needed by material from Appendix A,
“Computers and Data,” and Appendix B, “Program Control.”
Throughout the book, we emphasize good pedagogy.

• Each chapter begins with a set of learning objectives.


• Each chapter ends with a review section that includes important terms, a chapter
summary, and review exercises.
• Concepts are explained in clear, understandable language and are illustrated by
many fully worked-out examples.
• Important definitions, concepts, and rules are appropriately highlighted in notes.
• Programming tips and pitfalls are noted in the margins of the text.
• One of the best ways to learn a programming language is to read programs in that
language. Therefore, every important idea is illustrated in an example program
and accompanying output. There are approximately 150 complete programs in
the text, each of which we very carefully explain.

xv
xvi Preface

• The book contains over 800 exercises of varying types and levels of difficulty.
These exercises are placed at the end of each section rather than at the end of
each chapter so students can immediately reinforce their new knowledge. These
exercises include exercises, experiments, and programming problems.
º Almost every section contains exercises on the syntax and semantics of C++.
Most of these are of the paper and pencil type, although some require writing
a simple program.
º The experiments, which ask the student to investigate various aspects of the
C++ language, are a unique feature of the exercise sections. The experiments
improve the student’s understanding of the finer points of C++ and help the
student avoid common errors made by beginning programmers.
º The programming problems, which range from 10-20-line programs to full-scale
projects that require the use of several user-defined functions and/or classes,
are found in most sections of the book. The chapter-illustrative programs and
programming problems emphasize the business applications of C++.
• The book conforms to the ANSI C++ standard. All illustrative programs, howev-
er, can easily be adapted to nonstandard compilers. Therefore, the book can be
used with any C++ compiler.
• Topics are introduced on a need-to-know basis to provide motivation for the stu-
dent. Therefore, the book is not encyclopedic in its coverage of C++. In some
cases, all the relevant ideas surrounding a topic are spread throughout several
sections or chapters.
• Appendix A, “Computers and Data,” and Appendix B, “Program Control,” pro-
vide supplementary material for students who have a weak background in com-
puting. Appendixes A and B contain exercises.

CHANGES FROM THE FIRST EDITION

• The terminology and program constructs used have been updated to conform to
current practice.
• Several sections have been labeled as optional to improve the flow of the exposi-
tion and enable the reader and instructor to concentrate on the more important
concepts.
• In some chapters, notably Chapters 2 and 5, material has been rearranged to im-
prove readability.
• A section on the C++ Math Library functions has been added to Chapter 5.
• Chapter 12 in the first edition, “Friends and Operator Overloading,” has been
moved to the end of the book (Chapter 15) and has been renamed “Special Topics.”
• The section titled “Macros and Inline Functions,” has been moved from Chapter 5
to “Special Topics,” Chapter 15.
• The book now distinguishes C-style strings from objects in the string class.
Preface xvii

• To help students transition from Part I to the object-oriented concepts in Part II,
we include a transition chapter, Chapter 10, on the C++ string class. Object-
oriented concepts are introduced in this chapter so that students can begin in-
stantiating, using, and manipulating string objects without having to worry
about how to define a class.

CHAPTER OVERVIEW
Chapters 1–9 constitute Part I, “C++ Basics.” Chapter 1, “Introduction to C++,” intro-
duces the student to the basic anatomy of a C++ program. It covers the input and out-
put objects cin and cout, variables, integer data types, and arithmetic. Chapter 2,
“Real Numbers,” introduces the float and double data types, the compound assign-
ment, and increment and decrement operators.
Chapters 3 and 4 discuss the basic control structures of programming. Chapter 3,
“Iteration,” begins by covering relation conditions. Then it proceeds to discuss indefi-
nite iteration (the while and do statements), definite iteration (the for statement),
and nested loops. Chapter 4, “Decision Making,” covers the if statement, the logical
operators, nested if statements, and the switch statement.
Chapter 5 introduces the important concept of functions. Because the function is
new to most students, the concept is developed gradually—first with functions that do
not return a value, then functions having arguments, and, finally, functions that return a
value. We also include a discussion of scope and duration. An entire section is devoted
to discussing three programs that use functions. Special care is taken to show how the
program logic is modularized into functions. The chapter ends with a discussion of the
C++ Math Library functions.
Chapter 6, “Arrays,” shows how to properly define an array and reference its el-
ements. Care is taken to show how to use a for loop to process the elements of an
array. We also cover in some detail how to sort an array using the standard bubble
sort. Finally, we show how to declare and process multidimensional arrays.
Chapter 7 introduces pointers. To help the student understand this important
topic, we quickly put pointers to work by applying them to C-style strings. Illustrative
programs show how to count characters in a string, display a string in reverse, and
count words in a string. We also discuss arrays of strings and arrays of pointers.
Chapter 8, “Pointers, Arrays, and Functions,” reinforces the student’s knowledge
of strings and pointers. Call by address using pointers, call by reference, passing arrays
as function arguments, and functions that return pointers are discussed in detail. We
also cover some useful string library functions and character classification and conver-
sion functions. We also discuss the use of dynamic memory allocation using the new and
delete operators.
Chapter 9, “User-Defined Data Types and Tables,” discusses typedef, enumerat-
ed types, and structures. Special attention is given to the use of structures in defining
tables. A major application involves sorting and searching a table (an array of struc-
tures), including both sequential and binary searches. The chapter also discusses pointers
xviii Preface

to structures and using them as function arguments. This chapter can be omitted if time
is a consideration.
Chapters 10–15 comprise Part II, “Object-Oriented Programming.” Chapter 10,
“The string Class: An Introduction to Classes and Objects,” serves as a transition
from the emphasis on procedural programming of Part I to object orientation. The
chapter begins with a general discussion of object-oriented concepts. Then it illustrates
those concepts using the built-in string class. Sections discuss how to perform opera-
tions on string objects, how to manipulate string objects and make decisions with
string objects, and how to use string objects with functions. Upon completion of this
chapter, students should be comfortable with the object paradigm.
The material in Chapters 11–13 is unified through the gradual development of a
Savings Account class. As new object-oriented programming (OOP) concepts are in-
troduced, they are added to the Savings Account class. Chapter 11 introduces the read-
er to user-defined classes and objects. We discuss how to declare a class, instantiate
objects, and code methods, constructors, and destructors. The chapter ends with a thor-
ough discussion of function overloading and default method arguments.
Chapter 12, “Manipulating Objects,” is the longest chapter in the book. Some of
the topics, as outlined in the chapter introduction, can be omitted at first reading. The
chapter begins by discussing how to include array and pointer instance variables in a
class and how to use dynamic memory allocation in a constructor and destructor. Next,
the chapter discusses the copy constructor and when it is used. The many ways of using
the keyword const in C++ are then covered in detail. We also discuss functions that re-
turn objects as well as how to pass objects to functions by value, pointer, and reference.
Several of the issues relating to the dynamic allocation of objects are covered along
with the uses of static class data members and methods.
Chapter 13 covers the important concept of inheritance and related ideas. We use
one major example throughout most of the chapter to unify the material. After intro-
ducing the basic terminology of inheritance and how to construct a class hierarchy, the
chapter discusses the uses of methods in such a hierarchy and the concept of polymor-
phism. Pure virtual methods and abstract base classes complete the chapter.
Chapter 14 gives a thorough treatment of file processing in C++. The chapter be-
gins with a discussion of input/output (I/O) streams, the standard I/O class hierarchy,
and how to process simple text files. We then show how to process a file one character
at a time. Next, we discuss binary files and the random-access methods. These ideas are
then applied to the problems of processing a binary sequential file of records and to
randomly processing a binary file of records. The chapter culminates with a random-
file-access update program.
Chapter 15 covers several special topics. First we discuss the concepts of friend
functions and operator overloading. We emphasize the extensibility of the C++ opera-
tors by showing how to overload the arithmetic operators, assignment, the insertion
and extraction operators, the compound assignment operators, the relational opera-
tors, and the unary operators. We conclude the chapter with a discussion of the use of
macros and inline functions.
I thank Laura Steele and Alan Apt of Prentice Hall, who made the first edition of
this book possible. I also thank Kate Hargett and Mike Giacobbe for guiding me
through the second edition. A special thanks to Dean Susan Merritt of Pace University
Preface xix

who gave this project and me her enthusiastic support for the many years it took to
complete. Thanks also to Chin-Mei Huang for her helpful comments on an early ver-
sion of the manuscript, Anna Kristoferitsch for helping to solve some of the chapter ex-
ercises and, especially, Kenyata Millet, who spent many long hours solving the
programming problems and exercises. I also thank Esther Amiri for the work she did on
the exercises and programming problems in chapter 10. I thank Professor Gerald Wohl
of Pace University for having the courage to use the first draft of this book in his C++
courses, for catching many errors and typos, and for providing me with many helpful
comments about the book, and the many readers and reviewers who provided valuable
input to the second edition. Finally, I thank my family—my wife, Maria, and my sons,
John and Charles—for the help and love they have given me.
A note about the typefaces used in this book: In the program outputs, data that
the user inputs in response to program prompts is set in boldface to distinguish it from
output produced by the programs.
Reviewers for this edition:
Dennis D. Howard, University of Alaska Anchorage
Nitin Kale, University of Southern California
Dan Calderwood, College of the Redwoods
Safoora Fatima, Devry University
This page intentionally left blank
Part I C++ Basics

Chapter 1
Introduction to C++

OBJECTIVES

• To write a simple C++ program


• To use comments in a program
• To declare variables of different integer data types and decide when to use them
• To use the cout output stream to display strings and variable values
• To use the cin input stream to input data
• To use the arithmetic operators
• To understand and use the operator precedence rules
• To solve simple problems involving integers

WHY STUDY C++?


C++, pronounced “C plus plus,” is one of the most popular programming languages
used to develop computer applications. Many corporate computing departments have
adopted C++ as the language in which to develop in-house applications. Many soft-
ware vendors use C++ to write their application software. Why is C++ so popular and
why is learning it important?
• C++ is a “middle-level” language. Programming languages can be categorized as
high-level or low-level. Assembly languages are low-level languages. An assem-
bly language allows the programmer maximum control over the computer sys-
tem. The programmer can directly interface with and control the computer’s
hardware and operating system. This control comes at a price, however. Assembly
languages are hard to learn because they are highly symbolic and the program-
mer must take care of all the details of the program. Assembly-language pro-
grams are also difficult to maintain and debug. Perhaps most important,
assembly-language programs are not portable. An assembly-language program is

1
2 Chapter 1 Introduction to C++

specific to the hardware and operating system of the computer platform on which
it is developed. Thus, you cannot directly execute a PC assembly language pro-
gram on a Macintosh.
By contrast, high-level languages, such as COBOL, Visual Basic, and Java,
are easier to learn, maintain, and debug than assembly languages. The program
statements in such languages use English words and familiar mathematical sym-
bols to express instructions to the computer. Typically, each such instruction re-
places several equivalent assembly-language instructions. Thus, using a high-level
language is easier than using an assembly language. However, the price for this
ease of use is the loss of direct control over the computer system that you have in
an assembly language.
C++, although it is a middle-level language (and, therefore easier to learn
and use than an assembly language), contains many of the low-level capabilities
of an assembly language. Thus, C++ is sometimes called a “middle-level” lan-
guage. It is possible through C++ to attain almost as much control over the com-
puter as you can achieve with an assembly language.
• C++ is portable. Most high-level languages are portable in the sense that a pro-
gram written in a high-level language should execute, with minor modifications,
on several different computer systems. C++ is one of the most portable of all the
high-level languages. Properly written, a C++ program can run on several com-
puter systems with no modifications. Portability is important because it is now
common for a business to have several different types of computer systems (a
mainframe, minicomputers, workstations, PCs, and Macintoshes). A properly
written application in C++ should be portable to most, if not all, these systems.
Thus, portability eliminates the cost of developing the application several times
for different platforms.
• C++ is small. The C++ language does not contain many of the built-in features
present in other programming languages (such as in Visual Basic), which further
enhances its portability. For example, Visual Basic has about 150 keywords. (A
keyword is a word that has special meaning in the language.) C++, on the other
hand, has about 60 keywords. Visual Basic includes extensive capabilities to help
the programmer write programs. However, this greatly increases the complexity
of the Visual Basic language. In contrast, the designers of C++ tried to keep the
language as simple as possible by not building things into the language. Instead,
the programmer must use programmer-defined and built-in functions and classes.
This gives the C++ programmer great flexibility and allows the language to be
highly portable.
• C++ is an object-oriented extension of the C programming language. Dennis
Ritchie developed C at Bell Laboratories in 1972 to help write the UNIX oper-
ating system for the PDP-11 minicomputer. Today many mainframes and most
minicomputers, including Reduced Instruction Set Computing (RISC) work-
stations, and many Intel-based PCs and servers use the UNIX or Linux oper-
ating system. All versions of UNIX/Linux contain a version of C as their native
language. In other words, UNIX/Linux speaks C. Why is this important?
Section 1.1 Our First C++ Program 3

Before C, a systems programmer on such a computer system needed to use


assembly language to directly communicate with the computer. Now, along
with the applications programmer, the systems programmer can use C. In the
early 1980s, Bjarne Stroustrup of AT&T Bell Labs developed C++, which is an
object-oriented extension of C.
C is an example of a procedure-oriented programming language. Thus, to
develop a C program to accomplish a task, the programmer breaks down the task
into a series of steps. On the other hand, to develop an object-oriented C++ pro-
gram, the programmer views the problem as a set of interacting objects, each with
its own properties and behaviors.

This book is divided into parts. In Part I, Chapters 1 through 9, we concentrate on


the non-object-oriented aspects of C++. This will enable you to learn the basic con-
structs of C++ without the additional burden of learning object-oriented terminology
and concepts. Chapter 10, in Part II of the book, introduces you to object-oriented
ideas through the C++ built-in string class. We then cover all the important object-ori-
ented constructs that make C++ one of the most powerful tools for development of ob-
ject-oriented software.
Finally, it is important for you to learn C++, even if you do not intend to become
a professional programmer. As a person who is professionally involved with comput-
ers, it is important that you know a little of the language that many programmers
speak. Not to do so would be like beginning your professional career in a foreign coun-
try not knowing a word of the native language. You would quickly find out that you
must learn some of the native tongue to perform efficiently on the job. In a similar way,
so that you can communicate effectively with your colleagues, you should learn at least
some of the “native tongue” of the modern programmer—C++.

1.1 OUR FIRST C++ PROGRAM


One of the best ways to learn about the basic features of a programming language is to
study a small program written in that language. In this section, we discuss a simple C++
program that displays a two-line message on the computer screen. Before we do so, we
discuss some general ideas about how to develop a program.

1.1.1 The Program Development Cycle


You must take several steps each time you develop a program. The following six steps
are typical when developing a C++ program. See Figure 1.1.

Step 1: Define the Problem It is very important that you understand the problem you
are trying to solve. Make sure you read the problem specifications carefully.
Know what data is to be input into the program and what form that data should
be in. Also, know what processing has to be done to that data. Finally, determine
what the expected output is supposed to be and what form the output must take.
For example, suppose you are asked to write a simple program that simu-
lates a calculator.The program is to ask the user (the person running the program)
4 Chapter 1 Introduction to C++

Step 1: Define

Step 2: Design

Step 3: Code

Step 6: Test
source
code

Step 4: Compile and Link


compile

object executable Step 5:


code link code Execute

Figure 1.1

to enter two numbers, then the program is to output the sum of the numbers. Be-
fore you start doing anything, you have to define this problem more completely.
For example, should the program ask the user to enter the numbers? If so, how
should the program ask? What kind of numbers are to be input? Must they be
whole numbers or can they be decimal numbers? Should the numbers be input
one number per line, or can they both be input on one line? After the numbers are
input and added, how should the result be displayed? Do you want the input num-
bers output along with the sum, or do you just want to output the sum? If you want
the input numbers as well as the sum to be output, how do you want it done—in
column format or on one line?
As you can see, there are many questions to ask even in this simple problem—
and we did not ask any questions about the processing, because adding is a simple
calculation. Imagine how complex it would be to calculate a person’s income tax!
The important point here is to ensure that you solve the correct problem. Make
sure that you understand exactly what you have to do before you start the next step
in the development cycle. If you are not sure what you need to do, ask the person who
wants you to develop the program. If you are writing the program for yourself, then
you have to make all the decisions. Do not waste time solving the wrong problem.
Step 2: Design the Program There are several ways of describing program design. Two
common methods are by flowcharts and pseudocode. A flowchart is a graphic de-
scription of a program design that uses combinations of various standard flowchart
symbols. Figure 1.2 shows some standard symbols and the operations they repre-
sent.We shall use flowcharts to represent only the basic program control structures.
Pseudocode (literally, “false code”) describes program design using English.
Pseudocode avoids the syntax of a programming language and, instead, emphasizes
Section 1.1 Our First C++ Program 5

A group of program instructions that performs


Process Box a processing function

Tests a condition and takes one of two alternate


Decision Box paths, depending on the truth or falsity
of the condition

The beginning or end of a program


Terminal Symbol
or procedure

Indicates the direction of control


in the flowchart
Flowline

Where flowlines meet

Connector

Figure 1.2

the design of the problem solution. There is no standard form of pseudocode—you


make up your own rules. The only guideline is that the meaning of the pseudocode
should be clear to anyone reading it. We shall include a description of the
pseudocode of each program control structure that we introduce in the text. We
shall design most programs in Part I of this book using pseudocode.
When you design a program, it is important to check its logic before you
start to write the program code itself. If possible, have a friend or coworker check
your program design. The program designer is frequently too close to his or her
design to see some errors.
Step 3: Code the Program Note that in some cases, you do steps 3, 4, 5, and 6 (which
follow) in an Integrated Development Environment (IDE). Examples of IDEs
are Visual Studio.NET and Borland Enterprise Studio for C++ for the Win-
dows platform, and Code Forge for the Linux environment and KDevelop for
the UNIX environment. All the steps are performed selecting from pull-down
menus or clicking icons. All compiler error messages are listed in a window
separate from the edit window (see step 4). When you execute your program
(see step 5), it executes in a separate window. At no time do you have to leave
the IDE.
After you complete and check the program design, code the program. To
code a program means to translate the design from step 2 into a computer
programming language (C++, in our case). Code the program by entering it
into your IDE’s text editor, or any text editor on your computer system. Make
sure that you save the program to disk before proceeding to the next step.
6 Chapter 1 Introduction to C++

In the next step of the program development cycle, you will submit the pro-
gram code, called the source program or the source code, to the computer for
compilation.
Step 4: Compile and Link the Program The only language a given computer under-
stands is its own machine language. A machine language instruction is a binary-
coded instruction (consisting of zeros and ones) that commands the computer to
do one specific task, such as add 1 to a register. Each computer has its own ma-
chine language. The machine language for a Sun workstation is different from the
machine language of a Macintosh, which is different from the machine language
of an IBM PC, and so on. Because machine language is in binary, it is difficult to
write and find errors in machine language programs.
Because a computer understands only its own machine language, it cannot
execute high-level or middle-level language instructions directly. The computer,
using a program called a compiler, must translate middle-level and high-level lan-
guage programs into equivalent machine language programs. A compiler is a spe-
cialist. It translates only one high-level or middle-level language into a specific
machine language. A PC-based C++ compiler translates C++ into PC machine
language. The compiler cannot translate a different language (such as Java) and
cannot be used on a different type of computer (such as a Macintosh.)
A compiler has two main functions. First it checks the source program for
syntax errors. Syntax errors are errors in the grammar of the programming lan-
guage. If there are any fatal syntax errors (that is, errors so severe that the com-
piler does not understand the statement and cannot translate the statement into
machine language), the compiler will stop and notify you of the errors it found. If
the compiler finds no fatal errors, it translates each high-level language instruc-
tion into one or more machine language instructions. This machine language ver-
sion of the source program is the object program.
Although it is in machine language, the object program may not be ready to
execute. The program may contain references, called external references, to other
programs that a user may have written or that the C++ compiler provides for use
by all system users. In either case, you must use a program called a linker to
resolve these external references. The linker finds the other programs and makes
them part of your program. We call this process linking. The linker resolves ex-
ternal references and combines the object code with these other programs to pro-
duce the executable code. It is the executable code that the computer executes.
The steps necessary for you to compile and link a program depend on the
computer system and compiler on which you develop the program, and the IDE
you use. Some IDEs simply require selecting the compile and link options from
pull-down menus. Some IDEs require that you create a project in which to run
your program. Other IDEs require executing one or two statements at command
level to compile and link a program. Consult your program IDE’s manual or on-
line help for instructions on the procedure you must follow.
Step 5: Execute the Program Once you have compiled and linked the program, you
are ready to execute the program. Executing the program is usually quite simple.
In some IDEs, all you need to do is select the execute option from a menu or click
Section 1.1 Our First C++ Program 7

an icon. On other systems, you need to execute the program at command level.
Consult your program development environment user’s guide for the procedure
you must follow.
Step 6: Test and Debug the Program Even if a program executes, it does not mean that
the program is correct. Even if a program gives correct results using some data, it
does not mean that the program will give correct results using another set of data.
Make sure that you test your program under as many conditions as possible to try
to catch errors.

1.1.2 Errors in the Cycle


The six steps in developing a program form a cycle—the program development cycle.
An error at any step can force you to go back to an earlier step and begin over. Fol-
lowing are some errors that can occur in the cycle.

Errors in Step 1: An error at the problem definition stage can affect the entire
program; make sure that you understand the problem you are supposed to solve.
Errors can arise in most of the following steps because of a faulty understanding
of the problem.
Errors in Step 2: After the initial program design, you or a friend might discover
a flaw in the design. If this is the case, you have to redesign part or the entire
program.
Errors in Step 3: Errors in step 3, coding the program, can be caught by the IDE.
Many IDEs color code different syntactic elements of a program. This makes it
easier to catch obvious mistakes in your coding. Make sure that you save your
program after each correction that you make. Some coding errors, however, are
not highlighted by the IDE. Therefore, after you have entered your program in
the IDE’s text editor, read the entire program. It is also a good idea to check a
printed version of the program.
Errors in Step 4: If the compiler finds any fatal errors in your program, it will not
complete the translation of your program into machine language. You will re-
ceive a list of error messages detailing the type and location of each error the
compiler found. Then, you must go back to step 3, correct your errors, and start
the process over. Besides fatal errors, the compiler also may advise you of what it
thinks are mistakes. The compiler usually calls these warnings. Warnings are not
serious enough to stop the translation, but the compiler thinks you should be
made aware of them. If the compiler issues warnings, the compilation will take
place. However, you should try to correct the source of these warnings before you
execute the program unless you coded the source of the warning on purpose.
Statements that cause the compiler to issue warnings can cause some very subtle
errors in program output when you execute the program. In short, do not execute
your program until you have removed all syntax errors.
After a successful compile, there can be an error in the linking process. Usu-
ally, a linker error is caused by the inability of the linker to resolve an external ref-
erence. The most common cause of this error is the misspelling of the name of an
8 Chapter 1 Introduction to C++

external program. The linker cannot find the misspelled program because it does
not exist. Whatever the cause of the linker error, you must find and correct it.
Errors in Step 5: Assuming the compilation and linking are successful, you can ex-
ecute your program. Two types of errors can now occur. First, the program may
end during execution because it cannot execute a particular instruction. This is a
run-time error. When a program abnormally ends, the computer displays a mes-
sage showing the type of error that occurred. You must now locate the cause of
the error (which could be in the data processed by your program, not in the pro-
gram itself) and make the necessary changes. Many compilers have techniques
that you can use to locate run-time errors. These techniques include step-by-step
tracing of program instructions and the ability to stop the program at a predeter-
mined place to inspect the values of variables. Consult your compiler’s user’s
guide or on-line help for instructions on how to locate run-time errors.
Errors in Step 6: While testing your program with different sets of data, errors can
occur that are difficult to detect. In fact, they could go unnoticed. Although a
program executes, produces output, and ends successfully, it is not necessarily
correct. Check your output to see if it is unreasonable or if it contains obvious er-
rors. If so, you must find the cause of the error. At this point in the program de-
velopment cycle, the error is probably a logic error. The compiler checks the
program for syntax errors, but it cannot check for errors in logic. Faulty program
design causes most logic errors. If your program contains a logic error, you must
find its cause (which is sometimes very difficult), go back to step 2, redesign, re-
code, reenter, recompile, relink, and retest the program (and hope that you do not
introduce new errors along the way).
Occasionally, faulty coding causes logic errors. Faulty coding is code that is syn-
tactically correct but incorrectly translates the program design into program code. If
your program contains faulty coding, locate and correct the faulty code, and then reen-
ter, recompile, relink, and retest the program. As we work through this book, we shall
point out some common errors caused by faulty coding.
The general rule of program development is catch errors early. A mistake in step 2
might not show until step 6. If this happens, you must go back to step 2 and start the
cycle again. This wastes your time, computer time, and money. Be cautious, and work
slowly and deliberately. If you are careful at the beginning of program development,
your efforts will pay off in the end.

1.1.3 Displaying a Two-Line Message: dem01-1.cpp


The following is our first C++ program, dem01-1.cpp, followed by its output. The pro-
gram contains features of C++ that we will use throughout this book. Read the pro-
gram carefully. After the program code, we explain each line of the program.
// dem01-1.cpp
// John C. Molluzzo
#include <iostream>
using namespace std;
Section 1.1 Our First C++ Program 9

int main()
{
cout << "This is our first C++ program." << endl;
cout << "It works!!!" <<endl;
cout << endl;
return 0;
}

Program Output
This is our first C++ program.
It works!!!

1.1.4 Comments
The first two nonblank lines of dem01-1.cpp are comments. A comment begins with
the two characters // and continues to the end of the line. The first comment gives the
name of the program and the second gives the author of the program. A comment is
not an executable statement. That is, a comment does not result in the computer tak-
ing any action. Comments, which can appear anywhere in a C++ program, help to
describe parts of the program and are a valuable documentation tool. For exam-
ple, comments might describe what a program’s variables represent or the purpose
of a section of the program. Remember that comments are not executable state-
ments and, therefore, the C++ compiler ignores everything from // to the end of
the line.
Comment your programs to explain their code. You can follow the style that we
use in the programs in this book, although programmers frequently use other com-
menting styles. Be sure to include at least the name of the program and your name as
comments in your own programs.
The first comment shows that the name of this program is dem01-1.cpp. We use
the convention that a C++ source-code program name should be eight or fewer charac-
ters in length (the characters can be letters, digits, and the hyphen), followed by the .cpp
file-name extension. This naming convention conforms to the requirements of most
C++ compilers. (Note: Many UNIX/Linux C++ compilers require the extension .C on
the name of a C++ source-code file.)
There is a blank line separating the two comment lines in dem01-1.cpp. You can
insert blank lines anywhere in a C++ program. We shall separate the important parts
of each program by one or more blank lines to enhance the readability of our pro-
gram code.
Comments can span several lines, as shown by the following.
// This is our first C++ program. This line is a comment line.
// It is common practice to write multiple-line comments
// like this.

Before explaining the #include and using lines in dem01-1.cpp, we discuss the
remainder of the program.
10 Chapter 1 Introduction to C++

1.1.5 The Function main()


A C++ program is a collection of functions that work together to solve a problem. We
shall not discuss the exact nature of a C++ function until Chapter 5. For now, think of a
function as a part of a program that performs a single task. The collection of functions
that make up a C++ program must contain exactly one function called main(). The
function main() controls the C++ program by executing C++ statements and other
functions. A C++ program automatically begins execution at the first executable state-
ment of the function main().
A function in C++ can either produce, or return, a value that can be used by the
system or it can produce no value at all. The word int that precedes the word main()
tells the C++ compiler that main() produces an integer value. In Chapter 5, we shall
discuss how to write functions that do not produce a value. For now, place the word int
before the word main().
The statements in main() must be enclosed in braces {...}. Thus the name main() is
followed by a left brace {, which begins the function main(). The left brace is followed by
the program statements.The program ends with the matching right brace }.When program
execution reaches this matching right brace, the program stops. Code the left and right
braces in main() in column one and indent the program statements two spaces. This in-
denting convention, which we use throughout the book, makes the program easier to read.
Each cout statement in dem01-1.cpp ends in a semicolon. Semicolons are very
important in C++, as stated in Note 1.1.

Note 1.1 Semicolons


Each statement in a C++ program must end in a semicolon. Omitting a required
semicolon will cause a compiler syntax error.
A common error is to code a colon rather than a semicolon at the end of a
statement, so be careful to use the correct punctuation.

A statement in C++, which can span several lines, ends with a semicolon in much
the same way as an English sentence ends with a period. Omitting a required semi-
colon would be like omitting a period in English—you would be writing the equivalent
of a run-on sentence.
Because C++ is statement oriented, we can code the function main() of
dem01-1.cpp as follows and cause no syntax errors.
int main(){ cout << "This is our first C++ program." << endl;
cout << "It works!!!" <<endl; cout << endl; return 0;}
This code, however, is hard to read. Note 1.2 gives a good rule of thumb to use
when coding a C++ program.
It is very important to keep in mind that C++ is case sensitive. That is, when coding
C++ statements there is a difference between uppercase and lowercase letters. Coding
int Main()
is incorrect because we used an uppercase M instead of a lowercase m in the word main.
When a C++ program begins executing, it looks for a function named main(), not a
Section 1.1 Our First C++ Program 11

Note 1.2 Coding Statements


Code one statement on each line unless
• The statement is too long to fit on one line, or
• Writing the statement over several lines clarifies the meaning of the
statement.

function named Main(). Later, we shall adopt conventions for naming various C++ pro-
gram elements. These conventions will allow the use of uppercase letters to help us rec-
ognize the type of element each name represents. Until then, use lowercase letters for
everything except what appears inside double quotes "...", where you can use whatever
combination of letters you require.
The function main() can execute any of the following:
1. A built-in C++ statement. The program dem01-1.cpp does not contain any built-
in C++ statements. Much of this book is devoted to discussing the built-in C++
statements.
2. A function. The function main() can use any function whether it is a user-
defined function (one that the programmer defines and codes) or a standard li-
brary function (a precoded function that is part of the C++ system). We shall
learn about C++ functions throughout the rest of the book.
3. Operations on C++ streams, which we explain in the next section.
4. Other operations, which we shall encounter in later chapters.

1.1.6 The Output Stream cout


In C++, output is written to a data stream, which you can think of as a sequence of char-
acters. The stream cout (for “console output” and read as “see-out”) represents the
standard output stream, which is automatically “attached” to the user’s monitor when
the C++ program begins. Data can be sent to, or inserted into, the output stream cout
using the insertion operator, <<, which you can read as “is sent” or “gets”. Thus, read
cout << "Hello";
as “cout gets ‘Hello’” or “cout is sent ‘Hello’ ”.
Because the output stream is attached to the monitor, the data appears on the
screen. See Figure 1.3.
To insert a string (that is, a set of characters) into the output stream, enclose
the string in quotation marks. (Remember that you must end the statement with a
semicolon.) Thus,
cout << "This is our first C++ program.";
inserts the words "This is our first C++ program." into the output stream,
which, in turn, makes the words appear on the monitor, beginning at where the cursor
was when the statement was executed. If we follow the above cout by
cout << "It works!!!";
12 Chapter 1 Introduction to C++

Monitor Program
cout
<<

Use the output stream cout and the insertion operator << to send data to
the output stream.

Figure 1.3

the following would appear on the monitor:

This is our first C++ program.It works!!!

After the first cout executes, the cursor is left following the period after the word
program. Therefore, when the second cout is executed, the characters it sends to the
output stream appear beginning at the current location of the cursor, that is, immedi-
ately after the period.
To correct this problem, we use endl (end-of-line). When endl is sent to cout, it
forces the cursor to the beginning of the next line. Note that the last character in endl
is a lowercase l, NOT a 1 (the digit one).
cout << "This is our first C++ program." << endl;
cout << "It works!!!" << endl;

After the string "This is our first C++ program." is sent to cout, the state-
ment sends endl, which causes the screen cursor to move to the beginning of the next
line. Thus, more than one thing can be sent to cout in one statement by “cascading” the
<< operator. When several insertion operators are used in the same cout statement,
read the first one as “gets” or “is sent” and the subsequent ones as “followed by”.

This is our first C++ program.

The second of the two statements in our program displays "It works!!!" and then
sends endl to cout, which causes the cursor to move to the beginning of the next line.

It works!!!

The net effect is the following output.

This is our first C++ program.


It works!!!

One cout statement can display data on several lines. For example, the following
cout produces the same output as the two cout statements of dem01-1.cpp.
Section 1.1 Our First C++ Program 13

cout << "This is our first C++ program." << endl << "It works!!!" << endl;
To obtain double spacing between the displayed lines, code the following.
cout << "This is our first C++ program." << endl << endl;
cout << "It works!!!" << endl;

This is our first C++ program.


It works!!!

1.1.7 The return Statement


The last statement executed by main() should be the return statement. As noted previ-
ously, we declare the function main() to produce an integer value. The return 0; state-
ment does two things. First, it ends the execution of main(). Second, it sends the integer
value 0 back to the operating system to indicate that the program ended normally. In
Chapter 5, we shall see how to construct functions that return other types of values or no
value at all.

1.1.8 The Preprocessor Directive #include


Compiling a C++ program is a two-step procedure. First, a program called the
preprocessor analyzes the C++ source-code program and carries out all preprocessor
directives. Each preprocessor directive begins with a # character in the first position of
a line. Therefore, in dem01-1.cpp, the line
#include <iostream>
is a preprocessor directive. The preprocessor carries out its directives before the second
step in the compilation procedure, which translates your program into machine code.
Preprocessor directives usually occur before the main() statement, as in dem01-1.cpp.
The #include directive causes the preprocessor to replace the line containing
the #include directive with the text of the named header file (so-called because it usu-
ally appears at the beginning of the program) that appears inside the angle brackets < >.
Thus, the text of the named header file effectively becomes part of your program and is
subsequently compiled along with your program statements.
Header files usually contain information about constants, functions, classes, and other
C++ elements that frequently appear in C++ programs. (We shall learn about these as we
proceed through this book.) The header file iostream, which stands for “input/output
stream”, is one of a standard set of system header files that every C++ compiler provides.
The header file iostream contains information about the standard input/output streams.
In particular, it contains information about the object cout, which appears in dem01-1.cpp.
Therefore, if you omit #include <iostream> from your program, the compiler will not
recognize cout and will generate an error. See Experiment 1.1.
We use the header file iostream so often that we shall adopt the rule of Note 1.3.
Note that the preprocessor directive
#include <iostream>
does not end with a semicolon because a preprocessor directive is not a C++ language
statement. A preprocessor directive is an instruction that the preprocessor carries out
prior to the compilation of the program. See Note 1.4.
14 Chapter 1 Introduction to C++

Note 1.3 The iostream Header File


Always code
#include <iostream>
in all your programs. Code it before main().

Note 1.4 Preprocessor Directives and Semicolons


Preprocessor directives do not end with a semicolon.

As we learn how to use other features of C++, we shall introduce other standard
header files. We also shall learn other preprocessor directives.

1.1.9 The using Directive


The C++ language compiler uses many files to build a C++ executable program. In ad-
dition to the source file, which is the C++ program that you code, the compiler uses one
or more header files, such as iostream, and libraries of standard and user-defined func-
tions to create the executable program. Therefore, many programmers, including you,
have been involved in writing the code that goes into making your program work. It is,
therefore, possible that two or more people might have used the same name for two
entirely different things. This would lead to a compiler error. To avoid such conflicts,
C++ provides the mechanism of the namespace, which divides the names that pro-
grammers can use into named scopes. The directive
using namespace std;

allows us to code in our programs cout (and later cin) without having to qualify
these by coding std::cout (and std::cin). The using directive basically says that
we can use all names within the std namespace (cout and cin are two such names)
without qualification.
Perhaps an analogy will help clarify the use of namespaces. Suppose I am at a
meeting of 40 people, two of which, besides me, are named John. If the committee
chairperson says “John, did you finish your report?”, there would be confusion about
which of the three Johns she is talking to. Therefore, the chairperson must qualify the
name by saying “John Molluzzo, did you finish your report?” However, when I am
home in my own “standard namespace” and my wife wants me to take out the garbage,
all she needs to say is “John, please take out the garbage.” Since I am in my own house
(my “standard namespace”), there is no need for her to qualify my name.
Note that the using directive is a requirement of the C++ standard, which was
approved in 1998. Older compilers will not recognize the using directive. If the using
directive causes errors when you compile dem01-1.cpp, you probably have an older
Section 1.1 Our First C++ Program 15

compiler that does not conform to the new standard. In that case, remove the using di-
rective and recompile your program. It will then be necessary to make the same change
to all the sample programs in the book.

1.1.10 Execution of dem01-1.cpp


Now enter, compile, and execute the program dem01-1.cpp. How you do this depends
on the particular C++ compiler you use. Refer to your C++ language manual, your in-
structor, or a local expert. Some chapter exercises ask you to make slight changes to
dem01-1.cpp or to write your own simple C++ program. To do this, you must be famil-
iar with the editor that accompanies your compiler or a word processor that produces
ASCII text files. Again, refer to the appropriate language manual or your instructor.

1.1.11 Keywords, Multiline Comments, and Escape Sequences


Keywords. The word int as well as using, namespace, and return are examples
of keywords (or reserved words), which are words that have special meaning in
the C++ language. Table 1.1 lists the C++ keywords. You will learn the meanings
of many of these keywords as you work through this book.
Multiline Comments. Earlier in this section, we mentioned that you can make
multiline comments by prefixing each line with the double slash // as follows.
//This is the first of a multi-line comment.
//This is the third line.
//This is the final comment line.
Some programmers prefer to make multiline comments by using the
/*...*/ pair. C++ considers everything between the /* and the */ to be a com-
ment. Therefore, the previous comment can be coded as follows.
/*
This is the first of a multi-line comment.
This is the third line.
This is the final comment line.
*/

TABLE 1.1
asm do if return typedef
auto double inline short typeid
bool dynamic_cast int signed typename
break else long sizeof union
case enum mutable static unsigned
catch explicit namespace static_cast using
char export new struct virtual
class extern operator switch void
const false private template volatile
const_cast float protected this wchar_t
continue for public throw while
default friend register true
delete goto reinterpret_cast try
16 Chapter 1 Introduction to C++

All three lines between the /* and */ are considered comments. This tech-
nique is convenient when you want to comment out an entire block of code for
debugging purposes. However, be careful if you use this technique—remember to
end the comment with the */. Failure to do so will cause the compiler to treat
everything from the /* to the end of the file as a comment.
Escape Sequences. Using endl, as we did in dem01-1.cpp, is the most common way
to control line spacing in C++. A second, but less common way to control line
spacing is by using the newline escape sequence. Each escape sequence begins
with the backslash character \. The escape sequence that causes the cursor to
move to the beginning of a new line on the monitor screen is \n, the newline char-
acter. Therefore, the first of the following statements displays the string "This is
our first C++ program." and then causes the cursor to move to the beginning
of a new line. The two lines produce exactly the same output as dem01-1.cpp.
cout << "This is our first C++ program.\n";
cout << "It works!!!\n";

There are many escape sequences that you can use in a string that you send to
cout. Experiments 10, 11, and 12 ask you to experiment with some escape sequences.
Table 1.2 lists the common escape sequences. To use an escape sequence in a cout
statement, the escape sequence must be contained in a quoted string.

1.1.12 About the Exercises, Experiments, and Programming Problems


At the end of each section of this book is some combination of exercises, experiments,
and programming problems. You can do most of the exercises with paper and pencil,
although some may require you to write a short program. The exercises reinforce the
ideas discussed in the chapter. Try to complete as many as possible before going on to
the next chapter.
The experiments usually ask you to modify a program discussed in the text or ask
you to code and execute a simple program and interpret the output. Working with com-
puters is an experimental science. You can treat each of your programs as an experi-
ment: will the program work as you expect? To answer this question, carefully examine

TABLE 1.2

Escape Sequence Meaning

\a alert (bell)
\b backspace
\f form feed
\n new-line
\r carriage return
\t horizontal tab
\v vertical tab
\' single quotation mark
\" double quotation mark
\\ single back slash
\? question mark
Section 1.1 Our First C++ Program 17

and interpret the output of the program (the result of the experiment) and decide
whether the program (the experiment) worked correctly. Chemists, physicists, and bi-
ologists learn from both successful and failed experiments. You also can learn a great
deal about programming from programs that work as required and from programs
that do not work as required. In addition, the experience gained from doing the ex-
periments will help you avoid making mistakes when writing your own programs. Try
to do as many experiments as possible. The more you do, the more you will learn.
The programming problems range in difficulty from simple, straightforward
problems to problems that require considerable time to design, code, and test. Attempt
at least one programming problem in each chapter. In each programming problem, de-
sign the program, write the code, compile the program, and then test the program with
sample input data.

Exercises 1.1
1. What is wrong with the attempt at a multiline comment in main()?
// dem01-1.cpp
// John C++. Molluzzo

#include <iostream>
using namespace std;
int main()
{ // This is the body of the
function main()
cout << "This is our first C++ program." << endl;
cout << "It works!!!" << endl;
return 0;
}

2. What, if anything, is wrong with the following cout statement?


cout >> "My name is Maria; << endl

3. What, if anything, is wrong with the following program?


#Include <iostream> main(){ cout << "Is there something
wrong " << endl << endl cout << "with this program"?; }

Experiments 1.1
For each experiment concerning dem01-1.cpp, start with a fresh copy of dem01-1.cpp
and make the indicated changes.
1. Delete the #include <iostream> preprocessor directive from dem01-1.cpp. At-
tempt to compile and execute the resulting program. What message does your
compiler issue?
18 Chapter 1 Introduction to C++

2. As mentioned in this section, C++ is case sensitive. Replace the i in the pre-
processor directive #include by I and compile the resulting program. What mes-
sage does your compiler issue? Now replace the word cout by COUT. What
message does the compiler issue?
3. Every C++ statement must end with a semicolon. Intentionally omit the semi-
colon at the end of the first cout statement in dem01-1.cpp and compile the re-
sulting program. What message does your compiler issue?
4. A preprocessor directive must not end with a semicolon. Put a semicolon at the
end of the #include directive in dem01-1.cpp and compile the resulting pro-
gram. What message does your compiler issue?
5. The body of the function main() must be enclosed in braces {}. Omit either the
left brace 5or the right brace6 in dem01-1.cpp and compile the resulting pro-
gram. What message does your compiler issue?
6. If you are not sure if your compiler conforms to the new C++ standard, write a
program that will find out.
7. If your compiler conforms to the new C++ standard, remove the using statement
from dem01-1.cpp and compile the program. What happens?
8. If your compiler conforms to the new C++ standard, remove the using statement
from dem01-1.cpp and replace all occurrences of cout by std::cout. Recompile
the resulting program. What happens?
9. If your compiler conforms to the new C++ standard, add the .h in the #include
directive in dem01-1.cpp. Recompile the resulting program. What happens?
10. A useful escape sequence is the horizontal tab \t. It works like the tab stops on a
typewriter. Enter, compile, and execute the following program. What does the tab
escape sequence do?
// Tabs
#include <iostream>
using namespace std;
int main()
{
cout << "One\tTwo\tThree\tFour" << endl;
cout << "\tFive\tSix\tSeven" << endl;
cout << "\t\tEight\tNine" << endl;
cout << "\t\t\tTen" << endl;
return 0;
}
Based on the output, at what positions are your computer’s tabs set?
11. Another useful escape sequence is the alert \a, also called the bell or audible
tone. Enter, compile, and execute the following program. What does the alert es-
cape sequence do?
// Alert
#include <iostream>
using namespace std;
Section 1.1 Our First C++ Program 19

int main()
{
cout << "\a\a\aWake up!" << endl;
cout << "The program ran!!" << endl;
return 0;
}

12. When outputting a string with the cout statement, the double quote " indicates the
beginning or end of a character string and the backslash \ denotes the beginning of an
escape sequence. If you want the character string you are displaying to contain either
of these characters, you must use a corresponding escape sequence. Enter, compile,
and execute the following program.What do the \" and \\ escape sequences do?
// Quotes and Backslashes
#include <iostream>
using namespace std;
int main()
{
cout << "The following is enclosed in double quotes: \"Quote\""
<< endl << endl;
cout << This is a backslash: \\" << endl;
return 0;
}

Why are there two double quotes near the end of the first cout statement?

Programming Problems 1.1


1. Write a program that displays the following lines triple-spaced.
Hello!
This is your computer.
What is your name?

2. Write a program that has the same output as the program of Programming Prob-
lem 1, but uses just one cout statement.
3. Write a program that displays the following.
*********** * Welcome * ***********

4. Write a program that displays your first initial in block form using asterisks. For
example, the program that John writes would display the following.
*********
*
*
*
*
*****
20 Chapter 1 Introduction to C++

1.2 INTEGERS AND ARITHMETIC


The simplest type of numeric data that a programmer can define in a C++ program is
integer data. This section discusses how to declare and name integer variables, assign
values to them, and how to do arithmetic with them.

1.2.1 Identifiers
All programming languages, including C++, require that the programmer name vari-
ous items that a program uses. We refer to the names of these items as identifiers. An
identifier can be any name you choose as long it conforms to the rules of Note 1.5.

Note 1.5 Identifier Naming Rules


An identifier consists of up to 31 characters subject to the following rules:
1. The characters can be letters (uppercase or lowercase), digits, and under-
scores (_).
2. An identifier cannot begin with a digit.
3. An identifier cannot have the same spelling as a keyword.

The following identifier names are valid.


salary employee_discount _name4
x total_cost margin
Tax_Rate VAR Margin
Good programming practice requires that an identifier name reflect the purpose
or meaning of what the identifier represents. Thus, do not use the identifier p to repre-
sent the price of a computer. Instead, use either the identifier price or the identifier
computer_price.
An identifier cannot contain a space. Therefore, to improve readability, we shall
use the underscore to separate words. The identifier total_cost is easier to read than
the identifier totalcost. Although an underscore can be the first character in an iden-
tifier, we suggest that you avoid doing so to avoid conflict with identifiers used in sys-
tem header files. (Some programmers capitalize the second and subsequent words of
multi-word identifiers instead of using underscores. This naming method is called using
“in-caps” notation. For example, such programmers would use totalCost instead of
total_cost and totalGrossReceipts instead of total_gross_receipts.)
Do not forget that C++ is case sensitive. Therefore, the identifier profit_margin
is different from the identifier Profit_Margin.

1.2.2 Variables
A variable is a named location in the computer’s main memory that stores a particular
type of data. Because it is a location in computer memory, a variable can assume any
one of a set of permissible values. This is why we call such a location a variable.
Section 1.2 Integers and Arithmetic 21

In a C++ program, we define a variable in a declaration. A variable declaration


begins with the variable’s data type, which tells the kind of data that a program can
store at the location named by the variable. There are many data types in C++, includ-
ing built-in data types and user-defined data types. The data type is followed by the
name of the variable, which is followed by a semicolon.
The name of a variable is an identifier and, as such, is subject to Note 1.5. How-
ever, we shall adopt the variable naming convention of Note 1.6. Remember that this is
just a convention, that is, a rule that is used in this book, and is not a rule of the C++
language.

Note 1.6 Variable Names


We use only lowercase letters and the underscore for names of variables.

For example, the following is a variable declaration.


int i1;
In this declaration, the keyword int means that the named variable, i1, is of the
integer data type. Depending on a particular platform (a platform consists of the com-
puter hardware, operating system, and C++ compiler being used), an integer can be
two bytes (16 bits) or four bytes (32 bits). If two bytes (16 bits) are used to represent an
integer, 2 16 = 65536 integers (positive, negative, and zero) can be represented in an in-
teger variable. Half the integers in this range are negative (that is, less than zero) and
half are nonnegative (that is, greater than or equal to zero). Therefore, such an integer
variable would have a value in the range - 32768 to + 32767. (In computers that store
int-type variables in four bytes, the range for an int variable is the same as that for a
long. We discuss the type long and its range of values later in this chapter.) Experi-
ment 4 at the end of this section shows how to use the sizeof operator (which deter-
mines how many bytes a data type occupies) to find out how many bytes an integer
variable occupies on your computer.
Note that in many of the examples and demonstration programs in this book, we
shall use short names for some variables to shorten the code. For example, it is com-
mon practice to use i, i1, i2, j, and k, and so on, to represent generic integer variables,
and r, s, t, x, y, and z to represent generic double variables (see Chapter 2). However, in
our longer programs, we will use meaningful names for our variables as you should in
all your program solutions to the programming problems.
It is possible to declare more than one variable in one declaration. For example,
the following declares three integer variables i1, i2, and sum.
int i1,
i2,
sum;

Alternatively, you can write all the variables on one line as follows.
int i1, i2, sum;
22 Chapter 1 Introduction to C++

Note in both cases that there is a comma after each instance of i1 and i2, and
that the declaration ends with a semicolon after the last variable name. You can declare
any number of variables of the same type by separating their names by commas and
ending the declaration by a semicolon.
A variable can be declared anywhere in a C++ program. However, a variable
must be declared before it is used. Although not required by C++, we shall adopt the
practice of placing each variable declaration at the beginning of main() on a separate
line. This improves the readability of our programs and allows us to place a comment
after a variable’s name to explain its function in the program. In later chapters, we shall
discuss when it is appropriate to declare a variable elsewhere in the program.
The value of a variable is the data stored at that location in computer memory.
Declaring a variable does not give the variable any specific value. A declaration simply
reserves storage for that variable in the computer’s memory and associates the de-
clared name with that storage. Before the program places data into a variable, the
value of the variable is meaningless to the program. In this case, we say that the vari-
able contains garbage. It is up to the programmer to make sure that the program places
meaningful data into each variable.

1.2.3 Using Integer Variables: dem01-2.cpp


The second program that we discuss in this chapter asks the user to input values for the
integers, does arithmetic on these values, and displays the results. To write this pro-
gram, you need to learn how to input values into the variables, how to do arithmetic,
and how to display the results.
The program dem01-2.cpp has the following four-part structure.
1. Declare the variables.
2. Obtain the data from the user.
3. Do the required calculations with the data.
4. Output the results.
Many programs in the first part of this book have this four-part structure. We dis-
cuss the new features of the program after the program code.
// dem01-2.cpp
// This program demonstrates the use of integers in C++.
// The user enters two integers. The program adds, subtracts,
// multiplies, and divides the integers and outputs the
// results of the calculations.
#include <iostream>
using namespace std;
int main()
{
// Declare the variables
int i1,
i2,
Section 1.2 Integers and Arithmetic 23

sum,
difference,
product,
quotient,
remainder;
// Obtain the data from the user
cout << "Input an integer followed by a return: ";
cin >> i1;
cout << "Input an integer followed by a return: ";
cin >> i2;
// Do the arithmetic
sum = i1 + i2;
difference = i1 - i2;
product = i1 * i2;
quotient = i1 / i2;
remainder = i1 % i2;
// Output the results
cout << endl;
cout << "The sum of " << i1 << " and " << i2 << " is " << sum << endl;
cout << "The difference of " << i1 << " and " << i2 << " is "
<< difference << endl;
cout << "The product of " << i1 << " and “ << i2 << " is "
<< product << endl;
cout << "The quotient of " << i1 << " and " << i2 << " is "
<< quotient << endl;
cout << "The remainder when " << i1 << " is divided by " << i2
<< " is " << remainder << endl;
return 0;
}

Program Output
Input an integer followed by a return: 15
Input an integer followed by a return: 6
The sum of 15 and 6 is 21
The difference of 15 and 6 is 9
The product of 15 and 6 is 90
The quotient of 15 and 6 is 2
The remainder when 15 is divided by 6 is 3

1.2.4 Variable Declarations


The declaration in dem01-2.cpp reserves storage for seven integer variables but does
not place values into the seven storage locations. The program needs the variables i1
24 Chapter 1 Introduction to C++

and i2 to store the integers input by the user. It also needs the variables sum,
difference, product, quotient, and remainder to store the results of each arith-
metic calculation. Remember that because each of these variables is an integer, each of
their values must be in the range of an integer variable. Experiment 4 addresses the
question of what happens if one of these numbers is outside the permissible range.

1.2.5 Asking the User for Input: Prompts


The first cout statement in dem01-2.cpp, which is called a prompt, asks the program
user to enter an integer followed by a return. A program should always prompt the
user for the data that the program expects the user to enter. The prompt should be
short and should clearly specify the kind of data the user is to enter. Because the
prompt ends in a colon followed by a space, the cout leaves the cursor after this blank
space. The prompt looks like the following on the screen.

Input an integer followed by a return: _

1.2.6 The Input Stream cin


Just as output in C++ is done via the output stream, input is done via the input stream.
The input stream cin (for “console input” and read as “see-in”) is to input what cout is
to output: cin obtains the next data item from the input stream, which is attached to the
keyboard, and places it into the variable following the extraction operator, >>. When we
use the extraction operator on cin, cin obtains the next data item from the input
stream, that is, the next data item you type at the keyboard, and places a copy of it into
the variable that follows >>. See Figure 1.4. The statement cin >> i1; gets the integer
that the user enters at the keyboard in response to the prompt and places the integer’s
value into the variable i1.
The second cout statement in dem01-1.cpp prompts the user for the second inte-
ger. The statement cin >> i2; obtains the integer the user enters and places its value
into the variable i2.
The integer that the user enters can be preceded by a + or - sign, but it cannot
contain a comma or a decimal point. After retrieving the sign, if present, cin retrieves
only digits from the input buffer up to but not including the first non-digit it encoun-
ters. Thus, if the user enters 13,708 in response to the first prompt, cin will retrieve only
13 and assign it to i1. See Experiment 2.

Program
Monitor
Keyboard
cout cin
<< >>

Use cin and the extraction operator >> to remove data from the
input stream (the keyboard.)

Figure 1.4
Another Random Scribd Document
with Unrelated Content
their racial heritage. These British islands, particularly Jamaica and
Barbados (the latter one of the most densely populated spots in the
whole world) have been fertile sources of black emigration to other
islands and to the mainland.

Haiti is a purely Negro Republic, and offers a good illustration of


what the Negro accomplishes if left to himself, even though given all
the advantages of easy access to European civilization. The republic
of Santo Domingo occupies the other part of the same island; its
hybrid population has more Spanish and less Negro blood but it is
not by any means civilized.
In general the islands of the West Indies now contain nearly
8,000,000 people, the descendants of Negro slaves with a very small
but undiscoverable admixture of Indian blood and a somewhat larger
but still unimportant admixture of European stock. They present a
standing menace to the United States immigration policy, and afford
one of the principal arguments for extending stringent restrictions to
the Western Hemisphere. The whole Caribbean is in the process of
becoming a Negro territory. Such a result may be inevitable, but
adjacent nations which desire to remain white must protect
themselves while there is time.
In broad outline, the picture of Latin-America is the picture of a
diversified region occupied by some 80,000,000 people, mainly
Indians, but with varying proportions of White and Negro blood, the
former usually small in amount, the latter often large. The few
countries that may properly be called white are not emigrant-
exporting countries, and their inhabitants are for the most part non-
Nordic, therefore not particularly well adapted to incorporation in the
United States.
In conclusion, it may be remarked at this point that each successive
revolution in Latin America has tended toward hastening the
elimination of European blood and influence. It is usually the half-
breeds who revolt and they, in turn, are subject to the increasing
self-assertion of the pure native.

XVIII
THE NORDIC OUTLOOK
In the preceding chapters we have seen the unity of the nation
greatly impaired in race and religion and threatened in language, but
the country is still 70 per cent Nordic and 80 per cent Protestant,
and no one foreign language seriously threatens our English speech.
There are nearly 50 per cent of Old-Native American Whites in the
country at large, although they have been swamped by aliens in
New England and in the industrialized States of the Northeast.
The great majority of the senators of the United States are still of
old American stock and so are the members of the House of
Representatives. The leaders of the nation in science, education,
industry, and in the Army and Navy are still overwhelmingly Nordic,
so that with these elements in our favor we are still in a position to
check the increase of the other elements and contend against their
deleterious effects upon our institutions.
Much of the immigration during the last century has been identical
with the old British stock in all respects. The English and the Scotch
who have come over here, as well as the Scandinavians and most of
the Germans, and perhaps some other elements, are to be regarded
as reinforcements of the older stock. On the other hand, most of the
people from southern and eastern Europe must be regarded as
distinct menaces to our national unity.
The remedy is first and foremost the absolute suspension of all
immigration from all countries; and the signs of the times indicate
that such suspension is inevitable. Such a total suspension of
immigration would remove all grounds for charges of discrimination
against Asiatics, which now embarrass our foreign relations. At the
very least, the same quota limitations should be imposed on the
countries to the south of us as are enforced against Europe.
In view of the fact that during the great depression which began in
1929 we had millions of unemployed of our own people here, we
should be deaf to sentimental pleas for the admission of relatives of
any kind. If families are separated, it has not been through the fault
of the American people, and the immigrant can return whence he
came, if he wishes to join his family. As a matter of fact, it is only
one or two groups which are so vigorously clamoring for the
admission of relatives.
Not only should European immigration be entirely stopped but still
more, all immigration of every sort from countries to the south of us
should be barred. In the islands and on the coasts of the Caribbean,
and in Mexico and in Central America, to say nothing of the
countries farther south, we have a vast reservoir of Negroes, and of
Indians in the interior, who sooner or later will be drawn toward the
United States by the high wages of common labor. The strictest
legislation at this time is necessary to prevent this impending
invasion before it assumes the dimensions of a flood, such as has
already happened in the case of the Mexican Indians. If immigration
be not absolutely prohibited, at very least, no one should be allowed
to enter the United States, unless a visitor or traveller, except white
men of superior intellectual capacity distinctly capable of becoming
valuable American citizens.
The law of 1790 providing that no one could become a citizen of the
United States except free Whites was the law until the aftermath of
the Civil War added the word "black" or "of African descent" to those
who could be naturalized. This last provision should be repealed and
the blacks with the South American and Central American Indians
put on the same footing as the Orientals.
All Filipino immigration should be stopped before it becomes a
serious menace. If possible, half-breeds from Hawaii should not be
allowed entry and absolute restriction should be placed on the
entrance of Negroes and Mulattoes from Puerto Rico. There are now
swarms of them in the Harlem District of New York. This last is
simple justice to the American Negroes.
The increasing use of machines calls for less and less common labor,
and even in normal times there will be a surplus of man power for
the factories and the farms. Why should outsiders be allowed to
come in and take the jobs and lower the living standards of
American labor? This is one of the greatest questions before the
American people and the depression following 1929 has brought this
truth home.
We have now in this country over five million aliens who are not
citizens, more than a million of whom are said to be illegally here.
These last should be deported as fast as they can be located and
funds made available. There can be no better means of relieving
unemployment present or future than by such wholesale
deportation. We should begin with those aliens who have violated
our laws or who have become public charges and all such, now in
our penitentiaries and asylums, should be deported forthwith. When
that has been done and done fully, it should be followed by the
deportation of unemployed aliens.
Registration is necessary for the carrying out of any proper system
of deportation. Why any one should object to registration as a
proper means of identification is a mystery, unless there is a sinister
motive behind the desire to conceal identity.
A storm of protest will arise from the vociferous and influential
foreign blocs and from the radicals and half-breeds claiming to be
Americans, who will all rush to the defense of their kind. It is strange
to find how sensitive we are to any foreign criticism of things
American, but how prone we are to listen respectfully to local aliens,
who are urging their own interests at the expense of the national
welfare.
In order to curb the influence of these aliens and to prevent their
pernicious control by politicians, it would also be wise to suspend all
naturalization for a generation at least. Our citizenship in the past
has been made of little value by the absurd way that it has been
thrust upon foreigners. Nothing can be more ill-advised politically
than the Americanization programs of some worthy people. An
American is not made by conferring upon him the franchise, but by
the alien's voluntary and genuine acceptance of our language, laws,
institutions, and cultural traditions.
Even though the foregoing program were put into effect, which
would, possibly, be a "Counsel of Perfection," we would still have
with us an immense mass of Negroes and nearly as many southern
and eastern Europeans, intellectually below the standard of the
average American. The proper extension to and use by these
undesirable classes of a knowledge of birth control may be in the
future of substantial benefit, and the practice of sterilization of the
criminal and the intellectually unfit, now legally established in
twenty-seven States, can be resorted to with good result.
The fundamental question for this nation, as well as for the world at
large, is for the community itself to regulate births by depriving the
unfit of the opportunity of leaving behind posterity of their own
debased type. Our civilization has mercifully put an end to the cruel,
wasteful, and indiscriminate destruction of the unfit by Nature,
wherefore it is our duty, as exponents of that civilization, to
substitute scientific control, that civilization itself may be maintained.
Down to date the American stock has only just begun to intermarry
with the immigrant stock. When this process has gone further—and
it will go further—it will be more difficult to control the destinies of
the nation. It is therefore the duty of all Americans, and such of the
immigrant stock as are in sympathy with them, to face the problem
boldly and to take all eugenic means to encourage the multiplication
of desirable types and abate drastically the increase of the unfit and
miscegenation by widely diverse races.
So much for our internal problems. The problems outside of our
country are a different matter. In the last century the world has
grown smaller, and, perhaps, in the long run America must take her
part in international affairs.
The White Man's Burden
As Americans we are faced with the necessity of assuming our share
of a burden which has been carried by Great Britain for the last
three centuries—that is "the White Man's Burden,"—the duty of
policing the world and maintaining the prestige of the white man
throughout the Seven Seas. Due to the change in the industrial
situation all over the world and to the spread of the fatal
sentimentalism of the Anglo-Saxon, the lower races in Europe and
elsewhere are beginning to assert themselves. Everywhere from one
end of the world to the other is heard the cry of self-determination.
Americans already have much the same problem in the Philippines.
The attitude of the Imperial Government in London toward the
native races in its various Dominions has been in the past and still is
not unlike that of the Federal Government in Washington toward the
Negroes in our Southern States.
Americans must sympathize with the firm resolve of the handful of
white men in South Africa (less than a million and a half) to control
and regulate the Negro population there—numbering some seven
millions and in the midst of which they live. The same problem
arises in Australia and New Zealand where the Whites are
determined that their civilization shall not be swamped by Orientals.
We must also sympathize with the Whites in Kenya Colony in their
opposition to a filling of their country with cheap Hindu labor. As
Americans we can understand the Negro and recognize his cheerful
qualities, but we can have little sympathy with the Hindu whom we
have expressly barred from our Pacific Coast. These Hindus, with the
Chinese, have ruined the native races of many of the Polynesian
Islands. They have been for ages in contact with the highest
civilizations, but have failed to benefit by such contact, either
physically, intellectually, or morally.
Similar dangers exist on the Pacific Coast of Canada. The struggle
for the maintenance of the supremacy of the white man over the
native, or for that matter over the non-European, until now has been
maintained by Great Britain alone. Her ruling class has given the
world the greatest example since the days of Rome, of a just,
fearless, and unselfish government, but apparently the native does
not desire such a government.
The old imperial instinct that enabled Great Britain to retain control
of the white man's world appears to be coming to an end. The
weary Titan seems willing to turn over the burden of government to
the Dominions as fast as the latter demand it. This is evidenced also
by the proposal to give up the naval base at Singapore. If this base
is ever actually abandoned, it means England's withdrawal from the
supremacy of the Pacific. In such event, whether we Americans like
it or not—whether we intend it or not—the burden of the control of
the Pacific will pass in great measure to America. The future lies in
the Pacific rather than in the Atlantic, and with the completion of the
Panama Canal, America is brought face to face with Oriental
problems.
Australia and New Zealand, still more British Columbia, look for co-
operation and leadership to the United States as well as to Great
Britain, and we must be prepared to accept this responsibility.
We have our own troubles in respect to the Philippines. The
swarming of the Filipinos into the Pacific States brings with it a
repetition of the Chinese problem of sixty years ago. California is
determined that the white man there shall not be replaced by the
Chinese, the Japanese, the Mexican, or the Filipino. The Eastern
States should face this problem understandingly, and recognize the
simple fact that the white men on the Pacific Coast of the United
States and Canada are determined to maintain a white ownership of
the country, even though the East has been willing to see New
England swamped by French-Canadians and Polaks, and the
industrial centers of the North filled to overflowing with southern and
eastern Europeans.
When we talk about the maintenance of the white man's ideals and
culture and about the supremacy of the white man, we are talking
about two distinct things. One is the determination of the white man
to keep for himself his own countries, the United States, Great
Britain, Canada, South Africa, Australia, New Zealand, and many of
the smaller islands. With this determination Americans sympathize
and sooner or later we may be called on to help protect the White
race and the English language in these countries. It seems to be a
part of our destiny. The other phase of white supremacy is the white
man's effort to benefit the backward races and raise them to
civilization by instilling his language, his religion, and his culture into
Asiatics and Africans. This is the tendency of foreign missions, and it
leads sooner or later to a challenge by the natives of the control of
the Whites.
To rule justly, as the English have in India and Burma, is for the best
interest of the native. For example, the United States should either
firmly govern the Philippines, which, in the last analysis, is for the
interest and enrichment of the Filipinos, or else abandon them to
their own devices. If Japan ever gets hold of these islands, she will
keep them without regard to the wishes or interests of the native, as
that Empire is not greatly troubled with sentimentalists and native
sympathizers such as flourish in the United States.
The Japanese, the Chinese, the Hindus, and the Moslems have
cultures, customs, religions, arts, literatures, and institutions of their
own, which for them may be, and in many cases probably are, as
good as our own. The writer does not see any gain in destroying
these native elements of culture or replacing them indiscriminately
with the institutions of the white man to which those races are, for
the most part, unfitted. Democracy is an excellent example. It simply
will not work among Asiatics. In fact, its success is yet fully to be
proven in the Western World.
But the other side of the problem—whether we, the White race, shall
surrender our own culture, our own lands and our own traditions,
good or bad, to another race—presents a very different question.
Fortunately, in this case, Reason and Sentiment march hand in hand.
The prestige and strength of Europe and Great Britain have been
greatly impaired since the World War and Western civilization sooner
or later may be forced to hand on the Torch to America.
We see the Nordics again confronted across the Pacific by their
immemorial rivals, the Mongols. This will be the final arena of the
struggle between these two major divisions of man for world
dominance and the Nordic race in America may find itself bearing
the main brunt.
In the meantime, the Nordic race, that has built up, protected, and
preserved Western civilization, needs to realize the necessity of its
own solidarity and close co-operation. Upon this mutual
understanding rest the peace of the world and the preservation of its
civilization.
Let us take thought as to how we can best prepare for our share of
the task before us—that is, bear our share of the White Man's
Burden.

BIBLIOGRAPHY
Abbott, John S.C., Peter Stuyvesant. New York, Dodd, Mead &
Co., 1898.
Adams, Alexander A., The Plateau Peoples of South America.
(An Essay in Ethnic Psychology.) New York, Geo. Routledge &
Sons, Ltd., 1915.
Adams, James Truslow, The Founding of New England. Boston,
Atlantic Monthly Press, 1921.
——, The March of Democracy. New York, Charles Scribner's
Sons, 1932-33.
——, New England in the Republic, 1776-1850. Boston, Little
Brown, 1926.
——, Provincial Society, 1690-1763. New York, Macmillan Co.,
1927. Vol. III of series entitled A History of American Life.
——, Revolutionary New England, 1691-1776. Boston, Atlantic
Monthly Press, 1923.
Alsina, Juan A., European Immigration to the Argentine, 1898.
American Council of Learned Societies, Report of the committee
on linguistic and national stocks in the population of the United
States. Washington, D.C., 1932. (Reprint from annual report of
the American Historical Association for 1931, pp. 107-441.)
Arber, Edw. (ed.), Story of the Pilgrim Fathers. Boston,
Houghton Mifflin Co., 1897.
Arbois de Jubainville, M.H. d': 1. "Les Celts en Espagne," Revue
Celtique, Vols. XIV and XV.
——, 2. "Les Celts et les langues celtiques," Revue
archéologique, série 2, t. XLIII, pp. 87-96, 141-155.
——, 3. "Les Gaulois dans l'Italie du Nord," Rev. Celt., Vol. XI.
Avebury, Lord (Sir John Lubbock), Prehistoric Times, 7th ed.
New York, Henry Holt & Co.; London, Williams and Norgate,
1864-1913.
Avery, Elroy McKendree, A History of the United States and Its
People. Cleveland, Burroughs Bros., 1905.
Babcock, Kendrick Charles, The Scandinavian Element in the
U.S. Urbana, University of Illinois, 1914.
Baily, John, Esq., Central America. London, Trelawney Saunders,
1850.
Bancroft, Hubert Howe, History of Arizona and New Mexico,
1530-1888, Vol. XVII. San Francisco, The History Co., 1889.
——, History of California, 4 vols. San Francisco, A.L. Bancroft &
Co., 1884, 1885, 1886.
——, History of Oregon, 2 vols. San Francisco, The History Co.,
1886.
——, History of Washington, Idaho, and Montana. San
Francisco, The History Co., 1890.
Barker, Eugene C. (ed.), Readings in Texas History. Dallas,
Southwest Press, 1929.
Barker, Howard F., "The Founders of New England." American
Historical Review 38 (4): 702-713. July, 1933.
Bassanovitch, I., Materials on the Anthropology of the Bulgars:
The Lomsk District, pp. 3-186, 1891.
Beard, Charles and Mary, Rise of American Civilization. New
York, Macmillan, 1927.
Beddoe, John: 1. The Anthropological History of Europe, 1893.
——, 2. "The Kelts of Ireland," Journal of Anthropology, 1870-
1871, pp. 117-131.
——, 3. "On the Stature and Bulk of Man in the British Isles,"
Memoirs of the Anthropological Society, Vol. III, pp. 384-573.
London, 1867-1869.
——, 4. The Races of Britain. Bristol and London, 1885.
Bertrand, Alexandre (with S. Reinach), Les Celts dans les vallées
du Pô et du Danube. Paris, E. Leroux, 1894.
Binder, Julius, Die Plebs. Leipzig, G. Bohme, Deichert, 1909.
Biographical and Historical Memoirs of Northeast Arkansas.
Chicago, Goodspeed, 1889.
Blackmar, Frank W. (ed.), Kansas. Chicago, Standard Pub., 1912.
Blegen, Theodore C., Norwegian Migration to America.
Northfield, Minnesota, Norwegian American Historical Assn.,
1931.
Boam, Henry J., British Columbia. London, Sells Ltd., 1912.
Boni, G. Roma, Notizie degli Sclavi; série 5, pp. 123 seq. and
375 seq., 1903.
Bork, Ferdinand, Die Mitanni Sprache. Berlin, W. Peiser, 1909.
Boule, M., "Essai de paléontologie stratigraphique de l'homme,"
Revue d'anthropologie, série 3, t. III, pp. 129-144, 272-297,
385-411, 647-680, 1888.
Bourinot, Sir John G., Canada under British Rule, 1760-1900.
Cambridge, Massachusetts, University Press, 1900.
Bracq, Jean Charlemagne, The Evolution of French Canada. New
York, The Macmillan Company, 1924.
Breasted, James H.: 1. Ancient Times, A History of the World.
Boston, Ginn & Co., 1916.
——, 2. "The Origins of Civilization," Scientific Monthly, vols. IX,
nos. 4, 5, 6, and X, nos. 1, 2, 3.
——, 3. A Survey of the Ancient World. Boston, Ginn & Co.,
1919.
——, 4. History of Egypt, and other writings.
Bresette, Linna E., Mexicans in the United States: Report of a
Brief Survey. Washington, D.C., Natl. Catholic Welfare Conf.,
1929.
Breuil, L'Abbé H., "Les peintures rupestres d'Espagne," (avec
Serrano Gomez et Cabre Aguilo), L'Anthropologie, t. XXIII, 1912.
Brewer, Daniel Chauncey, The Conquest of New England by the
Immigrant. New York, Putnam's Sons, 1926.
Brown, John Henry, History of Texas, 2 vols. St. Louis, L.E.
Daniell.
Browne, William Hand, Maryland, The History of a Palatinate.
Boston, Houghton Mifflin Co., 1890.
Bruce, Philip Alexander, LL.B., LL.D., History of Virginia, 1607-
1763, vol. I. Chicago and New York, American Historical Society,
1924.
——, Institutional History of Virginia. New York, G.P. Putnam's
Sons, 1910.
Bruhnes, Jean, "Race et nation," Le Correspondant. Paris,
September, 1917.
Bryce, George, The Remarkable History of the Hudson Bay
Company. New York, Scribner, 1900.
Bryce, James, The Holy Roman Empire. Macmillan, 1904.
Buck, Solon, Illinois in 1818. Springfield, Illinois Centennial
Commission, 1917.
Bureau of the Census: Reports on Population.
Burke, U.R., A History of Spain, 2d ed. London, Longmans,
Green & Co., 1900.
Burrage, Henry S., D.D., The Beginnings of Colonial Maine,
Portland, Me., Marks Printing House, 1914.
Bury, J.B., A History of Greece. Macmillan, 1917.
Cable, George W., The Creoles of Louisiana. New York, Charles
Scribner's Sons, 1889.
Cahun, Léon, Histoire de l'Asie. Paris, Armand Colin et Cie.,
1896.
Caldwell, Bishop R., A Comparative Grammar of the Dravidian or
South Indian Family of Languages, 2d ed. London, K. Paul,
Trench, Trübner & Co., 1913.
Campbell, Charles, Introduction to the History of the Colony and
Ancient Dominion of Virginia. Richmond, B.B. Minor, 1847.
Candolle, Alphonse de, Histoire des sciences et des savants
depuis deux siècles, 2me éd. Genève, H. Georg, 1806-1893.
Carpenter, Niles, Immigrants and Their Children. Census
Monographs VII. Washington, D.C., Bureau of the Census, 1927.
É
Cartailhac, Émile, La France préhistorique d'après les sépultures
et les monuments, 2me éd. Paris, 1903.
Castle, William E., Genetics and Eugenics. Cambridge, Harvard
University Press, 1930. 4th ed.
Cattell, J. McKeen, "A Statistical Study of American Men of
Science," Science, N.S., vol. XXIV, nos. 621-623, and vol. XXXII,
nos. 827 and 828.
Chambers, Henry E., Mississippi Valley Beginnings. New York,
G.P. Putnam's Sons, 1922.
Chantre, Ernest, "Recherches anthropologiques dans l'Asie
occidentale," Extrait des Archives du musée d'histoire naturelle
de Lyon. Lyon, 1895.
Claiborne, J.F.H., Mississippi as a Province, Territory, and State,
vol. I. Jackson, Mississippi, Power & Barksdale, 1880.
Clay, Albert T., The Empire of the Amorites. Yale University
Press, 1919.
Cleland, Robert Glass, Ph.D., A History of California (The
American Period). New York, The Macmillan Co., 1930.
Clemenceau, Georges, South America Today. New York and
London, G. Putnam & Sons, 1911.
Coan, Charles F., Ph.D., A History of New Mexico, vol. I. Chicago
and New York, The American Historical Society, Inc., 1925.
Cobb, Sanford H., The Story of the Palatines. New York and
London, G.P. Putnam's Sons, 1897.
Cole, Arthur Charles, The Era of the Civil War. Springfield,
Illinois Centennial Commission, 1919.
Cole, Cyrenus, A History of the People of Iowa. Cedar Rapids,
Torch Press, 1921.
Collignon, R.: 1. "L'anthropologie au conseil de révision, etc.,"
Bulletin de la Société d'anthropologie, pp. 736-805, 1890. Also
Bull. Soc. d'anth., 1883.
——, 2. "Anthropologie de la France: Dordogne, Charente,
Creuse, Corrèze, Haute-Vienne," Mémoires de la Société
d'anthropologie, série 3, I, fasc. 3, pp. 3-79.
——, 3. "L'indice céphalique des populations françaises," L'Anth.,
série I, pp. 200-224, 1890.
Committee on Immigration and Naturalization, House of
Representatives. Hearings, especially 67th Cong., 3d session;
68th Cong., 1st session; 69th Cong., 1st session; 70th Cong.,
1st session and 2d session; 72d Cong., 1st session. (A valuable
series of reports, containing testimony of H.H. Laughlin and
other experts.) Washington, D.C., Government Printing Office,
1923-1932.
Conklin, Edwin G., Heredity and Environment. Princeton
University Press, 1929. 6th ed.
Cooke, John Esten, Virginia, A History of the People. Boston,
Houghton Mifflin Co., 1887.
Cotterill, R.S., History of Pioneer Kentucky. Cincinnati, Johnson
& Hardin, 1917.
Cowan, Helen I., British Emigration to British North America,
1783-1837. University of Toronto Library, 1928.
Coy, Owen Cochran, The Great Trek. Chicago, Powell Pub. Co.
Crawford, O.G.S., "Distribution of Early Bronze Age Settlements
in Britain," Geographical Journal, XL, pp. 184 seq., 1912.
Darwin, Charles, The Descent of Man, 2d ed. London, John
Murray, 1901.
Davenport, Charles B.: 1. The Feebly Inhibited, Nomadism ...
Inheritance of Temperament. Washington, D.C., Carnegie
Institution, 1915.
——, 2. Heredity in Relation to Eugenics. New York, Henry Holt
& Co., 1911.
Davidson, Alex., and Stuvé, Bernard, A Complete History of
Illinois from 1673 to 1873. Springfield, Illinois Journal Co., 1874.
Davis, John, Travels in Louisiana and the Floridas in the Year
1802. New York, I. Riley Co., 1806.
Davis, Walter B., History of Missouri. St. Louis, Hall & Co., 1876.
Dawkins, W. Boyd, Early Man in Britain. London, Macmillan,
1880.
Deniker, J., "Les races de l'Europe, Note préliminaire,"
L'anthropologie, vol. IX, pp. 113-133. Paris, 1898.
Dill, Samuel, Roman Society in the Last Century of the Western
Empire, 2d ed. Macmillan, 1906.
Eginhard, Life of Charlemagne, Glaister translation. London,
George Bell & Sons, 1877.
Esarey, Logan, A History of Indiana, vol. II. Indianapolis,
Bowen, 1918.
——, A History of Indiana from Its Exploration to 1850.
Indianapolis, W.K. Stewart, 1915.
Fairbanks, History of Florida, 1512-1842. Philadelphia, J. B.
Lippincott & Co., 1871.
Fanning, John William, Negro Migration. Bull. Univ. Georgia,
June, 1930.
Farish, Thomas Edwin: 1. History of Arizona, vol. III. San
Francisco, The Filmer Bros. Electrotype Co., 1916.
——, 2. History of Arizona, vol VI. San Francisco, The Filmer
Bros. Electrotype Co., 1918.
Faust, Albert Bernhardt, The German Element in the United
States, 2 vols. Boston and New York, Houghton Mifflin Co.,
1909.
Feist, Sigismund, Address to the International Congress at
Gratz. 1909.
Ferrero, Guglielmo, The Greatness and Decline of Rome. New
York, Putnam, 1909.
Ferris, Jacob, The States and Territories of the Great West. New
York, Miller, Orton & Mulligan, 1856.
Fish, Carl Russell, The Rise of the Common Man, 1830-1850.
New York, Macmillan, 1927.
Fisher, George Park, The Colonial Era. New York, Charles
Scribner's Sons, 1892.
Fisher, H.A.L., The Political History of England, vol. IV. Edited by
William Hunt and Reginald Poole. London, Longmans, Green &
Co., 1906.
Fisher, Sydney George: 1. The Making of Pennsylvania.
Philadelphia, J.B. Lippincott Co., 1896.
——, 2. The Quaker Colonies. New Haven, Yale University Press,
1921.
Fiske, John, The Dutch and Quaker Colonies in America, vols. I
and II. Boston, Houghton Mifflin Co., 1899.
Fleure, H.J. (with James, T.C.), "Anthropological Types in
Wales," Journal of the Royal Anthropological Institute of Great
Britain and Ireland, vol. XLVI, pp. 35-154.
——, (with L. Winstanley), "Anthropology and Our Older
Histories," Jour. Roy. Anth. Inst., vol. XLVIII, pp. 155 seq.
Flint, Timothy, History and Geography of the Mississippi Valley, 2
vols. Cincinnati, E.H. Flint, 1832.
Flower and Lydekker, Mammals, Living and Extinct. London,
Adam and Charles Black, 1891.
Foerster, Robert F., The Racial Problems Involved in Immigration
from Latin America and the West Indies to the United States.
Washington, D.C., U.S. Dept. of Labor, 1925.
Folwell, William Watts, Minnesota. Boston, Houghton Mifflin Co.,
1908.
Ford, Henry Jones, The Scotch-Irish in America. Princeton
University Press, 1915.
Fortier, Alcée, A History of Louisiana, 4 vols. New York, Manzi,
Joyant & Co., 1904.
Fosdick, Lucian J., The French Blood in America. New York, The
Baker & Taylor Co., 1911.
Frank, Tenney, "Race Mixture in the Roman Empire," American
Historical Review, vol. XII, no. 4, July, 1916.
Freeman, E.A.: 1. A Historical Geography of Europe. Edited by
J.B. Bury, 3d ed. London, Longmans, Green & Co., 1912.
——, 2. Race and Language. Historical Essays, series 3, pp. 173-
230. New York and London, Macmillan, 1879.
Fritsch, Gustave, Das Haupthaare und seiner Bildungsstätte bei
den Rassen des Menschen. Berlin, 1912.
Fuller, George W., A History of the Pacific Northwest, 3 vols.
New York, Alfred A. Knopf, 1931.
Galton, Sir Francis, Hereditary Genius. London and New York,
Macmillan & Co., 1892.
Gameau, F.X., History of Canada, vols. I and II. Montreal, John
Lovell, 1862.
Gayarre, Charles, Louisiana, Its History as a French Colony, vol.
II. New York, Wiley, 1852.
Geer, Baron Gerard de, "A Geochronology of the Last 12,000
Years," Compte-Rendu de la session 1910, du Congrès Géol.
Intern., vol. XI, fasc. 1, pp. 241-257.
Gibbon, Edward, Decline and Fall of the Roman Empire.
Gindley, Anton, History of the Thirty Years' War. New York, G.
Putnam's Sons, 1884.
Gjerset, Knut, The History of the Norwegian People. New York,
Macmillan, 1915.
Goodwin, John A., The Pilgrim Republic. Boston and New York,
Houghton Mifflin Co., 1909.
Gosnell, R.E., The Year Book of British Columbia. Victoria, B.C.,
Librarian Legislature Assembly, 1897.
Gosney, E.S., and Popenoe, Paul, Sterilization for Human
Betterment. New York, Macmillan, 1929.
Grant, Madison, "The Origin and Relationships of North
American Mammals," Eighth Annual Report of the New York
Zoological Society. New York, 1904.
——, The Passing of the Great Race. 4th ed. New York, Charles
Scribner's Sons, 1921.
Green, John R., A History of the English People. New York,
Harper, 1878.
Greene, Evarts B., and Virginia D. Harrington, American
population before the federal census of 1790. New York,
Columbia University Press, 1932.
Gregory, W.K.: 1. "The Dawn Man of Piltdown, England,"
American Museum Journal, vol. XIV. New York, May, 1914.
——, 2. "Facts and Theories of Evolution, with Special Reference
to the Origin of Man," Dental Cosmos, pp. 3-19, March, 1920.
——, 3. "Studies on the Evolution of the Primates," Bull. Amer.
Mus. Nat. Hist., vol. XXXV, article xix. New York, 1916.
Griffis, William Elliot: 1. The Story of New Netherland. Boston
and New York, Houghton Mifflin Co., 1909.
——, 2. The Story of the Walloons. Boston and New York,
Houghton Mifflin Co., 1923.
Gue, Benjamin F., History of Iowa. New York, Century History
Co., 1903.
Guillaume, H., F.R.G.S., The Amazon Provinces of Peru. London,
Wyman & Sons, 1888.
Haddon, A.C.: 1. The Races of Man and Their Distribution.
London, Milner & Co.
——, 2. The Study of Man. New York, Putnam; and London,
Bliss Sands, 1898.
——, 3. The Wanderings of Peoples. Cambridge University Press,
1912.
Haeckel, Ernst, The Riddle of the Universe. Harper, 1901.
Hale, Will, and Merritt, Dixon, A History of Tennessee and
Tennesseans, vols. I and III. Chicago, Lewis Pub. Co., 1913.
Hall, H.R., The Ancient History of the Near East, 3d ed. London,
Methuen & Co., 1916.
Hall, Prescott F.: 1. Immigration, 2d ed. New York, Henry Holt &
Co., 1908.
——, 2. "Immigration Restriction and World Eugenics," Journal
of Heredity, vol. X, no. 3, pp. 125-127. Washington, D.C., March,
1919.
Hamilton, Peter Joseph, The Colonization of the South, vol. III
of The History of North America, edited by Guy Carleton Lee.
Philadelphia, George Barrie & Sons, 1904.
Hanna, Charles A., The Scotch-Irish, or The Scot in North
Britain, Ireland, and America, 2 vols. New York, G. Putnam's
Sons, 1902.
Harper, Roland M., The Population of Mexico: an Analysis. Pan-
American Magazine 44 (4): 269-278. Apl., 1931.
Harrison, J.P., "On the Survival of Racial Features in the
Population of the British Isles," Jour. Roy. Anth. Inst., vol. XII,
pp. 243-258.
Hart, Albert B. (ed.), Commonwealth History of Massachusetts.
New York, States History Co., 1927-28.
Hawley, James H., History of Idaho, vol. I. Chicago, The S.J.
Clarke Pub. Co., 1920.
Henderson, Archibald, Conquest of the Old Southwest. New
York, The Century Co., 1920.
Herodotus, History of the World.
Hewatt, An Historical Account of the Rise and Progress of the
Colonies of South Carolina and Georgia, 2 vols. London,
Alexander Donaldson, 1779.
Hirt, Herman, Die Indo-Germanen, ihre Verbreitung, ihre
Urheimat und ihre Kultur. Strassburg, Trübner, 1905.
History of Tennessee. Nashville, Goodspeed Publishing
Company, 1886.
History of Welsh in Minnesota. Hughes, Edwards & Roberts,
1895.
Hittell, Theodore H., History of California, vol. III. San Francisco,
N.J. Stone & Co., 1897.
Hodgkin, Thos., Italy and Her Invaders.
Holmes, S.J., and S.L. Parker, "The Stabilized Natural Increase of
the Negro." Journal of the Amer. Statistical Asso., June 1, 1930.
Holmes, S.J., "The Biological Trend of the Negro." Univ. of Calif.
Chronicle, Jan., 1930.
Holmes, T. Rice, Ancient Britain, and the Conquests of Julius
Cæsar. Oxford University Press, 1907.
Homer, The Iliad; the Odyssey.
Houck, Louis, A History of Missouri, vols. I, II, and III. Chicago,
R.R. Donnelley & Sons, 1908.
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebookgate.com

You might also like