HOW TO PROGRAM EIGHTH EDITION GLOBAL EDITION with an introduction to C++ This page intentionally left blank HOW TO PROGRAM EIGHTH EDITION GLOBAL EDITION with an introduction to C++ Paul Deitel Deitel & Associates, Inc Harvey Deitel Deitel & Associates, Inc Global Edition contributions by Piyali Sengupta Boston Columbus Hoboken Indianapolis New York San Francisco Amsterdam Cape Town Dubai London Madrid Milan Munich Paris Montreal ˜ Paulo Sydney Hong Kong Seoul Singapore Taipei Tokyo Toronto Delhi Mexico City Sao Vice President and Editorial Director, ECS: Marcia J Horton Executive Editor: Tracy Johnson (Dunkelberger) Editorial Assistant: Kelsey Loanes Assistant Acquisitions Editor, Global Editions: Aditee Agarwal Program Manager: Carole Snyder Project Manager: Robert Engelhardt Project Editor, Global Editions: K.K Neelakantan Media Team Lead: Steve Wright R&P Manager: Rachel Youdelman R&P Senior Project Manager: William Opaluch Senior Operations Specialist: Maura Zaldivar-Garcia Senior Manufacturing Controller, Global Editions: Kay Holman Inventory Manager: Bruce Boundy Marketing Manager: Demetrius Hall Product Marketing Manager: Bram Van Kempen Media Production Manager, Global Editions: Vikram Kumar Marketing Assistant: Jon Bryant Cover Designer: Chuti Prasertsith / Michael Rutkowski / Marta Samsel Cover Art: © Igoror / Shutterstock Pearson Education Limited Edinburgh Gate Harlow Essex CM20 2JE England and Associated Companies throughout the world Visit us on the World Wide Web at: www.pearsonglobaleditions.com © Pearson Education Limited 2016 The rights of Paul Deitel and Harvey Deitel to be identified as the authors of this work have been asserted by them in accordance with the Copyright, Designs and Patents Act 1988 Authorized adaptation from the United States edition, entitled C How to Program: with an introduction to C++,8st edition, ISBN 978-0-13-397689-2, by Paul Deitel and Harvey Deitel published by Pearson Education © 2016 All rights reserved No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, without either the prior written permission of the publisher or a license permitting restricted copying in the United Kingdom issued by the Copyright Licensing Agency Ltd, Saffron House, 6–10 Kirby Street, London EC1N 8TS All trademarks used herein are the property of their respective owners The use of any trademark in this text does not vest in the author or publisher any trademark ownership rights in such trademarks, nor does the use of such trademarks imply any affiliation with or endorsement of this book by such owners British Library Cataloguing-in-Publication Data A catalogue record for this book is available from the British Library 10 ISBN 10: 1-292-11097-X ISBN 13: 978-1-292-11097-4 Typeset by GEX Publishing Services Printed in Malaysia In memory of Dennis Ritchie, creator of the C programming language and co-creator of the UNIX operating system Paul and Harvey Deitel Trademarks DEITEL, the double-thumbs-up bug and DIVE INTO are registered trademarks of Deitel and Associates, Inc Apple, Xcode, Swift, Objective-C, iOS and OS X are trademarks or registered trademarks of Apple, Inc Java is a registered trademark of Oracle and/or its affiliates Microsoft and/or its respective suppliers make no representations about the suitability of the information contained in the documents and related graphics published as part of the services for any purpose All such documents and related graphics are provided “as is” without warranty of any kind Microsoft and/ or its respective suppliers hereby disclaim all warranties and conditions with regard to this information, including all warranties and conditions of merchantability, whether express, implied or statutory, fitness for a particular purpose, title and non-infringement In no event shall Microsoft and/or its respective suppliers be liable for any special, indirect or consequential damages or any damages whatsoever resulting from loss of use, data or profits, whether in an action of contract, negligence or other tortious action, arising out of or in connection with the use or performance of information available from the services The documents and related graphics contained herein could include technical inaccuracies or typographical errors Changes are periodically added to the information herein Microsoft and/or its respective suppliers may make improvements and/or changes in the product(s) and/or the program(s) described herein at any time Partial screen shots may be viewed in full within the software version specified Other names may be trademarks of their respective owners Contents Appendices F, G and H are PDF documents posted online at the book’s Companion Website (located at www.pearsonglobaleditions.com/deitel) Preface 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 1.10 Introduction to Computers, the Internet and the Web Introduction Hardware and Software 1.2.1 Moore’s Law 1.2.2 Computer Organization Data Hierarchy Machine Languages, Assembly Languages and High-Level Languages The C Programming Language C Standard Library C++ and Other C-Based Languages Object Technology 1.8.1 The Automobile as an Object 1.8.2 Methods and Classes 1.8.3 Instantiation 1.8.4 Reuse 1.8.5 Messages and Method Calls 1.8.6 Attributes and Instance Variables 1.8.7 Encapsulation and Information Hiding 1.8.8 Inheritance Typical C Program-Development Environment 1.9.1 Phase 1: Creating a Program 1.9.2 Phases and 3: Preprocessing and Compiling a C Program 1.9.3 Phase 4: Linking 1.9.4 Phase 5: Loading 1.9.5 Phase 6: Execution 1.9.6 Problems That May Occur at Execution Time 1.9.7 Standard Input, Standard Output and Standard Error Streams Test-Driving a C Application in Windows, Linux and Mac OS X 1.10.1 Running a C Application from the Windows Command Prompt 1.10.2 Running a C Application Using GNU C with Linux 23 33 34 35 35 36 37 40 41 42 43 44 45 45 45 45 46 46 46 46 47 48 48 48 49 49 49 49 49 50 53 Contents 1.13 1.14 1.10.3 Running a C Application Using the Teminal on Mac OS X Operating Systems 1.11.1 Windows—A Proprietary Operating System 1.11.2 Linux—An Open-Source Operating System 1.11.3 Apple’s Mac OS X; Apple’s iOS for iPhone®, iPad® and iPod Touch® Devices 1.11.4 Google’s Android The Internet and World Wide Web 1.12.1 The Internet: A Network of Networks 1.12.2 The World Wide Web: Making the Internet User-Friendly 1.12.3 Web Services 1.12.4 Ajax 1.12.5 The Internet of Things Some Key Software Terminology Keeping Up-to-Date with Information Technologies Introduction to C Programming 2.1 2.2 2.3 2.4 2.5 2.6 2.7 Introduction A Simple C Program: Printing a Line of Text Another Simple C Program: Adding Two Integers Memory Concepts Arithmetic in C Decision Making: Equality and Relational Operators Secure C Programming Structured Program Development in C 3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8 3.9 3.11 3.12 3.13 Introduction Algorithms Pseudocode Control Structures The if Selection Statement The if…else Selection Statement The while Iteration Statement Formulating Algorithms Case Study 1: Counter-Controlled Iteration Formulating Algorithms with Top-Down, Stepwise Refinement Case Study 2: Sentinel-Controlled Iteration Formulating Algorithms with Top-Down, Stepwise Refinement Case Study 3: Nested Control Statements Assignment Operators Increment and Decrement Operators Secure C Programming C Program Control 4.1 Introduction 1.11 1.12 3.10 56 59 59 59 60 60 61 61 61 62 64 64 64 66 71 72 72 76 80 81 85 89 101 102 102 102 103 105 106 110 111 114 120 124 125 127 145 146 Contents 4.2 4.3 4.4 4.5 4.6 4.7 4.8 4.9 4.10 4.11 4.12 4.13 Iteration Essentials Counter-Controlled Iteration for Iteration Statement for Statement: Notes and Observations Examples Using the for Statement switch Multiple-Selection Statement do…while Iteration Statement break and continue Statements Logical Operators Confusing Equality (==) and Assignment (=) Operators Structured Programming Summary Secure C Programming C Functions 5.1 5.2 5.3 5.4 5.5 5.6 5.7 5.8 5.9 5.10 5.11 5.12 5.13 5.14 5.15 5.16 5.17 Introduction Modularizing Programs in C Math Library Functions Functions Function Definitions 5.5.1 square Function 5.5.2 maximum Function Function Prototypes: A Deeper Look Function Call Stack and Stack Frames Headers Passing Arguments By Value and By Reference Random Number Generation Example: A Game of Chance; Introducing enum Storage Classes Scope Rules Recursion Example Using Recursion: Fibonacci Series Recursion vs Iteration Secure C Programming C Arrays 6.1 6.2 6.3 6.4 Introduction Arrays Defining Arrays Array Examples 6.4.1 Defining an Array and Using a Loop to Set the Array’s Element Values 6.4.2 Initializing an Array in a Definition with an Initializer List 6.4.3 Specifying an Array’s Size with a Symbolic Constant and Initializing Array Elements with Calculations 146 147 148 151 152 155 161 162 164 167 169 174 189 190 190 191 193 193 194 197 198 200 204 205 206 210 214 216 219 222 226 227 246 247 247 249 249 249 250 252 Index Employee class 686 definition showing composition 688 definition with a static data member to track the number of Employee objects in memory 702 exercise 657 header 819 implementation file 820 member-function definitions 689, 702 employee identification number 38 empty member function of string 719 empty parameter list 596 empty parentheses 624, 625, 628 empty statement 110 empty string 632 encapsulation 46, 606, 631, 633, 665, 681, 691 encrypt 144 end line 585 “end of data entry” 114 end-of-file 158, 368, 377, 474, 478, 871 key combination 564 #endif 555 #endif preprocessor directive 662 endl stream manipulator 585 Enforcing Privacy with Cryptography 144 English-like abbreviations 40 Enhancing Class Date exercise 710 Enhancing Class Rectangle exercise 711 Enhancing Class Time exercise 709, 710 enqueue 527 Enter key 48, 78, 160, 584 enum 213, 460 enumeration 213, 461 enumeration constant 213, 460, 555 enumeration example 461 environment 47 EOF 158, 368, 851, 854 eof member function 851, 871 eofbit of stream 871 equality and relational operators 329 equality operator (==) 85, 736 204 error bits 854 error checking (in file processing) 491 error conditions 204 error detected in a constructor 892 error message 49 #error preprocessor directive 556 error state of a stream 851, 869, 870 errors 49 escape character 74, 422 escape sequence 74, 422, 435 Euler 301 event 572 exam results analysis 122 examination results problem 122 header 587 exception 613, 614, 882 handler 614 handling 587, 609, 882 out_of_range exception class 614 parameter 614 what member function of an exception object 614 exception class 883, 899 what virtual function 883 exception classes derived from common base class 893 header 883, 899 exception object 887 exception parameter 885 exceptions bad_alloc 893 bad_cast 899 bad_typeid 899 length_error 899 logic_error 899 out_of_range 899 overflow_error 899 underflow_error 900 exclusive write mode 480 executable image 48 executable program 75 execute 49 execute phase 48 executes 49 execution-time error 49 execution-time overhead 832 exit function 570, 675, 676, 895 atexit functions 571 EXIT_FAILURE 571 EXIT_SUCCESS 571 exp function 192 expand a macro 553 explicit constructor 751 explicit conversion 119 explicit keyword 636, 751 conversion operators 752 exponent 763 exponential complexity 225 991 exponential format 411 exponential function 192 exponential notation 412, 413 exponentiation 84 exponentiation operator 154 expression 155, 196 extensibility 801 extensibility of C++ 726 extensible programming language 608, 625 extern 214, 569 external linkage 570 external variable 215 F f or F for a float 572 function 192 Facebook 60 factorial 143, 183 factorial function 219, 220, 227 Fahrenheit temperatures 434 fail member function 871 failbit of stream 851, 855, 871 false boolean value 85 false boolean value 590 false boolean value 867 fatal error 49, 98, 115, 362 fatal logic error 110 fault-tolerant programs 614, 882 FCB 475, 477 fclose function 478 feature-complete 66 fenv.h 958 feof function 478, 491 fetch 361 fgetc function 475, 507 fgets function 377, 475 Fibonacci function 225, 227 Fibonacci series 223, 240 field 38 field of a class 39 field width 155, 411, 416, 419, 427, 855, 858 inputting data 427 fields larger than values being printed 864 FIFO (first-in first-out) 527 file 39, 474 file control block (FCB) 475, 477 file descriptor 475 file-matching program 505 file name 48 file offset 482 file open mode 477, 480 FILE pointer 475, 481 fabs 992 Index file position pointer 482, 491 FILE , predefined symbolic constant 557 file processing 846, 849 error checking 491 file scope 216, 667 FILE structure 475 filename extensions h 638 file-processing classes 849 fill character 664, 855, 858, 863, 864 fill member function 862, 864, 871 final class 814 member function 814 final release 66 final value 147 final value of a control variable 150, 152 find the minimum value in an array 305 first-in first-out (FIFO) 527 first refinement 114, 121 Fisher-Yates Shuffling Algorithm 446 five-card poker 352 fixed notation 850, 861, 866 fixed stream manipulator 861, 862, 866 flag value 114 flags 411, 419 flags member function of ios_base 868 flexible array member 967 flight simulator 842 float 117, 118, 119, 199 (float) cast operator 118 204 floating point 414, 861, 866 floating-point arithmetic 716 floating-point conversion specifiers 413, 417, 424 using 414 floating-point number 113, 117, 119 floating-point number in scientific format 866 floating-point size limits 204, 588 floating-point suffix f or F for a float 572 l or L for a long double 572 floor function 192 flow of control 89 flow of control of a virtual function call 833 flowchart 103, 105 if selection statement 106 sequence structure 104 while iteration statement 111 double-selection if/else statement 107 flowcharting C’s sequence structure 104 flowcharting the while iteration statement 162 flowcharting the single-selection if statement 106 flowcharting the while iteration statement 111 flowline 104, 106 flush buffer 585, 872 flushing stream 855 fmod function 193 fmtflags data type 868 fopen function 480 for header components 149 for iteration statement 105, 152 force a decimal point 850 forcing a plus sign 863 formal type parameter 603 format control string 78, 410, 411, 418, 423 format control string flags 419 format error 871 format of floating-point numbers in scientific format 866 format state 855, 868 format-state stream manipulators 861 formatted I/O 846 formatted input/output model 485 form-feed character (\f) 369 header 587 fprintf function 475 fprintf_s function 498 fputc function 475 fputs function 475 fractional parts 118 fractions 763 fragile software 786 fread function 475, 486 free function 511, 526 free function (global function) 665 free store 733 friend function 692, 768 friends are not member functions 694 Friends can access private members of class 692 friendship granted, not taken 692 front of a queue 510 fscanf function 475 function 498 fseek function 488 header 587 function 42, 48, 73, 174, 190, 586, 606 argument 191, 626 body 196 call 191, 196 call and return 205 caller 191 empty parameter list 596 empty parentheses 624, 625, 628 header 195, 196, 323, 343, 624 invoke 191, 194 local variable 629 multiple parameters 628 name 194, 215, 227, 340 overloading 599 parameter 194, 313, 315, 320, 625, 628 parameter list 628 pointer 340, 343 prototype 154, 195, 196, 198, 215, 313, 323, 592, 642 prototype scope 215, 216 return a result 632 return from 191, 192 scope 216 function body 624 function call 626 overhead 588 stack 201, 319 function call operator () 752, 835 function declaration (prototype) 195 function overloading 845 function pointer 832, 835 function prototype 642, 692 parameter names optional 643 function template 602, 907, 915 max 620 620 specialization 602 header 587 functions for manipulating data in the standard library containers 588 function-template specialization 907 fwrite 475, 486, 488 fscanf_s G game of craps 211, 300 Index game playing 206 “garbage value” 113 gcc compilation command 48 gcount function of istream 855 Gender Neutrality 69, 408 general utilities library (stdlib) 374 generalities 801 generating mazes randomly 356 generic pointer 329 generic programming 582, 907 get a value 633 get and set functions 633 get member function 851, 852 getc 555 getchar 378, 379, 507, 555 getline function of cin 853 getline function of the string header 627, 632 gigabyte 36 GitHub 59 global 644 global namespace scope 675, 701 global object constructors 675 global scope 675, 677 global variable 215, 216, 324, 446, 569, 598 Global Warming Facts Quiz 243 golden mean 222 golden ratio 222 good function of ios_base 871 Good Programming Practices overview 28 goodbit of stream 871 Google Maps 62 goto elimination 103 goto-less programming 103 goto statement 103, 216, 575, 576 GPS device 36 Graphical User Interface (GUI) 60 Greatest common divisor 227 Guess the Number exercise 239 GUI (Grahical User Interface) 60 guillemets (« and ») in the UML 638 H h filename extension 638 header files 588 halt 361 handle on an object 667 hard drive 35, 37, 48 hardcopy printer 49 hardware 34, 35, 40 hardware independent 41 hardware platform 42 has-a relationship 765, 686 h head of a queue 510, 527 header 638, 662 header (file) 73, 167, 204, 552, 586, 588, 646, 794 368 883 896 883, 899 376 374 381 627 838 609 complex.h 965 fenv.h 958 how they are located 641 inttypes.h 958 iso646.h 958 name enclosed in angle brackets (< >) 641 name enclosed in quotes (" ") 641 stdbool.h 961 stdint.h 958 tgmath.h 958 wchar.h 958 header file wctype.h 958 heap 733 helper function 668 heuristic 302 hex stream manipulator 856, 861, 865 hexadecimal 185, 369, 376, 411, 416 hexadecimal (base 16) number system 924 hexadecimal (base-16) number 850, 856, 861, 865 hexadecimal integer 310 hexadecimal notation 850 hide implementation details 691 hierarchical boss function/worker function relationship 191 hierarchy of exception classes 899 hierarchy of shapes 815 high-level language 40 highest level of precedence 82 high-level I/O 846 High-performance card shuffling and dealing simulation 444 histogram 256 Histogram printing 256 horizontal tab (\t) 74, 369 host object 686 993 HTML (HyperText Markup Language) 62 HTTP (HyperText Transfer Protocol) 62 Huge integers 762 HugeInt class 760 HugeInteger Class exercise 711 HyperText Markup Language (HTML) 62 HyperText Transfer Protocol (HTTP) 62 hypotenuse of a right triangle 237 I identifier(s) 77, 552 #if 555 if selection statement 85, 106, 109 if statements, relational operators, and equality operators 86 if else selection statement 104, 106, 121 flowchart 107 #ifdef preprocessor directive 555 #ifndef preprocessor directive 662, 555 ignore 724 ignore function of istream 854 image 48 implementation inheritance 818 implementation of a member function changes 673 implicit conversion 119, 750, 751 via conversion constructors 751 implicit first argument 694 implicit handle 667 implicit, user-defined conversions 750 implicitly virtual 809 improper implicit conversion 750 in-class initializers 663 INCITS/ISO/IEC 9899-1999 (C standard document) 42 include guard 660, 662 #include preprocessor directive 253, 551, 588 including a header multiple times 662 including headers 205 increment 151 increment a control variable 147, 150, 152 increment a pointer 327 increment operator (++) 125, 727 incremented 328 indefinite iteration 114, 146 994 Index indefinite postponement 336, 352 indentation 105, 109 independent software vendor (ISV) 586 index 256 index (subscript) 248 index notation 320 indirect base class 767 indirect derived class 826 indirection 308, 311, 832 indirection operator (*) 205, 309, 311 indirectly reference a value 308 inequality operator (!=) 736 infinite loop 110, 118, 150 infinite recursion 222 infix notation 544 infix-to-postfix conversion 544 information hiding 46, 216, 322, 606 inherit constructors from base class 792 inherit implementation 842 inherit interface 815, 842 inherit members of an existing class 765 inheritance 46, 605, 661, 667, 765, 767 examples 766 hierarchy 809 hierarchy for university CommunityMembers 766 implementation vs interface inheritance 818 relationships of the I/O-related classes 849 inheriting interface versus inheriting implementation 842 initial value of a control variable 147, 152 initialization phase 116 initialize a variable 79 initializer list 258 initializer_list class template 748 initializing a reference 594 initializing multidimensional arrays 279 initializing structures 440 initializing the elements of an array to zeros 250 initializing the elements of an array with an initializer list 251 inline function 588, 589, 747, 968 calculate the volume of a cube 589 inner block 216 innermost pair of parentheses 82 inorder traversal of a binary tree 227, 534, 537 input a line of text 853 input device 36 input from string in memory 587 input stream 851, 852 input unit 36 input/output operators 358 input/output stream header () 584 inputting data with a field width 427 inputting decimal, octal and hexadecimal values 879 inserting literal characters 411 insertion sort algorithm 942, 943, 945 instance 45 instance of a class 630 instance variable 46 instantiate an object of a class 606 instruction 49 instruction execution cycle 360 int type 73, 77, 200 integer 73, 77 integer arithmetic 716 integer array 247 Integer class definition 896 integer constant 320 integer conversion specifiers 411 using 412 integer division 82, 118 integer promotion 199 integer suffix l or L for a long int 572 ll or LL for a long long int 572 u or U for an unsigned int 572 integers prefixed with 32 (octal) 865 integers prefixed with 32x or 32X (hexadecimal) 865 IntegerSet class 712 integral size limits 204, 588 interactive attention signal 573 interactive computing 78 interface 606, 642 interface inheritance 818 interface of a class 642 internal linkage 570 internal spacing 863 internal stream manipulator 861, 863 International Standards Organization (ISO) 42 Internet 61 Internet of Things (IoT) 64 interpreter 41 interrupt 572 inttypes.h 958 invalid_argument invalid_argument class 899 exception class 663 inventory 506 inverted scan set 427 Invoice class (exercise) 657 invoke a function 191, 194 invoking a non-const member function on a const object 684 header 587, 847, 856 iOS 59 ios_base class 869 precision function 856 width member function 858 header 584, 587, 847, 848 iPod Touch 60 is-a relationship (inheritance) 765, 794 isalnum function 368, 369 isalpha function 368, 369 isblank function 369 iscntrl function 369, 372 isdigit function 368, 369 isgraph function 369, 372 islower function 369, 371 ISO (International Standards Organization) 42 iso646.h header file 958 isprint function 369, 372 ispunct function 369, 372 isspace function 369, 372 istream class 849 peek function 854 istream member function ignore 724 isupper function 371 ISV (independent software vendor) 586 isxdigit function 368, 369 iteration 226 iteration statement 103, 110 iterative function 275 header 587 J Jacobson, Ivar 608 Jacopini, G 103 Java programming language 44, 60 Jobs, Steve 60 justified field 864 Index K #line kernel 59 Kernighan, B W 42 key value 273 keyboard 35, 76, 78, 377, 584, 846, 848 keywords 89 added in C11 89 added in C99 89 table of keywords 590 Knight’s Tour 301 Brute Force approaches 303 Closed tour test 305 L l or L suffix for a long double literal 572 l or L suffix for a long int literal 572 label 216, 576 LAMP 64 large object 593 larger of two numbers 136 largest number problem 97 last-in, first-out (LIFO) 201, 521 order 907, 910 late binding 809 leading 865 leading 0x and leading 32X 861, 865 leading asterisks 406 leaf node 533 least access privilege 320 left child 533 left justify 155, 158, 411, 863 strings in a field 419 left-shift operator (>) 716 right stream manipulator 861, 862 right subtree 533 right-justifying integers in a field 417 rightmost (trailing) arguments 596 right-shift (>>) operator 449, 470 right-shift operator (>>) 848 rise-and-shine algorithm 102 Ritchie, D 41 robust application 882, 886 roll a six-sided die 207 root node of a binary tree 533, 548 rounded 119 rounding 95, 219, 411 rounding numbers 879 rounding toward negative infinity 967 rounding toward zero 967 rows 278 RTTI (runtime type information) 836, 839 rules of operator precedence 82 Rumbaugh, James 608 runtime error 49 runtime type information (RTTI) 836, 839 runtime_error class 883, 891, 899 what function 888 rvalue ("right value") 168, 594, 740 S SaaS (Software as a Service) 65 SalariedEmployee class header 822 SalariedEmployee class implementation file 823 savings account example 153 SavingsAccount class 712 scalar 263, 323 scaling 207 scaling factor 207, 210 scan characters 424 scan set 426 inverted 427 scanf 410 scanf function 78 scanf_s function 289 scanning images 36 scientific notation 412, 850, 866 scientific notation floating-point value 867 Index scientific stream manipulator 861, 866 scope 554 scope of an identifier 214, 215, 216 scope resolution operator (::) 644, 701, 910 Scoping example 217 screen 35, 36, 49 screen-manager program 801 scrutinize data 662 SDK (Software Development Kit) 65 search a linked list 227 search functions of the string handling library 385 search key 273 searching 273, 274 searching a binary tree 538 searching strings 381 second-degree polynomial 85 second refinement 115, 122 secondary storage 35 secondary storage device 48 secondary storage unit 37 Secure Coding in C and C++, 2/e 175 seed 210 seed the rand function 209 SEEK_CUR 490 SEEK_END 490 SEEK_SET 490 segmentation fault 80, 316 select a substring 752 selection sort 227, 953 recursive 953 selection sort algorithm 938, 939, 941 selection statement 105, 106 selection structure 103 self assignment 696, 745 self documenting 77 self-referential structure 438, 511 semicolon (;) 74, 88 send a message to an object 46 sentinel-controlled iteration 115, 116, 146 sentinel value 114, 115, 118, 136 separate interface from implementation 642 sequence structure 103, 105 sequential access file 475 sequential execution 103 sequential file 476 services of a class 633 header 587 set a value 633 set and get functions 633 set function 691 set_new_handler function 893, 895 set_new_handler specifying the function to call when new fails 895 setbase stream manipulator 856 setfill stream manipulator 664, 862, 864 205 setprecision stream manipulator 856 setw 724 setw stream manipulator 858, 862 Shape class hierarchy 767, 797 shell prompt on Linux 50 shift 207 Shifted, scaled integers produced by + rand() % 206 shifting value 210 “shipping” section of the computer 36 short 161, 199 short-circuit evaluation 166 showbase stream manipulator 861, 865 showpoint stream manipulator 861 showpos stream manipulator 861, 863 sibling 533 side effect 205, 215, 225, 591 Sieve of Eratosthenes 305 SIGABRT 573 SIGFPE 573 SIGILL 573 SIGINT 573 sign left justified 861 signal 572 signal handling 573 library 572 signal value 114 205, 572 signature 600, 727 signatures of overloaded prefix and postfix increment operators 727 signed decimal integer 411 significant digits 862 SIGSEGV 573 SIGTERM 573 simple condition 165 simple interest problem 138 simplest flowchart 169 Simpletron 507 Simpletron Machine Language (SML) 357, 358, 362 Simpletron simulator 357, 360, 362 simulation 206, 335 sin function 193 1001 sine 193 single-argument constructor 751, 752 single entry/single exit control statement 105, 106, 172 single inheritance 767 single quote (') character 415 single-selection statement 104 sinking sort 266 size member function of class string 649 size member function of vector 612 size_t 250, 381, 385 sizeof operator 324, 439, 507, 511, 555, 694 skipping whitespace 855, 861 skipws stream manipulator 861 small circle symbol 104, 106 smallest number problem 97 SML 357, 360, 362 SMS Language 408 software 34 Software as a Service (SaaS) 65 software asset 607 software-based simulation 357, 360 Software Development Kit (SDK) 65 software engineering 164, 216, 324, 642 data hiding 631, 633 encapsulation 633 reuse 638, 641 separate interface from implementation 642 set and get functions 633 Software Engineering Observations overview 29 software model 360 software reuse 43, 46, 193, 324, 570, 586, 765, 907 sort algorithms bucket sort 953 insertion sort 942 merge sort 945 Quicksort 954 recursive selection sort 953 selection sort 938 sort key 937 sorting 266, 937 strings 588 source code 638, 794 SourceForge 59 space 428 space flag 420 spaces for padding 864 1002 Index spam scanner 408 speaking to a computer 36 special characters 367 Special Section: Advanced String Manipulation Exercises 405 Special Section: Building Your Own Compiler 549 special symbol 37 split the array in merge sort 945 sprintf 377, 379 sqrt function 192 square brackets ([]) 247 square root 192, 857 srand 209 sscanf 377, 380 header 587 header 587 stack 200, 307, 437, 510, 521, 907 Stack class template 907, 914 stack frame 201 stack overflow 201 stack program 522 stack unwinding 887, 890, 892, 905 Stack 910, 914 Stack 914 Stack 912 stacked building blocks 172 stacking rule 169 Standard C 42 standard data types 325 standard error stream (stderr) 49, 410, 474 standard exception classes 899 standard input 78, 376, 564 standard input object (cin) 584, 847 standard input stream (stdin) 49, 410, 474 standard input/output header (stdio.h) 73 standard input/output library (stdio) 376 standard libraries 48 Standard Library class string 717 exception classes 900 exception hierarchy 899 headers header 204, 204, 551, 588 standard output object (cout) 584, 847 standard output stream (stdout) 49, 410, 474, 564 standard stream libraries 847 standard version of C 42 “standardized, interchangeable parts” 607 “warehouse” section of the computer 37 state bits 851 statement 74, 103, 624 statement terminator (;) 74 statements return 194 throw 664 try 614 static 214 static 215, 216, 260 static array 251 Static arrays are automatically initialized to zero if not explicitly initialized by the programmer 261 _Static_assert 558 static binding 809 static data member 700, 701 static data member tracking the number of objects of a class 703 static data members save storage 701 static data structures 575 static local object 676, 678, 679 static member 701 static member function 701 static storage duration 214 status bits 871 std::cin (standard input stream object) 584 std::cout (standard output stream object) 584 std::endl stream manipulator 585 stdarg.h 205, 565 stdbool.h 167, 961 stddef.h 205, 308 stderr (standard error stream) 49, 475 stdexcept header 587, 883, 899 must include in GNU C++ to use out_of_range 614 stdin (standard input stream) 49, 377, 475 stdint.h 958 stdio.h 73, 158, 205, 215, 376, 410, 475, 554 stdlib.h 205, 206, 374, 552, 570, 575 stdout (standard output stream) 49, 475, 478 StepStone 60 stepwise refinement 335 stepwise refinement, 114 “sticky” setting 664 storage class 214 storage class of an identifier 214 storage class specifiers 214 storage duration 214, 260 storage duration of an identifier 214 storage unit boundary 460 Store 358 stored array 513 straight-line form 82 strcat function 382 strchr function 386 strcmp function 383, 384 strcpy function 381, 382 strcspn function 385, 387 stream 410, 474 stream base 856 stream extraction operator >> ("get from") 584, 602, 716, 722, 744, 848, 851 stream input 848, 851 stream insertion operator ) operator 440, 441, 447 structure tag name 438, 439 structure type 438 structured programming 34, 72, 89, 102, 103, 575 structured programming summary 169 Structures 437 Student Inheritance Hierarchy 797 student poll analysis program 254 subclass 46, 765 subscript 248 subscripted name used as an rvalue 740 substr member function of class 650 substr member function of string 719 substring 752 substring length 752 subtract an integer from a pointer 327 subtracting one pointer from another 327 subtracting two pointers 329 subtraction 36 suffix floating point 572 integer 572 sum 96 sum of numbers 136 sum of the elements of an array 227, 253 superclass 46, 765 supermarket simulation 547 survey data analysis 268, 272 survey data analysis program 268 swapping values 938, 942 Swift 44 switch logic 815 switch multiple-selection statement 104, 156, 159 with break 160 symbol 98, 104 symbol value 924 symbolic constant 158, 252, 551, 553 synchronize operation of an istream and an ostream 872 synchronous error 891 syntax error 48, 110, 127, 169 string T tab 74, 99, 105, 422, 428 tables of values 278 tabular format 249 tail of a queue 510, 527 tan 193 tangent 193 Target-Heart-Rate Calculator 143, 658 Tax Plan Alternatives 188 TCP (Transmission Control Protocol) 61 TCP/IP 61 technical publications 66 telephone number program 403 telephone-number word problem 506 1003 template default type argument for a type parameter 914 definition 603 function 603 parameter list 603 template keyword 603, 908 template parameter 908 temporary copy 119 temporary double representation 154 temporary object 749 terabyte 37 terminate 49 terminate a program 895 terminating null character 258, 367, 368, 378, 414 termination housekeeping 675 termination model of exception handling 886 termination phase 116 termination request 573 ternary operator 107, 225 test characters 587 test state bits after an I/O operation 851 Test-Drive: Body Mass Index Calculator 69 Test-Drive: Carbon Footprint Calculator 69 text analysis 405 text processing 366 tgmath.h 958 The “FairTax” 188 The Twelve Days of Christmas 159 this pointer 694, 696, 704, 746 this pointer used explicitly 694 this pointer used implicitly and explicitly to access members of an object 695 Thompson, Ken 41 _Thread_local storage class specifier 214 throw an exception 614, 663, 664, 885 throw exceptions derived from standard exceptions 900 throw exceptions not derived from standard exceptions 900 throw keyword 887 throw point 886 throw standard exceptions 900 throwing exceptions from a catch 905 throwing the result of a conditional expression 905 1004 TicTacToe Index Class exercise 711 an input stream to an output stream 872 tilde character (~) 675 time 205 Time class 710 Time class containing a constructor with default arguments 669 Time class definition 661 Time class definition modified to enable cascaded memberfunction calls 697 Time class member-function definitions 662 Time class member-function definitions, including a constructor that takes arguments 670 Time Class Modification 713 STDC , predefined symbolic constant 558 TIME , predefined symbolic constant 558 205 token 386, 557 tokenizing strings 381 tokens 390 tokens in reverse 404 tolower function 371 top 114 top-down, stepwise refinement 114, 116, 120, 121 top of a stack 510 top-down stepwise refinement 335, 336 Tortoise and the Hare 353 total 113 toupper function 317, 371 Towers of Hanoi 227, 240 trailing zeros 413, 861 transaction file 505 transaction-processing program 486, 493 transfer of control 103, 358, 362 translation 40 translator program 40 Transmission Control Protocol (TCP) 61 trap 572 trap a SIGINT 573 traversing a binary tree 534 tree 84, 307, 437, 533 trigonometric cosine 193 trigonometric sine 193 trigonometric tangent 193 tripleByReference 620 tie tripleCallByValue 620 boolean value 85, 590 truncated 118 truth 165 truth table 165 try block 614, 885, 888, 891, 892 expires 886 try statement 614 turtle graphics 300 Twitter 62 two-dimensional array 278, 282, 334 representation of a deck of cards 336 two’s complement 931, 931 twos position 926 tying an output stream to an input stream 872 type 80 type checking 198 type mismatch 316 type of the this pointer 695 type parameter 603, 908, 914 type-safe linkage 592, 600 type_info class 838 typedef 443, 847 fstream 849 ifstream 849 iostream 847 istream 847 ofstream 849 ostream 847 type-generic macro 968 typeid 838, 899 typeinfo header 587, 838 typename keyword 603, 908 type-safe I/O 854 typesetting systems 366 true U u or U for an unsigned int 572 UML (Unified Modeling Language) 605, 608, 625 attribute 625 class diagram 625 constructor in a class diagram 638 data types 628 guillemets (« and ») 638 minus sign (–) 634 plus sign (+) 625 public operation 625 String type 628 unary operator 119, 127, 309 overload 721, 726 sizeof 324 unary scope resolution operator (::) 598 unbiased shuffling algorithm 446 unbuffered output 849 unbuffered standard error stream 847 uncaught exceptions 905 unconditional branch 575 #undef preprocessor directive 554, 557 underflow_error exception 900 underscore (_) 77 unformatted I/O 846, 847, 849, 851, 854 Unicode character set 37, 846 Unified Modeling Language (UML) 605, 608 unincremented copy of an object 733 uninitialized local reference causes a syntax error 595 union 446, 447, 469 unique_ptr class 896 built-in array 899 universal-time format 663 UNIX 41, 158, 564 unnamed bit field 460 unnamed bit field with a zero width 460 header 587 header 587 unresolved references 569 unsafe macro 558 unsigned decimal integer 411 unsigned hexadecimal integer 411 unsigned int 200 unsigned integer 448 unsigned long int 376 unsigned long long int 220, 222 unsigned octal integer 411 unsigned short 200 unstructured flowchart 173 untie an input stream from an output stream 872 unwinding the function call stack 889 uppercase letter 98, 204, 587 uppercase stream manipulator 861, 865, 867 user-defined class name 623 user-defined type 606, 624, 749 using a function template 603 using declaration in headers 640 using directive in headers 640 Index using the # flag with 421 usual arithmetic conversion rules 199 header 588 utility function 205, 668 w+ V wb va_arg wb+ va_copy wchar_t character type 847 wchar.h 958 567 macro 969 va_end 567 va_list 567 va_start 567 validate data 175 validation 648 validity checking 648 value 248 value of a variable 80 van Rossum, Guido 44 variable 77 variable arguments header stdarg.h 565 variable initialization 334 variable-length argument list 565, 566 variable-length array (VLA) 285 header 587 vector class 608 header 609 verbs in a system specification 606 vertical spacing 148 vertical tab ('\v') 369 vi 48 virtual destructor 814 virtual function 800, 808, 832, 834 call 834 call illustrated 833 table (vtable) 832 virtual memory 894, 895 Visual C# programming language 44 Visual C++ programming language 44 Visual Studio 48 visualizing recursion 227, 241 void * (pointer to void) 329, 391, 511 void keyword 624, 632 volatile information 36 volume of a cube 589 vtable 832, 834, 835 vtable pointer 835 file open mode 480 W3C (World Wide Web Consortium) 62 “walk off” either end of an array 735 warning message 650 file open mode 480 file open mode 480 wctype.h 958 web services 62 what member function of an exception object 614 what virtual function of class 883, 888, 894 exception while iteration statement 110, 111, 115, 122 flowchart 111 whitespace character 73, 105, 851, 852, 855 string literals separated 259 width implicitly set to 858 width member function of class 858 ios_base width of a bit field 457, 460 width setting 858 Windows 59, 564, 572 Windows operating system 59 World Population Growth 188 World Wide Web 61, 62 worst-case runtime for an algorithm 937 Wozniak, Steve 60 wraparound 732 write function of ostream 849, 854 writing to a file 478 X Xerox PARC (Palo Alto Research Center) 60 Z (zero) flag 421 zeroth element 247 W w file open mode 480 1005