Siêu thị PDFTải ngay đi em, trời tối mất

Thư viện tri thức trực tuyến

Kho tài liệu với 50,000+ tài liệu học thuật

© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

Introduction to Programming with C++
PREMIUM
Số trang
714
Kích thước
11.7 MB
Định dạng
PDF
Lượt xem
1377

Introduction to Programming with C++

Nội dung xem thử

Mô tả chi tiết

ONLINE ACCESS

Thank you for purchasing a new copy of Introduction to Programming with C++, Third Edition.

Your textbook includes six months of prepaid access to the book’s Companion Website. This

prepaid subscription provides you with full access to the following student support areas:

 



 









Use a coin to scratch off the coating and reveal your student access code.

Do not use a knife or other sharp object as it may damage the code.

To access the Introduction to Programming with C++, Third Edition, Companion Website for the







 











browser. The process takes just a couple of minutes and only needs to be completed once.

1. Go to www.pearsoninternationaleditions.com/liang

2. Click on Companion Website.

3. Click on the Register button.

4. On the registration page, enter your student access code* found beneath the scratch-off panel.

Do not type the dashes. You can use lower- or uppercase.

5. 

! 



 "#











process, simply click the Need Help? icon.

6. $ % &   



Introduction to Programming with C++ Companion Website!

To log in after you have registered:

You only need to register for this Companion Website once. After that, you can log in any time at

www.pearsoninternationaleditions.com/liang (% & 

prompted.

)



+/   "/  

 (# 0





(

 

 # "#

    (



no longer be valid.

Loop Statements

while (condition)

{

statements;

}

do

{

statements;

} while (condition);

for (init; condition;

adjustment)

{

statements;

}

if Statements

if (condition)

{

statements;

}

if (condition)

{

statements;

}

else

{

statements;

}

if (condition1)

{

statements;

}

else if (condition2)

{

statements;

}

else

{

statements;

}

Dynamic Memory Creation/Deletion

int* p1 = new int;

int* p2 = new int[10];

delete p1;

delete [] p2;

Array/Initializer

int list[10];

int list[] = {1, 2, 3, 4};

Multidimensional Array/Initializer

int list[10][15];

int list[2][2] = {{1, 2}, {3, 4}};

Frequently Used functions

time(0) returns current time

srand(seed) sets a new seed for generating random numbers

rand() returns a random integer

pow(a, b) returns ab

Character Functions

isdigit(c) returns true if c is a digit.

isalpha(c) returns true if c is a letter.

isalnum(c) returns true if c is a letter or a digit.

islower(c) returns true if c is a lowercase letter.

isupper(c) returns true if c is an uppercase letter.

tolower(c) returns a lowercase for c.

toupper(c) returns an uppercase for c.

C-String Functions

strlen returns string length

strcpy copies a string

strcat concatenate two strings

strcmp compares two strings

atol converts a string to a long value

itoa converts a an integer a string

The string Class Member Functions

append appends new contents to the string

insert inserts new contents to the string

at retrieves character from the string

[] string subscript operator

length returns the length of the string.

substr returns a substring from the string

switch Statements

switch (intExpression)

{

case value1:

statements;

break;

...

case valuen:

statements;

break;

default:

statements;

}

Companion Website: www.cs.armstrong.edu/liang/cpp3e

C++ Quick Reference

ONLINE ACCESS

Thank you for purchasing a new copy of Introduction to Programming with C++, Third Edition.

Your textbook includes six months of prepaid access to the book’s Companion Website. This

prepaid subscription provides you with full access to the following student support areas:

 



 









Use a coin to scratch off the coating and reveal your student access code.

Do not use a knife or other sharp object as it may damage the code.

To access the Introduction to Programming with C++, Third Edition  





time, you will need to register online using a computer with an Internet connection and a web

browser. The process takes just a couple of minutes and only needs to be completed once.

1. Go to www.pearsoninternationaleditions.com/liang

2. Click on Companion Website.

3. Click on the Register button.

4. On the registration page, enter your student access code* found beneath the scratch-off panel.

Do not type the dashes. You can use lower- or uppercase.

5. Follow the on-screen instructions. If you need help at any time during the online registration

process, simply click the Need Help? icon.

6.   ! "  



Introduction to Programming with C++ Companion Website!

To log in after you have registered:

You only need to register for this Companion Website once. After that, you can log in any time at

www.pearsoninternationaleditions.com/liang $ ! ""

prompted.

*Important: The access code can only be used once. This subscription is valid for six months

upon activation and is not transferable. If this access code has already been revealed, it may no

longer be valid.

Loop Statements

while (condition)

{

statements;

}

do

{

statements;

} while (condition);

for (init; condition;

adjustment)

{

statements;

}

if Statements

if (condition)

{

statements;

}

if (condition)

{

statements;

}

else

{

statements;

}

if (condition1)

{

statements;

}

else if (condition2)

{

statements;

}

else

{

statements;

}

Dynamic Memory Creation/Deletion

int* p1 = new int;

int* p2 = new int[10];

delete p1;

delete [] p2;

Array/Initializer

int list[10];

int list[] = {1, 2, 3, 4};

Multidimensional Array/Initializer

int list[10][15];

int list[2][2] = {{1, 2}, {3, 4}};

Frequently Used functions

time(0) returns current time

srand(seed) sets a new seed for generating random numbers

rand() returns a random integer

pow(a, b) returns ab

Character Functions

isdigit(c) returns true if c is a digit.

isalpha(c) returns true if c is a letter.

isalnum(c) returns true if c is a letter or a digit.

islower(c) returns true if c is a lowercase letter.

isupper(c) returns true if c is an uppercase letter.

tolower(c) returns a lowercase for c.

toupper(c) returns an uppercase for c.

C-String Functions

strlen returns string length

strcpy copies a string

strcat concatenate two strings

strcmp compares two strings

atol converts a string to a long value

itoa converts a an integer a string

The string Class Member Functions

append appends new contents to the string

insert inserts new contents to the string

at retrieves character from the string

[] string subscript operator

length returns the length of the string.

substr returns a substring from the string

switch Statements

switch (intExpression)

{

case value1:

statements;

break;

...

case valuen:

statements;

break;

default:

statements;

}

Companion Website: www.cs.armstrong.edu/liang/cpp3e

C++ Quick Reference

ALWAYS LEARNING PEARSON

Editorial Director: Marcia Horton

Learn more at www.myprogramminglab.com

MyProgrammingLab™

Through the power of practice and immediate personalized

feedback, MyProgrammingLab improves your performance.

get with the programming

International Edition contributions by

Anisha Sharma

This page intentionally left blank

Introduction to

Programming

With

C++

Third Edition

International Edition contributions by

Mohit P. Tahiliani

NITK Surathkal

Y. Daniel Liang

Armstrong Atlantic State University

Prentice Hall

Upper Saddle River Boston Columbus San Francisco New York

Indianapolis London Toronto Sydney Singapore Tokyo Montreal

Dubai Madrid Hong Kong Mexico City Munich Paris Amsterdam Cape Town

Editorial Director: Marcia Horton

Executive Editor: Tracy Johnson

Associate Editor: Carole Snyder

Editorial Assistant: Jenah Blitz-Stoehr

Director of Marketing: Christy Lesko

Marketing Manager: Yez Alayan

Marketing Coordinator: Kathryn Ferranti

Director of Production: Erin Gregg

Managing Editor: Scott Disanno

Production Project Manager: Kayla Smith-Tarbox

Publisher, International Edition: Angshuman Chakraborty

Publishing Administrator and Business Analyst,

International Edition: Shokhi Shah Khandelwal

Associate Print and Media Editor, International Edition:

Anuprova Dey Chowdhuri

Acquisitions Editor, International Edition: Sandhya Ghoshal

Publishing Administrator, International Edition: Hema Mehta

Project Editor, International Edition: Karthik Subramanian

Operations Supervisor: Nick Sklitsis

Manufacturing Buyer: Lisa McDowell

Art Director: Anthony Gemmellaro

Text and Cover Designer: Anthony Gemmellaro

Manager, Visual Research: Karen Sanatar

Manager, Rights and Permissions: Michael Joyce

Text Permission Coordinator: Brian Wysock

Cover Art: Tetra Images/Glow Images

Lead Media Project Manager: Renata Buetera

Full-Service Project Management: Laserwords

Cover Printer: Lehigh-Phoenix Color/Hagerstown

Pearson Education Limited

Edinburgh Gate

Harlow

Essex CM20 2JE

England

and Associated Companies throughout the world

Visit us on the World Wide Web at:

www.pearsoninternationaleditions.com

© Pearson Education Limited 2014

The rights of Y. Daniel Liang to be identified as author of this work have been asserted by him in accordance with the Copyright, Designs and Patents Act 1988.

Authorized adaptation from the United States edition, entitled Introduction to Programming With C++, Third Edition, ISBN 978-0-13-325281-1, by

Y. Daniel Liang, published by Pearson Education © 2014.

All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic,

mechanical, photocopying, recording or otherwise, without either the prior written permission of the publisher or a license permitting restricted copying in

the United Kingdom issued by the Copyright Licensing Agency Ltd, Saffron House, 6–10 Kirby Street, London EC1N 8TS.

All trademarks used herein are the property of their respective owners. The use of any trademark in this

text does not vest in the author or publisher any trademark ownership rights in such trademarks, nor does

the use of such trademarks imply any affiliation with or endorsement of this book by such owners.

Microsoft and/or its respective suppliers make no representations about the suitability of the information contained in the documents and related graphics

published as part of the services for any purpose. All such documents and related graphics are provided “as is” without warranty of any kind. Microsoft and/or

its respective suppliers hereby disclaim all warranties and conditions with regard to this information, including all warranties and conditions of merchantability,

whether express, implied or statutory, fitness for a particular purpose, title and non-infringement. In no event shall Microsoft and/or its respective suppliers be

liable for any special, indirect or consequential damages or any damages whatsoever resulting from loss of use, data or profits, whether in an action of contract,

negligence or other tortious action, arising out of or in connection with the use or performance of information available from the services.

The documents and related graphics contained herein could include technical inaccuracies or typographical errors. Changes are periodically added to the in￾formation herein. Microsoft and/or its respective suppliers may make improvements and/or changes in the product(s) and/or the program(s) described herein

at any time. Partial screen shots may be viewed in full within the software version specified.

Microsoft® and Windows® are registered trademarks of the Microsoft Corporation in the U.S.A. and other countries. This book is not sponsored or en￾dorsed by or affiliated with the Microsoft Corporation.

ISBN 10: 0-273-79324-1

ISBN 13: 978-0-273-79324-3

British Library Cataloguing-in-Publication Data

A catalogue record for this book is available from the British Library

10 9 8 7 6 5 4 3 2 1

14 13 12 11 10

Typeset in Times by Laserwords

Printed and bound by Courier Kendalville in The United States of America

The publisher’s policy is to use paper manufactured from sustainable forests.

This book is dedicated to my current and former C++

students. You have inspired and helped me

to continue to improve this book.

To Samantha, Michael, and Michelle

This page intentionally left blank

Dear Reader,

Many of you have provided feedback on previous editions of Introduction to Programming

with C++, and your comments and suggestions have greatly improved the book. This edition

has been substantially enhanced in presentation, organization, examples, exercises, and

supplements—including the following:

n Reorganized sections and chapters present subjects in a logical order

n Many new interesting examples and exercises stimulate interest

n Introduction of the string type in Chapter 4 enables students to write programs using

strings early

n Key Points at the beginning of each section highlight important concepts and materials

n Check Points at the end of each section verify the student’s understanding of the material

covered

Please visit www.cs.armstrong.edu/liang/cpp3e/correlation.html for a complete list of new

features as well as correlations to the previous edition.

This book teaches programming using a problem-driven method that focuses on problem

solving rather than syntax. We make introductory programming interesting by using thought

provoking problems in a broad context. The central thread of early chapters is on problem

solving. Appropriate syntax and libraries are introduced to enable readers to write programs to

solve problems. To support the teaching of programming in a problem-driven way, the book

provides a wide variety of problems at various levels of difficulty to motivate students. To

appeal to students in all majors, the problems cover many application areas, including math,

science, business, finance, gaming, and animation.

The book focuses on fundamentals first by introducing basic programming concepts and

techniques before designing custom classes. The fundamental concepts and techniques of

loops, functions, and arrays are the basis for programming. Building this strong foundation

prepares students to learn object-oriented programming and advanced C++ programming.

This book teaches C++. The fundamentals of problem solving and programming are the

same regardless of which programming language you use. You can learn programming using

any high-level programming language such as Python, Java, C++, or C#. Once you know how

to program in one language, it is easy to pick up other languages, because the basic techniques

for writing programs are the same.

The best way to teach programming is by example, and the only way to learn programming

is by doing. Basic concepts are explained by example and many exercises with various levels

of difficulty are provided for students to practice. In our programming courses, we assign

programming exercises after each lecture.

Our goal is to produce a text that teaches problem solving and programming in a broad con￾text using a wide variety of interesting examples. If you have any comments or suggestions for

improving this book, please email me.

Sincerely,

Y. Daniel Liang

y.daniel.liang@gmail.com

www.cs.armstrong.edu/liang

www.pearsoninternationaleditions.com/liang

what’s new?

problem driven

fundamentals first

examples and exercises

7

What’s New in This Edition?

This third edition substantially improves Introduction to Programming with C++, Second

Edition. The major improvements are as follows:

n A complete revision to enhance clarity, presentation, content, examples, and exercises

n New examples and exercises to motivate and stimulate student interest in programming

n Key Points that highlight the important concepts covered in each section

n Check Points that provide review questions to help students track their learning progress

and evaluate their knowledge about a major concept or example

n New VideoNotes that provide short video tutorials designed to reinforce the key concepts

n Introduction of string objects in Chapter 4 to enable strings to be used in the early part

of the book

n Introduction of simple input and output in Chapter 4 to enable students to write programs

using files early

n Inclusion of functions in Chapter 6, which now covers all issues related to functions

n Chapter sections on common errors and pitfalls to steer students away from common

programming errors

n Replacement of complex examples with simpler ones (e.g., Solving the Sudoku problem

in Chapter 8 is replaced by a problem of checking whether a solution is correct. The com￾plete solution to the Sudoku problem is moved to the Companion Website.)

n Expanded bonus Chapter 18 introduces algorithmic techniques: dynamic programming,

divide-and-conquer, backtracking, and greedy algorithm with new examples to design

efficient algorithms

n Introduction of new C++11 features of foreach loops and auto type inference in the bonus

chapters and of lambda functions in the supplements on the Companion Website

Pedagogical Features

The book uses the following elements to help students gain the most from the material:

n The chapter Objectives list what students should learn so that they can determine whether

they have met these objectives after completing the chapter.

n The chapter Introduction opens the discussion with representative problems to give the

reader an overview of what to expect.

n Key Points highlight the important concepts covered in each section.

n Check Points provide review questions to help students track their progress as they read

the chapter and evaluate their learning.

n Problems and Case Studies, carefully chosen and presented in an easy-to-follow style,

teach problem solving and programming concepts. The book uses many small, simple, and

stimulating examples to present important ideas.

n The Chapter Summary reviews the important subjects that students should understand

and remember. It helps them reinforce the key concepts of the chapter.

complete revision

new examples and exercises

Key Points

Check Points

VideoNotes

string objects early

simple IO early

functions in one chapter

common error sections

simplified examples

algorithm efficiency and

techniques

C++11

Preface

8

Preface 9

n Self-test quizzes are available online through MyProgrammingLab (www.myprogramminglab

.com) for students to self-test on programming concepts and techniques.

n Programming Exercises, grouped by sections, provide students with opportunities to ap￾ply their newly acquired skills. The level of difficulty is rated as easy (no asterisk), mod￾erate (*), hard (**), or challenging (***). The trick of learning programming is practice,

practice, and practice. To that end, the book provides numerous exercises.

n Notes, Tips, Cautions, and Pedagogical Notes are inserted throughout the text to offer

valuable advice and insight on important aspects of program development.

Note

Provides additional information on the subject and reinforces important concepts.

Tip

Teaches good programming style and practice.

Caution

Helps students avoid the pitfalls of programming errors.

Pedagogical Note

Gives advice on how to use the materials in the book effectively.

Flexible Chapter Orderings

The book provides flexible chapter orderings, as shown in the following diagram:

Chapter 1 Introduction to

Computers, Programs, and C++

Chapter 2 Elementary

Programming

Chapter 3 Selections

Chapter 4 Mathematical Functions,

Characters, and Strings

Chapter 5 Loops

Chapter 6 Functions

Chapter 9 Objects and Classes

Chapter 10 Object-Oriented

Thinking

Chapter 11 Pointers and Dynamic

Memory Management

Chapter 15 Inheritance and

Polymorphism

Chapter 14 Operator Overloading

Chapter 12 Templates, Vectors,

and Stacks

Chapter 17 Recursion

Chapter 18 Developing Efficient

Algorithms

Chapter 19 Sorting

Chapter 20 Linked Lists, Queues,

and Priority Queues

Chapter 21 Binary Search Trees

Chapter 16 Exception Handling

Chapter 24 Graphs and

Applications Chapter 8 Multidimensional

Arrays

Chapter 7 Single-Dimensional

Arrays and C-Strings

Chapter 13 File Input and Output

Chapter 22 STL Containers

Chapter 23 STL Algorithms

Chapter 26 AVL Trees and

Splay Trees

Chapter 25 Weighted Graphs and

Applications

Chapters

18–26 are

bonus

chapters

posted on

the book’s

Companion

Website

10 Preface

Organization of the Book

The chapters can be grouped into three parts, which together form a solid introduction to

problem solving and programming using C++.

Part I: Fundamentals of Programming (Chapters 1–8)

This part is a stepping-stone, which prepares you to embark on the journey of learning pro￾gramming with C++. You will begin to know C++ (Chapter 1) and will learn elementary

programming techniques with primitive data types, expressions, and operators (Chapter 2),

selection statements (Chapter 3), mathematical functions, characters, and strings (Chapter 4),

loops (Chapter 5), functions (Chapter 6), and arrays (Chapters 7–8).

Part II: Object-Oriented Programming (Chapters 9–16)

This part introduces object-oriented programming. C++ is an object-oriented programming

language that uses abstraction, encapsulation, inheritance, and polymorphism to provide great

flexibility, modularity, and reusability in developing software. You will learn programming

with objects and classes (Chapter 9); design classes (Chapter 10); explore pointers and dynamic

memory management (Chapter 11); develop generic classes using templates (Chapter 12); use

IO classes for file input and output (Chapter 13); use operators to simplify functions (Chap￾ter 14); define classes from base classes (Chapter 15); and create robust programs using ex￾ception handling (Chapter 16).

Part III: Algorithms and Data Structures (Chapter 17 and Bonus Chapters 18–26)

This part introduces the main subjects in a typical data structures course. Chapter 17 intro￾duces recursion to write functions for solving inherently recursive problems. Chapter 18

introduces how to measure algorithm efficiency in order to choose an appropriate algorithm

for applications. Chapter 19 presents various sorting algorithms and analyzes their complexi￾ties. You will learn how to design and implement linked lists, queues, and priority queues in

Chapter 20. Chapter 21 introduces binary search trees. Chapters 22 and 23 cover the standard

template library in C++. Chapters 24 and 25 introduce graph algorithms and applications.

Chapter 26 introduces balanced binary search trees.

C++ Development Tools

You can use a text editor, such as the Windows Notepad or WordPad, to create C++ programs,

and you can compile and run the programs from the command window. You can also use a

C++ development tool, such as Visual C++ or Dev-C++. These tools support an integrated

development environment (IDE) for rapidly developing C++ programs. Editing, compiling,

building, executing, and debugging programs are integrated in one graphical user interface.

Using these tools effectively will greatly increase your programming productivity. Creating,

compiling, and running programs using Visual C++ and Dev-C++ are introduced in the sup￾plements on the Companion Website. The programs in this book have been tested on Visual

C++ 2012 and the GNU C++ compiler.

Online Practice and Assessment

with MyProgrammingLab™

MyProgrammingLab helps students fully grasp the logic, semantics, and syntax of program￾ming. Through practice exercises and immediate, personalized feedback, MyProgrammingLab

improves the programming competence of beginning students who often struggle with the

basic concepts and paradigms of popular high-level programming languages.

A self-study and homework tool, a MyProgrammingLab course consists of hundreds of

small practice problems organized around the structure of this textbook. For students, the

Tải ngay đi em, còn do dự, trời tối mất!