SlideShare a Scribd company logo
1 of 52
Assignments
Assignment 1
Read Chapter 2: “Introduction to C++ Programming” and
complete exercise 2.16 on page 79. Add comments in your
program in C++ comments format. Write a one page report that
explains how your program works. Your paper must be
formatted according to, APA style as outlined in the Ashford
Writing Center. Make sure that your program reads numbers
from the user and calculates the results correctly. Add your
name, the course ID and name, and the instructor’s name in the
printout using string operation. Your program should be able to
read the input and print the results properly.
Submit your source code and executable file.
Please copy and paste your code into a Word or PDF document
for submission. (the Waypoint system does not accept .cpp
(C++) or .exe (executable) file types)
Assignment 2
In the textbook, on page 400, solve problem 7.18: What does the
following program do?. Copy the sample program and compile
it, then find the results. Submit a report which is more than one
page length to explain how the program works and how you can
improve it. Your report should be formatted according to APA
style as outlined in the Ashford Writing Center. Write
comments in C++ comments format in the source file, to explain
what the functions are and how they work.
Submit your source code and executable file.
Please copy and paste your code into a Word or PDF document
for submission. (the Waypoint system does not accept .cpp
(C++) or .exe (executable) file types)
Final Assignment
Create the following program which converts Fahrenheit to
Celsius. Your program must have the following functions:
· Read integer Fahrenheit temperatures from the user. You need
to check whether the input is the correct one or not. If the user
enters the incorrect number, ask it again.
· Use the formula: Celsius = (Fahrenheit – 32) * 5.0 / 9.0
· The output Celsius should be a floating point with two digits
of precision.
· The Celsius temperatures should be displayed with a sign of
positive or negative.
· The program should ask the user to continue or not. If the user
wants to do the conversion again, use repetitive statements such
as DO WHILE, FOR, or IF THEN ELSE to do the conversion
again.
· Add comments to explain the functions of the program.
Write a user manual of more than two pages to explain how to
use your program. Format your manual according to APA style
as outlined in the Ashford Writing Center. Your program should
run without any errors.
Submit your source code and executable file.
Submit your source code file. Please copy and paste your code
into a Word or PDF document for submission. (the Waypoint
system does not accept .cpp (C++) or .exe (executable) file
types)
Deitel® Ser
How To Program Series
C How to Program, 6/E
C++ How to Program, 7/E
Java How to Program, 8/E, Early Objects Version
Java How to Program, 8/E, Late Objects Version
Internet & World Wide Web How to Program, 4/E
Visual Basic® 2008 How to Program
Visual C#® 2008 How to Program, 3/E
Visual C++® 2008 How to Program, 2/E
Small Java™ How to Program, 6/E
Small C++ How to Program, 5/E
Simply Series
Simply C++: An Application-Driven
Tutorial Approach
Simply Java™ Programming: An
Application-Driven Tutorial
Approach
Simply C#: An Application-Driven
Tutorial Approach
Simply Visual Basic® 2008, 3/E: An
Application-Driven Tutorial
Approach
CourseSmart Web Books
www.deitel.com/books/CourseSmart.html
C++ How to Program, 5/E, 6/E & 7/E
Java How to Program, 6/E, 7/E & 8/E
Simply C++: An Application-Driven
Tutorial Approach
Simply Visual Basic 2008: An
Application-Driven Tutorial
Approach, 3/E
Small C++ How to Program, 5/E
Small Java How to Program, 6/E
Visual Basic® 2008 How to Program
Visual C#® 2008 How to Program, 3/E
ies Page
www.deitel.com/books/CourseSmart.html
Deitel® Developer Series
AJAX, Rich Internet Applications and
Web Development for Programmers
C++ for Programmers
C# 2008 for Programmers, 3/E
iPhone for Programmers:
An App-Driven Approach
Java for Programmers
Javascript for Programmers
LiveLessons Video Learning Products
www.deitel.com/books/LiveLessons/
Java Fundamentals Parts 1 and 2
C# Fundamentals Parts 1 and 2
C++ Fundamentals Parts 1 and 2
JavaScript Fundamentals Parts 1 and 2
To receive updates on Deitel publications, Resource Centers,
training courses, partner
offers and more, please register for the free Deitel® Buzz
Online e-mail newsletter at:
www.deitel.com/newsletter/subscribe.html
follow us on Twitter®
@deitel
and Facebook®
www.deitel.com/deitelfan/
To communicate with the authors, send e-mail to:
[email protected]
For information on government and corporate Dive-Into® Series
on-site seminars
offered by Deitel & Associates, Inc. worldwide, visit:
www.deitel.com/training/
or write to
[email protected]
For continuing updates on Prentice Hall/Deitel publications
visit:
www.deitel.com
www.pearsonhighered.com/deitel
Check out our Resource Centers for valuable web resources that
will help you master
Java, other important programming languages, software and
Internet- and web-related
topics:
www.deitel.com/ResourceCenters.html
www.deitel.com/books/LiveLessons
www.deitel.com/newsletter/subscribe.html
www.deitel.com/deitelfan
www.deitel.com/training
www.deitel.com
www.pearsonhighered.com/deitel
www.deitel.com/ResourceCenters.html
Library of Congress Cataloging-in-Publication Data
On file
Vice President and Editorial Director, ECS: Marcia J. Horton
Editor-in-Chief, Computer Science: Michael Hirsch
Associate Editor: Carole Snyder
Supervisor/Editorial Assistant: Dolores Mars
Director of Team-Based Project Management: Vince O’Brien
Senior Managing Editor: Scott Disanno
Managing Editor: Robert Engelhardt
A/V Production Editor: Greg Dulles
Art Director: Kristine Carney
Cover Design: Abbey S. Deitel, Harvey M. Deitel, Francesco
Santalucia, Kristine Carney
Interior Design: Harvey M. Deitel, Kristine Carney
Manufacturing Manager: Alexis Heydt-Long
Manufacturing Buyer: Lisa McDowell
Director of Marketing: Margaret Waples
Marketing Manager: Erin Davis
© 2010 by Pearson Education, Inc.
Upper Saddle River, New Jersey 07458
The authors and publisher of this book have used their best
efforts in preparing this book. These efforts include the
development, research, and testing of the theories and programs
to determine their effectiveness. The authors and pub-
lisher make no warranty of any kind, expressed or implied, with
regard to these programs or to the documentation
contained in this book. The authors and publisher shall not be
liable in any event for incidental or consequential dam-
ages in connection with, or arising out of, the furnishing,
performance, or use of these programs.
Many of the designations used by manufacturers and sellers to
distinguish their products are claimed as trademarks
and registered trademarks. Where those designations appear in
this book, and Prentice Hall and the authors were aware
of a trademark claim, the designations have been printed in
initial caps or all caps. All product names mentioned
remain trademarks or registered trademarks of their respective
owners.
All rights reserved. No part of this book may be reproduced, in
any form or by any means, without permission in
writing from the publisher.
Printed in the United States of America
10 9 8 7 6 5 4 3 2 1
ISBN-10: 0-13-612356-2
ISBN-13: 978-0-13-612356-9
Pearson Education Ltd., London
Pearson Education Australia Pty. Ltd., Sydney
Pearson Education Singapore, Pte. Ltd.
Pearson Education North Asia Ltd., Hong Kong
Pearson Education Canada, Inc., Toronto
Pearson Educación de Mexico, S.A. de C.V.
Pearson Education–Japan, Tokyo
Pearson Education Malaysia, Pte. Ltd.
Pearson Education, Inc., Upper Saddle River, New Jersey
Upper Saddle River, New Jersey 07458
P. J. Deitel
Deitel & Associates, Inc.
H. M. Deitel
Deitel & Associates, Inc.
Trademarks
DEITEL, the double-thumbs-up bug and DIVE INTO are
registered trademarks of Deitel and Associates,
Inc.
Microsoft, Visual C++, Internet Explorer and the Windows logo
are either registered trademarks or trade-
marks of Microsoft Corporation in the United States and/or
other countries.
In Memory of Clifford Stephens:
Your friendship, bright smile and
infectious laugh will be truly missed.
Paul and Harvey Deitel
Deitel Resource Centers
Our Resource Centers focus on the vast amounts of free content
available online. Find resources,
downloads, tutorials, documentation, books, e-books, journals,
articles, blogs, RSS feeds and more
on many of today’s hottest programming and technology topics.
For the most up-to-date list of our
Resource Centers, visit:
www.deitel.com/ResourceCenters.html
Let us know what other Resource Centers you’d like to see!
Also, please register for the free Deitel®
Buzz Online e-mail newsletter at:
www.deitel.com/newsletter/subscribe.html
Computer Science
Functional Programming
Regular Expressions
Programming
ASP.NET 3.5
Adobe Flex
Ajax
Apex
ASP.NET Ajax
ASP.NET
C
C++
C++ Boost Libraries
C++ Game Programming
C#
Code Search Engines and
Code Sites
Computer Game
Programming
CSS 2.1
Dojo
Facebook Developer Plat-
form
Flash 9
Functional Programming
Java
Java Certification and
Assessment Testing
Java Design Patterns
Java EE 5
Java SE 6
Java SE 7 (Dolphin)
Resource Center
JavaFX
JavaScript
JSON
Microsoft LINQ
Microsoft Popfly
.NET
.NET 3.0
.NET 3.5
OpenGL
Perl
PHP
Programming Projects
Python
Regular Expressions
Ruby
Ruby on Rails
Silverlight
UML
Visual Basic
Visual C++
Visual Studio Team Sys-
tem
Web 3D Technologies
Web Services
Windows Presentation
Foundation
XHTML
XML
Apple
iPhone
Objective-C
Cocoa
Games and Game
Programming
Computer Game Pro-
gramming
Computer Games
Mobile Gaming
Sudoku
Internet Business
Affiliate Programs
Competitive Analysis
Facebook Social Ads
Google AdSense
Google Analytics
Google Services
Internet Advertising
Internet Business
Initiative
Internet Public Relations
Link Building
Location-Based Services
Online Lead Generation
Podcasting
Search Engine Optimiza-
tion
Selling Digital Content
Sitemaps
Web Analytics
Website Monetization
YouTube and AdSense
Java
Java
Java Certification and
Assessment Testing
Java Design Patterns
Java EE 5
Java SE 6
Java SE 7 (Dolphin)
Resource Center
JavaFX
Microsoft
ASP.NET
ASP.NET 3.5
ASP.NET Ajax
C#
DotNetNuke (DNN)
Internet Explorer 7 (IE7)
Microsoft LINQ
.NET
.NET 3.0
.NET 3.5
SharePoint
Silverlight
Visual Basic
Visual C++
Visual Studio Team
System
Windows Presentation
Foundation
Windows Vista
Microsoft Popfly
Open Source &
LAMP Stack
Apache
DotNetNuke (DNN)
Eclipse
Firefox
Linux
MySQL
Open Source
Perl
PHP
Python
Ruby
Software
Apache
DotNetNuke (DNN)
Eclipse
Firefox
Internet Explorer 7 (IE7)
Linux
MySQL
Open Source
Search Engines
SharePoint
Skype
Web Servers
Wikis
Windows Vista
Web 2.0
Alert Services
Attention Economy
Blogging
Building Web
Communities
Community Generated
Content
Facebook Developer
Platform
Facebook Social Ads
Google Base
Google Video
Google Web Toolkit
(GWT)
Internet Video
Joost
Location-Based Services
Mashups
Microformats
Recommender Systems
RSS
Social Graph
Social Media
Social Networking
Software as a Service
(SaaS)
Virtual Worlds
Web 2.0
Web 3.0
Widgets
Dive Into® Web 2.0
eBook
Web 2 eBook
Other Topics
Computer Games
Computing Jobs
Gadgets and Gizmos
Ring Tones
Sudoku
www.deitel.com/ResourceCenters.html
www.deitel.com/newsletter/subscribe.html
Appendices E through I are PDF documents posted online at the
book’s Companion
Website (located at www.pearsonhighered.com/deitel).
Preface xxi
1 Introduction to Computers, the Internet
and the Web 1
1.1 Introduction 2
1.2 Computers: Hardware and Software 3
1.3 Computer Organization 4
1.4 Personal, Distributed and Client/Server Computing 5
1.5 The Internet and the World Wide Web 5
1.6 Machine Languages, Assembly Languages and High-Level
Languages 6
1.7 History of C 7
1.8 C Standard Library 8
1.9 C++ 9
1.10 Java 9
1.11 Fortran, COBOL, Pascal and Ada 10
1.12 BASIC, Visual Basic, Visual C++, C# and .NET 10
1.13 Key Software Trend: Object Technology 11
1.14 Typical C Program Development Environment 12
1.15 Hardware Trends 14
1.16 Notes About C and This Book 15
1.17 Web Resources 16
2 Introduction to C Programming 23
2.1 Introduction 24
2.2 A Simple C Program: Printing a Line of Text 24
2.3 Another Simple C Program: Adding Two Integers 28
2.4 Memory Concepts 33
2.5 Arithmetic in C 34
2.6 Decision Making: Equality and Relational Operators 38
3 Structured Program Development in C 54
3.1 Introduction 55
3.2 Algorithms 55
Contents
www.pearsonhighered.com/deitel
x Contents
3.3 Pseudocode 55
3.4 Control Structures 56
3.5 The if Selection Statement 58
3.6 The if…else Selection Statement 59
3.7 The while Repetition Statement 63
3.8 Formulating Algorithms Case Study 1: Counter-Controlled
Repetition 64
3.9 Formulating Algorithms with Top-Down, Stepwise
Refinement
Case Study 2: Sentinel-Controlled Repetition 66
3.10 Formulating Algorithms with Top-Down, Stepwise
Refinement
Case Study 3: Nested Control Structures 73
3.11 Assignment Operators 77
3.12 Increment and Decrement Operators 78
4 C Program Control 97
4.1 Introduction 98
4.2 Repetition Essentials 98
4.3 Counter-Controlled Repetition 99
4.4 for Repetition Statement 100
4.5 for Statement: Notes and Observations 103
4.6 Examples Using the for Statement 103
4.7 switch Multiple-Selection Statement 107
4.8 do…while Repetition Statement 113
4.9 break and continue Statements 114
4.10 Logical Operators 116
4.11 Confusing Equality (==) and Assignment (=) Operators
119
4.12 Structured Programming Summary 121
5 C Functions 140
5.1 Introduction 141
5.2 Program Modules in C 141
5.3 Math Library Functions 142
5.4 Functions 144
5.5 Function Definitions 144
5.6 Function Prototypes 148
5.7 Function Call Stack and Activation Records 151
5.8 Headers 151
5.9 Calling Functions By Value and By Reference 152
5.10 Random Number Generation 153
5.11 Example: A Game of Chance 158
5.12 Storage Classes 161
5.13 Scope Rules 164
5.14 Recursion 167
5.15 Example Using Recursion: Fibonacci Series 170
5.16 Recursion vs. Iteration 174
Contents xi
6 C Arrays 195
6.1 Introduction 196
6.2 Arrays 196
6.3 Defining Arrays 198
6.4 Array Examples 198
6.5 Passing Arrays to Functions 212
6.6 Sorting Arrays 216
6.7 Case Study: Computing Mean, Median and Mode Using
Arrays 218
6.8 Searching Arrays 223
6.9 Multiple-Subscripted Arrays 229
7 C Pointers 253
7.1 Introduction 254
7.2 Pointer Variable Definitions and Initialization 254
7.3 Pointer Operators 255
7.4 Passing Arguments to Functions by Reference 257
7.5 Using the const Qualifier with Pointers 261
7.6 Bubble Sort Using Call-by-Reference 267
7.7 sizeof Operator 270
7.8 Pointer Expressions and Pointer Arithmetic 273
7.9 Relationship between Pointers and Arrays 275
7.10 Arrays of Pointers 280
7.11 Case Study: Card Shuffling and Dealing Simulation 280
7.12 Pointers to Functions 285
8 C Characters and Strings 309
8.1 Introduction 310
8.2 Fundamentals of Strings and Characters 310
8.3 Character-Handling Library 312
8.4 String-Conversion Functions 317
8.5 Standard Input/Output Library Functions 322
8.6 String-Manipulation Functions of the String-Handling
Library 326
8.7 Comparison Functions of the String-Handling Library 329
8.8 Search Functions of the String-Handling Library 331
8.9 Memory Functions of the String-Handling Library 337
8.10 Other Functions of the String-Handling Library 341
9 C Formatted Input/Output 356
9.1 Introduction 357
9.2 Streams 357
9.3 Formatting Output with printf 357
9.4 Printing Integers 358
9.5 Printing Floating-Point Numbers 359
xii Contents
9.6 Printing Strings and Characters 361
9.7 Other Conversion Specifiers 362
9.8 Printing with Field Widths and Precision 363
9.9 Using Flags in the printf Format Control String 366
9.10 Printing Literals and Escape Sequences 368
9.11 Reading Formatted Input with scanf 369
10 C Structures, Unions, Bit Manipulations and
Enumerations 382
10.1 Introduction 383
10.2 Structure Definitions 383
10.3 Initializing Structures 386
10.4 Accessing Structure Members 386
10.5 Using Structures with Functions 388
10.6 typedef 388
10.7 Example: High-Performance Card Shuffling and Dealing
Simulation 389
10.8 Unions 391
10.9 Bitwise Operators 394
10.10 Bit Fields 403
10.11 Enumeration Constants 406
11 C File Processing 417
11.1 Introduction 418
11.2 Data Hierarchy 418
11.3 Files and Streams 420
11.4 Creating a Sequential-Access File 421
11.5 Reading Data from a Sequential-Access File 426
11.6 Random-Access Files 430
11.7 Creating a Random-Access File 431
11.8 Writing Data Randomly to a Random-Access File 433
11.9 Reading Data from a Random-Access File 436
11.10 Case Study: Transaction-Processing Program 437
12 C Data Structures 454
12.1 Introduction 455
12.2 Self-Referential Structures 456
12.3 Dynamic Memory Allocation 456
12.4 Linked Lists 458
12.5 Stacks 466
12.6 Queues 472
12.7 Trees 478
13 C Preprocessor 495
13.1 Introduction 496
Contents xiii
13.2 #include Preprocessor Directive 496
13.3 #define Preprocessor Directive: Symbolic Constants 496
13.4 #define Preprocessor Directive: Macros 497
13.5 Conditional Compilation 499
13.6 #error and #pragma Preprocessor Directives 500
13.7 # and ## Operators 500
13.8 Line Numbers 501
13.9 Predefined Symbolic Constants 501
13.10 Assertions 502
14 Other C Topics 507
14.1 Introduction 508
14.2 Redirecting I/O 508
14.3 Variable-Length Argument Lists 509
14.4 Using Command-Line Arguments 511
14.5 Notes on Compiling Multiple-Source-File Programs 512
14.6 Program Termination with exit and atexit 514
14.7 volatile Type Qualifier 515
14.8 Suffixes for Integer and Floating-Point Constants 516
14.9 More on Files 516
14.10 Signal Handling 518
14.11 Dynamic Memory Allocation: Functions calloc and
realloc 520
14.12 Unconditional Branching with goto 521
15 C++ as a Better C; Introducing
Object Technology 528
15.1 Introduction 529
15.2 C++ 529
15.3 A Simple Program: Adding Two Integers 530
15.4 C++ Standard Library 532
15.5 Header Files 533
15.6 Inline Functions 535
15.7 References and Reference Parameters 537
15.8 Empty Parameter Lists 542
15.9 Default Arguments 542
15.10 Unary Scope Resolution Operator 544
15.11 Function Overloading 545
15.12 Function Templates 548
15.13 Introduction to Object Technology and the UML 551
15.14 Wrap-Up 554
16 Introduction to Classes and Objects 560
16.1 Introduction 561
16.2 Classes, Objects, Member Functions and Data Members
561
xiv Contents
16.3 Defining a Class with a Member Function 562
16.4 Defining a Member Function with a Parameter 566
16.5 Data Members, set Functions and get Functions 569
16.6 Initializing Objects with Constructors 576
16.7 Placing a Class in a Separate File for Reusability 579
16.8 Separating Interface from Implementation 583
16.9 Validating Data with set Functions 589
16.10 Wrap-Up 594
17 Classes: A Deeper Look, Part 1 601
17.1 Introduction 602
17.2 Time Class Case Study 603
17.3 Class Scope and Accessing Class Members 609
17.4 Separating Interface from Implementation 611
17.5 Access Functions and Utility Functions 612
17.6 Time Class Case Study: Constructors with Default
Arguments 615
17.7 Destructors 620
17.8 When Constructors and Destructors are Called 621
17.9 Time Class Case Study: A Subtle Trap—Returning a
Reference to a
private Data Member 624
17.10 Default Memberwise Assignment 627
17.11 Wrap-Up 629
18 Classes: A Deeper Look, Part 2 635
18.1 Introduction 636
18.2 const (Constant) Objects and const Member Functions 636
18.3 Composition: Objects as Members of Classes 645
18.4 friend Functions and friend Classes 651
18.5 Using the this Pointer 654
18.6 static Class Members 659
18.7 Data Abstraction and Information Hiding 664
18.8 Wrap-Up 666
19 Operator Overloading 672
19.1 Introduction 673
19.2 Fundamentals of Operator Overloading 674
19.3 Restrictions on Operator Overloading 675
19.4 Operator Functions as Class Members vs. Global Function
676
19.5 Overloading Stream Insertion and Stream Extraction
Operators 678
19.6 Overloading Unary Operators 681
19.7 Overloading Binary Operators 682
19.8 Dynamic Memory Management 682
19.9 Case Study: Array Class 684
19.10 Converting between Types 696
Contents xv
19.11 Building a String Class 697
19.12 Overloading ++ and -- 698
19.13 Case Study: A Date Class 700
19.14 Standard Library Class string 704
19.15 explicit Constructors 708
19.16 Proxy Classes 711
19.17 Wrap-Up 715
20 Object-Oriented Programming: Inheritance 727
20.1 Introduction 728
20.2 Base Classes and Derived Classes 729
20.3 protected Members 732
20.4 Relationship between Base Classes and Derived Classes
732
20.4.1 Creating and Using a CommissionEmployee Class 733
20.4.2 Creating a BasePlusCommissionEmployee Class Without
Using Inheritance 738
20.4.3 Creating a CommissionEmployee–
BasePlusCommissionEmployee
Inheritance Hierarchy 743
20.4.4 CommissionEmployee–BasePlusCommissionEmployee
Inheritance Hierarchy Using protected Data 748
20.4.5 CommissionEmployee–BasePlusCommissionEmployee
Inheritance Hierarchy Using private Data 755
20.5 Constructors and Destructors in Derived Classes 762
20.6 public, protected and private Inheritance 770
20.7 Software Engineering with Inheritance 771
20.8 Wrap-Up 772
21 Object-Oriented Programming: Polymorphism 778
21.1 Introduction 779
21.2 Polymorphism Examples 780
21.3 Relationships Among Objects in an Inheritance Hierarchy
781
21.3.1 Invoking Base-Class Functions from Derived-Class
Objects 782
21.3.2 Aiming Derived-Class Pointers at Base-Class Objects
789
21.3.3 Derived-Class Member-Function Calls via Base-Class
Pointers 790
21.3.4 Virtual Functions 792
21.3.5 Summary of the Allowed Assignments Between Base-
Class
and Derived-Class Objects and Pointers 798
21.4 Type Fields and switch Statements 799
21.5 Abstract Classes and Pure virtual Functions 799
21.6 Case Study: Payroll System Using Polymorphism 801
21.6.1 Creating Abstract Base Class Employee 803
21.6.2 Creating Concrete Derived Class SalariedEmployee 806
21.6.3 Creating Concrete Derived Class HourlyEmployee 808
21.6.4 Creating Concrete Derived Class CommissionEmployee
811
xvi Contents
21.6.5 Creating Indirect Concrete Derived Class
BasePlusCommissionEmployee 813
21.6.6 Demonstrating Polymorphic Processing 814
21.7 (Optional) Polymorphism, Virtual Functions and Dynamic
Binding
“Under the Hood” 818
21.8 Case Study: Payroll System Using Polymorphism and
Runtime Type
Information with Downcasting, dynamic_cast, typeid and
type_info 822
21.9 Virtual Destructors 826
21.10 Wrap-Up 826
22 Templates 832
22.1 Introduction 833
22.2 Function Templates 833
22.3 Overloading Function Templates 837
22.4 Class Templates 837
22.5 Nontype Parameters and Default Types for Class
Templates 844
22.6 Notes on Templates and Inheritance 845
22.7 Notes on Templates and Friends 845
22.8 Notes on Templates and static Members 846
22.9 Wrap-Up 846
23 Stream Input/Output 851
23.1 Introduction 852
23.2 Streams 853
23.2.1 Classic Streams vs. Standard Streams 853
23.2.2 iostream Library Header Files 854
23.2.3 Stream Input/Output Classes and Objects 854
23.3 Stream Output 857
23.3.1 Output of char * Variables 857
23.3.2 Character Output Using Member Function put 857
23.4 Stream Input 858
23.4.1 get and getline Member Functions 858
23.4.2 istream Member Functions peek, putback and ignore 861
23.4.3 Type-Safe I/O 861
23.5 Unformatted I/O Using read, write and gcount 861
23.6 Introduction to Stream Manipulators 862
23.6.1 Integral Stream Base: dec, oct, hex and setbase 863
23.6.2 Floating-Point Precision (precision, setprecision) 864
23.6.3 Field Width (width, setw) 865
23.6.4 User-Defined Output Stream Manipulators 866
23.7 Stream Format States and Stream Manipulators 868
23.7.1 Trailing Zeros and Decimal Points (showpoint) 868
23.7.2 Justification (left, right and internal) 869
23.7.3 Padding (fill, setfill) 871
23.7.4 Integral Stream Base (dec, oct, hex, showbase) 872
Contents xvii
23.7.5 Floating-Point Numbers; Scientific and Fixed Notation
(scientific, fixed) 873
23.7.6 Uppercase/Lowercase Control (uppercase) 874
23.7.7 Specifying Boolean Format (boolalpha) 874
23.7.8 Setting and Resetting the Format State via Member
Function flags 875
23.8 Stream Error States 877
23.9 Tying an Output Stream to an Input Stream 879
23.10 Wrap-Up 879
24 Exception Handling 889
24.1 Introduction 890
24.2 Exception-Handling Overview 891
24.3 Example: Handling an Attempt to Divide by Zero 891
24.4 When to Use Exception Handling 897
24.5 Rethrowing an Exception 898
24.6 Exception Specifications 900
24.7 Processing Unexpected Exceptions 901
24.8 Stack Unwinding 901
24.9 Constructors, Destructors and Exception Handling 903
24.10 Exceptions and Inheritance 904
24.11 Processing new Failures 904
24.12 Class auto_ptr and Dynamic Memory Allocation 907
24.13 Standard Library Exception Hierarchy 909
24.14 Other Error-Handling Techniques 911
24.15 Wrap-Up 912
A Operator Precedence Charts 919
B ASCII Character Set 923
C Number Systems 924
C.1 Introduction 925
C.2 Abbreviating Binary Numbers as Octal and Hexadecimal
Numbers 928
C.3 Converting Octal and Hexadecimal Numbers to Binary
Numbers 929
C.4 Converting from Binary, Octal or Hexadecimal to Decimal
929
C.5 Converting from Decimal to Binary, Octal or Hexadecimal
930
C.6 Negative Binary Numbers: Two’s Complement Notation
932
D Game Programming: Solving Sudoku 937
D.1 Introduction 937
D.2 Deitel Sudoku Resource Center 938
D.3
Solution
Strategies 938
xviii Contents
D.4 Programming Sudoku Puzzle Solvers 942
D.5 Generating New Sudoku Puzzles 943
D.6 Conclusion 945
Appendices on the Web 946
Appendices E through I are PDF documents posted online at the
book’s Companion
Website (located at www.pearsonhighered.com/deitel).
E Game Programming with the Allegro C Library I
E.1 Introduction II
E.2 Installing Allegro II
E.3 A Simple Allegro Program III
E.4 Simple Graphics: Importing Bitmaps and Blitting IV
E.5 Animation with Double Buffering IX
E.6 Importing and Playing Sounds XVI
E.7 Keyboard Input XX
E.8 Fonts and Displaying Text XXV
E.9 Implementing the Game of Pong XXXI
E.10 Timers in Allegro XXXVII
E.11 The Grabber and Allegro Datafiles XLII
E.12 Other Allegro Capabilities LI
E.13 Allegro Resource Center LII
F Sorting: A Deeper Look LVIII
F.1 Introduction LIX
F.2 Big O Notation LIX
F.3 Selection Sort LX
F.4 Insertion Sort LXIV
F.5 Merge Sort LXVII
G Introduction to C99 LXXVIII
G.1 Introduction LXXIX
G.2 Support for C99 LXXIX
G.3 New C99 Headers LXXX
G.4 // Comments LXXX
G.5 Mixing Declarations and Executable Code LXXXI
G.6 Declaring a Variable in a for Statement Header LXXXII
G.7 Designated Initializers and Compound Literals LXXXIV
G.8 Type bool LXXXVII
G.9 Implicit int in Function Declarations LXXXVIII
G.10 Complex Numbers LXXXIX
G.11 Variable-Length Arrays XC
www.pearsonhighered.com/deitel
Contents xix
G.12 The snprintf Function: Helping Avoid Hacker Attacks
XCIII
G.13 Additions to the Preprocessor XCV
G.14 Other C99 Features XCVI
G.15 Web Resources XCIX
H Using the Visual Studio Debugger CIV
H.1 Introduction CV
H.2 Breakpoints and the Continue Command CV
H.3 Locals and Watch Windows CIX
H.4 Controlling Execution Using the Step Into, Step Over, Step
Out
and Continue Commands CXII
H.5 Autos Window CXIV
H.6 Wrap-Up CXVI
I Using the GNU Debugger CXVIII
I.1 Introduction CXIX
I.2 Breakpoints and the run, stop, continue and print Commands
CXIX
I.3 print and set Commands CXXIV
I.4 Controlling Execution Using the step, finish and next
Commands CXXVI
I.5 watch Command CXXVIII
I.6 Wrap-Up CXXX
Index 947
This page intentionally left blank
Welcome to the C programming language—and to C++, too!
This book presents leading-
edge computing technologies for students, instructors and
software development profes-
sionals.
At the heart of the book is the Deitel signature “live-code
approach.” Concepts are
presented in the context of complete working programs, rather
than in code snippets. Each
code example is immediately followed by one or more sample
executions. All the source
code is available at www.deitel.com/books/chtp6/.
We believe that this book and its support materials will give
you an informative, inter-
esting, challenging and entertaining introduction to C.
As you read the book, if you have questions, send an e-mail to
[email protected];
we’ll respond promptly. For updates on this book and its
supporting C and C++ software,
and for the latest news on all Deitel publications and services,
visit www.deitel.com.
New and Updated Features
Here are the updates we’ve made for C How to Program, 6/e:
• “Making a Difference” Exercises Set. We encourage you to
use computers and the
Internet to research and solve problems that really matter. These
new exercises are
meant to increase awareness of important issues the world is
facing. We hope
you’ll approach them with your own values, politics and beliefs.
• Tested All Code on Windows and Linux. We’ve tested every
program (the exam-
ples and the exercises) using both Visual C++ 2008 and GNU
GCC 4.3. The
code examples and exercise code solutions were also tested
using Visual Studio
2010 Beta.
• New Design. The book has a new interior design that
graphically serves to orga-
nize, clarify and highlight the information, and enhances the
book’s pedagogy.
• Improved Terminology Sections. We’ve added page numbers
for the defining oc-
currences of all terms in the terminology lists for easy
reference.
• Updated Coverage of C++ and Object-Oriented Programming.
We updated
Chapters 15–24 on object-oriented programming in C++ with
material from our
just published C++ How to Program, 7/e.
• Titled Programming Exercises. We’ve titled all the
programming exercises. This
helps instructors tune assignments for their classes.
• New Web Appendices. Chapters 15–17 from the previous
edition are now search-
able PDF Appendices E–G, available on the Companion Website
(see the access
card at the front of the book).
Preface
www.deitel.com/books/chtp6
www.deitel.com
xxii Preface
• New Debugger Appendices. We also added new debugging
appendices for Visual
C++® 2008 and GNU gdb.
• Order of Evaluation. We added cautions about order of
evaluation issues.
• We replaced all uses of gets (from <stdio.h>) with fgets,
because gets is now
deprecated.
• Additional Exercises. We added more function pointer
exercises. We also added
the Fibonacci exercise project that improves the Fibonacci
recursion example (tail
recursion).
• Secure C Programming Resource Center. We’ve posted a new
Secure C Program-
ming Resource Center at www.deitel.com/SecureC/. We’ve also
added notes
about secure C programming to the introductions in Chapter 7,
Pointers, and
Chapter 8, Strings.
• Game Programming with Allegro. We updated the chapter on
game program-
ming with the Allegro C library. In particular, we added
instructions on installing
the Allegro libraries for use with Visual C++® 2008 and GNU
GCC 4.3.
• Coverage of the C99 Standard. We updated and enhanced the
detailed appendix
on C99, which was reviewed by John Benito, Convener of ISO
WG14—the
Working Group responsible for the C Programming Language
Standard. Each
C99 concept is now keyed to the section where it can be taught
earlier in the
book. C99 is not incorporated throughout the book because
Microsoft does not
yet support it and a large percentage of C courses use
Microsoft's Visual C++®
compiler. For additional information, check out the C99
Standard section in our
C Resource center at www.deitel.com/C/. You'll find features of
C99, articles
from experts, the differences between Standard C and C99,
FAQs, downloads
and more.
• C++-Style // Comments. We discuss C++-style // comments
early for instructors
and students who’d prefer to use them. Although Microsoft C
does not yet sup-
port C99, it does support C99’s comments, which are borrowed
from C++.
• C Standard Library. Section 1.8 now references P.J. Plauger’s
Dinkumware web-
site (www.dinkumware.com/manuals/default.aspx) where
students can find
thorough searchable documentation for the C Standard Library
functions.
Other Features
Other features of C How to Program, 6/e, include:
Game Programming with the Allegro C Game Programming
Library
Appendix E introduces the Allegro game programming C
library. This library—originally
developed by Climax game programmer Shawn Hargreaves—
was created to be a powerful
tool for programming games in C while still remaining
relatively simple compared to oth-
er, more complicated graphics libraries such as DirectX and
OpenGL. In Appendix E, we
use Allegro’s capabilities to create the simple game of Pong.
Along the way, we demon-
strate how to display graphics, play sounds, receive input from
the keyboard and create
timed events—features you can use to create games of your
own. Students and instructors
www.deitel.com/SecureC
www.deitel.com/C
www.dinkumware.com/manuals/default.aspx
Web-Based Materials xxiii
alike will find Allegro challenging and entertaining. We include
extensive web resources
in our Allegro Resource Center (www.deitel.com/allegro), one
of which offers more
than 1000 open-source Allegro games.
Sorting: A Deeper Look
Sorting places data in order, based on one or more sort keys.
We begin our presentation
of sorting with a simple algorithm in Chapter 6. In Appendix F,
we present a deeper look
at sorting. We consider several algorithms and compare them
with regard to their memory
consumption and processor demands. For this purpose, we
introduce Big O notation,
which indicates how hard an algorithm may have to work to
solve a problem. Through
examples and exercises, Appendix F discusses the selection
sort, insertion sort, recursive
merge sort, recursive selection sort, bucket sort and recursive
Quicksort.
Web-Based Materials
This book is supported by substantial online materials. The
book’s Companion Website
(www.pearsonhighered.com/deitel; see the access card at the
front of the book) contains
the following appendices in searchable PDF format:
• Appendix E, Game Programming with the Allegro C Library
• Appendix F, Sorting: A Deeper Look
• Appendix G, Introduction to C99
• Appendix H, Using the Visual Studio Debugger
• Appendix I, Using the GNU Debugger
Dependency Charts
The dependency charts in Figs. 1–2 show the dependencies
among the chapters to help
instructors plan their syllabi. C How to Program, 6/e is
appropriate for CS1 and CS2 cours-
es, and intermediate-level C and C++ programming courses. The
C++ part of the book
assumes that you have studied the C part.
Teaching Approach
C How to Program, 6/e, contains a rich collection of examples.
We concentrate on demon-
strating the principles of good software engineering and
stressing program clarity.
Live-Code Approach. C How to Program, 6/e, is loaded with
“live-code” examples. Most
new concepts are presented in the context of complete working
C applications, followed
by one or more executions showing program inputs and outputs.
Syntax Shading
For readability, we syntax shade the code, similar to the way
most integrated-development
environments and code editors syntax color code. Our syntax-
shading conventions are:
comments appear like this
keywords appear like this
constants and literal values appear like this
all other code appears in black
www.deitel.com/allegro
www.pearsonhighered.com/deitel
xxiv Preface
Code Highlighting
We place gray rectangles around the key code.
Using Fonts for Emphasis. We place the key terms and the
index’s page reference for each
defining occurrence in bold blue text for easy reference. We
emphasize on-screen compo-
nents in the bold Helvetica font (e.g., the File menu) and C
program text in the Lucida
font (for example, int x = 5;).
Web Access. All of the source-code examples are available for
download from:
Fig. 1 | C chapter dependency chart.
www.deitel.com/books/chtp6/
Introduction
1 Introduction to Computers,
the Internet and the Web
Intro to Programming
2 Intro to C Programming
Control Statements,
Functions and Arrays
3 Structured Program
Development in C
4 C Program Control
5 C Functions
6 C Arrays
Pointers and Strings
8 C Characters and Strings
7 C Pointers
5.14–5.16 Recursion
12 C Data Structures
F Sorting: A Deeper Look
Data Structures
Other Topics, Game Programming and C99
C Chapter
Dependency
Chart
[Note: Arrows pointing into a
chapter indicate that chapter’s
dependencies.]
G Introduction to C99
E Game Programming with
the Allegro C Library
10 C Structures, Unions, Bit
Manipulations and Enumerations
Aggregate Types
Streams and Files
11 C File Processing
9 C Formatted Input/Output
13 C Preprocessor
14 Other C Topics
www.deitel.com/books/chtp6
Teaching Approach xxv
Quotations. Each chapter begins with quotations. We hope that
you enjoy relating these
to the chapter material.
Objectives. The quotes are followed by a list of chapter
objectives.
Illustrations/Figures. Abundant charts, tables, line drawings,
UML diagrams, programs
and program output are included.
Programming Tips
We include programming tips to help you focus on important
aspects of program devel-
opment. These tips and practices represent the best we’ve
gleaned from a combined seven
decades of programming and teaching experience.
Fig. 2 | C++ chapter dependency chart.
Good Programming Practice
The Good Programming Practices call attention to techniques
that will help you pro-
duce programs that are clearer, more understandable and more
maintainable.
Common Programming Error
Pointing out these Common Programming Errors reduces the
likelihood that you’ll
make them.
Error-Prevention Tip
These tips contain suggestions for exposing and removing bugs
from your programs; many
describe aspects of C that prevent bugs from getting into
programs in the first place.
Object-Based
Programming
C++ Chapter
Dependency
Chart
18 Classes: A Deeper
Look, Part 2
17 Classes: A Deeper
Look, Part 1
19 Operator Overloading
Object-Oriented
Programming
23 Stream
Input/Output
20 OOP: Inheritance
22 Templates21 OOP:
Polymorphism
24 Exception
Handling
15 C++ as a Better C;
Intro to Object Technology
16 Intro to Classes and Objects
[Note: Arrows pointing into a
chapter indicate that chapter’s
dependencies.]
xxvi Preface
Summary Bullets. We present a section-by-section, bullet-list
summary of the chapter.
Terminology. We include an alphabetized list of the important
terms defined in each chap-
ter with the page number of each term’s defining occurrence for
easy reference.
Self-Review Exercises and Answers. Extensive self-review
exercises and answers are includ-
ed for self-study.
Exercises. Each chapter concludes with a substantial set of
exercises including:
• simple recall of important terminology and concepts,
• identifying the errors in code samples,
• writing individual C statements,
• writing small portions of functions and classes,
• writing complete C functions, classes and programs, and
• major projects.
Instructors can use these exercises to form homework
assignments, short quizzes, major ex-
aminations and term projects. [NOTE: Please do not write to us
requesting access to the
Pearson Instructor’s Resource Center which contains the book’s
instructor supple-
ments, including the exercise solutions. Access is limited
strictly to college instructors
teaching from the book. Instructors may obtain access only
through their Pearson rep-
resentatives.
AssignmentsAssignment 1Read Chapter 2 Introduction to C++ .docx

More Related Content

Similar to AssignmentsAssignment 1Read Chapter 2 Introduction to C++ .docx

ADMSHS_Emp_Tech_Q1_M4_L1-Applied-productivity-tools-using-Word.pdf
ADMSHS_Emp_Tech_Q1_M4_L1-Applied-productivity-tools-using-Word.pdfADMSHS_Emp_Tech_Q1_M4_L1-Applied-productivity-tools-using-Word.pdf
ADMSHS_Emp_Tech_Q1_M4_L1-Applied-productivity-tools-using-Word.pdf
charmainejornadal
 
ECE specific internship offers for exam
ECE specific internship offers for examECE specific internship offers for exam
ECE specific internship offers for exam
raknin
 
Ece job adsautumn2013
Ece job adsautumn2013Ece job adsautumn2013
Ece job adsautumn2013
mfct33
 
ECE specific internship offers for exam
ECE specific internship offers for examECE specific internship offers for exam
ECE specific internship offers for exam
raknin
 
Sandeep Updated Resume
Sandeep Updated ResumeSandeep Updated Resume
Sandeep Updated Resume
Sandeep Sharma
 
mroden_resume29_writer_2016
mroden_resume29_writer_2016mroden_resume29_writer_2016
mroden_resume29_writer_2016
Martha Roden
 

Similar to AssignmentsAssignment 1Read Chapter 2 Introduction to C++ .docx (20)

ADMSHS_Emp_Tech_Q1_M4_L1-Applied-productivity-tools-using-Word.pdf
ADMSHS_Emp_Tech_Q1_M4_L1-Applied-productivity-tools-using-Word.pdfADMSHS_Emp_Tech_Q1_M4_L1-Applied-productivity-tools-using-Word.pdf
ADMSHS_Emp_Tech_Q1_M4_L1-Applied-productivity-tools-using-Word.pdf
 
app-and-web-brochure
app-and-web-brochureapp-and-web-brochure
app-and-web-brochure
 
SAC_Planning.pdf
SAC_Planning.pdfSAC_Planning.pdf
SAC_Planning.pdf
 
POS/408 ENTIRE CLASS UOP TUTORIALS
POS/408 ENTIRE CLASS UOP TUTORIALSPOS/408 ENTIRE CLASS UOP TUTORIALS
POS/408 ENTIRE CLASS UOP TUTORIALS
 
Chandrasekharmeruva
ChandrasekharmeruvaChandrasekharmeruva
Chandrasekharmeruva
 
ECE specific internship offers for exam
ECE specific internship offers for examECE specific internship offers for exam
ECE specific internship offers for exam
 
Ece job adsautumn2013
Ece job adsautumn2013Ece job adsautumn2013
Ece job adsautumn2013
 
Ece job adsautumn2013
Ece job adsautumn2013Ece job adsautumn2013
Ece job adsautumn2013
 
ECE specific internship offers for exam
ECE specific internship offers for examECE specific internship offers for exam
ECE specific internship offers for exam
 
Chapter 2- Prog101.ppt
Chapter 2- Prog101.pptChapter 2- Prog101.ppt
Chapter 2- Prog101.ppt
 
Report on web development
Report on web developmentReport on web development
Report on web development
 
(Effective Software Development Series) Bill Wagner - Effective C# (Covers C#...
(Effective Software Development Series) Bill Wagner - Effective C# (Covers C#...(Effective Software Development Series) Bill Wagner - Effective C# (Covers C#...
(Effective Software Development Series) Bill Wagner - Effective C# (Covers C#...
 
Sandeep Updated Resume
Sandeep Updated ResumeSandeep Updated Resume
Sandeep Updated Resume
 
mroden_resume29_writer_2016
mroden_resume29_writer_2016mroden_resume29_writer_2016
mroden_resume29_writer_2016
 
Data Science - Part II - Working with R & R studio
Data Science - Part II -  Working with R & R studioData Science - Part II -  Working with R & R studio
Data Science - Part II - Working with R & R studio
 
Shiny Agency's Facebook Development Guidelines
Shiny Agency's Facebook Development GuidelinesShiny Agency's Facebook Development Guidelines
Shiny Agency's Facebook Development Guidelines
 
Abc c program
Abc c programAbc c program
Abc c program
 
rupendrakumart
rupendrakumartrupendrakumart
rupendrakumart
 
POS 408 Creative and Effective/newtonhelp.com
POS 408 Creative and Effective/newtonhelp.comPOS 408 Creative and Effective/newtonhelp.com
POS 408 Creative and Effective/newtonhelp.com
 
POS 408 Extraordinary Life/newtonhelp.com 
POS 408 Extraordinary Life/newtonhelp.com POS 408 Extraordinary Life/newtonhelp.com 
POS 408 Extraordinary Life/newtonhelp.com 
 

More from rock73

BASEBALLRuns Scored (X)Wins (Y)70869875906547970480787957307166786.docx
BASEBALLRuns Scored (X)Wins (Y)70869875906547970480787957307166786.docxBASEBALLRuns Scored (X)Wins (Y)70869875906547970480787957307166786.docx
BASEBALLRuns Scored (X)Wins (Y)70869875906547970480787957307166786.docx
rock73
 
Based on Santa Clara University Ethics DialogueEthics .docx
Based on Santa Clara University Ethics DialogueEthics .docxBased on Santa Clara University Ethics DialogueEthics .docx
Based on Santa Clara University Ethics DialogueEthics .docx
rock73
 
Barbara Corcoran Learns Her Heart’s True Desires In her.docx
Barbara Corcoran Learns Her Heart’s True Desires  In her.docxBarbara Corcoran Learns Her Heart’s True Desires  In her.docx
Barbara Corcoran Learns Her Heart’s True Desires In her.docx
rock73
 
Bapsi Sidhwa’s Cracking India1947 PartitionDeepa Meh.docx
Bapsi Sidhwa’s Cracking India1947 PartitionDeepa Meh.docxBapsi Sidhwa’s Cracking India1947 PartitionDeepa Meh.docx
Bapsi Sidhwa’s Cracking India1947 PartitionDeepa Meh.docx
rock73
 
Barriers of therapeutic relationshipThe therapeutic relations.docx
Barriers of therapeutic relationshipThe therapeutic relations.docxBarriers of therapeutic relationshipThe therapeutic relations.docx
Barriers of therapeutic relationshipThe therapeutic relations.docx
rock73
 
Barada 2Mohamad BaradaProfessor Andrew DurdinReligions of .docx
Barada 2Mohamad BaradaProfessor Andrew DurdinReligions of .docxBarada 2Mohamad BaradaProfessor Andrew DurdinReligions of .docx
Barada 2Mohamad BaradaProfessor Andrew DurdinReligions of .docx
rock73
 

More from rock73 (20)

In a two- to three-page paper (excluding the title and reference pag.docx
In a two- to three-page paper (excluding the title and reference pag.docxIn a two- to three-page paper (excluding the title and reference pag.docx
In a two- to three-page paper (excluding the title and reference pag.docx
 
In a substantial paragraph respond to either one of the following qu.docx
In a substantial paragraph respond to either one of the following qu.docxIn a substantial paragraph respond to either one of the following qu.docx
In a substantial paragraph respond to either one of the following qu.docx
 
In a study by Dr. Sandra Levitsky, she considers why the economic,.docx
In a study by Dr. Sandra Levitsky, she considers why the economic,.docxIn a study by Dr. Sandra Levitsky, she considers why the economic,.docx
In a study by Dr. Sandra Levitsky, she considers why the economic,.docx
 
In a response of at least two paragraphs, provide an explanation o.docx
In a response of at least two paragraphs, provide an explanation o.docxIn a response of at least two paragraphs, provide an explanation o.docx
In a response of at least two paragraphs, provide an explanation o.docx
 
in a minimum of 1000 words, describe why baseball is Americas past .docx
in a minimum of 1000 words, describe why baseball is Americas past .docxin a minimum of 1000 words, describe why baseball is Americas past .docx
in a minimum of 1000 words, describe why baseball is Americas past .docx
 
In a minimum 200 word response, describe some ways how the public .docx
In a minimum 200 word response, describe some ways how the public .docxIn a minimum 200 word response, describe some ways how the public .docx
In a minimum 200 word response, describe some ways how the public .docx
 
In a weekly coordination meeting, several senior investigators from .docx
In a weekly coordination meeting, several senior investigators from .docxIn a weekly coordination meeting, several senior investigators from .docx
In a weekly coordination meeting, several senior investigators from .docx
 
In a memo, describe 1) the form and style of art as well as 2) the e.docx
In a memo, describe 1) the form and style of art as well as 2) the e.docxIn a memo, describe 1) the form and style of art as well as 2) the e.docx
In a memo, describe 1) the form and style of art as well as 2) the e.docx
 
In a minimum 200 word response explain the problems that law enforce.docx
In a minimum 200 word response explain the problems that law enforce.docxIn a minimum 200 word response explain the problems that law enforce.docx
In a minimum 200 word response explain the problems that law enforce.docx
 
In a minimum 200 word response explain some of the reasons why, in.docx
In a minimum 200 word response explain some of the reasons why, in.docxIn a minimum 200 word response explain some of the reasons why, in.docx
In a minimum 200 word response explain some of the reasons why, in.docx
 
In a maximum of 750 words, you are required to1. Summarize the ar.docx
In a maximum of 750 words, you are required to1. Summarize the ar.docxIn a maximum of 750 words, you are required to1. Summarize the ar.docx
In a maximum of 750 words, you are required to1. Summarize the ar.docx
 
in a two- to- three page paper (not including the title and referenc.docx
in a two- to- three page paper (not including the title and referenc.docxin a two- to- three page paper (not including the title and referenc.docx
in a two- to- three page paper (not including the title and referenc.docx
 
In a two- to three-page paper (not including the title and reference.docx
In a two- to three-page paper (not including the title and reference.docxIn a two- to three-page paper (not including the title and reference.docx
In a two- to three-page paper (not including the title and reference.docx
 
In a group, take a look at the two student essays included in this f.docx
In a group, take a look at the two student essays included in this f.docxIn a group, take a look at the two student essays included in this f.docx
In a group, take a look at the two student essays included in this f.docx
 
BASEBALLRuns Scored (X)Wins (Y)70869875906547970480787957307166786.docx
BASEBALLRuns Scored (X)Wins (Y)70869875906547970480787957307166786.docxBASEBALLRuns Scored (X)Wins (Y)70869875906547970480787957307166786.docx
BASEBALLRuns Scored (X)Wins (Y)70869875906547970480787957307166786.docx
 
Based on Santa Clara University Ethics DialogueEthics .docx
Based on Santa Clara University Ethics DialogueEthics .docxBased on Santa Clara University Ethics DialogueEthics .docx
Based on Santa Clara University Ethics DialogueEthics .docx
 
Barbara Corcoran Learns Her Heart’s True Desires In her.docx
Barbara Corcoran Learns Her Heart’s True Desires  In her.docxBarbara Corcoran Learns Her Heart’s True Desires  In her.docx
Barbara Corcoran Learns Her Heart’s True Desires In her.docx
 
Bapsi Sidhwa’s Cracking India1947 PartitionDeepa Meh.docx
Bapsi Sidhwa’s Cracking India1947 PartitionDeepa Meh.docxBapsi Sidhwa’s Cracking India1947 PartitionDeepa Meh.docx
Bapsi Sidhwa’s Cracking India1947 PartitionDeepa Meh.docx
 
Barriers of therapeutic relationshipThe therapeutic relations.docx
Barriers of therapeutic relationshipThe therapeutic relations.docxBarriers of therapeutic relationshipThe therapeutic relations.docx
Barriers of therapeutic relationshipThe therapeutic relations.docx
 
Barada 2Mohamad BaradaProfessor Andrew DurdinReligions of .docx
Barada 2Mohamad BaradaProfessor Andrew DurdinReligions of .docxBarada 2Mohamad BaradaProfessor Andrew DurdinReligions of .docx
Barada 2Mohamad BaradaProfessor Andrew DurdinReligions of .docx
 

Recently uploaded

Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
EADTU
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
中 央社
 
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaPersonalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
EADTU
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
AnaAcapella
 

Recently uploaded (20)

VAMOS CUIDAR DO NOSSO PLANETA! .
VAMOS CUIDAR DO NOSSO PLANETA!                    .VAMOS CUIDAR DO NOSSO PLANETA!                    .
VAMOS CUIDAR DO NOSSO PLANETA! .
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
 
Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...
 
How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17
 
Graduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptxGraduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptx
 
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptxAnalyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
 
UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024
 
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjjStl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
 
male presentation...pdf.................
male presentation...pdf.................male presentation...pdf.................
male presentation...pdf.................
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
 
MOOD STABLIZERS DRUGS.pptx
MOOD     STABLIZERS           DRUGS.pptxMOOD     STABLIZERS           DRUGS.pptx
MOOD STABLIZERS DRUGS.pptx
 
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaPersonalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
 
How to Manage Website in Odoo 17 Studio App.pptx
How to Manage Website in Odoo 17 Studio App.pptxHow to Manage Website in Odoo 17 Studio App.pptx
How to Manage Website in Odoo 17 Studio App.pptx
 
Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"
 
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading RoomSternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
 
Observing-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxObserving-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptx
 
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUMDEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
 

AssignmentsAssignment 1Read Chapter 2 Introduction to C++ .docx

  • 1. Assignments Assignment 1 Read Chapter 2: “Introduction to C++ Programming” and complete exercise 2.16 on page 79. Add comments in your program in C++ comments format. Write a one page report that explains how your program works. Your paper must be formatted according to, APA style as outlined in the Ashford Writing Center. Make sure that your program reads numbers from the user and calculates the results correctly. Add your name, the course ID and name, and the instructor’s name in the printout using string operation. Your program should be able to read the input and print the results properly. Submit your source code and executable file. Please copy and paste your code into a Word or PDF document for submission. (the Waypoint system does not accept .cpp (C++) or .exe (executable) file types) Assignment 2 In the textbook, on page 400, solve problem 7.18: What does the following program do?. Copy the sample program and compile it, then find the results. Submit a report which is more than one page length to explain how the program works and how you can improve it. Your report should be formatted according to APA style as outlined in the Ashford Writing Center. Write comments in C++ comments format in the source file, to explain what the functions are and how they work. Submit your source code and executable file. Please copy and paste your code into a Word or PDF document for submission. (the Waypoint system does not accept .cpp (C++) or .exe (executable) file types)
  • 2. Final Assignment Create the following program which converts Fahrenheit to Celsius. Your program must have the following functions: · Read integer Fahrenheit temperatures from the user. You need to check whether the input is the correct one or not. If the user enters the incorrect number, ask it again. · Use the formula: Celsius = (Fahrenheit – 32) * 5.0 / 9.0 · The output Celsius should be a floating point with two digits of precision. · The Celsius temperatures should be displayed with a sign of positive or negative. · The program should ask the user to continue or not. If the user wants to do the conversion again, use repetitive statements such as DO WHILE, FOR, or IF THEN ELSE to do the conversion again. · Add comments to explain the functions of the program. Write a user manual of more than two pages to explain how to use your program. Format your manual according to APA style as outlined in the Ashford Writing Center. Your program should run without any errors. Submit your source code and executable file. Submit your source code file. Please copy and paste your code into a Word or PDF document for submission. (the Waypoint system does not accept .cpp (C++) or .exe (executable) file types)
  • 3. Deitel® Ser How To Program Series C How to Program, 6/E C++ How to Program, 7/E Java How to Program, 8/E, Early Objects Version Java How to Program, 8/E, Late Objects Version Internet & World Wide Web How to Program, 4/E Visual Basic® 2008 How to Program Visual C#® 2008 How to Program, 3/E Visual C++® 2008 How to Program, 2/E Small Java™ How to Program, 6/E Small C++ How to Program, 5/E Simply Series Simply C++: An Application-Driven Tutorial Approach Simply Java™ Programming: An Application-Driven Tutorial Approach Simply C#: An Application-Driven Tutorial Approach
  • 4. Simply Visual Basic® 2008, 3/E: An Application-Driven Tutorial Approach CourseSmart Web Books www.deitel.com/books/CourseSmart.html C++ How to Program, 5/E, 6/E & 7/E Java How to Program, 6/E, 7/E & 8/E Simply C++: An Application-Driven Tutorial Approach Simply Visual Basic 2008: An Application-Driven Tutorial Approach, 3/E Small C++ How to Program, 5/E Small Java How to Program, 6/E Visual Basic® 2008 How to Program Visual C#® 2008 How to Program, 3/E ies Page www.deitel.com/books/CourseSmart.html Deitel® Developer Series AJAX, Rich Internet Applications and Web Development for Programmers
  • 5. C++ for Programmers C# 2008 for Programmers, 3/E iPhone for Programmers: An App-Driven Approach Java for Programmers Javascript for Programmers LiveLessons Video Learning Products www.deitel.com/books/LiveLessons/ Java Fundamentals Parts 1 and 2 C# Fundamentals Parts 1 and 2 C++ Fundamentals Parts 1 and 2 JavaScript Fundamentals Parts 1 and 2 To receive updates on Deitel publications, Resource Centers, training courses, partner offers and more, please register for the free Deitel® Buzz Online e-mail newsletter at: www.deitel.com/newsletter/subscribe.html follow us on Twitter® @deitel and Facebook® www.deitel.com/deitelfan/
  • 6. To communicate with the authors, send e-mail to: [email protected] For information on government and corporate Dive-Into® Series on-site seminars offered by Deitel & Associates, Inc. worldwide, visit: www.deitel.com/training/ or write to [email protected] For continuing updates on Prentice Hall/Deitel publications visit: www.deitel.com www.pearsonhighered.com/deitel Check out our Resource Centers for valuable web resources that will help you master Java, other important programming languages, software and Internet- and web-related topics: www.deitel.com/ResourceCenters.html www.deitel.com/books/LiveLessons www.deitel.com/newsletter/subscribe.html www.deitel.com/deitelfan www.deitel.com/training www.deitel.com www.pearsonhighered.com/deitel www.deitel.com/ResourceCenters.html Library of Congress Cataloging-in-Publication Data On file Vice President and Editorial Director, ECS: Marcia J. Horton Editor-in-Chief, Computer Science: Michael Hirsch Associate Editor: Carole Snyder
  • 7. Supervisor/Editorial Assistant: Dolores Mars Director of Team-Based Project Management: Vince O’Brien Senior Managing Editor: Scott Disanno Managing Editor: Robert Engelhardt A/V Production Editor: Greg Dulles Art Director: Kristine Carney Cover Design: Abbey S. Deitel, Harvey M. Deitel, Francesco Santalucia, Kristine Carney Interior Design: Harvey M. Deitel, Kristine Carney Manufacturing Manager: Alexis Heydt-Long Manufacturing Buyer: Lisa McDowell Director of Marketing: Margaret Waples Marketing Manager: Erin Davis © 2010 by Pearson Education, Inc. Upper Saddle River, New Jersey 07458 The authors and publisher of this book have used their best efforts in preparing this book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and pub- lisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in this book. The authors and publisher shall not be liable in any event for incidental or consequential dam- ages in connection with, or arising out of, the furnishing, performance, or use of these programs. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks and registered trademarks. Where those designations appear in this book, and Prentice Hall and the authors were aware of a trademark claim, the designations have been printed in initial caps or all caps. All product names mentioned remain trademarks or registered trademarks of their respective owners.
  • 8. All rights reserved. No part of this book may be reproduced, in any form or by any means, without permission in writing from the publisher. Printed in the United States of America 10 9 8 7 6 5 4 3 2 1 ISBN-10: 0-13-612356-2 ISBN-13: 978-0-13-612356-9 Pearson Education Ltd., London Pearson Education Australia Pty. Ltd., Sydney Pearson Education Singapore, Pte. Ltd. Pearson Education North Asia Ltd., Hong Kong Pearson Education Canada, Inc., Toronto Pearson Educación de Mexico, S.A. de C.V. Pearson Education–Japan, Tokyo Pearson Education Malaysia, Pte. Ltd. Pearson Education, Inc., Upper Saddle River, New Jersey Upper Saddle River, New Jersey 07458 P. J. Deitel Deitel & Associates, Inc. H. M. Deitel Deitel & Associates, Inc. Trademarks
  • 9. DEITEL, the double-thumbs-up bug and DIVE INTO are registered trademarks of Deitel and Associates, Inc. Microsoft, Visual C++, Internet Explorer and the Windows logo are either registered trademarks or trade- marks of Microsoft Corporation in the United States and/or other countries. In Memory of Clifford Stephens: Your friendship, bright smile and infectious laugh will be truly missed. Paul and Harvey Deitel Deitel Resource Centers Our Resource Centers focus on the vast amounts of free content available online. Find resources, downloads, tutorials, documentation, books, e-books, journals, articles, blogs, RSS feeds and more on many of today’s hottest programming and technology topics. For the most up-to-date list of our Resource Centers, visit: www.deitel.com/ResourceCenters.html Let us know what other Resource Centers you’d like to see! Also, please register for the free Deitel® Buzz Online e-mail newsletter at:
  • 10. www.deitel.com/newsletter/subscribe.html Computer Science Functional Programming Regular Expressions Programming ASP.NET 3.5 Adobe Flex Ajax Apex ASP.NET Ajax ASP.NET C C++ C++ Boost Libraries C++ Game Programming C# Code Search Engines and Code Sites Computer Game Programming CSS 2.1 Dojo Facebook Developer Plat- form Flash 9 Functional Programming Java Java Certification and Assessment Testing Java Design Patterns
  • 11. Java EE 5 Java SE 6 Java SE 7 (Dolphin) Resource Center JavaFX JavaScript JSON Microsoft LINQ Microsoft Popfly .NET .NET 3.0 .NET 3.5 OpenGL Perl PHP Programming Projects Python Regular Expressions Ruby Ruby on Rails Silverlight UML Visual Basic Visual C++ Visual Studio Team Sys- tem Web 3D Technologies Web Services Windows Presentation Foundation XHTML XML
  • 12. Apple iPhone Objective-C Cocoa Games and Game Programming Computer Game Pro- gramming Computer Games Mobile Gaming Sudoku Internet Business Affiliate Programs Competitive Analysis Facebook Social Ads Google AdSense Google Analytics Google Services Internet Advertising Internet Business Initiative Internet Public Relations Link Building Location-Based Services Online Lead Generation Podcasting Search Engine Optimiza- tion Selling Digital Content
  • 13. Sitemaps Web Analytics Website Monetization YouTube and AdSense Java Java Java Certification and Assessment Testing Java Design Patterns Java EE 5 Java SE 6 Java SE 7 (Dolphin) Resource Center JavaFX Microsoft ASP.NET ASP.NET 3.5 ASP.NET Ajax C# DotNetNuke (DNN) Internet Explorer 7 (IE7) Microsoft LINQ .NET .NET 3.0 .NET 3.5 SharePoint Silverlight Visual Basic Visual C++ Visual Studio Team
  • 14. System Windows Presentation Foundation Windows Vista Microsoft Popfly Open Source & LAMP Stack Apache DotNetNuke (DNN) Eclipse Firefox Linux MySQL Open Source Perl PHP Python Ruby Software Apache DotNetNuke (DNN) Eclipse Firefox Internet Explorer 7 (IE7) Linux MySQL Open Source Search Engines SharePoint Skype Web Servers
  • 15. Wikis Windows Vista Web 2.0 Alert Services Attention Economy Blogging Building Web Communities Community Generated Content Facebook Developer Platform Facebook Social Ads Google Base Google Video Google Web Toolkit (GWT) Internet Video Joost Location-Based Services Mashups Microformats Recommender Systems RSS Social Graph Social Media Social Networking Software as a Service (SaaS) Virtual Worlds
  • 16. Web 2.0 Web 3.0 Widgets Dive Into® Web 2.0 eBook Web 2 eBook Other Topics Computer Games Computing Jobs Gadgets and Gizmos Ring Tones Sudoku www.deitel.com/ResourceCenters.html www.deitel.com/newsletter/subscribe.html Appendices E through I are PDF documents posted online at the book’s Companion Website (located at www.pearsonhighered.com/deitel). Preface xxi 1 Introduction to Computers, the Internet and the Web 1 1.1 Introduction 2 1.2 Computers: Hardware and Software 3 1.3 Computer Organization 4 1.4 Personal, Distributed and Client/Server Computing 5 1.5 The Internet and the World Wide Web 5 1.6 Machine Languages, Assembly Languages and High-Level Languages 6
  • 17. 1.7 History of C 7 1.8 C Standard Library 8 1.9 C++ 9 1.10 Java 9 1.11 Fortran, COBOL, Pascal and Ada 10 1.12 BASIC, Visual Basic, Visual C++, C# and .NET 10 1.13 Key Software Trend: Object Technology 11 1.14 Typical C Program Development Environment 12 1.15 Hardware Trends 14 1.16 Notes About C and This Book 15 1.17 Web Resources 16 2 Introduction to C Programming 23 2.1 Introduction 24 2.2 A Simple C Program: Printing a Line of Text 24 2.3 Another Simple C Program: Adding Two Integers 28 2.4 Memory Concepts 33 2.5 Arithmetic in C 34 2.6 Decision Making: Equality and Relational Operators 38 3 Structured Program Development in C 54 3.1 Introduction 55 3.2 Algorithms 55 Contents www.pearsonhighered.com/deitel x Contents 3.3 Pseudocode 55 3.4 Control Structures 56 3.5 The if Selection Statement 58 3.6 The if…else Selection Statement 59 3.7 The while Repetition Statement 63
  • 18. 3.8 Formulating Algorithms Case Study 1: Counter-Controlled Repetition 64 3.9 Formulating Algorithms with Top-Down, Stepwise Refinement Case Study 2: Sentinel-Controlled Repetition 66 3.10 Formulating Algorithms with Top-Down, Stepwise Refinement Case Study 3: Nested Control Structures 73 3.11 Assignment Operators 77 3.12 Increment and Decrement Operators 78 4 C Program Control 97 4.1 Introduction 98 4.2 Repetition Essentials 98 4.3 Counter-Controlled Repetition 99 4.4 for Repetition Statement 100 4.5 for Statement: Notes and Observations 103 4.6 Examples Using the for Statement 103 4.7 switch Multiple-Selection Statement 107 4.8 do…while Repetition Statement 113 4.9 break and continue Statements 114 4.10 Logical Operators 116 4.11 Confusing Equality (==) and Assignment (=) Operators 119 4.12 Structured Programming Summary 121 5 C Functions 140 5.1 Introduction 141 5.2 Program Modules in C 141 5.3 Math Library Functions 142 5.4 Functions 144 5.5 Function Definitions 144 5.6 Function Prototypes 148 5.7 Function Call Stack and Activation Records 151
  • 19. 5.8 Headers 151 5.9 Calling Functions By Value and By Reference 152 5.10 Random Number Generation 153 5.11 Example: A Game of Chance 158 5.12 Storage Classes 161 5.13 Scope Rules 164 5.14 Recursion 167 5.15 Example Using Recursion: Fibonacci Series 170 5.16 Recursion vs. Iteration 174 Contents xi 6 C Arrays 195 6.1 Introduction 196 6.2 Arrays 196 6.3 Defining Arrays 198 6.4 Array Examples 198 6.5 Passing Arrays to Functions 212 6.6 Sorting Arrays 216 6.7 Case Study: Computing Mean, Median and Mode Using Arrays 218 6.8 Searching Arrays 223 6.9 Multiple-Subscripted Arrays 229 7 C Pointers 253 7.1 Introduction 254 7.2 Pointer Variable Definitions and Initialization 254 7.3 Pointer Operators 255 7.4 Passing Arguments to Functions by Reference 257 7.5 Using the const Qualifier with Pointers 261 7.6 Bubble Sort Using Call-by-Reference 267 7.7 sizeof Operator 270 7.8 Pointer Expressions and Pointer Arithmetic 273 7.9 Relationship between Pointers and Arrays 275
  • 20. 7.10 Arrays of Pointers 280 7.11 Case Study: Card Shuffling and Dealing Simulation 280 7.12 Pointers to Functions 285 8 C Characters and Strings 309 8.1 Introduction 310 8.2 Fundamentals of Strings and Characters 310 8.3 Character-Handling Library 312 8.4 String-Conversion Functions 317 8.5 Standard Input/Output Library Functions 322 8.6 String-Manipulation Functions of the String-Handling Library 326 8.7 Comparison Functions of the String-Handling Library 329 8.8 Search Functions of the String-Handling Library 331 8.9 Memory Functions of the String-Handling Library 337 8.10 Other Functions of the String-Handling Library 341 9 C Formatted Input/Output 356 9.1 Introduction 357 9.2 Streams 357 9.3 Formatting Output with printf 357 9.4 Printing Integers 358 9.5 Printing Floating-Point Numbers 359 xii Contents 9.6 Printing Strings and Characters 361 9.7 Other Conversion Specifiers 362 9.8 Printing with Field Widths and Precision 363 9.9 Using Flags in the printf Format Control String 366 9.10 Printing Literals and Escape Sequences 368 9.11 Reading Formatted Input with scanf 369 10 C Structures, Unions, Bit Manipulations and
  • 21. Enumerations 382 10.1 Introduction 383 10.2 Structure Definitions 383 10.3 Initializing Structures 386 10.4 Accessing Structure Members 386 10.5 Using Structures with Functions 388 10.6 typedef 388 10.7 Example: High-Performance Card Shuffling and Dealing Simulation 389 10.8 Unions 391 10.9 Bitwise Operators 394 10.10 Bit Fields 403 10.11 Enumeration Constants 406 11 C File Processing 417 11.1 Introduction 418 11.2 Data Hierarchy 418 11.3 Files and Streams 420 11.4 Creating a Sequential-Access File 421 11.5 Reading Data from a Sequential-Access File 426 11.6 Random-Access Files 430 11.7 Creating a Random-Access File 431 11.8 Writing Data Randomly to a Random-Access File 433 11.9 Reading Data from a Random-Access File 436 11.10 Case Study: Transaction-Processing Program 437 12 C Data Structures 454 12.1 Introduction 455 12.2 Self-Referential Structures 456 12.3 Dynamic Memory Allocation 456 12.4 Linked Lists 458 12.5 Stacks 466 12.6 Queues 472 12.7 Trees 478
  • 22. 13 C Preprocessor 495 13.1 Introduction 496 Contents xiii 13.2 #include Preprocessor Directive 496 13.3 #define Preprocessor Directive: Symbolic Constants 496 13.4 #define Preprocessor Directive: Macros 497 13.5 Conditional Compilation 499 13.6 #error and #pragma Preprocessor Directives 500 13.7 # and ## Operators 500 13.8 Line Numbers 501 13.9 Predefined Symbolic Constants 501 13.10 Assertions 502 14 Other C Topics 507 14.1 Introduction 508 14.2 Redirecting I/O 508 14.3 Variable-Length Argument Lists 509 14.4 Using Command-Line Arguments 511 14.5 Notes on Compiling Multiple-Source-File Programs 512 14.6 Program Termination with exit and atexit 514 14.7 volatile Type Qualifier 515 14.8 Suffixes for Integer and Floating-Point Constants 516 14.9 More on Files 516 14.10 Signal Handling 518 14.11 Dynamic Memory Allocation: Functions calloc and realloc 520 14.12 Unconditional Branching with goto 521 15 C++ as a Better C; Introducing Object Technology 528 15.1 Introduction 529
  • 23. 15.2 C++ 529 15.3 A Simple Program: Adding Two Integers 530 15.4 C++ Standard Library 532 15.5 Header Files 533 15.6 Inline Functions 535 15.7 References and Reference Parameters 537 15.8 Empty Parameter Lists 542 15.9 Default Arguments 542 15.10 Unary Scope Resolution Operator 544 15.11 Function Overloading 545 15.12 Function Templates 548 15.13 Introduction to Object Technology and the UML 551 15.14 Wrap-Up 554 16 Introduction to Classes and Objects 560 16.1 Introduction 561 16.2 Classes, Objects, Member Functions and Data Members 561 xiv Contents 16.3 Defining a Class with a Member Function 562 16.4 Defining a Member Function with a Parameter 566 16.5 Data Members, set Functions and get Functions 569 16.6 Initializing Objects with Constructors 576 16.7 Placing a Class in a Separate File for Reusability 579 16.8 Separating Interface from Implementation 583 16.9 Validating Data with set Functions 589 16.10 Wrap-Up 594 17 Classes: A Deeper Look, Part 1 601 17.1 Introduction 602 17.2 Time Class Case Study 603 17.3 Class Scope and Accessing Class Members 609
  • 24. 17.4 Separating Interface from Implementation 611 17.5 Access Functions and Utility Functions 612 17.6 Time Class Case Study: Constructors with Default Arguments 615 17.7 Destructors 620 17.8 When Constructors and Destructors are Called 621 17.9 Time Class Case Study: A Subtle Trap—Returning a Reference to a private Data Member 624 17.10 Default Memberwise Assignment 627 17.11 Wrap-Up 629 18 Classes: A Deeper Look, Part 2 635 18.1 Introduction 636 18.2 const (Constant) Objects and const Member Functions 636 18.3 Composition: Objects as Members of Classes 645 18.4 friend Functions and friend Classes 651 18.5 Using the this Pointer 654 18.6 static Class Members 659 18.7 Data Abstraction and Information Hiding 664 18.8 Wrap-Up 666 19 Operator Overloading 672 19.1 Introduction 673 19.2 Fundamentals of Operator Overloading 674 19.3 Restrictions on Operator Overloading 675 19.4 Operator Functions as Class Members vs. Global Function 676 19.5 Overloading Stream Insertion and Stream Extraction Operators 678 19.6 Overloading Unary Operators 681 19.7 Overloading Binary Operators 682 19.8 Dynamic Memory Management 682 19.9 Case Study: Array Class 684 19.10 Converting between Types 696
  • 25. Contents xv 19.11 Building a String Class 697 19.12 Overloading ++ and -- 698 19.13 Case Study: A Date Class 700 19.14 Standard Library Class string 704 19.15 explicit Constructors 708 19.16 Proxy Classes 711 19.17 Wrap-Up 715 20 Object-Oriented Programming: Inheritance 727 20.1 Introduction 728 20.2 Base Classes and Derived Classes 729 20.3 protected Members 732 20.4 Relationship between Base Classes and Derived Classes 732 20.4.1 Creating and Using a CommissionEmployee Class 733 20.4.2 Creating a BasePlusCommissionEmployee Class Without Using Inheritance 738 20.4.3 Creating a CommissionEmployee– BasePlusCommissionEmployee Inheritance Hierarchy 743 20.4.4 CommissionEmployee–BasePlusCommissionEmployee Inheritance Hierarchy Using protected Data 748 20.4.5 CommissionEmployee–BasePlusCommissionEmployee Inheritance Hierarchy Using private Data 755 20.5 Constructors and Destructors in Derived Classes 762 20.6 public, protected and private Inheritance 770
  • 26. 20.7 Software Engineering with Inheritance 771 20.8 Wrap-Up 772 21 Object-Oriented Programming: Polymorphism 778 21.1 Introduction 779 21.2 Polymorphism Examples 780 21.3 Relationships Among Objects in an Inheritance Hierarchy 781 21.3.1 Invoking Base-Class Functions from Derived-Class Objects 782 21.3.2 Aiming Derived-Class Pointers at Base-Class Objects 789 21.3.3 Derived-Class Member-Function Calls via Base-Class Pointers 790 21.3.4 Virtual Functions 792 21.3.5 Summary of the Allowed Assignments Between Base- Class and Derived-Class Objects and Pointers 798 21.4 Type Fields and switch Statements 799 21.5 Abstract Classes and Pure virtual Functions 799 21.6 Case Study: Payroll System Using Polymorphism 801 21.6.1 Creating Abstract Base Class Employee 803 21.6.2 Creating Concrete Derived Class SalariedEmployee 806 21.6.3 Creating Concrete Derived Class HourlyEmployee 808 21.6.4 Creating Concrete Derived Class CommissionEmployee 811 xvi Contents 21.6.5 Creating Indirect Concrete Derived Class BasePlusCommissionEmployee 813
  • 27. 21.6.6 Demonstrating Polymorphic Processing 814 21.7 (Optional) Polymorphism, Virtual Functions and Dynamic Binding “Under the Hood” 818 21.8 Case Study: Payroll System Using Polymorphism and Runtime Type Information with Downcasting, dynamic_cast, typeid and type_info 822 21.9 Virtual Destructors 826 21.10 Wrap-Up 826 22 Templates 832 22.1 Introduction 833 22.2 Function Templates 833 22.3 Overloading Function Templates 837 22.4 Class Templates 837 22.5 Nontype Parameters and Default Types for Class Templates 844 22.6 Notes on Templates and Inheritance 845 22.7 Notes on Templates and Friends 845 22.8 Notes on Templates and static Members 846 22.9 Wrap-Up 846 23 Stream Input/Output 851 23.1 Introduction 852 23.2 Streams 853 23.2.1 Classic Streams vs. Standard Streams 853 23.2.2 iostream Library Header Files 854 23.2.3 Stream Input/Output Classes and Objects 854 23.3 Stream Output 857 23.3.1 Output of char * Variables 857
  • 28. 23.3.2 Character Output Using Member Function put 857 23.4 Stream Input 858 23.4.1 get and getline Member Functions 858 23.4.2 istream Member Functions peek, putback and ignore 861 23.4.3 Type-Safe I/O 861 23.5 Unformatted I/O Using read, write and gcount 861 23.6 Introduction to Stream Manipulators 862 23.6.1 Integral Stream Base: dec, oct, hex and setbase 863 23.6.2 Floating-Point Precision (precision, setprecision) 864 23.6.3 Field Width (width, setw) 865 23.6.4 User-Defined Output Stream Manipulators 866 23.7 Stream Format States and Stream Manipulators 868 23.7.1 Trailing Zeros and Decimal Points (showpoint) 868 23.7.2 Justification (left, right and internal) 869 23.7.3 Padding (fill, setfill) 871 23.7.4 Integral Stream Base (dec, oct, hex, showbase) 872 Contents xvii 23.7.5 Floating-Point Numbers; Scientific and Fixed Notation (scientific, fixed) 873 23.7.6 Uppercase/Lowercase Control (uppercase) 874 23.7.7 Specifying Boolean Format (boolalpha) 874 23.7.8 Setting and Resetting the Format State via Member Function flags 875 23.8 Stream Error States 877 23.9 Tying an Output Stream to an Input Stream 879 23.10 Wrap-Up 879
  • 29. 24 Exception Handling 889 24.1 Introduction 890 24.2 Exception-Handling Overview 891 24.3 Example: Handling an Attempt to Divide by Zero 891 24.4 When to Use Exception Handling 897 24.5 Rethrowing an Exception 898 24.6 Exception Specifications 900 24.7 Processing Unexpected Exceptions 901 24.8 Stack Unwinding 901 24.9 Constructors, Destructors and Exception Handling 903 24.10 Exceptions and Inheritance 904 24.11 Processing new Failures 904 24.12 Class auto_ptr and Dynamic Memory Allocation 907 24.13 Standard Library Exception Hierarchy 909 24.14 Other Error-Handling Techniques 911 24.15 Wrap-Up 912 A Operator Precedence Charts 919 B ASCII Character Set 923 C Number Systems 924 C.1 Introduction 925 C.2 Abbreviating Binary Numbers as Octal and Hexadecimal Numbers 928 C.3 Converting Octal and Hexadecimal Numbers to Binary Numbers 929 C.4 Converting from Binary, Octal or Hexadecimal to Decimal 929 C.5 Converting from Decimal to Binary, Octal or Hexadecimal 930 C.6 Negative Binary Numbers: Two’s Complement Notation 932 D Game Programming: Solving Sudoku 937
  • 30. D.1 Introduction 937 D.2 Deitel Sudoku Resource Center 938 D.3 Solution Strategies 938 xviii Contents D.4 Programming Sudoku Puzzle Solvers 942 D.5 Generating New Sudoku Puzzles 943 D.6 Conclusion 945 Appendices on the Web 946 Appendices E through I are PDF documents posted online at the book’s Companion Website (located at www.pearsonhighered.com/deitel). E Game Programming with the Allegro C Library I E.1 Introduction II E.2 Installing Allegro II E.3 A Simple Allegro Program III
  • 31. E.4 Simple Graphics: Importing Bitmaps and Blitting IV E.5 Animation with Double Buffering IX E.6 Importing and Playing Sounds XVI E.7 Keyboard Input XX E.8 Fonts and Displaying Text XXV E.9 Implementing the Game of Pong XXXI E.10 Timers in Allegro XXXVII E.11 The Grabber and Allegro Datafiles XLII E.12 Other Allegro Capabilities LI E.13 Allegro Resource Center LII F Sorting: A Deeper Look LVIII F.1 Introduction LIX F.2 Big O Notation LIX F.3 Selection Sort LX F.4 Insertion Sort LXIV F.5 Merge Sort LXVII G Introduction to C99 LXXVIII G.1 Introduction LXXIX G.2 Support for C99 LXXIX G.3 New C99 Headers LXXX G.4 // Comments LXXX G.5 Mixing Declarations and Executable Code LXXXI G.6 Declaring a Variable in a for Statement Header LXXXII
  • 32. G.7 Designated Initializers and Compound Literals LXXXIV G.8 Type bool LXXXVII G.9 Implicit int in Function Declarations LXXXVIII G.10 Complex Numbers LXXXIX G.11 Variable-Length Arrays XC www.pearsonhighered.com/deitel Contents xix G.12 The snprintf Function: Helping Avoid Hacker Attacks XCIII G.13 Additions to the Preprocessor XCV G.14 Other C99 Features XCVI G.15 Web Resources XCIX H Using the Visual Studio Debugger CIV H.1 Introduction CV H.2 Breakpoints and the Continue Command CV H.3 Locals and Watch Windows CIX H.4 Controlling Execution Using the Step Into, Step Over, Step Out and Continue Commands CXII
  • 33. H.5 Autos Window CXIV H.6 Wrap-Up CXVI I Using the GNU Debugger CXVIII I.1 Introduction CXIX I.2 Breakpoints and the run, stop, continue and print Commands CXIX I.3 print and set Commands CXXIV I.4 Controlling Execution Using the step, finish and next Commands CXXVI I.5 watch Command CXXVIII I.6 Wrap-Up CXXX Index 947 This page intentionally left blank Welcome to the C programming language—and to C++, too! This book presents leading- edge computing technologies for students, instructors and software development profes-
  • 34. sionals. At the heart of the book is the Deitel signature “live-code approach.” Concepts are presented in the context of complete working programs, rather than in code snippets. Each code example is immediately followed by one or more sample executions. All the source code is available at www.deitel.com/books/chtp6/. We believe that this book and its support materials will give you an informative, inter- esting, challenging and entertaining introduction to C. As you read the book, if you have questions, send an e-mail to [email protected]; we’ll respond promptly. For updates on this book and its supporting C and C++ software, and for the latest news on all Deitel publications and services, visit www.deitel.com. New and Updated Features Here are the updates we’ve made for C How to Program, 6/e: • “Making a Difference” Exercises Set. We encourage you to
  • 35. use computers and the Internet to research and solve problems that really matter. These new exercises are meant to increase awareness of important issues the world is facing. We hope you’ll approach them with your own values, politics and beliefs. • Tested All Code on Windows and Linux. We’ve tested every program (the exam- ples and the exercises) using both Visual C++ 2008 and GNU GCC 4.3. The code examples and exercise code solutions were also tested using Visual Studio 2010 Beta. • New Design. The book has a new interior design that graphically serves to orga- nize, clarify and highlight the information, and enhances the book’s pedagogy. • Improved Terminology Sections. We’ve added page numbers for the defining oc- currences of all terms in the terminology lists for easy reference.
  • 36. • Updated Coverage of C++ and Object-Oriented Programming. We updated Chapters 15–24 on object-oriented programming in C++ with material from our just published C++ How to Program, 7/e. • Titled Programming Exercises. We’ve titled all the programming exercises. This helps instructors tune assignments for their classes. • New Web Appendices. Chapters 15–17 from the previous edition are now search- able PDF Appendices E–G, available on the Companion Website (see the access card at the front of the book). Preface www.deitel.com/books/chtp6 www.deitel.com xxii Preface • New Debugger Appendices. We also added new debugging
  • 37. appendices for Visual C++® 2008 and GNU gdb. • Order of Evaluation. We added cautions about order of evaluation issues. • We replaced all uses of gets (from <stdio.h>) with fgets, because gets is now deprecated. • Additional Exercises. We added more function pointer exercises. We also added the Fibonacci exercise project that improves the Fibonacci recursion example (tail recursion). • Secure C Programming Resource Center. We’ve posted a new Secure C Program- ming Resource Center at www.deitel.com/SecureC/. We’ve also added notes about secure C programming to the introductions in Chapter 7, Pointers, and Chapter 8, Strings. • Game Programming with Allegro. We updated the chapter on
  • 38. game program- ming with the Allegro C library. In particular, we added instructions on installing the Allegro libraries for use with Visual C++® 2008 and GNU GCC 4.3. • Coverage of the C99 Standard. We updated and enhanced the detailed appendix on C99, which was reviewed by John Benito, Convener of ISO WG14—the Working Group responsible for the C Programming Language Standard. Each C99 concept is now keyed to the section where it can be taught earlier in the book. C99 is not incorporated throughout the book because Microsoft does not yet support it and a large percentage of C courses use Microsoft's Visual C++® compiler. For additional information, check out the C99 Standard section in our C Resource center at www.deitel.com/C/. You'll find features of C99, articles from experts, the differences between Standard C and C99, FAQs, downloads
  • 39. and more. • C++-Style // Comments. We discuss C++-style // comments early for instructors and students who’d prefer to use them. Although Microsoft C does not yet sup- port C99, it does support C99’s comments, which are borrowed from C++. • C Standard Library. Section 1.8 now references P.J. Plauger’s Dinkumware web- site (www.dinkumware.com/manuals/default.aspx) where students can find thorough searchable documentation for the C Standard Library functions. Other Features Other features of C How to Program, 6/e, include: Game Programming with the Allegro C Game Programming Library Appendix E introduces the Allegro game programming C library. This library—originally developed by Climax game programmer Shawn Hargreaves— was created to be a powerful
  • 40. tool for programming games in C while still remaining relatively simple compared to oth- er, more complicated graphics libraries such as DirectX and OpenGL. In Appendix E, we use Allegro’s capabilities to create the simple game of Pong. Along the way, we demon- strate how to display graphics, play sounds, receive input from the keyboard and create timed events—features you can use to create games of your own. Students and instructors www.deitel.com/SecureC www.deitel.com/C www.dinkumware.com/manuals/default.aspx Web-Based Materials xxiii alike will find Allegro challenging and entertaining. We include extensive web resources in our Allegro Resource Center (www.deitel.com/allegro), one of which offers more than 1000 open-source Allegro games. Sorting: A Deeper Look
  • 41. Sorting places data in order, based on one or more sort keys. We begin our presentation of sorting with a simple algorithm in Chapter 6. In Appendix F, we present a deeper look at sorting. We consider several algorithms and compare them with regard to their memory consumption and processor demands. For this purpose, we introduce Big O notation, which indicates how hard an algorithm may have to work to solve a problem. Through examples and exercises, Appendix F discusses the selection sort, insertion sort, recursive merge sort, recursive selection sort, bucket sort and recursive Quicksort. Web-Based Materials This book is supported by substantial online materials. The book’s Companion Website (www.pearsonhighered.com/deitel; see the access card at the front of the book) contains the following appendices in searchable PDF format: • Appendix E, Game Programming with the Allegro C Library • Appendix F, Sorting: A Deeper Look
  • 42. • Appendix G, Introduction to C99 • Appendix H, Using the Visual Studio Debugger • Appendix I, Using the GNU Debugger Dependency Charts The dependency charts in Figs. 1–2 show the dependencies among the chapters to help instructors plan their syllabi. C How to Program, 6/e is appropriate for CS1 and CS2 cours- es, and intermediate-level C and C++ programming courses. The C++ part of the book assumes that you have studied the C part. Teaching Approach C How to Program, 6/e, contains a rich collection of examples. We concentrate on demon- strating the principles of good software engineering and stressing program clarity. Live-Code Approach. C How to Program, 6/e, is loaded with “live-code” examples. Most new concepts are presented in the context of complete working
  • 43. C applications, followed by one or more executions showing program inputs and outputs. Syntax Shading For readability, we syntax shade the code, similar to the way most integrated-development environments and code editors syntax color code. Our syntax- shading conventions are: comments appear like this keywords appear like this constants and literal values appear like this all other code appears in black www.deitel.com/allegro www.pearsonhighered.com/deitel xxiv Preface Code Highlighting We place gray rectangles around the key code. Using Fonts for Emphasis. We place the key terms and the index’s page reference for each
  • 44. defining occurrence in bold blue text for easy reference. We emphasize on-screen compo- nents in the bold Helvetica font (e.g., the File menu) and C program text in the Lucida font (for example, int x = 5;). Web Access. All of the source-code examples are available for download from: Fig. 1 | C chapter dependency chart. www.deitel.com/books/chtp6/ Introduction 1 Introduction to Computers, the Internet and the Web Intro to Programming 2 Intro to C Programming Control Statements, Functions and Arrays 3 Structured Program
  • 45. Development in C 4 C Program Control 5 C Functions 6 C Arrays Pointers and Strings 8 C Characters and Strings 7 C Pointers 5.14–5.16 Recursion 12 C Data Structures F Sorting: A Deeper Look Data Structures Other Topics, Game Programming and C99 C Chapter
  • 46. Dependency Chart [Note: Arrows pointing into a chapter indicate that chapter’s dependencies.] G Introduction to C99 E Game Programming with the Allegro C Library 10 C Structures, Unions, Bit Manipulations and Enumerations Aggregate Types Streams and Files 11 C File Processing 9 C Formatted Input/Output 13 C Preprocessor 14 Other C Topics
  • 47. www.deitel.com/books/chtp6 Teaching Approach xxv Quotations. Each chapter begins with quotations. We hope that you enjoy relating these to the chapter material. Objectives. The quotes are followed by a list of chapter objectives. Illustrations/Figures. Abundant charts, tables, line drawings, UML diagrams, programs and program output are included. Programming Tips We include programming tips to help you focus on important aspects of program devel- opment. These tips and practices represent the best we’ve gleaned from a combined seven decades of programming and teaching experience. Fig. 2 | C++ chapter dependency chart.
  • 48. Good Programming Practice The Good Programming Practices call attention to techniques that will help you pro- duce programs that are clearer, more understandable and more maintainable. Common Programming Error Pointing out these Common Programming Errors reduces the likelihood that you’ll make them. Error-Prevention Tip These tips contain suggestions for exposing and removing bugs from your programs; many describe aspects of C that prevent bugs from getting into programs in the first place. Object-Based Programming C++ Chapter Dependency Chart
  • 49. 18 Classes: A Deeper Look, Part 2 17 Classes: A Deeper Look, Part 1 19 Operator Overloading Object-Oriented Programming 23 Stream Input/Output 20 OOP: Inheritance 22 Templates21 OOP: Polymorphism 24 Exception Handling 15 C++ as a Better C; Intro to Object Technology
  • 50. 16 Intro to Classes and Objects [Note: Arrows pointing into a chapter indicate that chapter’s dependencies.] xxvi Preface Summary Bullets. We present a section-by-section, bullet-list summary of the chapter. Terminology. We include an alphabetized list of the important terms defined in each chap- ter with the page number of each term’s defining occurrence for easy reference. Self-Review Exercises and Answers. Extensive self-review exercises and answers are includ- ed for self-study. Exercises. Each chapter concludes with a substantial set of exercises including:
  • 51. • simple recall of important terminology and concepts, • identifying the errors in code samples, • writing individual C statements, • writing small portions of functions and classes, • writing complete C functions, classes and programs, and • major projects. Instructors can use these exercises to form homework assignments, short quizzes, major ex- aminations and term projects. [NOTE: Please do not write to us requesting access to the Pearson Instructor’s Resource Center which contains the book’s instructor supple- ments, including the exercise solutions. Access is limited strictly to college instructors teaching from the book. Instructors may obtain access only through their Pearson rep- resentatives.