Starting Out with C++: From Control Structures through Objects [6 ed.] 9780321545886, 0321545885, 2008008001


306 88 177MB

English Pages [1249]

Report DMCA / Copyright

DOWNLOAD PDF FILE

Table of contents :
Contents at a Glance
Contents
Preface
Chapter 1 - Introduction to Computers and Programming
Chapter 2 - Introduction to C++
2.1 The Parts of a C++ Program
2.2 The cout Object
2.3 The #include Directive
2.4 Variables and Literals
Sometimes a Number Isn't a Number
Literals
2.5 Identifiers
Legal Identifiers
2.6 Integer Data Types
Integer and Long Integer Literals
If You Plan to Continue in Computer Science: Hexadecimal and Octal Literals
2.7 The char Data Type
Character Literals
2.8 Floating-Point Data Types
Floating Point Literals
Assigning Floating-Point Values to Integer Variables
2.9 The bool Data Type
2.10 Determining the Size of a Data Type
2.11 Variable Assignments and Initialization
2.12 Scope
2.13 Arithmetic Operators
2.14 Comments
Single-line Comments
Multi-Line Comments
2.15 Focus on Software Engineering: Programming Style
2.16 If You Plan to Continue in Computer Science:Standard and Prestandard C++
Older Style Header Files
Absence of using namespace std;
An Older Style Program
Review Questions and Exercises
Short Answer
Multiple Choice
True or False
Algorithm Workbench
Find the Error
Programming Challenges
Serendipity Booksellers Software Development ProjectPart2: A Problem-Solving Exercise
Chapter 3 - Expressions and Interactivity
Chapter 4 - Making Decisions
4.1 Relational Operators
The Value of a Relationship
What Is Truth?
4.2 The if Statement
Be Careful with Semicolons
Programming Style and the if Statement
Comparing Floating-Point Numbers
And Now Back to Truth
Don't Confuse == With =
4.3 Flags
Integer Flags
4.4Expanding the if Statement
Don't forget the Braces!
4.5 The if/else Statement
4.6 Nested if Statements
Programming Style and Nested Decision Structures
Testing a Series of Conditions
4.7 The if/else if Statement
Using the Trailing else To Catch Errors
The if/else i f Statement Compared to a Nested Decision Structure
4.8 Menus
4.9 Logical Operators
The && Operator
The || Operator
The ! Operator
Precedence and Associativity of Logical Operators
4.10 Checking Numeric Ranges with Logical Operators
4.11 Focus on Software Engineering: Validating User Input
4.12 More About Variable Definitions and Scope
Variables with the Same Name
4.13 Comparing Strings
The strcmp Function
Using ! with strcmp
Sorting Strings
4.14 The Conditional Operator
Using the Value of a Conditional Expression
4.15 The switch Statement
Using switch in Menu Systems
4.16 Testing for File Open Errors
Review Questions and Exercises
Short Answer
Fill-in-the-Blank
Algorithm Workbench
True or False
Find the Errors
Programming Challenges
Serendipity Booksellers Software Development ProJect Part4: A Problem-Solving Exercise
Chapter 5 - Looping
5.1 The Increment and Decrement Operators
5.2 Introduction to Loops: The while Loop
5.3 Using the while Loop for Input Validation
5.4 Counters
5.5 The do-while Loop
5.6 The for Loop
The for Loop Is a Pretest Loop
Omitting the for Loop's Expressions
Avoid Modifying the Counter Variablein the Body of the for Loop
5.7 Keeping a Running Total
5.8 Sentinels
Figure 5-12 Logic for calculating a running total
5.9 Using a Loop to Read Data from a File
5.10 Focus on Software Engineering:Deciding Which Loop to Use
5.11 Nested Loops
5.12 Breaking Out of a Loop
Using break in a Nested Loop
5.13 The continue Statement
Review Questions and Exercises
Short Answer
Fill-in-the-Blank
Algorithm Workbench
True or False
Find the Errors
Programming Challenges
Serendipity Booksellers Software Development ProjectPartS: A Problem-Solving Exercise
Chapter 6 - Functions
6.1 Focus on Software Engineering: Modular Programming
6.2 Defining and Calling Functions
void Functions
Calling a Function
6.3 Function Prototypes
6.4 Sending Data into a Function
6.5 Passing Data by Value
6.6 Focus on Software Engineering: Using Functionsin a Menu-Driven Program
6.7 The return Statement
6.8 Returning a Value from a Function
Defining a Value-Returning Function
Calling a Value-Returning Function
6.9 Returning a Boolean Value
6.10 Local and Global Variables
Local Variables
Local Variable Lifetime
Initializing Local Variables with Parameter Values
Global Variables and Global Constants
Local and Global Variables with the Same Name
6.11 Static Local Variables
6.12 Default Arguments
6.13 Using Reference Variables as Parameters
6.14 Overloading Functions
6.15 The exit() Function
6.16 Stubs and Drivers
Review Questions and Exercises
Programming Challenges
Serendipity Booksellers Software Development ProjectPart6: A Problem-Solving Exercise
Chapter 7 - Arrays
7.1 Arrays Hold Multiple Values
Memory Requirements of Arrays
7.6 Focus on Software Engineering:Using Parallel Arrays
7.7 Arrays as Function Arguments
Some Useful Array Functions
7.8 Two-Dimensional Arrays
Passing Two-Dimensional Arrays to Functions
Summing All the Elements of a Two-Dlmemlonal Array
Summing the Rows of a Two-Dimensional Array
Summing the Columns of a Two-Dimensional Array
7.9 Arrays of Strings
Chapter 8 - Searching and Sorting Arrays
Chapter 9 - Pointers
Chapter 10 - Characters, Strings, and the string Class
Chapter 11 - Structured Data
Chapter 12 - Advanced File Operations
Chapter 13 - Introduction to Classes
Recommend Papers

Starting Out with C++: From Control Structures through Objects [6 ed.]
 9780321545886, 0321545885, 2008008001

  • 0 0 0
  • Like this paper and download? You can publish your own PDF file online for free in a few minutes! Sign Up
File loading please wait...
Citation preview

START~

NG OUT WITH Fr,o m Contr,o t Structures, through Objoects sixth edition

c++ Quick Reference c++ Data Types Data Type char unsigned char

Commonly Used Operators As signment Operators

Description

=

CbanK::ter

Assignment Combined addition/assignment Combined su btraction/assignment Combined multiplication/assignment Combined di vision/assignment Combined modulus/assignment

+..

Unsigned Character Integer

int Short integer short int short Same as short int unsigned short int Unsigned shon integer unsigned short Same as unsigned short int unsigned int Unsigned integer unsigned Same as unsigned int long i nt Long integer Same as long int long unsigned long int Unsigned long integer Sarneas unsigned long int unsigned long float Single precision floating point double precision floating point double long double Long double precision floating point

- ". *'"

1''''

Arithmetic Operators +

Addition Subtraction Multiplication Division Modulus (remainder)

..

1 %

Relational Operators
'" -!;-

Logical Operators AND

Ii Ii

II

OR

I

NOT

Increment/Decrement

Forms of the 1f Statement Simple if i f (expression) statement; if/else i f ( expression)

++

Example i f (x < y) x++;

Conditional Operator 7:

For-m:

Example

expression ? expression ; expression Example:

i f (x < y)

x++;

,statement; else

lncrement Decrement

x '" a < b ? a : b; The sratement above works like:

else

statement;

if(3t.

Video Notes

A se ries of on[me videos, developed specifically for this book, are availab[e for viewing at http : //www.aw.com/gaddis/ videonotes. Icons appear throughout the text alerring the student to videos about specific tOpics.

Checkpoints

Checkpoints are questions placed throughout each chapter as a self-test STUd y aid. Answers fat a[ 1 Checkpoint questions a re provided on the student CD so students can check how well they have learned a new topic.

Notes

Notes appear at appropriate places throughout the text. They are short explanations of interesting or often misunderstood points relevam to rhe topic at hand.

Warnings

Warnings are notcs that caution the studcnt about certain C++ features, programming techniques, or practices that can lead to malfunctioning programs or lost data.

Preface

Case Studies

Case studies that simulate real-world applications appear in many chapters throughout the rext, with complete code provided for each one on the student CD. These case studies are designed to highlight the major wpics of the chapter in which they appear.

Review Questions and Exercises

Each chapter presents a thorough and diverse set of review questions, such as fill-in-the-blank and short answer, that check the student's mastery of the basic material presented in the chapter. These are followed by exercises requiring problem solving and analysis, such as the Algorithm Workbench, Predict the Output, and Find the Errors sections. Answers to the odd numbered review questions and review exercises are provided on the student CD.

Programming Challenges

Each chapter offers a pool of programming exerc ises designed to solidify the student's know ledge of the topics currently being studied. In most cases the assignments present real-world problems to be solved. When applicable, these exe rcises inclu de input validation rules.

Group Projects

There are several group programming projects throughout the text, intended to be constructed by a team of students. One student might build the program's user inte rface, while another student writes the mathemat ical code, and another designs and implemems a class the program uses. This process is similar (Q the way many professional programs are written and encourages team work within the classroom.

Software Development Project: Serendipity Booksellers

T his is an on-going project that instructors can optiona lly assign to teams of students. It systematically develops a "real-world" softwa re package: a point-of-sale program for t he fic tlrious Serendipity Bookse llers organization. The Serendipity assignment for each chapter adds more func tionality ro the software, using constructs and techniques covered in that chapter. When complete, the program will act as a cash register, manage an invemory darabase, and prod uce a variety of reports.

C++ Quick Reference Guide

Fo r easy access, a quick reference guide to the C++ language is printed on the la st page of the book and the ins ide back cover.

xxi

x x ii

Preface

Supplements Student CD This CD includes: •

Borland Turbo c++ Explorer Edition



Answers co all Checkpoint questions (Appendix N)



Answers



Complete source codc for every program included in rhe book



Additional case studies, complete with source code



A full set of appendices (including several tu(Onals) that accompany the book

(0

all odd-numbered Review Questions and Exercises (Appendix 0)

If a CD did not come with your book or you can't locare your CD, you can access most of these items at http : //www . aw.com/cssupport/

Other CDs Upon Request Professors should cOntact their campus Addison-Wesley representative for the specific ISBN to order this book packaged with Microsoft Visual C++ 2008 Express Edition.

MyCodeMate-Your Own T.A. Just a Click Away Addison-Wesley's MyCodeMate is a book-specific Web resource that provides tutorial help and evaluation of student programs. Example programs throughout the book and selected Programming Challenges from every chapter have been integrated inro MyCodeMate. Using this tool , a student is able to write and compile programs from any computer with Internet access, and receive guidance and feedback on how to proceed and on how to address com piler error messages. InStructors can track each student's progress on Programming Challenges from the text or can develop projects of their OWll. A comp limentary subscription to MyCodeMate is offered when the access code is ordered in a package with a new copy of this text. Subscriptions can also be purchased online. For more information visit http:// www.mycodemate.com. or contact your campus Addison-Wesley representative .

Instructor Resources T he following supplements arc available to qualified instructors only: •

Answers



Solutions for all Programmmg Challenges in the text



PowerPoint presentation slides for every chapter



Computerized test bank



Answers



Solutions for all Srudenr Lab Manual programs

to

to

all Review Questions in the text

all Student Lab Manual questions

Visit the Addison-Wesley Instructor Resource Cenrer (http : //www . aw . com/ire) or send an email to [email protected] information on how to access them.



Preface

Textbook Web site A Web site for the Starting Out with C++ series of books is located at the following URL: http://www.aw.com/gaddisbooks

Get this book the way you want it! This book is part of Pearson Education's custom database for Compurer Science textbooks. Use OUf online PubSelect system to select just the chapters you need from this, and other, Pearson Education CS textbooks. You can edit the sequence ro exactly match your course organization and teaching approach. Visit www . pearsoncustom . com/csfordetails.

Which Gaddis C++ book is right for you? The Starring Our with C++ Series includes three books, one of which is sure to fit your cou rse:



Starting Out with C+ +: From Control Structures through Objects (formerly called the "Standard VersIon");

• •

Starting Ollt with C++: Early Objects (fo rmerly called the" Alternate Version"); Starting Out with C++: Brief Version.

The following chart will help you determine which book is right for your co urse .

• FROM CONTROL STRUCTURES THROUGH OBJECTS • BRIEF VERSION

• EARLY OBJECTS

LATE INTRODUCTION OF OBJECTS Classes are introduced in Chapter 13 of the standard tcxt and Chapter 11 of thc brief text, after control structures, functions, arrays, and pointers. Advanced OOP tOpics, such as inheritance and polymorphism, are covered in the following rwo chapters.

EARlIER INTRODUCTION OF OBJECTS Classes are inrroduced in Chapter 7, after comrol srructures and functions, but before arrays and pointers. Their usc is then integrated into the remainder of the text. Advanced OOP topics, such as inheritance and polymorphism, are covered in Chapters 11 and 15.

USE OF C-STRINGS Null-terminated C-strings are used throughout, with the C++ string class covered briefly.

USE OF s t r ing OBJECTS Standa rd library str ing class objects are used throughout, with C-strings covered briefly.

INTRODUCTION OF DATA STRUCTURES AND RECURSION Linked lists, stacks and queues, and binary trees are introduced in the final chapters of the standard text. Recursion is covered after stacks and queues, but before binary trees. These copics are nOt covered in [he brief text, though it does have appendices dealing with linked lists and recursion.

INTRODUCTION OF DATA STRUCTURES AND RECURSION Linked lists, stacks and queues, and binary trees are inrroduced in the final chapters of the text, after the chapter on res.ign) · Prl I cpp'

!j/It~~~t""~

.l

!_~~

a..

• DeW;

I I Ge~ the n~r Q! h~~r. vork~d. cout « - Hov aacy hcur~ d~ d yeu weer?

ci.n »

h our" ,

I I Get COUt «

~

12

lS

eUI

»

hourly pay race.

- Holl :weh do .tAt e:

~OClU

gee p aid per hour? ";

:6:

17: u:

:~

"23,,

I I Calculate che pay . pay • hou r " • rate; II Ol",pla:.' che pay.

coue «

- You bavt e ar ned S-

«

pay

« eod1;

l-

Rltl';'Q.

CIC

n,IP

Reltb'y. P.MII

"'''CIa'' 0 ;

+.

Content

Co6e

. . - t;

.. \- \.. l,.. 1100'S



""" What Is a Program Made of? CON CE PT: There ace certain elements that are common to all programming languages.

Language Elements All programming languages have a few things in common . Table 1-2 lists the common elements you will find in almost every language.

Let's look at some specific parts of Program 1-1 (the pay-calculating program) to see examples of each element listed in the table above. For your convenience, Program 1-1 IS listed again.

1.4 What Is a Prog ram Made of?

Table 1-2 Language

Element Key Words

Description Words thar have a special meaning. Key words may only be used for their inrended purpose. Key words are also known as reserved words.

Progra mmer-Defined Words or names defined by the programmer. They are symbolic names that refer ro variables or programming routines . Operarors Operators perform operarions on one or more opcmnds. An operand is usual ly a piece of data, like a number.

Identifiers

Punctuation

Punctuation ch aracters that mark the beginning or ending of a statement, or

Syntax

separate items in a lise. Rules tbat must be followed when constructing a program. Syntax dictates how key words and ope rators may be used, and where punctuation symbols ml,lsr appear.

Program 1-1

1

II This program calculates the user's pay .

2

3

' include