C How to Program (3rd Edition)
PrefaceWelcome to ANSI/ISO Standard C, and to C++ and Java™, too! This book is by an old guy and a young guy. The old guy (HMD; Massachusetts Institute of Technology 1967) has been programming and/or teaching programming for 39 years. The young guy (PJD; MIT 1991) has been programming for 18 years and has .caught the teaching and writing "bug." The old guy programs and teaches from experience; the young guy does so from an inexhaustible reserve of energy. The old guy wants clarity; the young guy wants performance. The old guy appreciates elegance and beauty; the young guy wants results. We got together to produce a book we hope you will find informative, interesting and entertaining.   Why We Wrote C How to Program:In most educational environments, C is taught to people who know how to program. Many educators believe that the complexity of C, and a number of other difficulties, make C unworthy for a first programming course—precisely the target course for this book. So why did we write this text?Dr. Harvey M. Deitel taught introductory programming courses in college environments for two decades with an emphasis on developing clearly written, well-structured programs. Much of what is taught in these courses is the basic principles of structured programming, with an emphasis on the effective use of control structures and functionalization. We have presented this material exactly the way HMD has done in his college courses. Students are highly motivated by the fact that they are learning a language that will be immediately useful to them as they leave the university environment.Our goal was clear: Produce a C programming textbook for introductory university-level courses in computer programming for students with little or no programming experience, yet offer the deep and rigorous treatment of theory and practice demanded by traditional C courses. To meet these goals, we produced a book larger than other C texts—this because our text also patiently teaches structured programming principles. Hundreds of thousands of students worldwide learned C from the earlier editions of this book.The book contains a rich collection of examples, exercises and projects drawn from many fields to provide the student with a chance to solve interesting real-world problems. The book also concentrates on the principles of good software engineering and stresses program clarity through use of the structured programming methodology. We teach by example.   C How to Program: Third EditionThe material from C How to Program: Third Edition has been meticulously reviewed by many industry and academic experts, including the head of the ANSI C committee. We have considerably polished the material from the second edition, especially the chapter on pointers.In the second edition of C How to Program, we included a seven-chapter introduction to C++ and Object-Oriented Programming. In the interim, many universities have decided to incorporate an introduction to C++ and Object-Oriented Programming into their C courses. So in this edition, we have expanded our C++ treatment to nine chapters—sufficient text, exercises and laboratories for a one-semester course. We have also added seven chapters on object-oriented programming with Java, including discussions of graphics programming, graphical user interface (GUI) with Java Swing components and multimedia programming.In 1999, the International Standards Organization approved anew version of C, known as C99; but as of this writing, no C99 compilers were available. Therefore, we were not able to make our code examples compatible with C99. When C99 compilers become available, we will test every program in the textbook and list any discrepancies on our Web site (deitel). We will also post code examples with explanations of the new C99 features on that Web site. Appendix B contains a comprehensive list of C99 resources on the Internet and World Wide Web. For more information on C99—and to purchase a copy of the standards document (ISO/IEC 9899:1999)—visit the Web site of the American National Standards Institute (ANSI), (ansi).C How to Program: Third Edition Ancillary PackageWe have worked hard to produce a textbook and ancillaries that we hope you and your students will find valuable. We would like to thank Borland for providing the products included on the CD-ROM in the back of this textbook; these products enable the reader to compile and run programs in C, C++ and Java. The following ancillary resources are available:C How to Program: Third Edition's 270 program examples are included on the CD-ROM in the back of the textbook and are also available for download at deitel. This helps instructors prepare lectures faster and helps students master C. When extracting the source code from the ZIP file, you must use a ZIP-file reader such as WinZip (winzip) or PKZIP (pkware) that understands directories. The file should be extracted into a separate directory (e.g., chtp3e_examples). Students should compile and execute each program they study in the text.A full version of Borland C++ Compiler 5.5 is provided on the textbook's CDROM. This software allows students to edit, compile and debug C and C++ programs from the command line. A 60-day trial version of Borland C++Builder 5 is also included; this product provides a complete integrated C/C++ development environment.  A trial version of JBuiLder 3.5 is provided on the textbook's CD-ROM. This software enables students to edit, compile and debug Java programs in an integrated development environment.  The Instructor's Manual CD contains answers to most of the exercises in the textbook. The programs are separated into directories by chapter and exercise number. NOTE: Please do not write to us requesting the instructor's CD. Distribution of this CD is limited strictly to college professors teaching from the book. Instructors may obtain the solutions manual only from their Prentice Hall representatives.  Companion Web Site (prenhall/deitel) provides instructor and student resources. Instructor resources include textbook appendices (e.g., Appendix A, "Internet and World Wide Web Resources") and a syllabus manager for lesson planning. Student resources include chapter objectives, true/false review questions with answers, chapter highlights, reference materials and a message board.  Customizable PowerPoint® Instructor Lecture Notes, including source code and key discussion points for each program and major illustration. These lecture notes are available for instructors and students at no charge at our deitel Web site. Although instructors may modify these notes and use them in class presentations, please be aware that these notes are copyrighted by Prentice Hall and may not be used without the express written permission of Prentice Hall.   About this BookC How to Program contains a rich collection of examples, exercises and projects drawn from many fields to provide the student with a chance to solve interesting real-world problems. The book concentrates on the principles of good software engineering and stresses program clarity. We teach by example.This book is written by educators who spend most of their time teaching and writing about edge-of-the-practice programming languages. The text places a strong emphasis on pedagogy. For example, virtually every new concept of either C, C++ or Java is presented in the context of a complete, working program immediately followed by a window showing the program's inputs and outputs. Reading these programs is much like entering and running them on a computer. We call this our "live-code approach."Among the other pedagogical devices in the text are a set of Objectives and an Outline at the beginning of every chapter; Common Programming Errors, Good Programming Practices, Performance Tips, Portability Tips, Software Engineering Observations and Testing and Debugging Tips enumerated in, and summarized at, the end of each chapter; comprehensive bullet-list-style Summary and alphabetized Terminology sections in each chapter; Self-Review Exercises and Answers in each chapter; and the richest collection of Exercises in any C book.The exercises range from simple recall questions to lengthy programming problems to major projects. Instructors requiring substantial term projects will find many appropriate problems listed in the exercises, especially in the later chapters. We have put a great deal of effort into the exercises to enhance the value of this course for the student.In writing this book, we have used a variety of C compilers. For the most part, the programs in the text will work on all ANSI/ISO C compiler, including the Borland C++ compiler included with this book.The C material (Chapters 2-14) follows the ANSI C standard published in 1990. Many features of ANSI C will not work with pre-ANSI C versions and may not work with ISO C99 compilers, when they become available. See the reference manuals for your particular system for more details about the language, or obtain a copy of ANSI/ISO 9899: 1990, "American National Standard for Information Systems—Programming Language C," from the American National Standards Institute, 11 West 42nd Street, New York, New York 10036.The C++ material is based on the C++ programming language as developed by Accredited Standards Committee X3, Information Technology and its Technical Committee X3J16, Programming Language C++, respectively. The C and C++ languages were approved by the International Standards Organization (ISO). For further details, contact:X3 Secretariat1250 Eye Street NWWashington DC 20005The serious programmer should read these documents carefully and reference them regularly. These documents are not tutorials. Rather they define their respective languages with the extraordinary level of precision that compiler implementors and "heavy-duty" developers demand.The Java chapters are based on Sun Microsystems most recent Java release-the Java 2 Platform. Sun provides an implementation of the Java 2 Platform called the Java 2 Software Development Kit (J2SDK), version 1.3 that includes the minimum set of tools you need to write software in Java. For further details on the latest implementation of Java, visit (java.sun).We have carefully audited our presentation against these documents and documentation. Our book is intended to be used at the introductory and intermediate levels. We have not attempted to cover every feature discussed in these comprehensive documents.ObjectivesEach chapter begins with a statement of objectives. This tells the student what to expect and gives the student an opportunity, after reading the chapter, to determine if he or she has met these objectives. It is a confidence builder and a source of positive reinforcement.QuotationsThe learning objectives are followed by a series of quotations. Some are humorous, some are philosophical and some offer interesting insights. Our students enjoy relating the quotations to the chapter material. You may appreciate some of the quotations more after reading the chapters.OutlineThe chapter outline helps the student approach the material in top-down fashion. This, too, helps students anticipate what is to come and set a comfortable and effective learning pace.SectionsEach chapter is organized into small sections that address key C, C++ or Java topics.12,187 Lines of Syntax-Highlighted Code in 270 Example Programs(with Program Outputs)We present C, C++ and Java features in the context of complete, working programs; each program is immediately followed by a window containing the outputs produced when the program is run—we call this our "live-code approach." This enables the student to confirm that the programs run as expected. Relating outputs back to the program statements that produce those outputs is an excellent way to learn and to reinforce concepts. Our programs exercise the diverse features of C, C++ and Java. Reading the book carefully is much like entering and running these programs on a computer. The code is "syntax highlighted" with keywords appearing in the second color of the book, comments appearing in a lighter shade of that color and the rest of each program appearing in black. This makes it much easier to read the code-students will especially appreciate the syntax highlighting when they read the many more substantial programs we present.473 Illustrations/FiguresAn abundance of colorized charts and line drawings is included. The discussions of control structures in Chapters 3 and 4 feature carefully drawn flowcharts. (Note: We do not teach the use of flowcharting as a program development tool, but we do use a brief flowchart-oriented presentation to specify the precise operation of C's control structures.) Chapter 12, "Data Structures," uses colorized line drawings to illustrate the creation and maintenance of linked lists, queues, stacks and binary trees. The remainder of the book is abundantly illustrated.784 Programming TipsWe have included six design elements to help students focus on important aspects of program development, testing and debugging, performance and portability. We highlight hundreds of these tips in the form of Good Programming Practices, Common Programming Errors, Performance Tips, Portability Tips, Software Engineering Observations and Testing and Debugging Tips. These tips and practices represent the best we have been able to glean from almost six decades (combined) of programming and teaching experience. One of our students—a mathematics major—told us recently that she feels this approach is somewhat like the highlighting of axioms, theorems and corollaries in mathematics books; it provides a basis on which to build good software.163 Good Programming PracticesGood Programming Practices are highlighted in the text. They call the student's attention to techniques that help produce better programs. When we teach introductory courses to nonprogrammers, we state that the "buzzword" of each course is "clarity," and we tell the students that we will highlight (in these Good Programming Practices) techniques for writing programs that are clearer, more understandable and more maintainable.  262 Common Programming ErrorsStudents learning a language—especially in their first programming course—tend to make certain kinds of errors frequently. Focusing on these Common Programming Errors helps students avoid making the same errors. It also helps reduce long lines outside instructors' offices during office hours!  76 Performance TipsIn our experience, teaching students to write clear and understandable programs is by far the most important goal for a first programming course. But students want to write the programs that run the fastest, use the least memory, require the smallest number of keystrokes, or dazzle in other nifty ways. Students really care about performance. They want to know what they can do to "turbo charge" their programs. So we have include Performance Tips to highlight opportunities for improving program performance.  41 Portability TipsSoftware development is a complex and expensive activity. Organizations that develop software must often produce versions customized to a variety of computers and operating systems. So there is a strong emphasis today on portability, i.e., on producing software that will run on a variety of computer systems with few, if any, changes. Many people tout C/C++ as appropriate languages for developing portable software, especially because ANSI/ISO C and C++ are the global standards for those languages. Some people assume that if they implement an application in C++, the application will automatically be portable. This is simply not the case. Achieving portability requires careful and cautious design. There are many pitfalls. We include numerous Portability Tips to help students write portable code. Java was designed to maximize portability, but Java programs can also require modifications to "port" them.  187 Software Engineering ObservationsThe Software Engineering Observations highlight techniques, architectural issues and design ' issues, etc. that affect the architecture and construction of software systems, especially large-scale systems. Much of what the student learns here will be useful in upper-level courses and in industry as the student begins to work with large, complex real-world systems. C, C++ and Java are especially effective languages for performing good software engineering.  23 Testing and Debugging TipsThis "tip type" may be misnamed. When we decided to incorporate Testing and Debugging Tips into this new edition, we thought these tips would be suggestions for testing programs to expose bugs and suggestions for removing those bugs. In fact, most of these tips tend to be observations about capabilities and features of C, C++ and Java that prevent bugs from getting into programs in the first place.  32 Look-and-Feel ObservationsIn the Java portion of this book, we provide Look-and-Feel Observations to highlight graphical user interface conventions. These observations help students design their own graphical user interfaces to conform with industry norms.SummaryEach chapter ends with additional pedagogical devices. We present an extensive, bulletlist-style Summary in every chapter. This helps the student review and reinforce key concepts. There is an average of 37 summary bullets per chapter.TerminologyWe include a Terminology section with an alphabetized list of the important terms defined in the chapter—again, further reinforcement. There is an average of 73 terms per chapter.Summary of Tips, Practices and ErrorsWe collect and list from the chapter the Good Programming Practices, Common Programming Errors, Look-and-Feel Observations, Performance Tips, Portability Tips. Software Engineering Observations and Testing and Debugging Tips.728 Self-Review Exercises and Answers (Count Includes Separate Parts)Extensive Self-Review Exercises and Answers to Self-Review Exercises are included for self study. This gives the student a chance to build confidence with the material and prepare to attempt the regular exercises.994 Exercises (Count Includes Separate Parts; 1722 Total Exercises)Each chapter concludes with a substantial set of exercises including simple recall of important terminology and concepts; writing individual program statements; writing small portions of functions and C++/Java classes; writing complete functions, C++/Java classes and programs; and writing major term projects. The large number of exercises enables instructors to tailor their courses to the unique needs of their audiences and to vary course assignments each semester. Instructors can use these exercises to form homework assignments, short quizzes and major examinations.550 page Instructor's Manual with Solutions to the ExercisesThe solutions for the exercises are included on the Instructor's CD and on the disks available only to instructors through their Prentice Hall representatives. NOTE: Please do not write to us requesting the instructor's CD. Distribution of this CD is limited strictly to college professors teaching from the book. Instructors may obtain the solutions manual only from their Prentice Hall representatives.5058 Index Entries (Total of 8268 Counting Multiple References)We have included an extensive Index at the back of the book. This helps the student find any term or concept by keyword. The Index is useful to people reading the book for the first time and is especially useful to practicing programmers who use the book as a reference. Most of the terms in the Terminology sections appear in the Index (along with many more index items from each chapter). Thus, the student can use the Index in conjunction with the Terminology sections to be sure he or she has covered the key material of each chapter.   A Tour of the BookThe book is divided into four major parts. The first part, Chapters 1 through 14,.presents a thorough treatment of the C programming language including a formal introduction to structured programming. The second part (Chapters 15 through 23)—unique among C textbooks—presents a substantial treatment of C++ and object-oriented programming sufficient for an upper-level undergraduate college course. The third part—Chapters 24 through 30 (and also unique among C books) —presents a thorough introduction to Java 2, including graphics programming, graphical user interface (GUI) programming using Java Swing, multimedia programming and event-driven programming. The fourth part, Appendices A through E, presents a variety of reference materials that support the main text.Chapter 1—Introduction to Computers, the Internet and the World Wide Web— discusses what computers are, how they work and how they are programmed. It introduces the notion of structured programming and explains why this set of techniques has fostered a revolution in the way programs are written. The chapter gives a brief history of the development of programming languages from machine languages, to assembly languages, to high-level languages. The origins of the C, C++ and Java programming languages are discussed. The chapter includes an introduction to a typical C programming environment. We discuss the explosion in interest in the Internet that has occurred with the advent of the World Wide Web and the Java programming language.Chapter 2—Introduction to C Programming—gives a concise introduction to writing C programs. A detailed treatment of decision making and arithmetic operations in C is presented. After studying this chapter, the student will understand how to write simple, but complete, C programs.Chapter 3—Structured Program Development—is probably the most important chapter in the text, especially for the serious student of computer science. It introduces the notion of algorithms (procedures) for solving problems. It explains the importance of structured programming in producing programs that are understandable, debuggable, maintainable and more likely to work properly on the first try. It introduces the fundamental control structures of structured programming, namely the sequence, selection (if and if /else) and repetition (while) structures. It explains the technique of top-down, stepwise refinement that is critical to the production of properly structured programs. It presents the popular program design aid, structured pseudocode. The methods and approaches used in Chapter 3 are applicable to structured programming in any programming language, not just C. This chapter helps the student develop good programming habits in preparation for dealing with the more substantial programming tasks in the remainder of the text.Chapter 4—C Program Control—refines the notions of structured programming and introduces additional control structures. It examines repetition in detail and compares the alternatives of counter-controlled loops and sentinel-controlled loops. The for structure is introduced as a convenient means for implementing counter-controlled loops. The switch selection structure and the do/while repetition structure are presented. The chapter concludes with a discussion of logical operators.Chapter 5—C Functions—discusses the design and construction of program modules. C's function-related capabilities includes standard library functions, programmer-defined functions, recursion and call-by-value capabilities. The techniques presented in Chapter 5 are essential to the production and appreciation of properly structured programs, especially the kinds of larger programs and software that system programmers and application programmers are likely to develop in real-world applications. The "divide and conquer" strategy is presented as an effective means for solving complex problems by dividing them into simpler interacting components. Students enjoy the treatment of random numbers and simulation, and they appreciate the discussion of the dice game of craps which makes elegant use of control structures. The chapter offers a solid introduction to recursion and includes a table summarizing the dozens of recursion examples and exercises distributed throughout the remainder of the book. Some books leave recursion for a chapter late in the book; we feel this topic is best covered gradually throughout the text. The extensive collection of exercises at the end of the Chapter 5 includes several classical recursion problems such as the Towers of Hanoi.Chapter 6—C Arrays—discusses the structuring of data into arrays, or groups, of related data items of the same type. The chapter presents numerous examples of both single- sub scripted arrays and double- subscripted arrays. It is widely recognized that structuring data properly is just as important as using control structures effectively in the development of properly structured programs. Examples in the chapter investigate various common array manipulations, printing histograms, sorting data, passing arrays to functions and an introduction to the field of survey data analysis (with sample statistics). A feature of this chapter is the careful presentation of elementary sorting and searching techniques and the presentation of binary searching as a dramatic improvement over linear searching. The end-of-chapter exercises include a variety of interesting and challenging problems, such as improved sorting techniques, the design of an airline reservations system, an introduction to the concept of turtle graphics (made famous in the LOGO language) and the Knight's Tour and Eight Queens problems that introduce the notions of heuristic programming so widely employed in the field of artificial intelligence.Chapter 7—C Pointers—presents one of the most powerful and difficult to master features of the C language, namely pointers. The chapter provides detailed explanations of pointer operators, call by reference, pointer expressions, pointer arithmetic, the relationship between pointers and arrays, arrays of pointers and pointers to functions. The chapter exercises include a simulation of the classic race between the tortoise and the hare, card shuffling and dealing algorithms and recursive maze traversals. A special section entitled "Building Your Own Computer" is also included. This section explains machine language programming and proceeds with a project involving the design and implementation of a computer simulator that allows the reader to write and run machine language programs. This unique feature of the text will be especially useful to the reader who wants to understand how computers really work. Our students enjoy this project and often implement substantial enhancements, many if which are suggested in the exercises. In Chapter 12, another special section guides the reader through building a compiler; the machine language produced by the compiler is then executed on the machine language simulator produced in Chapter 7.Chapter 8—C Characters and Strings—deals with the fundamentals of processing nonnumeric data. The chapter includes a complete walkthrough of the character and string processing functions available in C's libraries. The techniques discussed here are widely used in building word processors, page layout and typesetting software and text-processing applications. The chapter includes an interesting collection of exercises that explore text-processing applications. The student will enjoy the exercises on writing limericks, writing random poetry, converting English to pig Latin, generating seven-letter words that are equivalent to a given telephone number, text justification, check protection, writing a check amount in words, generating Morse Code, metric conversions and dunning letters. The last exercise challenges the student to use a computerized dictionary to create a crossword puzzle generator.Chapter 9—C Formatted Input/Output—presents all the powerful formatting capabilities of printf and scanf. We discuss printf's output formatting capabilities such as rounding floating point values to a given number of decimal places, aligning columns of numbers, right justification and left justification, insertion of literal information, forcing a plus sign, printing leading zeros, using exponential notation, using octal and hexadecimal numbers and controlling field widths and precisions. We discuss all of printf's escape sequences for cursor movement, printing special characters and causing an audible alert. We examine all of scanf's input formatting capabilities including inputting specific types of data and skipping specific characters in an input stream. We discuss all of scanf's conversion specifiers for reading decimal, octal, hexadecimal, floating point, character and string values. We discuss scanning inputs to match (or not match) the characters in a scan set. The chapter exercises test virtually all of C's formatted input/output capabilities.Chapter 10—C Structures, Unions, Bit Manipulations and Enumerations—presents a variety of important features. Structures are like records in Pascal and other programming languages-they group data items of various types. Structures are used in Chapter 11 to form files consisting of records of information. Structures are used in conjunction with pointers and dynamic memory allocation in Chapter 12 to form dynamic data structures such as linked lists, queues, stacks and trees. Unions enable an area of memory to be used for different types of data at different times; such sharing can reduce a program's memory requirements or secondary-storage requirements. Enumerations provide a convenient means of defining useful symbolic constants; this helps make programs more self-documenting. C's powerful bit manipulation capabilities enable programmers to write programs that exercise lower-level hardware capabilities. This helps programs process bit strings, set individual bits on or off and store information more compactly. Such capabilities, often found only in low-level assembly languages, are valued by programmers writing system' software such as operating systems and networking software. A feature of the chapter is its revised, high-performance card shuffling and dealing simulation. This is an excellent opportunity for the instructor to emphasize the quality of algorithms.Chapter 11—C File Processing—discusses the techniques used to process text files with sequential access and random access. The chapter begins with an introduction to the data hierarchy from bits, to bytes, to fields, to records, to files. Next, C's simple view of files and streams is presented. Sequential-access files are discussed using programs that show how to open and close files, how to store data sequentially in a file and how to read data sequentially from a file. Random-access files are discussed using programs that show how to create a file sequentially for random access, how to read and write data to a file with random access and how to read data sequentially from a randomly accessed file. The fourth random-access program combines many of the techniques of accessing files both sequentially and randomly into a complete transaction-processing program. Students in our industry seminars have told us that after studying the material on file processing, they were able to produce substantial fileprocessing programs that were immediately useful in their organizations.Chapter 12—C Data Structures—discusses the techniques used to create and manipulate dynamic data structures. The chapter begins with discussions of self-referential structures and dynamic memory allocation and proceeds with a discussion of how to create and maintain various dynamic data structures including linked lists, queues (or waiting lines), stacks and trees. For each type of data structure, we present complete, working programs and show sample outputs. The chapter helps the student master pointers. The chapter includes abundant examples using indirection and double indirection-a particularly difficult concept. One problem when working with pointers is that students have trouble visualizing the data structures and how their nodes are linked together. So we have included illustrations that show the links, and the sequence in which they are created. The binary tree example is a superb capstone for the study of pointers and dynamic data structures. This example creates a binary tree; enforces duplicate elimination; and introduces recursive preorder, inorder and postorder tree traversals. Students have a genuine sense of accomplishment when they study and implement this example. They particularly appreciate seeing that the inorder traversal prints the node values in sorted order. The chapter includes a substantial collection of exercises. A highlight of the exercises is the special section "Building Your Own Compiler." The exercises walk the student through the development of an infix-to-postfix-conversion program and a postfix-expression-evaluation program. We then modify the postfix evaluation algorithm to generate machine-language code. The compiler places this code in a file (using the techniques of Chapter 11). Students then run the machine language produced by their compilers on the software simulators they built in the exercises of Chapter 7!Chapter 13—The C Preprocessor—provides detailed discussions of the preprocessor directives. The chapter includes detailed information on the #include directive that causes a copy of a specified file to be included in place of the directive before the file is compiled and the #define directive that creates symbolic constants and macros. The chapter explains conditional compilation for enabling the programmer to control the execution of preprocessor directives and the compilation of program code. The # operator that converts its operand to a string and the ## operator that concatenates two tokens are discussed. Predefined symbolic constants _LINE_, _FILE_, _DATE_, and _TIME_ are presented. Finally, macro assert of the assert.h header is discussed. Macro assert is valuable in program testing, debugging, verification and validation.Chapter 14—C Advanced Topics—presents additional topics including several advanced topics not ordinarily covered in introductory courses. We show how to redirect program input to come from a file, redirect program output to be placed in a file, redirect the output of one program to be the input of another-this called "piping", append the output of a program to an existing file, develop functions that use variable-length argument lists, pass command-line arguments to function main and use them in a program, compile programs whose components are spread across multiple files, register functions with atexit to be executed at program termination, terminate program execution with function exit, use the const and volatile type qualifiers, specify the type of a numeric constant using the integer and floating-point suffixes, use the signal-handling library to trap unexpected events, create and use dynamic arrays with calloc and realloc, and use unions as a space-saving technique.Chapter 15—C++ as a "Better C"—introduces the non-object-oriented features of C++. These features improve the process of writing procedural programs. The chapter discusses single-line comments, stream input/output, declarations, creating new data types, function prototypes and type checking, inline functions (as a replacement for macros), reference parameters, the const qualifier, dynamic memory allocation, default arguments, the unary scope resolution operator, function overloading, linkage specifications and function templates.Chapter 16—C++ Classes and Data Abstraction—begins our discussion of object-based programming. The chapter represents a wonderful opportunity for teaching data abstraction the "right way"-through a language (C++) expressly devoted to implementing abstract data types (ADTs). In recent years, data abstraction has become a major topic in introductory computing courses. Chapters 16 through 18 include a solid treatment of data abstraction. Chapter 16 discusses implementing ADTs as C++-style classes and why this approach is superior to using structs, accessing class members, separating interface from implementation, using access functions and utility functions, initializing objects with constructors, destroying objects with destructors, assignment by default memberwise copy and software reusability. One of the chapter exercises challenges the reader to develop a class for complex numbers.Chapter 17—C++ Classes Part II—continues the study of classes and data abstraction. The chapter discusses declaring and using constant objects, constant member functions, composition-the process of building classes that have objects of other classes as members, friend functions and friend classes that have special access rights to the private and protected members of classes, the this pointer that enables an object to know its own address, dynamic memory allocation, static class members for containing and manipulating class-wide data, examples of popular abstract data types (arrays, strings and queues), container classes and iterators. The chapter exercises ask the student to develop a savings account class and a class for holding sets of integers. We discuss dynamic memory allocation with new and delete. When new fails, it returns a 0 pointer in pre-standard C++. We use this pre-standard style in Chapters 17 through 22. We defer to Chapter 23 the discussion of the new style of new failure in which new now "throws an exception." We motivate the discussion of static class members with a video-game-based example. We emphasize throughout the book and in our professional seminars how important it is to hide implementation details from clients of a class.Chapter 18—C++ Operator Overloading—is one of the most popular topics in our C++ courses. Students really enjoy this material. They find it a perfect match with the discussion of abstract data types in Chapters 16 and 17. Operator overloading enables the programmer to tell the compiler how to use existing operators with objects of new class types. C++ already knows how to use these operators with objects of built-in types such as integers, floating point numbers and characters. But suppose we create a new string class—what would the plus sign mean when used between string objects? Many programmers use plus with strings to mean concatenation. The chapter discusses the fundamentals of operator overloading, restrictions in operator overloading, overloading with class member functions vs. with nonmember functions, overloading unary and binary operators and converting between types. A feature of the chapter is the substantial case study of an array class, a huge-integer class and a complex numbers class (the last two appear with full source code in the exercises). This material is different from what you do in most programming languages and courses. Operator overloading is a complex topic, but an enriching one. Using operator overloading wisely helps you add that extra "polish" to your classes. With the techniques of Chapters 16, 17 and 18, it is possible to craft a Date class that, if we had been using it for the last two decades, could easily have eliminated a major portion of the so-called "Year 2000 (or Y2K) Problem." One of the exercises encourages the reader to add operator overloading to class Complex to enable convenient manipulation of objects of this class with operator symbols-as in mathematics-rather than with function calls as the student did in the Chapter 17 exercises.Chapter 19—C++ Inheritance—deals with one of the most fundamental capabilities of objectoriented programming languages. Inheritance is a form of software reusability in which new classes are developed quickly and easily by absorbing the capabilities of existing classes and adding appropriate new capabilities. The chapter discusses the notions of base classes and derived classes, protected members, public inheritance, protected inheritance, private inheritance, direct base classes, indirect base classes, constructors; and destructors in base classes and derived classes and software engineering with inheritance. The chapter compares inheritance ("is a" relationships) with composition ("has a" relationships) and introduces "uses a" and "knows a" relationships. A feature of the chapter is its several substantial case studies. In particular, a lengthy case study implements a point, circle, cylinder class hierarchy. The exercises ask the student to compare the creation of new classes by inheritance vs. composition; to extend the various inheritance hierarchies discussed in the chapter; to write an inheritance hierarchy for quadrilaterals, trapezoids, parallelograms, rectangles and squares; and to create a more general shape hierarchy with two-dimensional shapes and three-dimensional shapes.Chapter 20—C++ Virtual Functions and Polymorphism—deals with another of the fundamental capabilities of object-oriented programming, namely polymorphic behavior. When many classes are related through inheritance to a common base class, each derived-class object may be treated as a base-class object. This enables programs to be written in a general manner independent of the specific types of the derived-class objects. New kinds of objects can be handled by the same program, thus making systems more extensible. Polymorphism enables programs to eliminate complex switch logic in favor of simpler "straight-line" logic. A screen manager of a video game, for example, can simply send a draw message to every object in a linked list of objects to be drawn. Each object knows how to draw itself. A new object can be added to the program without modifying that program as long as that new object also knows how to draw itself. This style of programming is typically used to implement today's popular graphical user interfaces (GUIs). The chapter discusses the mechanics of achieving polymorphic behavior through the use of virtual functions. It distinguishes between abstract classes (from which objects cannot be instantiated) and concrete classes (from which objects can be instantiated). Abstract classes are useful for providing an inheritable interface to classes throughout the hierarchy. A feature of the chapter is its polymorphism case study of the point, circle, cylinder shape hierarchy discussed in Chapter 19. The chapter exercises ask the student to discuss a number of conceptual issues and approaches, add abstract classes to the shape hierarchy, develop a basic graphics package—and pursue all these projects with virtual functions and polymorphic programming. Our professional audiences insisted that we provide a deeper explanation that showed precisely how polymorphism is implemented in C++, and hence, precisely what execution time and memory "costs" one must pay when programming with this powerful capability. We responded by developing an illustration in the section entitled "Polymorphism, virtual Functions and Dynamic Binding "Under the Hood" that shows the vtables (virtual function tables) that the C++ compiler automatically builds to support the polymorphic programming style. We drew these tables in our classes in which we discussed the point, circle, cylinder shape hierarchy. Our audiences indicated that this indeed gave them the information to decide whether polymorphism was an appropriate programming style for each new project they would tackle. We have included this presentation in Section 20.9 and the vtable illustration in Fig. 20.2. Please study this presentation carefully. It will give you a much deeper understanding of what is really occurring in the computer when you program with inheritance and polymorphism.Chapter 21—C++ Stream Input/Output—contains a comprehensive treatment of C++ objectoriented input/output. The chapter discusses the various I/O capabilities of C++ including output with the stream insertion operator, input with the stream extraction operator, type-safe I/O (a nice improvement over C), formatted I/O, unformatted I/O (for performance), stream manipulators for controlling the stream base (decimal, octal, or hexadecimal), floating-point numbers, controlling field widths, user-defined manipulators, stream format states, stream error states, 1/O of objects of user-defined types and tying output streams to input streams (to ensure that prompts actually appear before the user is expected to enter responses). The extensive exercise set asks the student to write various programs that test most of the 1/O capabilities discussed in the text.Chapter 22—C++ Templates—discusses one of the more recent additions to C++. Function templates were introduced in Chapter 15. Class templates enable the programmer to capture the essence of an abstract data type (such as a stack, an array, or a queue) and then create-with minimal additional code-versions of that ADT for particular types (such as a queue of int, a queue of float, a queue of strings, etc.). For this reason, template classes are often called parameterized types. The chapter discusses using type parameters and nontype parameters and considers the interaction among templates and other C++ concepts, such as inheritance, friends and static members. The exercises challenge the student to write a variety of function templates and class templates, and to employ these in complete programs.Chapter 23—C++ Exception Handling—discusses one of the more recent enhancements to the C++ language. Exception handling enables the programmer to write programs that are more robust, more fault tolerant and more appropriate for business-critical and mission-critical environments. The chapter discusses when exception handling is appropriate; introduces the basics of exception handling with try blocks, throw statements and catch blocks; indicates how and when to rethrow an exception; explains how to write an exception specification and process unexpected exceptions; and discusses the important ties between exceptions and constructors, destructors and inheritance. We discuss rethrowing an exception and we illustrate both ways new can fail when memory is exhausted. Prior to the C++ draft standard new failed by returning 0, much as malloc fails in C by returning a NULL pointer value. We show the new style of new failing by throwing a bad_alloc (bad allocation) exception. We illustrate how to use set-new-handler to specify a custom function to be called to deal with memory exhaustion situations. We discuss the auto_ptr class template to guarantee that dynamically allocated memory will be properly deleted to avoid memory leaks.Chapter 24—Introduction to Java Applications and Applets—introduces a typical Java programming environment and provides a lightweight introduction to programming applications and applets in the Java programming language. Some of the input and output is performed using a new graphical user interface (GUI) element called JOptionPane that provides predefined windows (called dialogs) for input and output. JOptionPane handles ouputting data to windows and inputting data from windows. The chapter introduces applets using several of the sample demonstration applets supplied with the Java 2 Software Development Kit (J2SDK). We use appletviewer (a utility supplied with the J2SDK) to execute several sample applets. We then write Java applets that perform tasks similar to the applications written earlier in the chapter, and we explain the similarities and differences between applets and applications. After studying this chapter, the student will understand how to write simple, but complete, Java applications and applets. The next several chapters use both applets and applications to demonstrate additional key programming concepts.Chapter 25—Beyond C & C++: Operators, Methods & Arrays—focuses on both the similarities and differences among Java, C and C++. The chapter discusses the primitive types in Java and how they differ from C/C++, as well as some differences in terminology. For example, what we call a function in C/C++ is called a method in Java. The chapter also contains a discussion of logical operators-&& (logical AND), & (boolean logical AND),   (logical OR),  (boolean logical inclusive OR), ^ (boolean logical exclusive OR) and ! (NOT). applications. The topic of method overloading (as compared to function overloading in C++) is motivated and explained. In this chapter, we also introduce events and event handling—elements required for programming graphical user interfaces. Events are notifications of state change such as button clicks, mouse clicks, pressing a keyboard key, etc. Java allows programmers to respond to various events with by coding methods called event handlers. We also introduce arrays in Java, which are processed as full-fledged objects. This is further evidence of Java's commitment to almost 100% object-orientation. We discuss the structuring of data into arrays, or groups, of related data items of the same type. The chapter presents numerous examples of both single-subscripted arrays and double-subscripted arrays.Chapter 26—Java Object-Based Programming—begins our deeper discussion of classes. The chapter focuses on the essence and terminology of classes and objects. What is an object? What is a class of objects? What does the inside of an object look like? How are objects created? How are they destroyed? How do objects communicate with one another? Why are classes such a natural mechanism for packaging software as reusable componentry? The chapter discusses implementing abstract data types as Java-style classes, accessing class members, enforcing information hiding with private instance variables, separating interface from implementation, using access methods and utility methods, initializing objects with constructors and using overloaded constructors. The chapter discusses declaring and using constant references, composition—the process of building classes that have as members references to objects, the this reference that enables an object to "know itself," dynamic memory allocation, static class members for containing and manipulating class-wide data and examples of popular abstract data types such as stacks and queues. The chapter also introduces the package statement and discusses how to create reusable packages. The chapter exercises challenge the student to develop classes for complex numbers, rational numbers, times, dates, rectangles, huge integers, a class for playing Tic-Tac-Toe, a savings account class and a class for holding sets of integers.Chapter 27—Java Object-Oriented Programming—discusses the relationships among classes of objects, and programming with related classes. How can we exploit commonality between classes of objects to minimize the amount of work it takes to build large software systems? What is polymorphism? What does it mean to "program in the general" rather than "programming in the specific?" How does programming in the general make it easy to modify systems and add new features with minimal effort? How can we program for a whole category of objects rather than programming individually for each. type of object? The chapter deals with one of the most fundamental capabilities of object-oriented programming languages, inheritance, which is a form of software reusability in which new classes are developed quickly and easily by absorbing the capabilities of existing classes and adding appropriate new capabilities. The chapter discusses the notions of superclasses and subclasses, protected members, direct superclasses, indirect superclasses, use of constructors in superclasses and subclasses and software engineering with inheritance. We introduce inner classes that help hide implementation details. Inner classes are most frequently used to create GUI event handlers. Named inner classes can be declared inside other classes and are useful in defining common event handlers for several GUI components. Anonymous inner classes are declared inside methods and are used to create one object—typically an event handler for a specific GUI component. The chapter compares inheritance ("is a" relationships) with composition ("has a" relationships). A feature of the chapter is its case study implementation of a point, circle and cylinder class hierarchy. The exercises ask the student to compare the creation of new classes by inheritance vs. composition; to extend the inheritance hierarchies discussed in the chapter; to write an inheritance hierarchy for quadrilaterals, trapezoids, parallelograms, rectangles and squares; and to create a more general shape hierarchy with two-dimensional shapes and three-dimensional shapes. The chapter explains polymorphic behavior. When many classes are related through inheritance to a common superclass, each subclass object may be treated as a superclass object. This enables programs to be written in a general manner independent of the specific types of the subclass objects. New kinds of objects can be handled by the same program, thus making systems more extensible. Polymorphism enables programs to eliminate complex switch logic in favor of simpler "straight-line" logic. A video game screen manager, for example, can send a "draw" message to every object in a linked list of objects to be drawn. Each object knows how to draw itself. A new type of object can be added to the program without modifying that program as long as that new object also knows how to draw itself. This style of programming is typically used to implement today's popular graphical user interfaces. The chapter distinguishes between abstract classes (from which objects cannot be instantiated) and concrete classes (from which objects can be instantiated). The chapter also introduces interfaces-sets of methods that must be defined by any class that implements the interface. Interfaces are Java's replacement for the dangerous (albeit powerful) feature of C++ called multiple inheritance.Chapters 28 and 29 were co-authored with our colleague, Mr. Tem Nieto of Deitel & Associates, Inc. Tern's infinite patience, attention to detail, illustration skills and creativity are apparent throughout these chapters.Chapter 28—Java Graphics and Java2D—begins a run of chapters that present the multimedia "sizzle" of Java. Traditional C and C++ programming are pretty much confined to character-mode input/output. Some versions of C++ are supported by platform-dependent class libraries that can do graphics, but using these libraries makes your applications nonportable. Java's graphics capabilities are platform independent and hence, portable—and we mean portable in a worldwide sense. You can develop graphics-intensive Java applets and distribute them over the World Wide Web to colleagues everywhere and they will run nicely on the local Java platforms. We discuss graphics contexts and graphics objects; drawing strings, characters and bytes; color and font control; screen manipulation and paint modes; and drawing lines, rectangles, rounded rectangles, 3dimensional rectangles, ovals, arcs and polygons. We introduce the Java2D API, new in Java 2, which provides powerful graphical manipulation tools. The chapter has many figures that painstakingly illustrate each of these graphics capabilities with live-code examples, appealing screen outputs, detailed features tables and detailed line art.Chapter 29—Java Graphical User Interface Components—introduces the creation of applets and applications with user-friendly graphical user interfaces (GUIs). This chapter focuses on Java's new Swing GUI components. These platform-independent GUI components are written entirely in Java. This provides Swing GUI components with great flexibility—they can be customized to look like the computer platform on which the program executes, or they can use the standard Java look-and-feel that provides an identical user interface across all computer platforms. We discuss the new javax.swing package, which provides much more powerful GUI components than the Java 1.1 java.awt components. Through its many programs, tables and line drawings, the chapter illustrates GUI design principles, the javax.swing hierarchy, labels, push buttons, text fields, text areas, combo boxes, check boxes, panels, scrolling panels, custom panels, handling mouse events, windows, menus and using three of Java's simpler GUI layout managers, namely FlowLayout, BorderLayout and GridLayout. The chapter concentrates on Java's delegation event model for GUI processing. The exercises challenge the student to create specific GUIs, exercise various GUI features, develop drawing programs that let the user draw with the mouse and control fonts.Chapter 30—Java Multimedia: Images, Animation, Audio and Video—deals with Java's capabilities for making computer applications "come alive." It is remarkable that students in first programming courses will be writing applications with all these capabilities. The possibilities are intriguing. Students now access (over the Internet and through CDROM technology) vast libraries of graphics images, audios and videos and can weave their own together with those in the libraries to form creative applications. Already most new computers come "multimedia equipped." Dazzling term papers and classroom presentations are being prepared by students with access to vast public domain libraries of images, drawings, voices, pictures, videos, animations and the like. A "paper" when most of us were in the earlier grades was a collection of characters, possibly handwritten, possibly typewritten. A "paper" can be a multimedia "extravaganza." It can hold your interest, pique your curiosity, make you feel what the subjects of the paper felt when they were making history. Multimedia can make your science labs much more exciting. Textbooks can come alive. Instead of looking at a static picture of some phenomenon, you can watch that phenomenon occur in a colorful, animated, presentation with sounds, videos and various other effects. People can learn more, learn it in more depth and experience more viewpoints. A feature of the chapter is the image maps discussion that enable a program to sense the presence of the mouse pointer over a region of an image, without clicking the mouse. We present a live-code image map application with the icons Prentice Hall artists created for our Java Multimedia Cyber Classroom programming tips. As the user moves the mouse pointer across the six icon images, the type of tip is displayed, either "Good Programming Practice" for the thumbs-up icon, "Portability Tip" for the bug with the suitcase icon, and so on.Several Appendices provide valuable reference material. We present Internet and World Wide Web resources for C, C++ and Java in Appendix A; a list of C99 Internet and World Wide Web resources in Appendix B; complete operator precedence and associativity charts for C, C++ and Java in Appendix C; the set of ASCII character codes in Appendix D; Appendix E is a complete tutorial on number systems including many self-review exercises with answers.