100% found this document useful (2 votes)
63 views

Full download C programming from problem analysis to program design 4th ed Edition D S Malik pdf docx

The document provides links to download various programming ebooks, including 'C Programming from Problem Analysis to Program Design' by D.S. Malik, and other related titles. It includes details about the 4th edition of the C++ programming book, its content structure, and ISBN information. The document also emphasizes the availability of additional educational resources on the ebookultra.com website.

Uploaded by

corcoonuh
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
100% found this document useful (2 votes)
63 views

Full download C programming from problem analysis to program design 4th ed Edition D S Malik pdf docx

The document provides links to download various programming ebooks, including 'C Programming from Problem Analysis to Program Design' by D.S. Malik, and other related titles. It includes details about the 4th edition of the C++ programming book, its content structure, and ISBN information. The document also emphasizes the availability of additional educational resources on the ebookultra.com website.

Uploaded by

corcoonuh
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/ 73

Visit https://ebookultra.

com to download the full version and


explore more ebooks

C programming from problem analysis to program


design 4th ed Edition D S Malik

_____ Click the link below to download _____


https://ebookultra.com/download/c-programming-from-
problem-analysis-to-program-design-4th-ed-edition-d-s-
malik/

Explore and download more ebooks at ebookultra.com


Here are some suggested products you might be interested in.
Click the link to download

Java TM Programming From Problem Analysis to Program


Design 5th Edition D. S. Malik

https://ebookultra.com/download/java-tm-programming-from-problem-
analysis-to-program-design-5th-edition-d-s-malik/

Problem Solving and Program Design in C Third Edition Jeri


R. Hanly

https://ebookultra.com/download/problem-solving-and-program-design-in-
c-third-edition-jeri-r-hanly/

Introduction to Numerical Analysis 2nd Edition D. C.


Sanyal

https://ebookultra.com/download/introduction-to-numerical-
analysis-2nd-edition-d-c-sanyal/

Visual C 2010 How to Program 4th Edition 1 29 pdf Paul


Deitel

https://ebookultra.com/download/visual-c-2010-how-to-program-4th-
edition-1-29-pdf-paul-deitel/
Analysis and Design of Analog Integrated Circuits 4th ed
Edition Paul R. Gray

https://ebookultra.com/download/analysis-and-design-of-analog-
integrated-circuits-4th-ed-edition-paul-r-gray/

Programming and Problem Solving with C Comprehensive


Comprehensive Edition Nell B. Dale

https://ebookultra.com/download/programming-and-problem-solving-with-
c-comprehensive-comprehensive-edition-nell-b-dale/

C how to program Tenth Edition Deitel

https://ebookultra.com/download/c-how-to-program-tenth-edition-deitel/

Programming C 2nd ed Edition Jesse Liberty

https://ebookultra.com/download/programming-c-2nd-ed-edition-jesse-
liberty/

C Programming in Linux 1st edition Edition Haskins D.

https://ebookultra.com/download/c-programming-in-linux-1st-edition-
edition-haskins-d/
C programming from problem analysis to program
design 4th ed Edition D S Malik Digital Instant Download
Author(s): D S Malik
ISBN(s): 9781423902096, 1423902092
Edition: 4th ed
File Details: PDF, 11.47 MB
Year: 2009
Language: english
C++ PROGRAMMING:
FROM PROBLEM ANALYSIS TO PROGRAM DESIGN

FOURTH EDITION

D.S. MALIK

Australia  Brazil  Japan  Korea  Mexico  Singapore  Spain  United Kingdom  United States
C++ Programming: From Problem Analysis ª 2009 Course Technology, Cengage Learning
to Program Design, Fourth Edition
ALL RIGHTS RESERVED. No part of this work covered by the
by D.S. Malik copyright herein may be reproduced, transmitted, stored or used
Senior Product Manager: Alyssa Pratt in any form or by any means graphic, electronic, or mechanical,
including but not limited to photocopying, recording, scanning,
Acquisitions Editor: Amy Jollymore digitizing, taping, Web distribution, information networks, or
Content Product Manager: Jill Braiewa information storage and retrieval systems, except as permitted
Marketing Manager: Bryant Chrzan under Section 107 or 108 of the 1976 United States Copyright Act,
without the prior written permission of the publisher.
Editorial Assistant: Patrick Frank
Print Buyer: Julio Esperas
For product information and technology assistance, contact us at
Cover Designer: Lisa Kuhn, Curio Press, LLC Cengage Learning Customer & Sales Support, 1-800-354-9706
Compositor: Integra For permission to use material from this text or product, submit
all requests online at cengage.com/permissions
Art Director: Marissa Falco
Further permissions questions can be emailed to
Validation: Green Pen Quality Assurance permissionrequest@cengage.com
Proofreader: Green Pen Quality Assurance
Indexer: Liz Cunningham ISBN-13: 978-1-4239-0209-6
ISBN-10: 1-4239-0209-2
Course Technology
25 Thomson Place
Boston, MA 02210
USA
Visual C++ .NET and PowerPoint are registered trademarks
of the Microsoft Corporation; Pentium is a registered
trademark of Intel Corporation; IBM is a registered trademark
of Industrial Business Machines.
Disclaimer
Course Technology reserves the right to revise this publication
and make changes from time to time in its content without
notice.
The programs in this book are for instructional purposes only.
They have been tested with care, but are not guaranteed for any
particular intent beyond educational purposes. The authors and
the publisher do not offer any warranties or representations, nor
do they accept any liabilities with respect to the programs.
Cengage Learning is a leading provider of customized
learning solutions with office locations around the globe,
including Singapore, the United Kingdom, Australia, Mexico,
Brazil, and Japan. Locate your local office at:
international.cengage.com/region
Cengage Learning products are represented in Canada
by Nelson Education, Ltd.
For your lifelong learning solutions, visit
course.cengage.com
Visit our corporate website at cengage.com

Printed in Canada
1 2 3 4 5 6 7 14 13 12 11 10 09 08
TO

My Daughter

Shelly Malik
BRIEF CONTENTS

PREFACE xxvii

1. An Overview of Computers and Programming Languages 1

2. Basic Elements of C++ 29

3. Input/Output 115

4. Control Structures I (Selection) 167

5. Control Structures II (Repetition) 231

6. User-Defined Functions I 307

7. User-Defined Functions II 345

8. User-Defined Simple Data Types, Namespaces,


and the string Type 415

9. Arrays and Strings 469

10. Applications of Arrays (Searching and Sorting)


and the vector Type 545

11. Records (structs) 603

12. Classes and Data Abstraction 641

13. Inheritance and Composition 717

14. Pointers, Classes, Virtual Functions, and Abstract Classes 785

15. Overloading and Templates 853

16. Exception Handling 943

17. Recursion 981

18. Linked Lists 1017

19. Stacks and Queues 1111


vi | C++ Programming: From Problem Analysis to Program Design, Fourth Edition

APPENDIX A Reserved Words 1219

APPENDIX B Operator Precedence 1221

APPENDIX C Character Sets 1223

APPENDIX D Operator Overloading 1227

APPENDIX E Additional C++ Topics 1229

APPENDIX F Header Files 1251

APPENDIX G Memory Size on a System and Random


Number Generator 1261

APPENDIX H Standard Template Library (STL) 1263

APPENDIX I Answers to Odd-Numbered Exercises 1305

INDEX 1327
TABLE OF CONTENTS

Preface xxvii

AN OVERVIEW OF COMPUTERS
1 AND PROGRAMMING LANGUAGES 1
Introduction 2

A Brief Overview of the History of Computers 2

Elements of a Computer System 3


Hardware 4
Central Processing Unit 4
Main Memory 5
Secondary Storage 6
Input /Output Devices 6
Software 6

The Language of a Computer 6

The Evolution of Programming Languages 8

A C++ Program 10

Processing a C++ Program 12

Programming with the Problem


Analysis–Coding–Execution Cycle 14

Programming Methodologies 22
Structured Programming 22
Object-Oriented Programming 22

ANSI/ISO Standard C++ 24

Quick Review 24

Exercises 26
viii | C++ Programming: From Problem Analysis to Program Design, Fourth Edition

BASIC ELEMENTS OF C++ 29


2 The Basics of a C++ Program 30
Comments 32
Special Symbols 32
Reserved Words (Keywords) 33
Identifiers 33
Whitespaces 34

Data Types 34
Simple Data Types 35
Floating-Point Data Types 38

Arithmetic Operators and Operator Precedence 40


Order of Precedence 44

Expressions 45
Mixed Expressions 46

Type Conversion (Casting) 48

string Type 50

Input 51
Allocating Memory with Constants and Variables 52
Putting Data into Variables 54
Assignment Statement 54
Saving and Using the Value of an Expression 58
Declaring and Initializing Variables 59
Input (Read) Statement 60
Variable Initialization 63

Increment and Decrement Operators 67

Output 69

Preprocessor Directives 77
namespace and Using cin and cout in a Program 78
Using the string Data Type in a Program 78

Creating a C++ Program 79

Program Style and Form 83


Syntax 83
Use of Blanks 84
Table of Contents | ix

Use of Semicolons, Brackets, and Commas 84


Semantics 84
Naming Identifiers 84
Prompt Lines 85
Documentation 86
Form and Style 86

More on Assignment Statements 88

Programming Example: Convert Length 99

Programming Example: Make Change 93

Quick Review 97

Exercises 99

Programming Exercises 107

INPUT/OUTPUT 115
3 I/O Streams and Standard I/O Devices 116
cin and the Extraction Operator >> 117

Using Predefined Functions in a Program 123


cin and the get Function 125
cin and the ignore Function 126
The putback and peek Functions 128
The Dot Notation Between I/O Stream Variables
and I/O Functions: A Precaution 130

Input Failure 131


The clear Function 133

Output and Formatting Output 135


setprecision Manipulator 135
fixed Manipulator 136
showpoint Manipulator 136
setw 138

Additional Output Formatting Tools 141


setfill Manipulator 141
left and right Manipulators 143
Input/Output and the string Type 145
x | C++ Programming: From Problem Analysis to Program Design, Fourth Edition

File Input/Output 146

Programming Example: Movie Ticket Sale and


Donation to Charity 150

Programming Example: Student Grade 155

Quick Review 158

Exercises 160

Programming Exercises 163

CONTROL STRUCTURES I (SELECTION) 167


4 Control Structures 168

Relational Operators 169


Relational Operators and Simple Data Types 171
Comparing Floating-point Numbers for equality 171
Comparing Characters 172
Relational Operators and the string Type 173

Logical (Boolean) Operators and Logical Expressions 175


Order of Precedence 177
Short-Circuit Evaluation 181
int Data Type and Logical (Boolean) Expressions 182
bool Data Type and Logical (Boolean) Expressions 183

Selection: if and if...else 184


One-Way Selection 185
Two-Way Selection 187
Compound (Block of) Statements 191
Multiple Selections: Nested if 192
Comparing if...else Statements with
a Series of if Statements 196
Using Pseudocode to Develop, Test, and Debug a Program 196
Input Failure and the if Statement 199
Confusion Between the Equality Operator (==) and
the Assignment Operator (=) 202
Conditional Operator (?:) 203
switch Structures 204
Table of Contents | xi

Terminating a Program with the


assert Function 211

Programming Example: Cable Company Billing 213

Quick Review 219

Exercises 220

Programming Exercises 225

CONTROL STRUCTURES II (REPETITION) 231


5 Why Is Repetition Needed? 232

while Looping (Repetition) Structure 233

Designing while loops 235


Case 1: Counter-Controlled while Loops 236
Case 2: Sentinel-Controlled while Loops 239
Case 3: Flag-Controlled while Loops 243
Case 4: EOF-Controlled while Loops 247
eof Function 248
More on Expressions in while Statements 249

Programming Example: Checking


Account Balance 250

Programming Example: Fibonacci Number 259

for Looping (Repetition) Structure 264

Programming Example: Classifying Numbers 270

do...while Looping (Repetition) Structure 274

Choosing the Right Looping Structure 278

break and continue Statements 278

Nested Control Structures 281

Quick Review 288

Exercises 290

Programming Exercises 300


xii | C++ Programming: From Problem Analysis to Program Design, Fourth Edition

USER-DEFINED FUNCTIONS I 307


6 Predefined Functions 308

User-Defined Functions 311

Value-Returning Functions 312


Syntax: Value-Returning Functions 314
Syntax: Formal Parameter List 314
Function Call 314
Syntax: Actual Parameter List 314
return Statement 315
Syntax: return Statement 315
Function Prototype 318
Syntax: Function Prototype 319
Flow of Execution 325

Programming Example: Largest Number 326

Programming Example: Cable Company 327

Quick Review 333

Exercises 335

Programming Exercises 340

USER-DEFINED FUNCTIONS II 345


7 Void Functions 346
Void Functions without Parameters 346
Void Functions with Parameters 349

Value Parameters 354

Reference Variables as Parameters 356

Value and Reference Parameters and Memory Allocation 360

Reference Parameters and Value-Returning Functions 370

Scope of an Identifier 370

Global Variables, Named Constants, and Side Effects 374

Static and Automatic Variables 376


Table of Contents | xiii

Function Overloading: An Introduction 378

Functions with Default Parameters 380

Programming Example: Classify Numbers 383

Programming Example: Data Comparison 388

Quick Review 398

Exercises 400

Programming Exercises 407

USER-DEFINED SIMPLE DATA TYPES,


8 NAMESPACES, AND THE string TYPE 415
Enumeration Type 416
Declaring Variables 418
Assignment 418
Operations on Enumeration Types 419
Relational Operators 419
Input /Output of Enumeration Types 420
Functions and Enumeration Types 422
Declaring Variables When Defining the Enumeration Type 424
Anonymous Data Types 424
typedef Statement 425

Programming Example: The Game of Rock, Paper,


and Scissors 426

Namespaces 437

string Type 442


Additional string Operations 446
length Function 446
size Function 448
find Function 449
substr Function 452
swap Function 454

Programming Example: Pig Latin Strings 454


Quick Review 460
xiv | C++ Programming: From Problem Analysis to Program Design, Fourth Edition

Exercises 463

Programming Exercises 466

ARRAYS AND STRINGS 469


9 Arrays 471
Accessing Array Components 472
Processing One-Dimensional Arrays 475
Array Index Out of Bounds 479
Array Initialization During Declaration 480
Partial Initialization of Arrays During Declaration 480
Some Restrictions on Array Processing 481
Arrays as Parameters to Functions 482
Constant Arrays as Formal Parameters 483
Base Address of an Array and Array in Computer Memory 485
Functions Cannot Return a Value of the Type Array 488
Integral Data Type and Array Indices 491
Other Ways to Declare Arrays 491

C-strings (Character Arrays) 492


String Comparison 494
Reading and Writing Strings 496
String Input 496
String Output 497
Specifying Input/Output Files at Execution Time 498
string Type and Input/Output Files 498

Parallel Arrays 499

Two- and Multidimensional Arrays 500


Accessing Array Components 502
Two-Dimensional Array Initialization During Declaration 503
Two-Dimensional Arrays and Enumeration Types 503
Initialization 507
Print 507
Input 507
Sum by Row 508
Sum by Column 508
Table of Contents | xv

Largest Element in Each Row and Each Column 508


Reversing Diagonal 509
Passing Two-Dimensional Arrays as Parameters to Functions 511
Arrays of Strings 514
Arrays of Strings and the string Type 514
Arrays of Strings and C-Strings (Character Arrays) 515
Another Way to Declare a Two-Dimensional Array 516
Multidimensional Arrays 517

Programming Example: Code Detection 518

Programming Example: Text Processing 525

Quick Review 532

Exercises 534

Programming Exercises 539

APPLICATIONS OF ARRAYS (SEARCHING


10 AND SORTING) AND THE vector TYPE 545
List Processing 546
Searching 546
Bubble Sort 551
Selection Sort 555
Insertion Sort 559
Sequential Search on an Ordered List 566
Binary Search 569
Performance of Binary Search 572

vector Type (class) 574

Programming Example: Election Results 579

Quick Review 595

Exercises 597

Programming Exercises 600


xvi | C++ Programming: From Problem Analysis to Program Design, Fourth Edition

RECORDS ( struct S) 603


11 Records (structs) 604
Accessing struct Members 606
Assignment 608
Comparison (Relational Operators) 609
Input /Output 610
struct Variables and Functions 610
Arrays versus structs 611
Arrays in structs 612
structs in Arrays 614
structs within a struct 617

Programming Example: Sales Data Analysis 621

Quick Review 635

Exercises 635

Programming Exercises 637

CLASSES AND DATA ABSTRACTION 641


12 Classes 642
Unified Modeling Language Class Diagrams 645
Variable (Object) Declaration 646
Accessing Class Members 647
Built-in Operations on Classes 648
Assignment Operator and Classes 649
Class Scope 650
Functions and Classes 650
Reference Parameters and Class Objects (Variables) 650
Implementation of Member Functions 651
Accessor and Mutator Functions 656
Order of public and private Members of a Class 661
Constructors 662
Invoking a Constructor 664
Invoking the Default Constructor 664
Invoking a Constructor with Parameters 665
Constructors and Default Parameters 668
Table of Contents | xvii

Classes and Constructors: A Precaution 670


Arrays of Class Objects (Variables) and Constructors 671
Destructors 673

Data Abstraction, Classes, and Abstract Data Types 674

A struct versus a class 676

Information Hiding 677

Executable Code 681

Static Members of a Class 685

Programming Example: Candy Machine 691

Quick Review 706

Exercises 708

Programming Exercises 713

INHERITANCE AND COMPOSITION 717


13 Inheritance 718
Redefining (Overriding) Member Functions
of the Base Class 721
Constructors of Derived and Base Classes 728
Multiple Inclusions of a Header File 736
C++ Stream Classes 738
Protected Members of a Class 739
Inheritance as public, protected, or private 739

Composition 743

Object-Oriented Design (OOD) and


Object-Oriented Programming (OOP) 748
Identifying Classes, Objects, and Operations 750

Programming Example: Grade Report 751

Quick Review 772

Exercises 773

Programming Exercises 779


xviii | C++ Programming: From Problem Analysis to Program Design, Fourth Edition

POINTERS, CLASSES, VIRTUAL FUNCTIONS, AND


14 ABSTRACT CLASSES 785
Pointer Data Type and Pointer Variables 786
Declaring Pointer Variables 786

Address of Operator (&) 787

Dereferencing Operator (*) 788

Classes, Structs, and Pointer Variables 794

Initializing Pointer Variables 797

Dynamic Variables 797


Operator new 798
Operator delete 799

Operations on Pointer Variables 801

Dynamic Arrays 803


Functions and Pointers 806
Pointers and Function Return Values 806
Dynamic Two-Dimensional Arrays 807

Shallow versus Deep Copy and Pointers 810

Classes and Pointers: Some Peculiarities 812


Destructor 813
Assignment Operator 814
Copy Constructor 816

Inheritance, Pointers, and Virtual Functions 823


Classes and Virtual Destructors 830

Abstract Classes and Pure Virtual Functions 830

Address of Operator and Classes 838

Quick Review 841

Exercises 844

Programming Exercises 851


Table of Contents | xix

OVERLOADING AND TEMPLATES 853


15 Why Operator Overloading Is Needed 854

Operator Overloading 855


Syntax for Operator Functions 856
Overloading an Operator: Some Restrictions 856
Pointer this 857
Friend Functions of Classes 862
Operator Functions as Member Functions
and Nonmember Functions 865
Overloading Binary Operators 868
Overloading the Stream Insertion (<<) and
Extraction (>>) Operators 874
Overloading the Assignment Operator (=) 879
Overloading Unary Operators 887
Operator Overloading: Member versus Nonmember 893
Classes and Pointer Member Variables (Revisited) 894
Operator Overloading: One Final Word 894

Programming Example: clockType 894

Programming Example: Complex Numbers 903

Overloading the Array Index (Subscript) Operator ([]) 908

Programming Example: newString 910

Function Overloading 916

Templates 917
Function Templates 917
Class Templates 919

Quick Review 927

Exercises 929

Programming Exercises 934

EXCEPTION HANDLING 943


16 Handling Exceptions within a Program 944
C++ Mechanisms of Exception Handling 948
xx | C++ Programming: From Problem Analysis to Program Design, Fourth Edition

try/catch Block 948


Using C++ Exception Classes 955

Creating Your Own Exception Classes 959


Rethrowing and Throwing an Exception 965

Exception Handling Techniques 970


Terminate the Program 970
Fix the Error and Continue 970
Log the Error and Continue 972
Stack Unwinding 972
Quick Review 976
Exercises 978
Programming Exercises 980

RECURSION 981
17 Recursive Definitions 982
Direct and Indirect Recursion 985
Infinite Recursion 985

Problem Solving Using Recursion 986


Tower of Hanoi: Analysis 997

Recursion or Iteration? 998

Programming Example: Converting a Number from


Binary to Decimal 999

Programming Example: Converting a Number from


Decimal to Binary 1004

Quick Review 1008

Exercises 1009

Programming Exercises 1012

LINKED LISTS 1017


18 Linked Lists 1018
Linked Lists: Some Properties 1019
Building a Linked List 1028
Table of Contents | xxi

Linked List as an ADT 1032


Structure of Linked List Nodes 1034
Member Variables of the class linkedListType 1034
Linked List Iterators 1034
Print the List 1041
Length of a List 1041
Retrieve the Data of the First Node 1042
Retrieve the Data of the Last Node 1042
Begin and End 1042
Copy the List 1043
Destructor 1044
Copy Constructor 1044
Overloading the Assignment Operator 1045

Unordered Linked Lists 1045


Search the List 1046
Insert the First Node 1047
Insert the Last Node 1048
Header File of the Unordered Linked List 1053

Ordered Linked Lists 1054


Search the List 1056
Insert a Node 1056
Insert First and Insert Last 1061
Delete a Node 1062
Header File of the Ordered Linked List 1063

Print a Linked List in Reverse Order


(Recursion Revisited) 1066

Doubly Linked Lists 1069


Default Constructor 1072
isEmptyList 1072
Destroy the List 1072
Initialize the List 1073
Length of the List 1073
Print the List 1073
Reverse Print the List 1073
Search the List 1074
First and Last Elements 1074
xxii | C++ Programming: From Problem Analysis to Program Design, Fourth Edition

Circular Linked Lists 1080

Programming Example: Video Store 1081

Quick Review 1101

Exercises 1101

Programming Exercises 1105

STACKS AND QUEUES 1111


19 Stacks 1112
Stack Operations 1114

Implementation of Stacks as Arrays 1116


Initialize Stack 1119
Empty Stack 1120
Full Stack 1120
Push 1120
Return the Top Element 1122
Pop 1122
Copy Stack 1124
Constructor and Destructor 1124
Copy Constructor 1125
Overloading the Assignment Operator (=) 1125
Stack Header File 1126

Programming Example: Highest GPA 1130

Linked Implementation of Stacks 1134


Default Constructor 1137
Empty Stack and Full Stack 1138
Initialize Stack 1138
Push 1139
Return the Top Element 1141
Pop 1141
Copy Stack 1143
Constructors and Destructors 1144
Overloading the Assignment Operator (=) 1144
Table of Contents | xxiii

Stack as Derived from the


class unorderedLinkedList 1146

Application of Stacks: Postfix Expressions Calculator 1148


Main Algorithm 1153
Function evaluateExpression 1153
Function evaluateOpr 1155
Function discardExp 1157
Function printResult 1157

Removing Recursion: Nonrecursive Algorithm to Print a


Linked List Backward 1160

Queues 1167
Queue Operations 1167
Implementation of Queues as Arrays 1169
Linked Implementation of Queues 1180
Queue Derived from the class
unorderedLinkedListType 1185

Application of Queues: Simulation 1186


Designing a Queuing System 1187
Customer 1188
Server 1191
Server List 1194
Waiting Customers Queue 1199
Main Program 1201

Quick Review 1206

Exercises 1207

Programming Exercises 1213

APPENDIX A: RESERVED WORDS 1219

APPENDIX B: OPERATOR PRECEDENCE 1221

APPENDIX C: CHARACTER SETS 1223


xxiv | C++ Programming: From Problem Analysis to Program Design, Fourth Edition

ASCII (American Standard Code for


Information Interchange) 1223

EBCDIC (Extended Binary Coded Decimal


Interchange Code) 1224

APPENDIX D: OPERATOR OVERLOADING 1227

APPENDIX E: ADDITIONAL C++ TOPICS 1229


Binary (Base 2) Representation of a
Nonnegative Integer 1229
Converting a Base 10 Number to a
Binary Number (Base 2) 1229
Converting a Binary Number (Base 2) to Base 10 1231
Converting a Binary Number (Base 2) to Octal (Base 8)
and Hexadecimal (Base 16) 1232

More on File Input/Output 1234


Binary Files 1234
Random File Access 1240

Naming Conventions of Header Files in ANSI/ISO


Standard C++ and Standard C++ 1248

APPENDIX F: HEADER FILES 1251


Header File cassert (assert.h) 1251

Header File cctype (ctype.h) 1252

Header File cfloat (float.h) 1253

Header File climits (limits.h) 1254

Header File cmath (math.h) 1256


Header File cstddef (stddef.h) 1257
Header File cstring (string.h) 1257
Table of Contents | xxv

APPENDIX G: MEMORY SIZE ON A SYSTEM


AND RANDOM NUMBER GENERATOR 1261
Random Number Generator 1262

APPENDIX H: STANDARD TEMPLATE


LIBRARY (STL) 1263
Components of the STL 1263

Container Types 1264


Sequence Containers 1264
Sequence Container: Vectors 1264
Member Functions Common to All Containers 1273
Member Functions Common to Sequence Containers 1275
copy Algorithm 1276
Sequence Container: deque 1280
Sequence Container: list 1283

Iterators 1288
IOStream Iterators 1289
Container Adapters 1289

Algorithms 1293
STL Algorithm Classification 1293
STL Algorithms 1295
Functions fill and fill_n 1295
Functions find and find_if 1298
Functions remove and replace 1299
Functions search, sort, and binary_search 1301

APPENDIX I: ANSWERS TO ODD-NUMBERED


EXERCISES 1305
Chapter 1 1305

Chapter 2 1308

Chapter 3 1310

Chapter 4 1310
xxvi | C++ Programming: From Problem Analysis to Program Design, Fourth Edition

Chapter 5 1311

Chapter 6 1313

Chapter 7 1313

Chapter 8 1314

Chapter 9 1315

Chapter 10 1316

Chapter 11 1316

Chapter 12 1317

Chapter 13 1319

Chapter 14 1320

Chapter 15 1321

Chapter 16 1322

Chapter 17 1323

Chapter 18 1323

Chapter 19 1324

INDEX 1327
PREFACE

W E L C O M E T O T H E F O U R T H E D I T I O N O F C++ Programming: From Problem Analysis to


Program Design. Designed for a first Computer Science (CS1) C++ course, this text provides
a breath of fresh air to you and your students. The CS1 course serves as the cornerstone of the
Computer Science curriculum. My primary goal is to motivate and excite all CS1 students,
regardless of their level. Motivation breeds excitement for learning. Motivation and
excitement are critical factors that lead to the success of the programming student. This text
is a culmination and development of my classroom notes throughout more than fifty semesters
of teaching successful programming to Computer Science students.
C++ Programming: From Problem Analysis to Program Design started as a collection of brief
examples, exercises, and lengthy programming examples to supplement the books that were
in use at our university. It soon turned into a collection large enough to develop into a text.
The approach taken in this book is, in fact, driven by the students’ demand for clarity and readability.
The material was written and rewritten until the students felt comfortable with it. Most of the
examples in this book resulted from student interaction in the classroom.
As with any profession, practice is essential. Cooking students practice their recipes. Budding
violinists practice their scales. New programmers must practice solving problems and writing
code. This is not a C++ cookbook. We do not simply list the C++ syntax followed by an
example; we dissect the ‘‘why’’ behind all the concepts. The crucial question of ‘‘why?’’ is
answered for every topic when first introduced. This technique offers a bridge to learning
C++. Students must understand the ‘‘why?’’ in order to be motivated to learn.
Traditionally, a C++ programming neophyte needed a working knowledge of another
programming language. This book assumes no prior programming experience. However,
some adequate mathematics background, such as college algebra, is required.

Changes in the Fourth Edition


The fourth edition contains more than 20 new programming exercises in Chapters 2 to 13, and
15. Certain programming examples and programming exercises require input from a file. In the
earlier editions the input file was assumed to be stored on the floppy disk in drive A. However,
newer computers label drives differently. So in this edition, we assume that the input file is in
the same directory (subdirectory) as the project containing the source code file. Furthermore,
some parts of Chapters 1, 2, 4, and 5 are rewritten and updated. When a programming
assignment is given, typically, students are required to include the author of the program and
a brief explanation describing the purpose of the program. To emphasize this requirement,
Programming Examples in each chapter are modified by including comments showing the
author(s) of the programs and a brief explanation describing the purpose of the program.
xxviii | C++ Programming: From Problem Analysis to Program Design, Fourth Edition

Approach
The programming language C++, which evolved from C, is no longer considered an
industry-only language. Numerous colleges and universities use C++ for their first program-
ming language course. C++ is a combination of structured programming and object-oriented
programming, and this book addresses both types.
This book can be easily divided into two parts: structured programming and object-oriented
programming. The first 11 chapters form the structured programming part; Chapters 12
through 19 form the object-oriented part. However, only the first seven chapters are essential
to move on to the object-oriented portion.
In July 1998, ANSI/ISO Standard C++ was officially approved. This book focuses on ANSI/
ISO Standard C++. Even though the syntax of Standard C++ and ANSI/ISO Standard C++
is very similar, Chapter 8 discusses some of the features of ANSI/ISO Standard C++ that are
not available in Standard C++.
Chapter 1 briefly reviews the history of computers and programming languages. The reader can
quickly skim through this chapter and become familiar with some of the hardware components
and the software parts of the computer. This chapter contains a section on processing a C++
program. This chapter also describes structured and object-oriented programming.
Chapter 2 discusses the basic elements of C++. After completing this chapter, students
become familiar with the basics of C++ and are ready to write programs that are complicated
enough to do some computations. Input/output is fundamental to any programming
language. It is introduced early, in Chapter 3, and is covered in detail.
Chapters 4 and 5 introduce control structures to alter the sequential flow of execution.
Chapters 6 and 7 study user-defined functions. It is recommended that readers with no prior
programming background spend extra time on Chapters 6 and 7. Several examples are provided
to help readers understand the concepts of parameter passing and the scope of an identifier.
Chapter 8 discusses the user-defined simple data type (enumeration type), the namespace
mechanism of ANSI/ISO Standard C++, and the string type. The earlier versions of C did
not include the enumeration type. Enumeration types have very limited use; their main
purpose is to make the program readable. This book is organized such that readers can skip
the section on enumeration types during the first reading without experiencing any disconti-
nuity, and then later go through this section.
Chapter 9 discusses arrays in detail. Chapter 10 describes various searching and sorting
algorithms as well as an introduction to the vector class. Chapter 11 introduces records
(structs). The introduction of structs in this book is similar to C structs. This chapter is
optional; it is not a prerequisite for any of the remaining chapters.
Chapter 12 begins the study of object-oriented programming (OOP) and introduces classes.
The first half of this chapter shows how classes are defined and used in a program. The second
half of the chapter introduces abstract data types (ADTs). This chapter shows how classes in
C++ are a natural way to implement ADTs. Chapter 13 continues with the fundamentals of
Preface | xxix

object-oriented design (OOD) and OOP and discusses inheritance and composition. It
explains how classes in C++ provide a natural mechanism for OOD and how C++ supports
OOP. Chapter 13 also discusses how to find the objects in a given problem.
Chapter 14 studies pointers in detail. After introducing pointers and how to use them in a
program, this chapter highlights the peculiarities of classes with pointer data members and
how to avoid them. Moreover, this chapter also discusses how to create and work with
dynamic two-dimensional arrays. Chapter 14 also discusses abstract classes and a type of
polymorphism accomplished via virtual functions.
Chapter 15 continues the study of OOD and OOP. In particular, it studies polymorphism
in C++. The chapter specifically discusses two types of polymorphism—overloading and
templates.
Chapter 16 discusses exception handling in detail. Chapter 17 introduces and discusses recur-
sion. Moreover, this is a standalone chapter, so it can be studied anytime after Chapter 10.
Chapters 18 and 19 are devoted to the study of data structures. Discussed in detail are linked
lists in Chapter 18 and stacks and queues in Chapter 19. The programming code developed in
these chapters is generic. These chapters effectively use the fundamentals of OOD.
Appendix A lists the reserved words in C++. Appendix B shows the precedence and
associativity of the C++ operators. Appendix C lists the ASCII (American Standard Code
for Information Interchange) and EBCDIC (Extended Binary Coded Decimal Interchange
Code) character sets. Appendix D lists the C++ operators that can be overloaded.
Appendix E has three objectives. First, we discuss how to convert a number from decimal to
binary and binary to decimal. We then discuss binary and random access files in detail.
Finally, we describe the naming conventions of the header files in both ANSI/ISO Standard
C++ and Standard C++. Appendix F discusses some of the most widely used library
routines, and includes the names of the standard C++ header files. The programs in
Appendix G show how to print the memory size for the built-in data types on your system
as well as how to use a random number generator. Appendix H gives an introduction to
the Standard Template Library, and Appendix I provides the answers to odd-numbered
exercises in the book.
xxx | C++ Programming: From Problem Analysis to Program Design, Fourth Edition

How to Use the Book


This book can be used in various ways. Figure 1 shows the dependency of the chapters.

Chapter 1

Chapter 2

Chapter 3

Chapter 4

Chapter 5

Chapter 6

Chapter 7

Chapter 8 Chapter 9*

Chapter 10 Chapter 11 Chapter 12

Chapter 13 Chapter 14 Chapter 16

Chapter 15

Chapter 17

Chapter 18

Chapter 19

FIGURE 1 Chapter dependency diagram


Preface | xxxi

In Figure 1, dotted lines mean the preceding chapter is used in one of the sections of the
chapter and is not necessarily a prerequisite for the next chapter. For example, Chapter 9
covers arrays in detail. In Chapters 11 and 12, we show the relationship between arrays and
structs and arrays and classes, respectively. However, if Chapter 12 is studied before
Chapter 9, then the section dealing with arrays in Chapter 12 can be skipped without any
discontinuation. This particular section can be studied after studying chapter 9.
It is recommended that the first seven chapters be covered sequentially. After covering the
first seven chapters, if the reader is interested in learning OOD and OOP early, then Chapter
12 can be studied right after Chapter 7. Chapter 8 can be studied any time after Chapter 7.
After studying the first seven chapters in sequence, some of the approaches are:
1. Study chapters in the sequence: 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19.
2. Study chapters in the sequence: 9, 12, 14, 15, 13, 17, 18, 19, 10, 16.
3. Study chapters in the sequence: 12, 9, 10, 14, 15, 13, 17, 18, 19, 16.
4. Study chapters in the sequence: 12, 9, 14, 15, 13, 17, 18, 19, 10, 16.
FEATURES OF THE BOOK

Four-color
interior design
shows
accurate C++
code and
related
comments.
More than 300
visual diagrams,
both extensive
and exhaustive,
illustrate difficult
concepts.
Notes highlight important facts about
the concepts introduced in the
chapter.

Numbered examples
illustrate the key
concepts with their
relevant code. The
programming code
in these examples is
followed by a
Sample Run. An
explanation then
follows that
describes what each
line in the code
does.
Programming
Examples are
complete programs
featured in each
chapter. These
examples include the
accurate, concrete
stages of Input,
Output, Problem
Analysis and
Algorithm Design, and
a Complete Program
Listing.
Exercises further
reinforce learning
and ensure that
students have, in
fact, mastered the
material.
Programming
Exercises challenge
students to write
C++ programs with
a specified
outcome.
SUPPLEMENTAL RESOURCES

The following supplemental materials are available when this book is used in a classroom
setting.

Student Online Companion


This robust Web site, accessible at www.course.com/malik/cpp, offers students a plethora of
review and self-assessment options. Each chapter includes a Concepts Review, Chapter
Summary, Key Terms, Self-Tests, and Assignments. In addition, the Online Companion
features related Web links, source code for all chapters, and compiler tutorials.
All instructor teaching tools, outlined below, are available with this book on a single
CD-ROM.

Electronic Instructor’s Manual


The Instructor’s Manual that accompanies this textbook includes:
• Additional instructional material to assist in class preparation, including suggestions
for lecture topics.
• Solutions to all the end-of-chapter materials, including the Programming Exercises.

ExamViewÒ
This textbook is accompanied by ExamView, a powerful testing software package that allows
instructors to create and administer printed, computer (LAN-based), and Internet exams.
ExamView includes hundreds of questions that correspond to the topics covered in this
text, enabling students to generate detailed study guides that include page references for
further review. These computer-based and Internet testing components allow students to take
exams at their computers, and save the instructor time because each exam is graded auto-
matically.

PowerPoint Presentations
This book comes with Microsoft PowerPoint slides for each chapter. These are included as a
teaching aid for classroom presentations, either to make available to students on the network
for chapter review, or to be printed for classroom distribution. Instructors can add their own
slides for additional topics that they introduce to the class.
Supplemental Resources | xxxix

Distance Learning
Course Technology Cengage Learning is proud to present online courses in WebCT and
Blackboard to provide the most complete and dynamic learning experience possible. When
you add online content to one of your courses, you’re adding value to your course: Topic
Reviews, Practice Tests, Review Questions, Assignments, PowerPoint presentations, and,
most of all, a gateway to the 21st century’s most important information resource. We hope
you will make the most of your course, both online and offline. For more information on
how to bring distance learning to your course, contact your local Course Technology
Cengage Learning sales representative.

Source Code
The source code, in ANSI/ISO Standard C++, is available at www.course.com, and is also
available on the Teaching Tools CD-ROM. The input files needed to run some of the
programs are also included with the source code.

Solution Files
The solution files for all Programming Exercises, in ANSI/ISO C++, are available at
www.course.com, and are also available on the Teaching Tools CD-ROM. The input files
needed to run some of the Programming Exercises are also included with the solution files.
ACKNOWLEDGEMENTS

There are many people that I must thank who, one way or another, contributed to the success
of this book. First, I would like to thank all the students who, during the preparation, were
spontaneous in telling me if certain portions needed to be reworded for better understanding
and clearer reading. Next, I would like to thank those who e-mailed numerous comments to
improve upon the second edition. I am thankful to Professors S.C. Cheng, John N.
Mordeson, and Vasant Raval for constantly supporting this project. I must thank Lee I.
Fenicle, Director, Office of Technology Transfer, Creighton University, for his involvement,
support, and for providing encouraging words when I needed them. I am also very grateful to
the reviewers who reviewed earlier versions of this book and offered many critical suggestions
on how to improve it.
I would like to thank the reviewers of the proposal package: William Barrett, San Jose State
University; Vana Doufexi, Northwestern University; William Duncan, Louisiana State Uni-
versity; Brian Noble, University of Michigan; Kami Makki, University of Toledo; Jeanna
Matthews, Clarkson University; Patricia Smallwood, Regis University; David Topham,
Ohlone College; and Umit Uyar, City College of New York. The reviewers will recognize
that their criticisms have not been overlooked and, in fact, made this a better book. All this
would not have been possible without the careful planning of Senior Product Manager Alyssa
Pratt. I extend my sincere thanks to Alyssa, as well as to Content Project Manager Jill
Braiewa. I also thank Tintu Thomas of Integra Software Services for assisting us in keeping
the project on schedule and Green Pen Quality Assurance for carefully testing the code.
I am thankful to my parents for their blessings.
Finally, I am thankful for the support of my wife Sadhana and especially my daughter Shelly,
to whom this book is dedicated. She cheered me up whenever I was overwhelmed during the
writing of this book, and also made sure that the corrections were in place. Shelly always
draws special joy whenever I undertake such projects.
I welcome any comments concerning the text. Comments may be forwarded to the following
e-mail address: malik@creighton.edu
D. S. Malik
CHAPTER

1
A N O VERVIEW OF C OMPUTERS
AND P ROGRAMMING L ANGUAGES
IN THIS CHAPTER, YOU WILL:

n Learn about different types of computers


n Explore the hardware and software components of a computer
system
n Learn about the language of a computer
n Learn about the evolution of programming languages
n Examine high-level programming languages
n Discover what a compiler is and what it does
n Examine a C++ program
n Explore how a C++ program is processed
n Learn what an algorithm is and explore problem-solving
techniques
n Become aware of structured design and object-oriented design
programming methodologies
n Become aware of Standard C++ and ANSI/ISO Standard C++
2 | Chapter 1: An Overview of Computers and Programming Languages

Introduction
Terms such as ‘‘the Internet,’’ which were unfamiliar just 20 years are now common.
Students in elementary school regularly ‘‘surf ’’ the Internet and use computers to design
their classroom projects. Many people use the Internet to look for information and to
communicate with others. This is all made possible by the availability of different software,
also known as computer programs. Without software, a computer is useless. Software is
developed by using programming languages. The programming language C++ is especially
well suited for developing software to accomplish specific tasks. Our main objective is to help
you learn how to write programs in the C++ programming language. Before you begin
programming, it is useful to understand some of the basic terminology and different
components of a computer. We begin with an overview of the history of computers.

A Brief Overview of the History of Computers


The first device known to carry out calculations was the abacus. The abacus was invented in
Asia, but was used in ancient Babylon, China, and throughout Europe until the late middle
ages. The abacus uses a system of sliding beads in a rack for addition and subtraction. In 1642,
the French philosopher and mathematician Blaise Pascal invented the calculating device
called the Pascaline. It had eight movable dials on wheels and could calculate sums up to
eight figures long. Both the abacus and Pascaline could perform only addition and subtrac-
tion operations. Later in the 17th century, Gottfried von Leibniz invented a device that was
able to add, subtract, multiply, and divide. In 1819, Joseph Jacquard, a French weaver,
discovered that the weaving instructions for his looms could be stored on cards with holes
punched in them. While the cards moved through the loom in sequence, needles passed
through the holes and picked up threads of the correct color and texture. A weaver could
rearrange the cards and change the pattern being woven. In essence, the cards programmed a
loom to produce patterns in cloth. The weaving industry may seem to have little in common
with the computer industry. However, the idea of storing information by punching holes on
a card proved to be of great importance in the later development of computers.
In the early and mid-1800s, Charles Babbage, an English mathematician and physical
scientist, designed two calculating machines—the difference engine and the analytical
engine. The difference engine could perform complex operations such as squaring
numbers automatically. Babbage built a prototype of the difference engine, but the actual
device was never produced. The analytical engine’s design included input device, data
storage, a control unit that allowed processing instructions in any sequence, and output
devices. However, the designs remained in blueprint stage. Most of Babbage’s work is
known through the writings of his colleague Ada Augusta, Countess of Lovelace. Augusta
is considered the first computer programmer.
At the end of the 19th century, U.S. Census officials needed help in accurately tabulating
the census data. Herman Hollerith invented a calculating machine that ran on electricity
and used punched cards to store data. Hollerith’s machine was immensely successful.
Hollerith founded the Tabulating Machine Company, which later became the computer
and technology corporation known as IBM.
Elements of a Computer System | 3

The first computer-like machine was the Mark I. It was built, in 1944, jointly by IBM and
Harvard University under the leadership of Howard Aiken. Punched cards were used to feed 1
data into the machine. The Mark I was 52 feet long, weighed 50 tons, and had 750,000 parts.
In 1946, the ENIAC (Electronic Numerical Integrator and Calculator) was built at the
University of Pennsylvania. It contained 18,000 vacuum tubes and weighed some 30 tons.
The computers that we know today use the design rules given by John von Neumann in
the late 1940s. His design included components such as an arithmetic logic unit, a control
unit, memory, and input/output devices. These components are described in the next
section. Von Neumann’s computer design makes it possible to store the programming
instructions and the data in same memory space. In 1951, the UNIVAC (Universal
Automatic Computer) was built and sold to the U.S. Census Bureau.
In 1956, the invention of transistors resulted in smaller, faster, more reliable, and more
energy-efficient computers. This era also saw the emergence of the software development
industry with the introduction of FORTRAN and COBOL, two early programming
languages. In the next major technological advancement, transistors were replaced by tiny
integrated circuits or ‘‘chips.’’ Chips are smaller and cheaper than transistors and can contain
thousands of circuits on a single chip. They give computers tremendous processing speed.
In 1970, the microprocessor, an entire CPU on a single chip, was invented. In 1977,
Stephen Wozniak and Steven Jobs designed and built the first Apple computer in their
garage. In 1981, IBM introduced its personal computer (PC). In the 1980s, clones of the
IBM PC made the personal computer even more affordable. By the mid-1990s, people
from many walks of life were able to afford them. Computers continue to become faster
and less expensive as technology advances.
Modern-day computers are powerful, reliable, and easy to use. They can accept spoken-word
instructions and imitate human reasoning through artificial intelligence. Expert systems assist
doctors in making diagnoses. Mobile computing applications are growing significantly. Using
hand held devices, delivery drivers can access global positioning satellites (GPS) to verify
customer locations for pickups and deliveries. Cell phones permit you to check your e-mail,
make airline reservations, see how stocks are performing, and access your bank accounts.
Although there are several categories of computers, such as mainframe, midsize, and
micro, all computers share some basic elements, described in the next section.

Elements of a Computer System


A computer is an electronic device capable of performing commands. The basic commands
that a computer performs are input (get data), output (display result), storage, and perfor-
mance of arithmetic and logical operations.
In today’s market, personal computers are sold with descriptions such as a Pentium 4
Processor 2.80 GHz, 1 GB RAM, 250 GB HD, VX750 19" Silver Flat CRT Color
Monitor, preloaded with software such as an operating system, games, encyclopedias, and
application software such as word processors or money management programs. These
descriptions represent two categories: hardware and software. Items such as ‘‘Pentium 4
4 | Chapter 1: An Overview of Computers and Programming Languages

Processor 2.80 GHz, 1GB RAM, 250GB HD, VX750 19" Silver Flat CRT Color Monitor’’
fall into the hardware category; items such as ‘‘operating system, games, encyclopedias, and
application software’’ fall into the software category. Let’s consider the hardware first.

Hardware
Major hardware components include the central processing unit (CPU); main memory
(MM), also called random access memory (RAM); input/output devices; and secondary
storage. Some examples of input devices are the keyboard, mouse, and secondary storage.
Examples of output devices are the screen, printer, and secondary storage. Let’s look at
each of these components in more detail.

Central Processing Unit


The central processing unit (CPU) is the brain of the computer and the single most
expensive piece of hardware in a personal computer. The more powerful the CPU, the faster
the computer. The main components of the CPU are the control unit (CU), arithmetic logic
unit (ALU), and registers. Figure 1-1 shows how certain components of the CPU fit
together.

Central Processing Unit (CPU)


Control Unit (CU)

Instruction Register (IR) Input Device


Program Counter (PC)

Output Device

Arithmetic Logic Unit (ALU)

Main Memory

Secondary Storage

FIGURE 1-1 Hardware components of a computer


Elements of a Computer System | 5

The CPU components shown in Figure 1-1 work as follows:


• The control unit (CU) has three main functions: fetch and decode the
1
instructions, control the flow of information (instructions or data) in and out
of main memory, and control the operation of the CPU’s internal components.
• The arithmetic logic unit (ALU) carries out all arithmetic and logical
operations.
• The CPU contains various registers. Some of these registers are for
special purposes. For example, the instruction register (IR) holds the
instruction currently being executed. The program counter (PC)
points to the next instruction to be executed. All registers provide
temporary storage. The number of registers in the CPU is small.

Main Memory
The main memory is directly connected to the CPU. All programs must be loaded into
main memory before they can be executed. Similarly, all data must be brought into main
memory before a program can manipulate it. When the computer is turned off, every-
thing in main memory is lost for good.
The main memory is an ordered sequence of cells, called memory cells. Each cell has a
unique location in main memory, called the address of the cell. These addresses help you
access the information stored in the cell. Figure 1-2 shows main memory with storage cells.

. .
. .
. .
1000 54
1001 A
. .
. .
. .
2000
2001
. .
. .
. .

FIGURE 1-2 Main memory with some data

Today’s computers come with main memory consisting of millions to billions of cells.
Although Figure 1-2 shows data stored in cells, the content of a cell can be either a
programming instruction or data. Moreover, this figure shows the data as numbers and
letters. However, as explained later in this chapter, main memory stores everything as
sequences of 0s and 1s. The memory addresses also are expressed as sequences of 0s and 1s.
Another Random Scribd Document
with Unrelated Content
Mantin, L.
Marshall, Elias J.
Marshall, Hugh Lewis
Marshall, John, Jr.
Marshall, Joseph Taylor
Marshall, Samuel B.
Mather, Elisha
Maurry, James
McCrocklin, Jesse Lindsey
McFaddin, Nathaniel A.
McFadin, William M.
McFall, Samuel
McGown, Samuel
McIntire, William
McLaughlin, James
McLaughlin, William
McMaster, William
McMillan, Andrew
McMillan, James
McNutt, Robert
Means, William
Merritt, Robert
Moore, Azariah G.
Moore, John D.
Moore, Lewis
Moore, Morris
Morris, Burrel
Morris, George
Morris, James H.
Morris, Spencer
Newton, John
Norment, Thomas

Owen, James D.

Page, Soloman Calvin


Parker, Wiley
Peebles, Richard Rodgers
Pennington, J. M.
Perry, Sion W.
Perry, William M.
Pettus, William
Pevehouse, Preston
Pier, James B.
Pleasants, George Washington
Polk, Thomas
Polk, William P.
Potts, R.
Prewitt, Elisha
Price, Hardy William Brown
Price, Perry
Price, Robert
Price, William

Rankin, David
Raper, Daniel
Reamos, Sherwood Y.
Rhodes, John B.
Rhorer, Conrad
Ricks, George Washington
Robbins, Early
Roberts, Stephen R.
Robertson, Sterling Clack
Robinett, Enoch
Robinett, James M.
Robinson, Benjamin W.
Robinson, James
Rowlett, Alexander W.

Scaggs, John H.
Scott, Robert
Seaton, George Washington
Sharp, John
Simpson, Jeremiah W.
Smith, John G.
Smith, William A.
Smith, William P.
Smith, William W.
Snodgrass, J. G.
Splane, Peyton R.
Splane, Thomas M.
Stephens, John
Stevenson, Thomas B.
Swoap, Benjamin Franklin

Taylor, Josiah
Teal, Henry
Thompson, Thomas
Tinnett, Robert
Tollett, Wesley
Tong, John B.
Townsend, Moses
Townsend, P. John
Townsend, Stephen
Townsend, William

Vardeman, Henry W.
Varner, Martin
Vaughan, Richard

Walker, John
Walker, Josiah
Walling, John C.
Whitehead, Nicholas
Whitlock, Robert
Wilburn, Ransom
Williams, Edward
Williams, Hezekiah, Sr.
Williams, Jesse
Winnett, Robert
Winters, Agabus
Wood, William Riley
Woods, Joseph H.
Wright, Gilbert

Yarborough, Joseph Randolph

Zuber, William Physick


ACKNOWLEDGMENTS

Frontispiece “Battle of San Jacinto” is a photograph of a painting by


Henry A. McArdle.

Sam Houston’s picture is a photograph by Elwood M. Payne, of an


etching made from a daguerreotype in the San Jacinto Museum of
History.

Mr. Payne also photographed the base of the monument, showing the
inscriptions.

Picture of Santa Anna is a photograph by Paul Peters of a


daguerreotype in the Museum.

The photographs of the Brigham monument and the Santa Anna


surrender marker also are by Paul Peters.

The surrender of Santa Anna is a photograph by Harry Pennington,


Jr., of a painting by W. H. Huddle.

The map showing the route of Sam Houston’s army was drawn by L.
W. Kemp. Map of San Jacinto battleground by Ed Kilman.

44
Bronze armillary sun dial erected on the battlefield in memory of the
nine Texans killed or mortally wounded at San Jacinto.

The dial, wrought by Julian Muench, measures twenty-five feet in


circumference. It was constructed with funds raised by the Daughters
of the Republic of Texas and the Texas Veterans association and was
dedicated April 21, 1940.
Footnotes

[1]
This plantation belonging to Groce has been confused by the
historian John Henry Brown, and perhaps others, with another
plantation he owned which was situated in the present county of
Grimes, and known as “Groce’s Retreat.”

[2]
Thomas J. Rusk, Secretary of War, and other Texans who were in
the battle said the battle cry was “Remember the Alamo!”
“Remember La Bahia!”

[3]
With “Deaf” Smith in the detail that destroyed the bridge were
Young P. Alsbury, John Coker, John Garner, Moses Lapham. Edwin
R. Rainwater and Dimer W. Reaves.

[4]
In his official report of the battle, April 25, 1836, Houston said 783
Texans took part. Yet in a roster published later he listed 845
officers and men at San Jacinto, and by oversight omitted Captain
Alfred H. Wyly’s Company. In a Senate speech February 28, 1859,
Houston said his effective force never exceeded 700 at any point.
Conclusive evidence in official records brings the total number at
San Jacinto up to 910.

[5]
Several veterans of the battle said the tune played was “Yankee
Doodle.”
[6]
With Sylvester in the capture of Santa Anna were Joel W. Robison,
Joseph D. Vermillion, Alfred H. Miles and David Cole.
Transcriber’s Notes
Retained publication information from the printed edition: this
eBook is public-domain in the country of publication.
Silently corrected a few palpable typos.
In the text versions only, text in italics is delimited by
_underscores_.
*** END OF THE PROJECT GUTENBERG EBOOK THE BATTLE OF
SAN JACINTO AND THE SAN JACINTO CAMPAIGN ***

Updated editions will replace the previous one—the old editions


will be renamed.

Creating the works from print editions not protected by U.S.


copyright law means that no one owns a United States
copyright in these works, so the Foundation (and you!) can copy
and distribute it in the United States without permission and
without paying copyright royalties. Special rules, set forth in the
General Terms of Use part of this license, apply to copying and
distributing Project Gutenberg™ electronic works to protect the
PROJECT GUTENBERG™ concept and trademark. Project
Gutenberg is a registered trademark, and may not be used if
you charge for an eBook, except by following the terms of the
trademark license, including paying royalties for use of the
Project Gutenberg trademark. If you do not charge anything for
copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such
as creation of derivative works, reports, performances and
research. Project Gutenberg eBooks may be modified and
printed and given away—you may do practically ANYTHING in
the United States with eBooks not protected by U.S. copyright
law. Redistribution is subject to the trademark license, especially
commercial redistribution.

START: FULL LICENSE


THE FULL PROJECT GUTENBERG LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK

To protect the Project Gutenberg™ mission of promoting the


free distribution of electronic works, by using or distributing this
work (or any other work associated in any way with the phrase
“Project Gutenberg”), you agree to comply with all the terms of
the Full Project Gutenberg™ License available with this file or
online at www.gutenberg.org/license.

Section 1. General Terms of Use and


Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand,
agree to and accept all the terms of this license and intellectual
property (trademark/copyright) agreement. If you do not agree
to abide by all the terms of this agreement, you must cease
using and return or destroy all copies of Project Gutenberg™
electronic works in your possession. If you paid a fee for
obtaining a copy of or access to a Project Gutenberg™
electronic work and you do not agree to be bound by the terms
of this agreement, you may obtain a refund from the person or
entity to whom you paid the fee as set forth in paragraph 1.E.8.

1.B. “Project Gutenberg” is a registered trademark. It may only


be used on or associated in any way with an electronic work by
people who agree to be bound by the terms of this agreement.
There are a few things that you can do with most Project
Gutenberg™ electronic works even without complying with the
full terms of this agreement. See paragraph 1.C below. There
are a lot of things you can do with Project Gutenberg™
electronic works if you follow the terms of this agreement and
help preserve free future access to Project Gutenberg™
electronic works. See paragraph 1.E below.
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright
law in the United States and you are located in the United
States, we do not claim a right to prevent you from copying,
distributing, performing, displaying or creating derivative works
based on the work as long as all references to Project
Gutenberg are removed. Of course, we hope that you will
support the Project Gutenberg™ mission of promoting free
access to electronic works by freely sharing Project Gutenberg™
works in compliance with the terms of this agreement for
keeping the Project Gutenberg™ name associated with the
work. You can easily comply with the terms of this agreement
by keeping this work in the same format with its attached full
Project Gutenberg™ License when you share it without charge
with others.

1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside
the United States, check the laws of your country in addition to
the terms of this agreement before downloading, copying,
displaying, performing, distributing or creating derivative works
based on this work or any other Project Gutenberg™ work. The
Foundation makes no representations concerning the copyright
status of any work in any country other than the United States.

1.E. Unless you have removed all references to Project


Gutenberg:

1.E.1. The following sentence, with active links to, or other


immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project
Gutenberg™ work (any work on which the phrase “Project
Gutenberg” appears, or with which the phrase “Project
Gutenberg” is associated) is accessed, displayed, performed,
viewed, copied or distributed:

This eBook is for the use of anyone anywhere in the United


States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it
away or re-use it under the terms of the Project Gutenberg
License included with this eBook or online at
www.gutenberg.org. If you are not located in the United
States, you will have to check the laws of the country where
you are located before using this eBook.

1.E.2. If an individual Project Gutenberg™ electronic work is


derived from texts not protected by U.S. copyright law (does not
contain a notice indicating that it is posted with permission of
the copyright holder), the work can be copied and distributed to
anyone in the United States without paying any fees or charges.
If you are redistributing or providing access to a work with the
phrase “Project Gutenberg” associated with or appearing on the
work, you must comply either with the requirements of
paragraphs 1.E.1 through 1.E.7 or obtain permission for the use
of the work and the Project Gutenberg™ trademark as set forth
in paragraphs 1.E.8 or 1.E.9.

1.E.3. If an individual Project Gutenberg™ electronic work is


posted with the permission of the copyright holder, your use and
distribution must comply with both paragraphs 1.E.1 through
1.E.7 and any additional terms imposed by the copyright holder.
Additional terms will be linked to the Project Gutenberg™
License for all works posted with the permission of the copyright
holder found at the beginning of this work.

1.E.4. Do not unlink or detach or remove the full Project


Gutenberg™ License terms from this work, or any files
containing a part of this work or any other work associated with
Project Gutenberg™.

1.E.5. Do not copy, display, perform, distribute or redistribute


this electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1
with active links or immediate access to the full terms of the
Project Gutenberg™ License.

1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if
you provide access to or distribute copies of a Project
Gutenberg™ work in a format other than “Plain Vanilla ASCII” or
other format used in the official version posted on the official
Project Gutenberg™ website (www.gutenberg.org), you must,
at no additional cost, fee or expense to the user, provide a copy,
a means of exporting a copy, or a means of obtaining a copy
upon request, of the work in its original “Plain Vanilla ASCII” or
other form. Any alternate format must include the full Project
Gutenberg™ License as specified in paragraph 1.E.1.

1.E.7. Do not charge a fee for access to, viewing, displaying,


performing, copying or distributing any Project Gutenberg™
works unless you comply with paragraph 1.E.8 or 1.E.9.

1.E.8. You may charge a reasonable fee for copies of or


providing access to or distributing Project Gutenberg™
electronic works provided that:

• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”

• You provide a full refund of any money paid by a user who


notifies you in writing (or by e-mail) within 30 days of receipt
that s/he does not agree to the terms of the full Project
Gutenberg™ License. You must require such a user to return or
destroy all copies of the works possessed in a physical medium
and discontinue all use of and all access to other copies of
Project Gutenberg™ works.

• You provide, in accordance with paragraph 1.F.3, a full refund of


any money paid for a work or a replacement copy, if a defect in
the electronic work is discovered and reported to you within 90
days of receipt of the work.

• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.

1.E.9. If you wish to charge a fee or distribute a Project


Gutenberg™ electronic work or group of works on different
terms than are set forth in this agreement, you must obtain
permission in writing from the Project Gutenberg Literary
Archive Foundation, the manager of the Project Gutenberg™
trademark. Contact the Foundation as set forth in Section 3
below.

1.F.

1.F.1. Project Gutenberg volunteers and employees expend


considerable effort to identify, do copyright research on,
transcribe and proofread works not protected by U.S. copyright
law in creating the Project Gutenberg™ collection. Despite these
efforts, Project Gutenberg™ electronic works, and the medium
on which they may be stored, may contain “Defects,” such as,
but not limited to, incomplete, inaccurate or corrupt data,
transcription errors, a copyright or other intellectual property
infringement, a defective or damaged disk or other medium, a
computer virus, or computer codes that damage or cannot be
read by your equipment.

1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except


for the “Right of Replacement or Refund” described in
paragraph 1.F.3, the Project Gutenberg Literary Archive
Foundation, the owner of the Project Gutenberg™ trademark,
and any other party distributing a Project Gutenberg™ electronic
work under this agreement, disclaim all liability to you for
damages, costs and expenses, including legal fees. YOU AGREE
THAT YOU HAVE NO REMEDIES FOR NEGLIGENCE, STRICT
LIABILITY, BREACH OF WARRANTY OR BREACH OF CONTRACT
EXCEPT THOSE PROVIDED IN PARAGRAPH 1.F.3. YOU AGREE
THAT THE FOUNDATION, THE TRADEMARK OWNER, AND ANY
DISTRIBUTOR UNDER THIS AGREEMENT WILL NOT BE LIABLE
TO YOU FOR ACTUAL, DIRECT, INDIRECT, CONSEQUENTIAL,
PUNITIVE OR INCIDENTAL DAMAGES EVEN IF YOU GIVE
NOTICE OF THE POSSIBILITY OF SUCH DAMAGE.

1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you


discover a defect in this electronic work within 90 days of
receiving it, you can receive a refund of the money (if any) you
paid for it by sending a written explanation to the person you
received the work from. If you received the work on a physical
medium, you must return the medium with your written
explanation. The person or entity that provided you with the
defective work may elect to provide a replacement copy in lieu
of a refund. If you received the work electronically, the person
or entity providing it to you may choose to give you a second
opportunity to receive the work electronically in lieu of a refund.
If the second copy is also defective, you may demand a refund
in writing without further opportunities to fix the problem.

1.F.4. Except for the limited right of replacement or refund set


forth in paragraph 1.F.3, this work is provided to you ‘AS-IS’,
WITH NO OTHER WARRANTIES OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.

1.F.5. Some states do not allow disclaimers of certain implied


warranties or the exclusion or limitation of certain types of
damages. If any disclaimer or limitation set forth in this
agreement violates the law of the state applicable to this
agreement, the agreement shall be interpreted to make the
maximum disclaimer or limitation permitted by the applicable
state law. The invalidity or unenforceability of any provision of
this agreement shall not void the remaining provisions.

1.F.6. INDEMNITY - You agree to indemnify and hold the


Foundation, the trademark owner, any agent or employee of the
Foundation, anyone providing copies of Project Gutenberg™
electronic works in accordance with this agreement, and any
volunteers associated with the production, promotion and
distribution of Project Gutenberg™ electronic works, harmless
from all liability, costs and expenses, including legal fees, that
arise directly or indirectly from any of the following which you
do or cause to occur: (a) distribution of this or any Project
Gutenberg™ work, (b) alteration, modification, or additions or
deletions to any Project Gutenberg™ work, and (c) any Defect
you cause.

Section 2. Information about the Mission


of Project Gutenberg™
Project Gutenberg™ is synonymous with the free distribution of
electronic works in formats readable by the widest variety of
computers including obsolete, old, middle-aged and new
computers. It exists because of the efforts of hundreds of
volunteers and donations from people in all walks of life.

Volunteers and financial support to provide volunteers with the


assistance they need are critical to reaching Project
Gutenberg™’s goals and ensuring that the Project Gutenberg™
collection will remain freely available for generations to come. In
2001, the Project Gutenberg Literary Archive Foundation was
created to provide a secure and permanent future for Project
Gutenberg™ and future generations. To learn more about the
Project Gutenberg Literary Archive Foundation and how your
efforts and donations can help, see Sections 3 and 4 and the
Foundation information page at www.gutenberg.org.

Section 3. Information about the Project


Gutenberg Literary Archive Foundation
The Project Gutenberg Literary Archive Foundation is a non-
profit 501(c)(3) educational corporation organized under the
laws of the state of Mississippi and granted tax exempt status
by the Internal Revenue Service. The Foundation’s EIN or
federal tax identification number is 64-6221541. Contributions
to the Project Gutenberg Literary Archive Foundation are tax
deductible to the full extent permitted by U.S. federal laws and
your state’s laws.

The Foundation’s business office is located at 809 North 1500


West, Salt Lake City, UT 84116, (801) 596-1887. Email contact
links and up to date contact information can be found at the
Foundation’s website and official page at
www.gutenberg.org/contact
Section 4. Information about Donations to
the Project Gutenberg Literary Archive
Foundation
Project Gutenberg™ depends upon and cannot survive without
widespread public support and donations to carry out its mission
of increasing the number of public domain and licensed works
that can be freely distributed in machine-readable form
accessible by the widest array of equipment including outdated
equipment. Many small donations ($1 to $5,000) are particularly
important to maintaining tax exempt status with the IRS.

The Foundation is committed to complying with the laws


regulating charities and charitable donations in all 50 states of
the United States. Compliance requirements are not uniform
and it takes a considerable effort, much paperwork and many
fees to meet and keep up with these requirements. We do not
solicit donations in locations where we have not received written
confirmation of compliance. To SEND DONATIONS or determine
the status of compliance for any particular state visit
www.gutenberg.org/donate.

While we cannot and do not solicit contributions from states


where we have not met the solicitation requirements, we know
of no prohibition against accepting unsolicited donations from
donors in such states who approach us with offers to donate.

International donations are gratefully accepted, but we cannot


make any statements concerning tax treatment of donations
received from outside the United States. U.S. laws alone swamp
our small staff.

Please check the Project Gutenberg web pages for current


donation methods and addresses. Donations are accepted in a
number of other ways including checks, online payments and
credit card donations. To donate, please visit:
www.gutenberg.org/donate.

Section 5. General Information About


Project Gutenberg™ electronic works
Professor Michael S. Hart was the originator of the Project
Gutenberg™ concept of a library of electronic works that could
be freely shared with anyone. For forty years, he produced and
distributed Project Gutenberg™ eBooks with only a loose
network of volunteer support.

Project Gutenberg™ eBooks are often created from several


printed editions, all of which are confirmed as not protected by
copyright in the U.S. unless a copyright notice is included. Thus,
we do not necessarily keep eBooks in compliance with any
particular paper edition.

Most people start at our website which has the main PG search
facility: www.gutenberg.org.

This website includes information about Project Gutenberg™,


including how to make donations to the Project Gutenberg
Literary Archive Foundation, how to help produce our new
eBooks, and how to subscribe to our email newsletter to hear
about new eBooks.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookultra.com

You might also like