1. Trang chủ
  2. » Công Nghệ Thông Tin

Starting out with c++ early objects

1,3K 522 1
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Starting Out With C++
Tác giả Gaddis
Trường học University of Texas at Dallas
Chuyên ngành Computer Science
Thể loại textbook
Năm xuất bản 2005
Thành phố Dallas
Định dạng
Số trang 1.337
Dung lượng 15,53 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Đây là quyển sách tiếng anh về lĩnh vực công nghệ thông tin cho sinh viên và những ai có đam mê. Quyển sách này trình về lý thuyết ,phương pháp lập trình cho ngôn ngữ C và C++.

Trang 1

Unprecedented Praise for Starting Out with C++

I want to tell you that I believe your C++ text is the most thorough one available I have used 5 different ones since

1992 and every one assumes the students know things that they do not You cover every detail Thank you

—David McLeod, Belmont Technical College, OH The students have found your book to be easy to read and understand—a great accomplishment

—Al Cawns, Webster University, MO

I listen to what students say about the books I select Their response to Gaddis is unusually positive They really like the book

—Jeffrey A Kent, Los Angeles Valley College, CA Greetings, I’m using your book in an introductory course in C++ at University of Texas at Dallas Your book is GREAT!!

It abstracts the complexity of C++ down to the core cepts that we can build on Thanks!

con-—Jim Burke, student

…just wanted to tell you that your book has made a lot of difference in my life Your book is absolutely “Awesome.”

You have a lot of examples in the book which help a lot.

Thanks again!

—Saud Faisal, student

I have adopted and am currently teaching from the Gaddis second edition textbook This is by far the best C++ book that I have taught with.

—Deedee Herrera, Dodge City CC, KS

I like it better than the one we are using for our second semester C++ course

—Dr Ron Bass, Austin Community College, TX

I took a good look at your 2nd edition as I revised my class

to use it and I think you did a super job Moving recursion and splitting the chapter on arrays made a great book even better Congratulations!

—Carol Schwab, Webster University, MO

I have adopted this book for courses at both Inver Hills Community College and Century College in Minnesota this semester I have not been disappointed It works for me.

—Ray Larson, Century College, MN

This book is very, very exhaustive in its coverage I didn’t even go through a part of it But aside from its bulk, it was a very good introduction to programming Gaddis does an excellent job of showing how to program step-by-step, and makes it easy to teach yourself.

The book also contains a quick reference section where you can look up frequently used commands without having

to find them in the text This book is highly recommended for beginning (and even continuing) programmers

—Reviewer from The University of Texas at Dallas

Learned quite a bit from this textbook needed for my C++ class in college I was pleasantly surprised at how well writ- ten this book was, considering the topic it is covering Great Book! I’m keeping mine seeing as it will come in handy with

my future programming endeavors Too bad other books aren’t as well written

text-—Craig Croteau, Dunedin, FL

I used this book for the first semester of college C++ It is an excellent textbook Some C++ textbooks have large amounts

of text with few examples, making them very hard to read and understand.

This book is filled with examples in short sections about specific C++ elements I have kept it as a reference as infor- mation is easy to find and the examples make it easy to understand and implement.

I have two other books on C++, but if I were teaching a C++ class, I would use this book.

—Karen Ryberg, Bismarck, ND

Trang 2

The book itself is fantastic Everything is laid out in an easy

to read fashion Truly a C++ beginners book.…Thanks for writing a book that was so educational Tony!

—Student from Dover, NH

This book is just amazing.…It goes in-depth on almost everything in C++ It’ll teach you pretty much everything you need except the most advanced topics Its a tough book since it covers so much, but it’s definitely worth the time and money if you’re willing to invest in it.

—A reader

Gaddis is an extraordinary writer. Gaddis’ text is working much better than I expected The ancillary materials espe- cially the test bank and Power Point presentations add greatly to our ability to do some solid, diverse, and effective teaching

—George Harrison, Norfolk State University, VA

Could you please tell me when “Starting Out with Java” by Tony Gaddis will be available for purchase? I am a sopho- more at Augusta State University, and my school’s first pro- gramming class uses “Starting out with C++.” I am transferring to UGA and their first class teaches JAVA So I have to teach it to myself I love your C++ book—it makes everything so easy to understand, and I know that I can’t go wrong with the JAVA text.

—Christopher Savage, student

I’ve never seen a beginners C++ book that is as well tured and reader-friendly as this one If you are in the mar- ket for an intro to C++ book, look no further

struc-—A reader

I have found the Gaddis book to be a wonderful textbook for our students It is highly readable, and I am pleased that

most students are actually reading the text.

—Brenda Boyce, C++ Instructor

Beginners using the Linux operating system and compiling with gcc will not have a problem with the examples in this book I like the fact that the author even explains how to compile programs under Linux, which helped me out a lot, being a beginner myself

—Justin Sinclair, San Francisco, CA

As an instructor in the community-college system, I have dents with wide-ranging abilities—from remedial to advanced Though I haven’t had time to study the whole book (yet), it has many good features, all of which I can’t list The most important to me is how the book proceeds Though this book is exhaustive (i.e., covers each of its topics very thoroughly), it goes step-by-step to teach the basics of the programming process in an organized fashion Such a pro- gressive approach is MUCH better than a “here’s EVERY- THING on one topic” approach (see any book by the Deitels); beginning students don’t NEED to know the details Any pro- gramming instructor who thinks about how he/she learned will recognize that he/she learned broad, general basics and only picked up the details through practice.

stu-…Mr Gaddis’ book is the BEST I’ve seen in years

—Reviewer, Wake Technical Community College

Gaddis’ book is a good, solid book and teachers should be successful using it Students in our Bachelors program find the book clear, easy to follow and therefore, they like it very much.

—An instructor from Touro College, NY

This is an excellent book for those looking to learn the C++ language It starts off with the absolute basics and goes through medium-level OOP programming.

—Reviewer from Dallas, TX

My students say Gaddis is the best thing they’ve seen since sliced bread.

—Tom Gilman, College of the Desert

Trang 3

Early Objects

5th Edition

Tony Gaddis Judy Walters Godfrey Muganda

Trang 4

Publisher Greg Tobin Senior Acquisitions Editor Michael Hirsch Editorial Assistant Lindsey Triebel Managing Editor Patty Mahtani Cover Designer Joyce Cosentino Wells Media Producer Bethany Tidd Marketing Manager Michelle Brown Marketing Assistant Dana Lopreato Senior Manufacturing Buyer Caroline Fell Text Design, Composition Stephen Adams Proofreader Kristin Furino Production Coordination Mario M Rodriguez Access the latest information about Addison-Wesley titles from our World Wide Web site:

http://www.aw-bc.com/computing Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trade- marks Where those designations appear in this book, and Addison-Wesley was aware of a trademark claim, the designations have been printed in initial caps or all caps.

The programs and applications presented in this book have been included for their instructional value They have been tested with care but are not guaranteed for any particular purpose The publisher does not offer any warran- ties or representations, nor does it accept any liabilities with respect to the programs or applications

Library of Congress Cataloging-in-Publication Data

Copyright © 2006 Pearson Education, Inc

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 the prior writ- ten permission of the publisher Printed in the United States of America For information on obtaining permis- sion for use of material in this work, please submit a written request to Pearson Education, Inc., Rights and Contracts Department, 75 Arlington Street, Suite 300, Boston, MA 02116, fax your request to 617-848-7047, or e-mail at http://www.pearsoned.com/legal/permissions.htm.

ISBN 0-321-38348-6

1 2 3 4 5 6 7 8 9 10—CRW—09 08 07 06 05

Trang 5

CHAPTER 9 Searching and Sorting Arrays 567 CHAPTER 10 Pointers 607

CHAPTER 11 More About Classes and Object-Oriented Programming 657 CHAPTER 12 More About Characters, Strings, and the string Class 761 CHAPTER 13 Advanced File and I/O Operations 821

CHAPTER 14 Recursion 889 CHAPTER 15 Polymorphism, Virtual Functions, and Multiple Inheritance 917 CHAPTER 16 Exceptions, Templates, and the Standard Template Library (STL) 957 CHAPTER 17 Linked Lists 1009

CHAPTER 18 Stacks and Queues 1055 CHAPTER 19 Binary Trees 1095 Appendix A The ASCII Character Set 1121 Appendix B Operator Precedence and Associativity 1125 Appendices on the accompanying student CD

Appendix C An Object-Oriented System Development Primer Appendix D Using UML in Class Design (NEW)

Appendix E Namespaces Appendix F Passing Command Line Arguments Appendix G Header File and Library Function Reference Appendix H Binary Numbers and Bitwise Operations Appendix I C++ Casts and Run-Time Type Identification Appendix J Multi-Source File Programs

Appendix K Introduction to Microsoft Visual C++ 6.0 Appendix L Introduction to Borland C++ Builder 5.0 Appendix M Introduction to Microsoft Visual C++ NET Appendix N NET and Managed C++ (NEW)

Appendix O Introduction to Flowcharting Appendix P Answers to Checkpoints Appendix Q Answers to Odd-Numbered Review Questions

Trang 7

1.5 Input, Processing, and Output 16 1.6 The Programming Process 18 1.7 Procedural and Object-Oriented Programming 22 1.8 Case Studies 24

1.9 Review Questions and Exercises 25 CHAPTER 2 Introduction to C++ 29

2.1 The Parts of a C++ Program 29 2.2 The cout Object 33

2.3 The #include Directive 37 2.4 Standard and Prestandard C++ 39 2.5 Variables, Constants, and the Assignment Statement 40 2.6 Identifiers 45

2.7 Integer Data Types 47 2.8 The char Data Type 52 2.9 The C++ string Class 56 2.10 Floating-Point Data Types 57 2.11 The bool Data Type 61 2.12 Determining the Size of a Data Type 62 2.13 More on Variable Assignments and Initialization 63 2.14 Scope 64

2.15 Arithmetic Operators 65 2.16 Comments 68

2.17 Focus on Software Engineering: Programming Style 70 2.18 Case Studies 72

2.19 Review Questions and Exercises 72 CHAPTER 3 Expressions and Interactivity 79

3.1 The cin Object 79 3.2 Mathematical Expressions 85 3.3 Implicit Type Conversion 93

Trang 8

viii

3.4 Explicit Type Conversion 95 3.5 Overflow and Underflow 98 3.6 Named Constants 101 3.7 Multiple and Combined Assignment 107 3.8 Formatting Output 111

3.9 Working with Characters and String Objects 121 3.10 Using C-Strings 128

3.11 More Mathematical Library Functions 133 3.12 Introduction to Files 138

3.13 Focus on Object-Oriented Programming: Member Functions 146 3.14 Focus on Debugging: Hand Tracing a Program 147

3.15 Green Fields Landscaping Case Study—Part 1 149 3.16 Additional Case Studies 152

3.17 Review Questions and Exercises 152 CHAPTER 4 Making Decisions 167

4.1 Relational Operators 167 4.2 The if Statement 173 4.3 The if/else Statement 183 4.4 The if/elseif Statement 186 4.5 Menus 192

4.6 Nested if Statements 194 4.7 Logical Operators 198 4.8 Checking Numeric Ranges with Logical Operators 206 4.9 Validating User Input 207

4.10 More About Variable Definitions and Scope 209 4.11 Comparing Characters and Strings 215

4.12 The Conditional Operator 219 4.13 The switch Statement 223 4.14 Enumerated Data Types 232 4.15 Testing for File Open Errors 235 4.16 Focus on Testing and Debugging: Validating Output Results 236 4.17 Green Fields Landscaping Case Study—Part 2 239

4.18 Additional Case Studies 243 4.19 Review Questions and Exercises 243

5.1 The Increment and Decrement Operators 255 5.2 Introduction to Loops: The while Loop 260 5.3 Counters 264

5.4 Letting the User Control the Loop 266 5.5 Keeping a Running Total 268

5.6 Sentinels 269 5.7 Using a Loop to Read Data From a File 271

Trang 9

5.8 The do-while and for Loops 274 5.9 Deciding Which Loop to Use 284 5.10 Nested Loops 285

5.11 Breaking Out of a Loop 288 5.12 The continue Statement 290 5.13 Focus on Software Engineering: Using Loops for Data Validation 292 5.14 Focus on Testing and Debugging: Creating Good Test Data 295 5.15 Central Mountain Credit Union Case Study 298

5.16 Additional Case Studies 303 5.17 Review Questions and Exercises 303 CHAPTER 6 Functions 313

6.1 Modular Programming 313 6.2 Defining and Calling Functions 314 6.3 Function Prototypes 322

6.4 Sending Data into a Function 324 6.5 Passing Data by Value 328 6.6 The return Statement 332 6.7 Returning a Value from a Function 334 6.8 Returning a Boolean Value 338 6.9 Using Functions in a Menu-Driven Program 340 6.10 Local and Global Variables 343

6.11 Static Local Variables 349 6.12 Default Arguments 353 6.13 Using Reference Variables as Parameters 357 6.14 Overloading Functions 365

6.15 The exit() Function 369 6.16 Stubs and Drivers 373 6.17 Little Lotto Case Study 376 6.18 Additional Case Studies 381 6.19 Review Questions and Exercises 381 CHAPTER 7 Introduction to Classes and Objects 391

7.1 Combining Data into Structures 391 7.2 Accessing Structure Members 394 7.3 Initializing a Structure 398 7.4 Nested Structures 402 7.5 Structures as Function Arguments 406 7.6 Returning a Structure from a Function 410 7.7 Unions 413

7.8 Abstract Data Types 417 7.9 Object-Oriented Programming 419 7.10 Introduction to Classes 423 7.11 Introduction to Objects 425

Trang 10

7.12 Defining Member Functions 427 7.13 Focus on Software Engineering: Design Considerations 434 7.14 Using a Constructor with a Class 439

7.15 Overloading Constructors 440 7.16 Destructors 443

7.17 Input Validation Objects 447 7.18 Using Private Member Functions 451 7.19 Home Software Company OOP Case Study 454 7.20 Focus on Software Engineering: Object-Oriented Analysis 461 7.21 Additional Case Studies 464

7.22 Review Questions and Exercises 464

8.1 Arrays Hold Multiple Values 477 8.2 Accessing Array Elements 479 8.3 Inputting and Displaying Array Contents 481 8.4 Array Initialization 487

8.5 Processing Array Contents 493 8.6 Using Parallel Arrays 502 8.7 The typedef Statement 506 8.8 Arrays as Function Arguments 507 8.9 Two-Dimensional Arrays 516 8.10 Arrays with Three or More Dimensions 524 8.11 Vectors 528

8.12 National Commerce Bank Case Study 540 8.13 Arrays of Structures 543

8.14 Arrays of Class Objects 547 8.15 Additional Case Studies 555 8.16 Review Questions and Exercises 556 CHAPTER 9 Searching and Sorting Arrays 567

9.1 Focus on Software Engineering: Introduction to Search Algorithms 567 9.2 Demetris Leadership Center Case Study—Part 1 574

9.3 Focus on Software Engineering: Introduction to Sorting Algorithms 581 9.4 Demetris Leadership Center Case Study—Part 2 589

9.5 Sorting and Searching Vectors 596 9.6 Additional Case Studies 601 9.7 Review Questions and Exercises 602 CHAPTER 10 Pointers 607

10.1 Getting the Address of a Variable 607

10.2 Pointer Variables 609

10.3 The Relationship Between Arrays and Pointers 613

10.4 Pointer Arithmetic 617

10.5 Initializing Pointers 619

Trang 11

10.6 Comparing Pointers 621 10.7 Pointers as Function Parameters 624 10.8 Focus on Software Engineering: Dynamic Memory Allocation 628 10.9 Focus on Software Engineering: Returning Pointers from Functions 632 10.10 Pointers to Structures and Class Objects 635

10.11 Focus on Software Engineering: Selecting Members of Objects 641 10.12 United Cause Relief Agency Case Study 643

10.13 Additional Case Studies 651 10.14 Review Questions and Exercises 652 CHAPTER 11 More About Classes and Object-Oriented Programming 657

11.1 The this Pointer and Constant Member Functions 657 11.2 Static Members 662

11.3 Friends of Classes 669 11.4 Memberwise Assignment 675 11.5 Copy Constructors 677 11.6 Operator Overloading 685 11.7 Type Conversion Operators 721 11.8 Convert Constructors 726 11.9 Object Composition 730 11.10 Inheritance 732

11.11 Protected Members and Class Access 736 11.12 Constructors, Destructors, and Inheritance 742 11.13 Overriding Base Class Functions 747

11.14 Case Studies 750 11.15 Review Questions and Exercises 750 CHAPTER 12 More About Characters, Strings, and the string Class 761

12.1 C-strings 761 12.2 Library Functions for Working with C-Strings 766 12.3 String/Numeric Conversion Functions 778 12.4 Character Testing 781

12.5 Character Case Conversion 786 12.6 Writing Your Own C-String Handling Functions 788 12.7 More About the C++ string Class 794

12.8 Creating Your Own String Class 799 12.9 Advanced Software Enterprises Case Study 811 12.10 Additional Case Studies 813

12.11 Review Questions and Exercises 814 CHAPTER 13 Advanced File and I/O Operations 821

13.1 Files 821 13.2 Output Formatting 830 13.3 Passing File Stream Objects to Functions 838 13.4 More Detailed Error Testing 840

Trang 12

13.5 Member Functions for Reading and Writing Files 844

13.6 Working with Multiple Files 854

13.7 Binary Files 855

13.8 Creating Records with Structures 859

13.9 Random-Access Files 863

13.10 Opening a File for Both Input and Output 870

13.11 Online Friendship Connections Case Study: Object Serialization 875

13.12 Additional Case Studies 880

13.13 Review Questions and Exercises 881

CHAPTER 14 Recursion 889

14.1 Introduction to Recursion 889

14.2 The Recursive Factorial Function 897

14.3 The Recursive gcd Function 899

14.4 Solving Recursively Defined Problems 900

14.5 A Recursive Binary Search Function 902

14.6 Focus on Problem Solving and Program Design: The QuickSort Algorithm 904 14.7 Focus on Problem Solving: Exhaustive and Enumeration Algorithms 908 14.8 Focus on Software Engineering: Recursion Versus Iteration 912

14.9 Case Studies 913

14.10 Review Questions and Exercises 913

CHAPTER 15 Polymorphism, Virtual Functions, and Multiple Inheritance 917

15.1 Type Compatibility in Inheritance Hierarchies 917

15.2 Polymorphism and Virtual Member Functions 921

15.3 Abstract Base Classes and Pure Virtual Functions 926

15.4 Multiple and Virtual Inheritance 931

15.5 Focus on Object-Oriented Programming: Composition Versus Inheritance 940 15.6 Secure Encryption Systems, Inc Case Study 945

15.7 Review Questions and Exercises 949

CHAPTER 16 Exceptions, Templates, and the Standard Template Library (STL) 957 16.1 Exceptions 957

16.2 Function Templates 969

16.3 Class Templates 978

16.4 Class Templates and Inheritance 984

16.5 Introduction to the Standard Template Library 988

16.6 Case Studies 1003

16.7 Review Questions and Exercises 1003

CHAPTER 17 Linked Lists 1009

17.1 Introduction to the Linked List ADT 1009

17.2 Linked List Operations 1016

17.3 A Linked List Template 1032

17.4 Recursive Linked List Operations 1037

Trang 13

17.5 Variations of the Linked List 1043 17.6 The STL list Container 1044 17.7 Reliable Software Systems, Inc Case Study 1046 17.8 Additional Case Studies 1049

17.9 Review Questions and Exercises 1050 CHAPTER 18 Stacks and Queues 1055

18.1 Introduction to the Stack ADT 1055 18.2 Dynamic Stacks 1065

18.3 The STL stack Container 1069 18.4 Introduction to the Queue ADT 1071 18.5 Dynamic Queues 1079

18.6 The STL deque and queue Containers 1082 18.7 Focus on Problem Solving and Program Design: Eliminating Recursion 1085 18.8 Review Questions and Exercises 1090

CHAPTER 19 Binary Trees 1095

19.1 Definition and Applications of Binary Trees 1095 19.2 Binary Search Tree Operations 1099

19.3 Template Considerations for Binary Search Trees 1116 19.4 Case Studies 1116

19.5 Review Questions and Exercises 1116

Trang 15

What’s New in the Fifth Edition

 Several Programming Challenges in each chapter have been selected for inclusion in

Addison-Wesley’s MyCodeMate MyCodeMate allows students to complete the

Program-ming Challenges on-line, with automated assistance and feedback provided as needed It also provides instructors with information on student progress and helps with course management

 The double data type, rather than the float data type, has become the standard used throughout the book for floating-point variables

 The standard has been adopted throughout the book of giving named constants fier names consisting entirely of uppercase characters and underscores For example: const double INTEREST_RATE = 03;

identi- Array size declarators, previously specified with literals, are now specified with named constants For example:

const int SIZE = 20;

double sample[SIZE];

Trang 16

 The appendices have been reorganized and each appendix is now stored in its own PDF file, with numbering starting from page 1 This will make it easier for students to locate appendix information

 Two new appendices have been added:

– Using UML in Class Design – NET and Managed C++

 A UML icon has been added throughout the text where appropriate to refer students to the contents of the new appendix

 New and improved Programming Challenges have been added throughout the book Beginning with Chapter 7, additional problems that use classes have been added

 Each Programming Challenge integrated into MyCodeMate is followed in the text by a

“twin” problem that has the student either build on the original program or create a new program that is similar in design to it

Organization of the Text

This text teaches C++ in a step-by-step fashion Each chapter covers a major set of topics andbuilds knowledge as the student progresses through the book Although the chapters can beeasily taught in their existing sequence, flexibility is provided The following dependency dia-gram (Figure P-1) suggests possible sequences of instruction

Chapter 1 covers fundamental hardware, software, and programming concepts Theinstructor may choose to skip this chapter if the class has already mastered those topics Chap-ters 2 through 6 cover basic C++ syntax, data types, expressions, selection structures, repetitionstructures, and functions Each of these chapters builds on the previous chapter and should becovered in the order presented

Chapter 7 introduces object-oriented programming and includes structures and classes Itcan be covered any time after Chapter 6, but before Chapter 11 Instructors who prefer to intro-duce arrays before classes can do so by covering Chapter 8 before Chapter 7 In this case it willonly be necessary to postpone sections 8.13 and 8.14 until Chapter 7 has been covered

As the diagram (Figure P-1) illustrates, in the second half of the book Chapters 11, 12, 13,and 14 can be covered in any order Chapters 11, 15, and 16, however, should be done insequence Instructors who wish to introduce data structures at an earlier point in the course,without having first covered advanced C++ and OOP features, can do so by covering Chapter

17 (Linked Lists), followed by Chapters 18 and 19 (Stacks & Queues and Binary Trees), anytime after Chapter 14 (Recursion) In this case it is necessary to simply omit the sections inChapters 17–19 that deal with templates and the Standard Template Library

Trang 17

Figure P-1

Chapter 1 Introduction

Chapters 2–6 Basic Language Elements

Chapter 10 Pointers

Chapter 7 OOP Introduction

Chapter 8 Arrays

Chapter 11 More OOP

Chapter 12 Advanced Strings

Chapter 13 Advanced Files and I/O

Chapter 14 Recursion

Chapter 17 Linked Lists

Chapter 15 Adv OOP

Chapter 16 Exceptions Templates and STL

Chapter 18 Stacks and Queues

Chapter 19 Binary Trees

Chapter 9 Searching and Sorting

Trang 18

Brief Overview of Each Chapter

Chapter 1: Introduction to Computers and Programming

This chapter provides an introduction to the field of computer science and covers the mentals of hardware, software, operating systems, programming, problem solving, and soft-ware engineering The components of programs, such as key words, variables, operators, andpunctuation are covered The tools of the trade, such as hierarchy charts and pseudocode arealso presented

funda-Chapter 2: Introduction to C++

This chapter gets the student started in C++ by introducing the basic parts of a C++ program,data types, variable definitions, assignment statements, constants, comments, program output,and simple arithmetic operations The C++ string class is presented and string objects are usedfrom this point on in the book as the primary method of handling strings Programming styleconventions are introduced and good programming style is modeled here, as it is throughoutthe text An optional section explains the difference between ANSI standard and prestandardC++ programs

Chapter 3: Expressions and Interactivity

In this chapter the student learns to write programs that input and handle numeric, character,and string data The use of arithmetic operators and the creation of mathematical expressionsare covered, with emphasis on operator precedence Debugging is introduced, with a section onhand tracing a program Sections are also included on using sequential files, on simple outputformatting, on data type conversion and type casting, and on using library functions that workwith numbers For those who wish to cover them, there is also a section on C-strings

Chapter 4: Making Decisions

Here the student learns about relational expressions and how to control the flow of a programwith the if, if/else, and if/elseif statements Logical operators, the conditional operator,and the switch statement are also covered Applications of these constructs, such as menu-driven programs, are illustrated This chapter also continues the theme of debugging with asection on validating output results

Chapter 5: Looping

This chapter covers C++’s repetitive control mechanisms The while loop, do-while loop, andfor loop are taught, along with a variety of methods to control them These include usingcounters, user input, end sentinels, and end-of-file signals Applications utilizing loops, such asdata validation, are covered The emphasis on testing and debugging continues, with a section

on creating good test data

Trang 19

Chapter 6: Functions

In this chapter the student learns how and why to modularize programs, using both void and

value returning functions Parameter passing is covered, with emphasis on when arguments

should be passed by value versus when they need to be passed by reference Scope of variables is

covered and sections are provided on local versus global variables and on static local variables

Overloaded functions are also introduced and demonstrated

Chapter 7: Introduction to Classes and Objects

In this chapter the text begins to focus on the object-oriented paradigm There is a general

introduction to object-oriented analysis and to object-oriented programming, as well as

spe-cific material provided on how to group and encapsulate data using both structures and classes

Member variables and member functions are introduced and the student learns how to write

and call member functions Information is also provided on which member variables and

func-tions should be public and which should be private

Chapter 8: Arrays

In this chapter the student learns to create and work with single and multidimensional arrays

Many examples of array processing are provided including examples illustrating how to find

the sum, average, highest and lowest values in an array and how to sum the rows, columns, and

all elements of a two-dimensional array Programming techniques using parallel arrays are also

demonstrated and the student is shown how to use a data file as an input source to populate an

array STL vectors are introduced and compared to arrays Sections on arrays of structures and

arrays of class objects have been placed at the end of the chapter, so they can be covered now or

saved for later if the instructor wishes to cover this chapter before Chapter 7

Chapter 9: Searching and Sorting Arrays

Here the student learns the basics of searching for information stored in arrays and of sorting

arrays The chapter covers the Linear Search, Binary Search, Bubble Sort, and Selection Sort

algorithms In addition there is a section on sorting and searching STL vectors

Chapter 10: Pointers

This chapter explains how to use pointers The topics include pointer arithmetic, initialization

of pointers, comparison of pointers, pointers and arrays, pointers and functions, dynamic

memory allocation, and more

Chapter 11: More About Classes and Object-Oriented Programming

This chapter continues the study of classes and object-oriented programming It covers object

composition and inheritance as well as constant member functions, static members, friends,

memberwise assignment, copy constructors, operator overloading, object type conversion

operators, and convert constructors

Trang 20

Chapter 12: More about Characters, Strings, and the string Class

This chapter covers standard library functions for working with characters and C-strings andincludes a review of the internal storage of C-strings Topics such as passing C-strings to func-tions, and conversion between numeric and string forms are covered Additional materialabout the C++ string class and its member functions and operators is also presented

Chapter 13: Advanced File and I/O Operations

This chapter covers sequential access, random access, text, and binary files The various modesfor opening files are discussed, as well as the many methods for reading and writing file con-tents Advanced output formatting is also covered

Chapter 14: Recursion

In this chapter recursion is defined and demonstrated A visual trace of recursive calls is vided and recursive applications are discussed Many recursive algorithms are presented,including recursive functions for finding factorials, finding a greatest common denominator(GCD), performing a binary search, and sorting (QuickSort) For students who need morechallenge, there is a section on exhaustive and enumeration algorithms

pro-Chapter 15: Polymorphism, Virtual Functions, and

Dis-Chapter 17: Linked Lists

This chapter introduces concepts and techniques needed to work with lists A linked list ADT isdeveloped and the student is taught to code operations such as creating a linked list, appending

a node, traversing the list, searching for a node, inserting a node, deleting a node, and ing a list A linked list class template is also demonstrated

destroy-Chapter 18: Stacks and Queues

In this chapter the student learns to create and use static and dynamic stacks and queues Theoperations of stacks and queues are defined, and templates for each ADT are demonstrated

Trang 21

Chapter 19: Binary Trees

This chapter covers the binary tree ADT and demonstrates many binary tree operations The

student learns to traverse a tree, insert an element, delete an element, replace an element, test

for an element, and destroy a tree

Appendices

Appendix A: The ASCII Character Set A list of the ASCII and extended ASCII characters

and their codes

Appendix B: Operator Precedence and Associativity A list of the C++ operators with

their precedence and associativity

The following appendices are on the accompanying student CD

Appendix C: An Object-Oriented System Development Primer A short

introduc-tionto object-oriented analysis and design

Appendix D: Using UML in Class Design (NEW) A brief introduction to the Unified

Modeling Language (UML) with examples of its use

Appendix E: Namespaces An explanation of namespaces and their purpose, with

exam-ples provided on how to define a namespace and access its members

Appendix F: Passing Command Line Arguments An introduction to writing C++

programs that accept command line arguments This appendix will be useful to students

work-ing in a command line environment, such as UNIX or Linux

Appendix G: Header File and Library Function Reference A reference for the C++

library functions and header files used in the book

Appendix H: Binary Numbers and Bitwise Operations A guide to the binary number

system and the C++ bitwise operators, as well as a tutorial on the internal storage of integers

Appendix I: C++ Casts and Run-Time Type Identification An introduction to the

different ways of doing type casting in C++, and to run-time type identification

Appendix J: Multi-Source File Programs A tutorial on how to create, compile, and link

programs with multiple source files Includes the use of function header files, class specification

files, and class implementation files

Appendix K: Introduction to Microsoft Visual C++ 6.0 A tutorial on how to start a

project using Microsoft Visual C++, compile and run a program, save source files, and more

The Visual C++ 6.0 getline() bug is documented and a solution provided

Appendix L: Introduction to Borland C++ Builder 5.0 A tutorial on how to start a

Borland C++ Builder project, compile and run a program, save source files, and more

Appendix M: Introduction to Microsoft Visual C++ NET A tutorial on how to start a

project using Microsoft Visual C++ NET, compile and run a program, save source files, and more

Appendix N: NET and Managed C++ (NEW) A short introduction to Microsoft NET

and managed C++

Trang 22

Appendix O: Introduction to Flowcharting A tutorial which introduces flowchartingand its symbols Includes handling sequence, selection, case, repetition, and calls to other mod-ules Sample flowcharts for several of the book’s example programs are presented

Appendix P: Answers to Checkpoints A tool students can use to assess their standing by comparing their answers to the Checkpoint exercises against this appendix Theanswers to all Checkpoint exercises are included

under-Appendix Q: Answers to Odd-Numbered Review Questions Another tool studentscan use to gauge their understanding and progress

Features of the Text

Concept Statements Each major section of the text starts with a concept statement This

statement summarizes the ideas of the section

Example Programs The text has over 350 complete example programs, each designed to

highlight the topic currently being studied In most cases, these arepractical, real-world examples Source code for these programs isprovided so that students can run the programs themselves

Program Output After each example program there is a sample of its screen output This

immediately shows the student how the program should function

Checkpoints Checkpoints are questions placed throughout each chapter as a self-test

study aid Answers for all Checkpoint questions are provided on the dent CD so students can check how well they have learned a new topic

stu-Notes Notes appear at appropriate places throughout the text They are

short explanations of interesting or often misunderstood points evant to the topic at hand

rel-Warnings Warnings are notes that caution the student about certain C++

features, programming techniques, or practices that can lead tomalfunctioning programs or lost data

Case Studies Case studies that simulate real-world applications appear in many

chapters throughout the text, with complete code provided for eachone on the student CD These case studies are designed to highlightthe major topics of the chapter in which they appear

Review Questions Each chapter presents a thorough and diverse set of review questions,

and Exercises such as fill-in-the-blank and short answer, that check the student’s

mas-tery of the basic material presented in the chapter These are followed

by exercises requiring problem solving and analysis, such as the

Algorithm Workbench, Predict the Output, and Find the Errors sections Each chapter ends with a Soft Skills exercise which focuses on commu-

nication and group process skills Answers to the odd numbered reviewquestions and review exercises are provided on the student CD

Trang 23

Programming Challenges Each chapter offers a pool of programming exercises designed to

solidify the student’s knowledge of the topics currently being ied In most cases the assignments present real-world problems to

stud-be solved When applicable, these exercises include input tion rules

valida-Group Projects There are several group programming projects throughout the text,

intended to be constructed by a team of students One studentmight build the program’s user interface, while another studentwrites the mathematical code, and another designs and implements

a class the program uses This process is similar to the way manyprofessional programs are written and encourages team workwithin the classroom

Software Development Project:

Serendipity Booksellers This is an on-going project that instructors can optionally assign to

teams of students It systematically develops a “real world” softwarepackage: a point-of-sale program for the fictitious SerendipityBooksellers organization The Serendipity assignment for eachchapter adds more functionality to the software, using constructsand techniques covered in that chapter When complete, the pro-gram will act as a cash register, manage an inventory database, andproduce a variety of reports

Supplements

Student CD

This CD includes:

 Answers to all Checkpoint questions (Appendix P)

 Answers to all odd-numbered Review Questions and Exercises (Appendix Q)

 Complete source code for every program included in the book

 Additional case studies, complete with source code

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

 Borland C++ Builder 6.0, Personal Edition

If a CD did not come with your book or you can’t locate your CD, you can access most of these

items at http://www.aw.com/cssupport/

Other CDs Upon Request (contact your campus Addison-Wesley representative for the

specific ISBN to order)

 Microsoft Visual C++ 6.0

 Microsoft Visual C++ NET

 CodeWarrior

Trang 24

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

Pro-gramming Challenges from every chapter have been integrated into 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 compiler errormessages Instructors can track each student’s progress on Programming Challenges from the

text or can develop projects of their own A complimentary subscription to MyCodeMate is

offered when the access code is ordered in a package with a new copy of this text

Subscrip-tions can also be purchased online For more information visit www.mycodemate.com, or tact your campus Addison-Wesley representative

con-Instructor Resources

The following supplements are available to qualified instructors only Visit the Addison-WesleyInstructor Resource Center (www.aw.com/irc) or send an email to computing@aw.com forinformation on how to access them:

 Answers to all Review Questions in the text

 Solutions for all Programming Challenges in the text

 PowerPoint presentation slides for every chapter

 Computerized test bank

 Answers to all Student Lab Manual questions

 Solutions for all Student Lab Manual programs

Additional Supplements

The following supplementary material is also available for this textbook Contact your campusAddison-Wesley representative for more information

 Lab Manual to Accompany Starting Out with C++: Early Objects, 5th Edition,

co-authored by Judy Walters, Dean Defino, and Michael Bardzell

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

Trang 25

Which Gaddis C++ book is right for you?

The Starting Out with C++ Series includes three books, one of which is sure to fit your course:

 Starting Out with C++: Control Structures through Objects (formerly called the “Standard

Version”);

 Starting Out With C++: Early Objects (formerly called the “Alternate Version”);

 Starting Out with C++: Brief Version.

The following chart will help you determine which book is right for your course

 From Control Structures through Objects

 Brief Version  Early Objects LATE INTRODUCTION OF OBJECTS

Classes are introduced in Chapter 13 of the standard text and Chapter 11 of the brief text, after control structures, functions, arrays, and pointers Advanced OOP topics, such as inheritance and polymorphism, are covered in the following two chapters.

EARLIER INTRODUCTION OF OBJECTS

Classes are introduced in Chapter 7, after control structures and functions, but before arrays and pointers Their use 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 STRING OBJECTS

Standard library string 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 topics are not covered in the 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 introduced in the final chapters of the text, after the chapter on recursion

Trang 26

Northern Virginia Community College

Lister Wayne Horn

Pensacola Junior College

Trang 28

The authors would like to thank their families for their tremendous support throughout thisproject We would also like to thank everyone at Addison-Wesley who was part of our produc-tion and marketing team We are fortunate to be able to rely on people like Michelle Brown,Caroline Fell, Patty Mahtani, Ginny Michaud, Bethany Tidd, Lindsey Triebel, Joyce Wells, andPhil Isenhour An especially big thanks goes to Michael Hirsch, our editor at Addison-Wesley,who was instrumental in guiding the production of this book We also want to thank ourproject manager, Mario Rodriguez, our compositor, Stephen Adams, our secretary, JanetGonyo, and our PowerPoint producer, Chris Kardaras, who all dedicated many hours to mak-ing this book the best book it could be Finally, we want to thank our long-time friend andmentor Richard Jones for his guidance and expertise over the many editions of this book Youare all great people to work with!

About the Authors

Tony Gaddis is the principal author of the “Starting Out with” series of textbooks Tony teachescomputer science courses at Haywood Community College in North Carolina He is a highlyacclaimed instructor who was previously selected as the North Carolina Community College

“Teacher of the Year,” and has received the Teaching Excellence award from the National tute for Staff and Organizational Development Besides C++ books, the “Starting Out with”series includes introductory books using the Java™ programming language, Microsoft® VisualBasic® NET, and Microsoft® C#®, all published by Addison-Wesley

Insti-Judy Walters is an Associate Professor of Computer Science at North Central College in ville, Illinois In addition to her many computer science courses, she enjoys teaching a freshmancourse on film and literature She also enjoys studying foreign languages and cultures, andrecently developed a new course in technology and society, which she taught in Costa Rica Fall,

Naper-2005, as part of the college’s international studies program

Godfrey Muganda is also an Associate Professor of Computer Science at North Central College,where he chairs the Computer Science Department He teaches a wide variety of courses atboth the undergraduate and graduate levels including courses in Object-Oriented Program-ming, Comparative Programming Languages, and Compiler Design His primary researchinterests are in the area of Fuzzy Sets and Systems He won the North Central College facultyaward for outstanding scholarship in 1993

Trang 29

1

Introduction to Computers and Programming

Every profession has tools that make its job ier to do Carpenters use hammers, saws, andmeasuring tapes Mechanics use wrenches,screwdrivers, and ratchets Electronics techni-cians use probes, scopes, and meters Sometools are unique and can be categorized asbelonging to a single profession For example, surgeons have certain tools that are designedspecifically for surgical operations Those tools probably aren’t used by anyone other than sur-geons There are some tools, however, that are used in several professions Screwdrivers, forinstance, are used by mechanics, carpenters, and many others

eas-The computer is a tool that is used by so many professions, it cannot be easily categorized It canperform so many different jobs that it is perhaps the most versatile tool ever made To the accoun-tant, computers balance books, analyze profits and losses, and prepare tax reports To the factoryworker, computers control manufacturing machines and track production To the mechanic, com-puters analyze the various systems in an automobile and pinpoint hard-to-find problems

1.4 What Is a Program Made of?

1.5 Input, Processing, and Output

1.6 The Programming Process

1.7 Procedural and Object-Oriented Programming

Trang 30

What makes the computer so useful? Quite simply, the computer can do such a wide variety

of tasks because it can be programmed It is a machine specifically designed to follow instructions

Because of the computer’s programmability, it doesn’t belong to any single profession

Computers are designed to do whatever job their programs, or software, tell them to do.

Computer programmers do a very important job They create software that transforms puters into the specialized tools of many trades Without programmers, the users of computerswould have no software, and without software, computers would not be able to do anything.Computer programming is both an art and a science It is an art because every aspect of aprogram should be carefully designed Listed below are a few of the things that must bedesigned for any real-world computer program:

com- The logical flow of the instructions

 The mathematical procedures

 The appearance of the screens

 The way information is presented to the user

 The program’s “user-friendliness”

 Manuals and other forms of written documentationThere is also a scientific, or engineering side to programming Because programs rarelywork right the first time they are written, a lot of experimentation, correction, and redesigning

is required This demands patience and persistence of the programmer Writing softwaredemands discipline as well Programmers must learn special languages like C++ because com-puters do not understand English or other human languages Languages such as C++ havestrict rules that must be carefully followed

Both the artistic and scientific nature of programming makes writing computer softwarelike designing a car: Both cars and programs should be functional, efficient, powerful, easy touse, and pleasing to look at

Hardware

Hardware refers to the physical components that a computer is made of A computer, as we

gen-erally think of it, is not an individual device, but a system of devices Like the instruments in asymphony orchestra, each device plays its own part A typical computer system consists of thefollowing major components:

CONCEPT

All computer systems consist of similar hardware devices and software components This section provides an overview of standard computer hardware and software organization

Trang 31

1 The central processing unit (CPU)

2 Main memory (RAM)

3 Secondary storage devices

4 Input devices

5 Output devicesThe organization of a computer system is depicted in Figure 1-1

The CPU

At the heart of a computer is its central processing unit, or CPU The CPU’s job is to fetch

instructions, follow the instructions, and produce some result or resultant information

Inter-nally, the central processing unit consists of two parts: the control unit and the arithmetic and

logic unit (ALU) The control unit coordinates all of the computer’s operations It is responsible

for determining where to get the next instruction and regulating the other major components

of the computer with control signals The arithmetic and logic unit, as its name suggests, is

designed to perform mathematical operations The organization of the CPU is shown in

Figure 1-2

Figure 1-1

Figure 1-2

Input Device

Output Device

Secondary Storage Devices

Main Memory

Central Processing Unit

Central Processing Unit

Instruction (Input)

Arithmetic and Logic Unit

Control Unit

Result (Output)

Trang 32

A program is a sequence of instructions stored in the computer’s memory When a

com-puter is running a program, the CPU is engaged in a process known formally as the fetch/ decode/execute cycle The steps in the fetch/decode/execute cycle are as follows:

Fetch The CPU’s control unit fetches, from main memory, the next instruction

in the sequence of program instructions

Decode The instruction is encoded in the form of a number The control unit

decodes the instruction and generates an electronic signal

Execute The signal is routed to the appropriate component of the computer

(such as the ALU, a disk drive, or some other device) The signal causes the component to perform an operation

These steps are repeated as long as there are instructions to perform

Main Memory

Commonly known as random-access memory, or RAM, the computer’s main memory is a

device that holds information Specifically, RAM holds the sequences of instructions in the grams that are running and the data those programs are using

pro-Memory is divided into sections, or cells, that each holds an equal amount of data Eachcell is made of eight “switches” that may be either on or off A switch that is in the on positionusually represents the number 1, while a switch in the off position usually represents the num-ber 0 The computer stores data by setting the switches in a memory cell to a pattern that repre-

sents a character of information Each of these switches is known as a bit, which stands for binary digit Each cell, which is a collection of eight bits, is known as a byte.

Each byte is assigned a unique number known as an address The addresses are ordered

from lowest to highest A byte is identified by its address in much the same way a post office box

is identified by an address Figure 1-3 shows a group of memory cells with their addresses Inthe illustration, sample data is stored in memory The number 149 is stored in the cell with theaddress 16, and the number 72 is stored at address 23

RAM is usually a volatile type of memory, used only for temporary storage When thecomputer is turned off, the contents of RAM are erased

Trang 33

Secondary Storage

Secondary storage is a type of memory that can hold data for long periods of time—even when

there is no power to the computer Frequently used programs are stored in secondary memory

and loaded into main memory as needed Important information, such as word processing

documents, payroll data, and inventory figures, is saved to secondary storage as well

The most common type of secondary storage device is the disk drive A disk drive stores

information by magnetically encoding it onto a circular disk There are several different types of

disks, each with advantages and disadvantages The most common types are hard disks, floppy

disks, and Zip disks Hard disks are capable of storing large amounts of information and can

access information quickly Hard disks are not portable, however Floppy disks are portable, but

hold only a small amount of information and are relatively slow to access Zip disks, which are

also portable, can hold considerably more information than floppy disks and are often used to

hold back up copies of hard disk files Lately optical devices, such as the compact disc (CD), have

become popular for data storage Information is not recorded magnetically on a CD, but rather is

encoded as a series of pits on the disc surface The CD drive uses a laser to detect the pits and thus

reads the encoded information CDs can hold large amounts of data, and because recordable CD

drives are now commonplace, they make a suitable backup medium

Input Devices

Input is any information the computer collects from the outside world The device that collects

the information and sends it to the computer is called an input device Common input devices

are the keyboard, mouse, scanner, digital camera, and microphone Disk drives and CD drives

can also be considered input devices because programs and information are retrieved from

them and loaded into the computer’s memory

Output Devices

Output is any information the computer sends to the outside world It might be a sales report, a

list of names, or a graphic image The information is sent to an output device, which formats

and presents it Common output devices are monitors, printers, and speakers Output sent to a

monitor is sometimes called “soft copy,” while output sent to a printer is called “hard copy.”

Disk drives and CD burners can also be considered output devices because the CPU sends

information to them so it can be saved

Software

As previously mentioned, software refers to the programs that run on a computer There are

two general categories of software: operating systems and application software An operating

sys-tem is a set of programs that manages the computer’s hardware devices and controls their

pro-cesses Operating systems fall into one of the following categories

Single tasking A single tasking operating system is capable of running only one

pro-gram at a time The computer devotes all its hardware resources and CPU time to each program as it executes MS-DOS is an example of a single tasking operating system

Trang 34

Multitasking A multitasking operating system is capable of running multiple

pro-grams at once Through a technique called time sharing, the system

divides the allocation of hardware resources and the attention of the CPU among all the executing programs UNIX, Windows 2000, and Windows XP are multitasking operating systems

In addition, operating systems fall into one of the following categories, which describe thenumber of users they can accommodate

Single user This type of system allows only one user to operate the computer at a

time MS-DOS and Windows 2000 are single user operating systems

Multiuser Multiuser systems allow several users to run programs and operate the

computer at once Most variations of the UNIX operating system are multiuser systems

Application software refers to programs that make the computer useful to the user Theseprograms solve specific problems or perform general operations that satisfy the needs of the user.Word processing, spreadsheet, and database packages are all examples of application software

What Is a Program?

Computers are designed to follow instructions A computer program is a set of instructions thattells the computer how to solve a problem or perform a task For example, suppose we want thecomputer to calculate someone’s gross pay Here is a list of things the computer should do:

Checkpoint

1.1 Why is the computer used by so many different people, in so many different professions?

1.2 List the five major hardware components of a computer system

1.3 Internally, the CPU consists of what two units?

1.4 Describe the steps in the fetch/decode/execute cycle

1.5 What is a memory address?

1.6 Explain why computers have both main memory and secondary storage

1.7 What are the two general categories of software?

1.8 What is the difference between a single tasking system and a multitasking system?

1.9 What is the difference between a single user system and a multiuser system?

CONCEPT

A program is a set of instructions a computer follows in order to perform a task

A programming language is a special language used to write computer programs

Trang 35

1 Display a message on the screen asking “How many hours did you work?”

2 Wait for the user to enter the number of hours worked Once the user enters a number, store it in memory

3 Display a message on the screen asking “How much do you get paid per hour?”

4 Wait for the user to enter an hourly pay rate Once the user enters a number, store it

in memory

5 Multiply the number of hours by the amount paid per hour, and store the result in memory

6 Display a message on the screen that tells the amount of money earned The message must include the result of the calculation performed in step 5

Collectively, these instructions are called an algorithm An algorithm is a set of well-defined

steps for performing a task or solving a problem Notice these steps are sequentially ordered

Step 1 should be performed before step 2, and so forth It is important that these instructions

be performed in their proper sequence

In order for a computer to perform instructions such as the pay-calculating algorithm, thesteps must be converted to a form the computer can process In reality, the CPU only processes

instructions written in machine language If you were to look at a machine language program,

you would only see a stream of numbers The CPU interprets these numbers as commands As

you might imagine, the process of encoding an algorithm in machine language is very tedious

and difficult Computer programming languages, which use words instead of numbers, were

invented to ease this task Programmers can write their programs in a language such as C++,

and then use special software to convert the program into machine language

Program 1-1 shows how the pay-calculating algorithm might be written in C++

double hours, rate, pay;

cout << "How many hours did you work? ";

cin >> hours;

cout << "How much do you get paid per hour? ";

cin >> rate;

pay = hours * rate;

cout << "You have earned $" << pay << endl;

return 0;

}

Program Output with Example Input Shown in Bold

How many hours did you work? 10 [Enter]

How much do you get paid per hour? 15 [Enter]

You have earned $150

Trang 36

The “Program Output with Example Input Shown in Bold” shows what the program will display

on the screen when it is running In the example, the user enters 10 for the number of hoursworked and 15 for the hourly pay rate The program displays the earnings, which are $150

Programming Languages

In a broad sense, there are two categories of programming languages: low-level and high-level

A low-level language is close to the level of the computer, which means it resembles the numeric

machine language of the computer more than the natural language of humans The easiest

lan-guages for people to learn are high-level lanlan-guages They are called “high-level” because they are

closer to the level of human-readability than computer-readability Figure 1-4 illustrates theconcept of language levels

Figure 1-4

10100010 11101011Low level (machine language)

cout << "Enter the number ";

cout << "of hours worked: ";

cin >> hours;

cout << "Enter the hourly ";

cout << "pay rate: ";

cin >> rate;

High level (Close to human language)

Trang 37

Many high-level languages have been created Table 1-1 lists a few of the well-known ones

In addition to the high-level features necessary for writing applications such as payroll tems and inventory programs, C++ also has many low-level features C++ is based on the C

sys-language, which was invented for purposes such as writing operating systems and compilers

Because C++ evolved from C, it carries all of C’s low-level capabilities with it

C++ is popular not only because of its mixture of low- and high-level features, but also

because of its portability This means that a C++ program can be written on one type of

com-puter and then run on many other types of systems This usually requires that the program is

recompiled on each type of system, but the program itself may need little or no change

significant changes when moved to a different type of system Examples of such graphical environments are Windows, the X-Window System, and the Macintosh operating system.

Table 1-1 Well-Known High-Level Programming Languages

BASIC Beginners All-purpose Symbolic Instruction Code A general programming language originally

designed to be simple enough for beginners to learn.

FORTRAN Formula Translator A language designed for programming complex mathematical algorithms.

COBOL Common Business-Oriented Language A language designed for business applications.

Pascal A structured, general-purpose language designed primarily for teaching programming.

C A structured, general-purpose language developed at Bell Laboratories C offers both high-level and

low-level features.

C++ Based on the C language, C++ offers object-oriented features not found in C Also invented at Bell

Laboratories.

C# Pronounced “C sharp.” A language invented by Microsoft for developing applications based on the

Microsoft NET platform.

Java An object-oriented language invented at Sun Microsystems Java may be used to develop programs

that run over the Internet, in a Web browser.

Visual Basic A Microsoft programming language and software development environment that allows

programmers to quickly create Windows-based applications.

Trang 38

Source Code, Object Code, and Executable Code

When a C++ program is written, it must be typed into the computer and saved to a file A text editor, which is similar to a word processing program, is used for this task The statements written by the programmer are called source code, and the file they are saved in is called the source file

After the source code is saved to a file, the process of translating it to machine language can

begin During the first phase of this process, a program called the preprocessor reads the source

code The preprocessor searches for special lines that begin with the # symbol These lines tain commands that cause the preprocessor to modify the source code in some way During the

con-next phase the compiler steps through the preprocessed source code, translating each source

code instruction into the appropriate machine language instruction This process will uncover

any syntax errors that may be in the program Syntax errors are illegal uses of key words,

opera-tors, punctuation, and other language elements If the program is free of syntax errors, the

compiler stores the translated machine language instructions, which are called object code, in an object file.

Although an object file contains machine language instructions, it is not a complete gram Here is why: C++ is conveniently equipped with a library of prewritten code for per-forming common operations or sometimes-difficult tasks For example, the library containshardware-specific code for displaying messages on the screen and reading input from the key-board It also provides routines for mathematical functions, such as calculating the square

pro-root of a number This collection of code, called the run-time library, is extensive Programs

almost always use some part of it When the compiler generates an object file, however, it doesnot include machine code for any run-time library routines the programmer might have used

During the last phase of the translation process, another program called the linker combines

the object file with the necessary library routines Once the linker has finished with this step,

an executable file is created The executable file contains machine language instructions, or executable code, and is ready to run on the computer.

Figure 1-5 illustrates the process of translating a source file into an executable file Theentire process of invoking the preprocessor, compiler, and linker can be initiated with a singleaction For example, on a Linux system, the following command causes the C++ programnamed hello.cpp to be preprocessed, compiled, and linked The executable code is stored in afile named hello

g++ -o hello hello.cpp

Appendix M on the student CD explains how compiling works in NET.

Trang 39

Many development systems, particularly those on personal computers, have integrated

develop-ment environdevelop-ments (IDEs) These environdevelop-ments consist of a text editor, compiler, debugger, and

other utilities integrated into a package with a single set of menus Preprocessing, compiling,

linking, and even executing a program is done with a single click of a button, or by selecting a

single item from a menu Figure 1-6 shows a screen from the Microsoft Visual C++ 6.0 IDE

Figure 1-5

Source Code

Preprocessor

Modified Source Code

Compiler

Object Code

Executable Code Linker

Source code is entered with a text editor by the programmer.

#include <iostream>

using namespace std;

int main( ) {

cout << "Hello World\n";

return 0;

}

Trang 40

1.4 What Is a Program Made of?

1.11 Why were computer programming languages invented?

1.12 What is the difference between a high-level language and a low-level language?

1.13 What does portability mean?

1.14 Explain the operations carried out by the preprocessor, compiler, and linker

1.15 Explain what is stored in a source file, an object file, and an executable file

1.16 What is an integrated development environment?

CONCEPT

There are certain elements that are common to all programming languages

Ngày đăng: 19/03/2014, 14:13

TỪ KHÓA LIÊN QUAN