C How to Program (9th Edition) PDF
Document Details
Uploaded by DependableBodhran3050
BSS
2022
Paul Deitel and Harvey Deitel
Tags
Summary
This is a textbook on the C programming language, covering various concepts and applications. It introduces fundamental programming concepts, software technologies, and discusses big data and AI. The book is suitable for undergraduate computer science students.
Full Transcript
HOW TO PROGRAM NINTH EDITION with Case Studies Introducing Applications Programming and Systems PAUL DEITEL Programming HARVEY DEITEL Deitel® Series Page Intro to Series...
HOW TO PROGRAM NINTH EDITION with Case Studies Introducing Applications Programming and Systems PAUL DEITEL Programming HARVEY DEITEL Deitel® Series Page Intro to Series REVEL™ Interactive Multimedia Intro to Python® for Computer Science REVEL™ for Deitel Java™ and Data Science: Learning to Program REVEL™ for Deitel Python® with AI, Big Data and the Cloud E-Books How To Program Series https://VitalSource.com C How to Program, 9/E https://RedShelf.com https://Chegg.com Java™ How to Program, Early Objects Version, 11/E Intro to Python® for Computer Science Java™ How to Program, Late Objects and Data Science: Learning to Program Version, 11/E with AI, Big Data and the Cloud C++ How to Program, 10/E Java™ How to Program, 10/E and 11/E Android™ How to Program, 3/E C++ How to Program, 9/E and 10/E Internet & World Wide Web How to C How to Program, 8/E and 9/E Program, 5/E Android™ How to Program, 2/E and 3/E Visual Basic® 2012 How to Program, 6/E Visual Basic® 2012 How to Program, 6/E Visual C#® How to Program, 6/E Visual C#® How to Program, 6/E LiveLessons Video Training Deitel® Developer Series https://deitel.com/LiveLessons/ Python® for Programmers Python® Fundamentals Java™ for Programmers, 4/E Java™ Fundamentals C++20 for Programmers C++20 Fundamentals Android™ 6 for Programmers: An App- C11/C18 Fundamentals Driven Approach, 3/E C# 6 Fundamentals C for Programmers with an Introduction Android™ 6 Fundamentals, 3/E to C11 C# 2012 Fundamentals C# 6 for Programmers JavaScript Fundamentals JavaScript for Programmers Swift™ Fundamentals Swift™ for Programmers To receive updates on Deitel publications, please join the Deitel communities on Facebook®—https://facebook.com/DeitelFan Twitter®—@deitel LinkedIn®—https://linkedin.com/company/deitel-&-associates YouTube™—https://youtube.com/DeitelTV To communicate with the authors, send e-mail to: [email protected] For information on Deitel programming-languages corporate training offered online and on-site worldwide, write to [email protected] or visit: https://deitel.com/training/ For continuing updates on Pearson/Deitel publications visit: https://deitel.com https://pearson.com/deitel Content Development: Tracy Johnson Content Management: Dawn Murrin, Tracy Johnson Content Production: Carole Snyder Product Management: Holly Stark Product Marketing: Wayne Stevens Rights and Permissions: Anjali Singh Please contact https://support.pearson.com/getsupport/s/ with any queries on this content. Copyright © 2022 by Pearson Education, Inc. or its affiliates, 221 River Street, Hoboken, NJ 07030. All Rights Reserved. Manufactured in the United States of America. This publication is protected by copyright, and permission should be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photo- copying, recording, or otherwise. For information regarding permissions, request forms, and the appropriate contacts within the Pearson Education Global Rights and Permissions department, please visit https://www.pearsoned.com/permissions/. PEARSON, ALWAYS LEARNING, and REVEL are exclusive trademarks owned by Pearson Education, Inc. or its affiliates in the U.S. and/or other countries. Unless oth- erwise indicated herein, any third-party trademarks, logos, or icons that may appear in this work are the property of their respective owners, and any references to third- party trademarks, logos, icons, or other trade dress are for demonstrative or descrip- tive purposes only. Such references are not intended to imply any sponsorship, endorsement, authorization, or promotion of Pearson’s products by the owners of such marks, or any relationship between the owner and Pearson Education, Inc., or its affiliates, authors, licensees, or distributors. Library of Congress Cataloging-in- Publication Data Library of Congress Cataloging-in-Publication Data On file ScoutAutomatedPrintCode ISBN-10: 0-13-540467-3 ISBN-13: 978-0-13-739839-3 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 and the double-thumbs-up bug are registered trademarks of Deitel and Asso- ciates, Inc. Apple, Xcode, Swift, Objective-C, iOS and macOS are trademarks or registered trademarks of Apple, Inc. Java is a registered trademark of Oracle and/or its affiliates. Linux is a registered trademark of Linus Torvalds. Microsoft and/or its respective suppliers make no representations about the suit- ability 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 sup- pliers 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 con- sequential 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 inac- curacies 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 D–G are PDF documents posted online at the book’s Companion Website (located at https://www.pearson.com/deitel). Preface xix Before You Begin li 1 Introduction to Computers and C 1 1.1 Introduction 2 1.2 Hardware and Software 4 1.2.1 Moore’s Law 4 1.2.2 Computer Organization 5 1.3 Data Hierarchy 8 1.4 Machine Languages, Assembly Languages and High-Level Languages 11 1.5 Operating Systems 13 1.6 The C Programming Language 16 1.7 The C Standard Library and Open-Source Libraries 18 1.8 Other Popular Programming Languages 19 1.9 Typical C Program-Development Environment 21 1.9.1 Phase 1: Creating a Program 21 1.9.2 Phases 2 and 3: Preprocessing and Compiling a C Program 21 1.9.3 Phase 4: Linking 22 1.9.4 Phase 5: Loading 23 1.9.5 Phase 6: Execution 23 1.9.6 Problems That May Occur at Execution Time 23 1.9.7 Standard Input, Standard Output and Standard Error Streams 24 1.10 Test-Driving a C Application in Windows, Linux and macOS 24 1.10.1 Compiling and Running a C Application with Visual Studio 2019 Community Edition on Windows 10 25 1.10.2 Compiling and Running a C Application with Xcode on macOS 29 viii Contents 1.10.3 Compiling and Running a C Application with GNU gcc on Linux 32 1.10.4 Compiling and Running a C Application in a GCC Docker Container Running Natively over Windows 10, macOS or Linux 34 1.11 Internet, World Wide Web, the Cloud and IoT 35 1.11.1 The Internet: A Network of Networks 36 1.11.2 The World Wide Web: Making the Internet User-Friendly 37 1.11.3 The Cloud 37 1.11.4 The Internet of Things 38 1.12 Software Technologies 39 1.13 How Big Is Big Data? 39 1.13.1 Big-Data Analytics 45 1.13.2 Data Science and Big Data Are Making a Difference: Use Cases 46 1.14 Case Study—A Big-Data Mobile Application 47 1.15 AI—at the Intersection of Computer Science and Data Science 48 2 Intro to C Programming 55 2.1 Introduction 56 2.2 A Simple C Program: Printing a Line of Text 56 2.3 Another Simple C Program: Adding Two Integers 60 2.4 Memory Concepts 64 2.5 Arithmetic in C 65 2.6 Decision Making: Equality and Relational Operators 69 2.7 Secure C Programming 73 3 Structured Program Development 85 3.1 Introduction 86 3.2 Algorithms 86 3.3 Pseudocode 87 3.4 Control Structures 88 3.5 The if Selection Statement 90 3.6 The if…else Selection Statement 92 3.7 The while Iteration Statement 96 3.8 Formulating Algorithms Case Study 1: Counter-Controlled Iteration 97 3.9 Formulating Algorithms with Top-Down, Stepwise Refinement Case Study 2: Sentinel-Controlled Iteration 99 3.10 Formulating Algorithms with Top-Down, Stepwise Refinement Case Study 3: Nested Control Statements 106 3.11 Assignment Operators 110 3.12 Increment and Decrement Operators 111 3.13 Secure C Programming 114 Contents ix 4 Program Control 133 4.1 Introduction 134 4.2 Iteration Essentials 134 4.3 Counter-Controlled Iteration 135 4.4 for Iteration Statement 136 4.5 Examples Using the for Statement 140 4.6 switch Multiple-Selection Statement 144 4.7 do…while Iteration Statement 150 4.8 break and continue Statements 151 4.9 Logical Operators 153 4.10 Confusing Equality (==) and Assignment (=) Operators 157 4.11 Structured-Programming Summary 158 4.12 Secure C Programming 163 5 Functions 179 5.1 Introduction 180 5.2 Modularizing Programs in C 180 5.3 Math Library Functions 182 5.4 Functions 183 5.5 Function Definitions 184 5.5.1 square Function 184 5.5.2 maximum Function 187 5.6 Function Prototypes: A Deeper Look 188 5.7 Function-Call Stack and Stack Frames 191 5.8 Headers 195 5.9 Passing Arguments by Value and by Reference 197 5.10 Random-Number Generation 197 5.11 Random-Number Simulation Case Study: Building a Casino Game 202 5.12 Storage Classes 207 5.13 Scope Rules 209 5.14 Recursion 212 5.15 Example Using Recursion: Fibonacci Series 216 5.16 Recursion vs. Iteration 219 5.17 Secure C Programming—Secure Random-Number Generation 222 Random-Number Simulation Case Study: The Tortoise and the Hare 241 6 Arrays 243 6.1 Introduction 244 6.2 Arrays 244 6.3 Defining Arrays 246 6.4 Array Examples 246 x Contents 6.4.1 Defining an Array and Using a Loop to Set the Array’s Element Values 247 6.4.2 Initializing an Array in a Definition with an Initializer List 248 6.4.3 Specifying an Array’s Size with a Symbolic Constant and Initializing Array Elements with Calculations 249 6.4.4 Summing the Elements of an Array 250 6.4.5 Using Arrays to Summarize Survey Results 250 6.4.6 Graphing Array Element Values with Bar Charts 252 6.4.7 Rolling a Die 60,000,000 Times and Summarizing the Results in an Array 253 6.5 Using Character Arrays to Store and Manipulate Strings 255 6.5.1 Initializing a Character Array with a String 255 6.5.2 Initializing a Character Array with an Initializer List of Characters 255 6.5.3 Accessing the Characters in a String 255 6.5.4 Inputting into a Character Array 255 6.5.5 Outputting a Character Array That Represents a String 256 6.5.6 Demonstrating Character Arrays 256 6.6 Static Local Arrays and Automatic Local Arrays 258 6.7 Passing Arrays to Functions 260 6.8 Sorting Arrays 264 6.9 Intro to Data Science Case Study: Survey Data Analysis 267 6.10 Searching Arrays 272 6.10.1 Searching an Array with Linear Search 272 6.10.2 Searching an Array with Binary Search 274 6.11 Multidimensional Arrays 278 6.11.1 Illustrating a Two-Dimensional Array 278 6.11.2 Initializing a Double-Subscripted Array 279 6.11.3 Setting the Elements in One Row 281 6.11.4 Totaling the Elements in a Two-Dimensional Array 281 6.11.5 Two-Dimensional Array Manipulations 281 6.12 Variable-Length Arrays 285 6.13 Secure C Programming 289 7 Pointers 309 7.1 Introduction 310 7.2 Pointer Variable Definitions and Initialization 311 7.3 Pointer Operators 312 7.4 Passing Arguments to Functions by Reference 315 7.5 Using the const Qualifier with Pointers 319 7.5.1 Converting a String to Uppercase Using a Non-Constant Pointer to Non-Constant Data 320 Contents xi 7.5.2 Printing a String One Character at a Time Using a Non-Constant Pointer to Constant Data 320 7.5.3 Attempting to Modify a Constant Pointer to Non-Constant Data 322 7.5.4 Attempting to Modify a Constant Pointer to Constant Data 323 7.6 Bubble Sort Using Pass-By-Reference 324 7.7 sizeof Operator 328 7.8 Pointer Expressions and Pointer Arithmetic 330 7.8.1 Pointer Arithmetic Operators 331 7.8.2 Aiming a Pointer at an Array 331 7.8.3 Adding an Integer to a Pointer 331 7.8.4 Subtracting an Integer from a Pointer 332 7.8.5 Incrementing and Decrementing a Pointer 332 7.8.6 Subtracting One Pointer from Another 332 7.8.7 Assigning Pointers to One Another 332 7.8.8 Pointer to void 332 7.8.9 Comparing Pointers 333 7.9 Relationship between Pointers and Arrays 333 7.9.1 Pointer/Offset Notation 333 7.9.2 Pointer/Subscript Notation 334 7.9.3 Cannot Modify an Array Name with Pointer Arithmetic 334 7.9.4 Demonstrating Pointer Subscripting and Offsets 334 7.9.5 String Copying with Arrays and Pointers 336 7.10 Arrays of Pointers 338 7.11 Random-Number Simulation Case Study: Card Shuffling and Dealing 339 7.12 Function Pointers 344 7.12.1 Sorting in Ascending or Descending Order 344 7.12.2 Using Function Pointers to Create a Menu-Driven System 347 7.13 Secure C Programming 349 Special Section: Building Your Own Computer as a Virtual Machine 362 Special Section—Embedded Systems Programming Case Study: Robotics with the Webots Simulator 369 8 Characters and Strings 387 8.1 Introduction 388 8.2 Fundamentals of Strings and Characters 388 8.3 Character-Handling Library 390 8.3.1 Functions isdigit, isalpha, isalnum and isxdigit 391 8.3.2 Functions islower, isupper, tolower and toupper 393 8.3.3 Functions isspace, iscntrl, ispunct, isprint and isgraph 394 8.4 String-Conversion Functions 396 8.4.1 Function strtod 396 xii Contents 8.4.2 Function strtol 397 8.4.3 Function strtoul 398 8.5 Standard Input/Output Library Functions 399 8.5.1 Functions fgets and putchar 399 8.5.2 Function getchar 401 8.5.3 Function sprintf 401 8.5.4 Function sscanf 402 8.6 String-Manipulation Functions of the String-Handling Library 403 8.6.1 Functions strcpy and strncpy 404 8.6.2 Functions strcat and strncat 405 8.7 Comparison Functions of the String-Handling Library 406 8.8 Search Functions of the String-Handling Library 408 8.8.1 Function strchr 409 8.8.2 Function strcspn 410 8.8.3 Function strpbrk 410 8.8.4 Function strrchr 411 8.8.5 Function strspn 411 8.8.6 Function strstr 412 8.8.7 Function strtok 413 8.9 Memory Functions of the String-Handling Library 414 8.9.1 Function memcpy 415 8.9.2 Function memmove 416 8.9.3 Function memcmp 416 8.9.4 Function memchr 417 8.9.5 Function memset 417 8.10 Other Functions of the String-Handling Library 419 8.10.1 Function strerror 419 8.10.2 Function strlen 419 8.11 Secure C Programming 420 Pqyoaf X Nylfomigrob Qwbbfmh Mndogvk: Rboqlrut yua Boklnxhmywex 434 Secure C Programming Case Study: Public-Key Cryptography 440 9 Formatted Input/Output 449 9.1 Introduction 450 9.2 Streams 450 9.3 Formatting Output with printf 451 9.4 Printing Integers 452 9.5 Printing Floating-Point Numbers 453 9.5.1 Conversion Specifiers e, E and f 454 9.5.2 Conversion Specifiers g and G 454 9.5.3 Demonstrating Floating-Point Conversion Specifiers 455 9.6 Printing Strings and Characters 456 Contents xiii 9.7 Other Conversion Specifiers 457 9.8 Printing with Field Widths and Precision 458 9.8.1 Field Widths for Integers 458 9.8.2 Precisions for Integers, Floating-Point Numbers and Strings 459 9.8.3 Combining Field Widths and Precisions 460 9.9 printf Format Flags 461 9.9.1 Right- and Left-Alignment 461 9.9.2 Printing Positive and Negative Numbers with and without the + Flag 462 9.9.3 Using the Space Flag 462 9.9.4 Using the # Flag 463 9.9.5 Using the 0 Flag 463 9.10 Printing Literals and Escape Sequences 464 9.11 Formatted Input with scanf 465 9.11.1 scanf Syntax 466 9.11.2 scanf Conversion Specifiers 466 9.11.3 Reading Integers 467 9.11.4 Reading Floating-Point Numbers 468 9.11.5 Reading Characters and Strings 468 9.11.6 Using Scan Sets 469 9.11.7 Using Field Widths 470 9.11.8 Skipping Characters in an Input Stream 471 9.12 Secure C Programming 472 10 Structures, Unions, Bit Manipulation and Enumerations 481 10.1 Introduction 482 10.2 Structure Definitions 483 10.2.1 Self-Referential Structures 483 10.2.2 Defining Variables of Structure Types 484 10.2.3 Structure Tag Names 484 10.2.4 Operations That Can Be Performed on Structures 484 10.3 Initializing Structures 486 10.4 Accessing Structure Members with. and -> 486 10.5 Using Structures with Functions 488 10.6 typedef 488 10.7 Random-Number Simulation Case Study: High-Performance Card Shuffling and Dealing 489 10.8 Unions 492 10.8.1 union Declarations 493 10.8.2 Allowed unions Operations 493 10.8.3 Initializing unions in Declarations 493 10.8.4 Demonstrating unions 494 xiv Contents 10.9 Bitwise Operators 495 10.9.1 Displaying an Unsigned Integer’s Bits 496 10.9.2 Making Function displayBits More Generic and Portable 497 10.9.3 Using the Bitwise AND, Inclusive OR, Exclusive OR and Complement Operators 498 10.9.4 Using the Bitwise Left- and Right-Shift Operators 501 10.9.5 Bitwise Assignment Operators 503 10.10 Bit Fields 504 10.10.1 Defining Bit Fields 504 10.10.2 Using Bit Fields to Represent a Card’s Face, Suit and Color 505 10.10.3 Unnamed Bit Fields 507 10.11 Enumeration Constants 507 10.12 Anonymous Structures and Unions 509 10.13 Secure C Programming 510 Special Section: Raylib Game-Programming Case Studies 520 Game-Programming Case Study Exercise: SpotOn Game 526 Game-Programming Case Study: Cannon Game 527 Visualization with raylib—Law of Large Numbers Animation 529 Case Study: The Tortoise and the Hare with raylib— a Multimedia “Extravaganza” 531 Random-Number Simulation Case Study: High-Performance Card Shuffling and Dealing with Card Images and raylib 533 11 File Processing 539 11.1 Introduction 540 11.2 Files and Streams 540 11.3 Creating a Sequential-Access File 542 11.3.1 Pointer to a FILE 543 11.3.2 Using fopen to Open a File 543 11.3.3 Using feof to Check for the End-of-File Indicator 543 11.3.4 Using fprintf to Write to a File 544 11.3.5 Using fclose to Close a File 544 11.3.6 File-Open Modes 545 11.4 Reading Data from a Sequential-Access File 547 11.4.1 Resetting the File Position Pointer 548 11.4.2 Credit Inquiry Program 548 11.5 Random-Access Files 552 11.6 Creating a Random-Access File 553 11.7 Writing Data Randomly to a Random-Access File 555 11.7.1 Positioning the File Position Pointer with fseek 557 11.7.2 Error Checking 558 11.8 Reading Data from a Random-Access File 558 Contents xv 11.9 Case Study: Transaction-Processing System 560 11.10 Secure C Programming 566 AI Case Study: Intro to NLP—Who Wrote Shakespeare’s Works? 576 AI/Data-Science Case Study—Machine Learning with GNU Scientific Library 582 AI/Data-Science Case Study: Time Series and Simple Linear Regression 588 Web Services and the Cloud Case Study—libcurl and OpenWeatherMap 589 12 Data Structures 595 12.1 Introduction 596 12.2 Self-Referential Structures 597 12.3 Dynamic Memory Management 598 12.4 Linked Lists 599 12.4.1 Function insert 603 12.4.2 Function delete 605 12.4.3 Functions isEmpty and printList 607 12.5 Stacks 608 12.5.1 Function push 612 12.5.2 Function pop 613 12.5.3 Applications of Stacks 613 12.6 Queues 614 12.6.1 Function enqueue 619 12.6.2 Function dequeue 620 12.7 Trees 621 12.7.1 Function insertNode 624 12.7.2 Traversals: Functions inOrder, preOrder and postOrder 625 12.7.3 Duplicate Elimination 626 12.7.4 Binary Tree Search 626 12.7.5 Other Binary Tree Operations 626 12.8 Secure C Programming 627 Special Section: Systems Software Case Study—Building Your Own Compiler 636 13 Computer-Science Thinking: Sorting Algorithms and Big O 657 13.1 Introduction 658 13.2 Efficiency of Algorithms: Big O 659 13.2.1 O(1) Algorithms 659 13.2.2 O(n) Algorithms 659 13.2.3 O(n2) Algorithms 659 xvi Contents 13.3 Selection Sort 660 13.3.1 Selection Sort Implementation 661 13.3.2 Efficiency of Selection Sort 664 13.4 Insertion Sort 665 13.4.1 Insertion Sort Implementation 665 13.4.2 Efficiency of Insertion Sort 668 13.5 Case Study: Visualizing the High-Performance Merge Sort 668 13.5.1 Merge Sort Implementation 669 13.5.2 Efficiency of Merge Sort 673 13.5.3 Summarizing Various Algorithms’ Big O Notations 674 14 Preprocessor 681 14.1 Introduction 682 14.2 #include Preprocessor Directive 683 14.3 #define Preprocessor Directive: Symbolic Constants 683 14.4 #define Preprocessor Directive: Macros 684 14.4.1 Macro with One Argument 685 14.4.2 Macro with Two Arguments 686 14.4.3 Macro Continuation Character 686 14.4.4 #undef Preprocessor Directive 686 14.4.5 Standard-Library Macros 686 14.4.6 Do Not Place Expressions with Side Effects in Macros 687 14.5 Conditional Compilation 687 14.5.1 #if…#endif Preprocessor Directive 687 14.5.2 Commenting Out Blocks of Code with #if…#endif 688 14.5.3 Conditionally Compiling Debug Code 688 14.6 #error and #pragma Preprocessor Directives 689 14.7 # and ## Operators 690 14.8 Line Numbers 690 14.9 Predefined Symbolic Constants 691 14.10 Assertions 691 14.11 Secure C Programming 692 15 Other Topics 699 15.1 Introduction 700 15.2 Variable-Length Argument Lists 700 15.3 Using Command-Line Arguments 702 15.4 Compiling Multiple-Source-File Programs 704 15.4.1 extern Declarations for Global Variables in Other Files 704 15.4.2 Function Prototypes 705 15.4.3 Restricting Scope with static 705 15.5 Program Termination with exit and atexit 706 15.6 Suffixes for Integer and Floating-Point Literals 708 Contents xvii 15.7 Signal Handling 708 15.8 Dynamic Memory Allocation Functions calloc and realloc 711 15.9 goto: Unconditional Branching 713 A Operator Precedence Chart 719 B ASCII Character Set 721 C Multithreading/Multicore and Other C18/C11/C99 Topics 723 C.1 Introduction 724 C.2 Headers Added in C99 725 C.3 Designated Initializers and Compound Literals 725 C.4 Type bool 727 C.5 Complex Numbers 728 C.6 Macros with Variable-Length Argument Lists 730 C.7 Other C99 Features 730 C.7.1 Compiler Minimum Resource Limits 730 C.7.2 The restrict Keyword 730 C.7.3 Reliable Integer Division 731 C.7.4 Flexible Array Members 731 C.7.5 Type-Generic Math 732 C.7.6 Inline Functions 732 C.7.7 __func__ Predefined Identifier 732 C.7.8 va_copy Macro 733 C.8 C11/C18 Features 733 C.8.1 C11/C18 Headers 733 C.8.2 quick_exit Function 733 C.8.3 Unicode® Support 733 C.8.4 _Noreturn Function Specifier 734 C.8.5 Type-Generic Expressions 734 C.8.6 Annex L: Analyzability and Undefined Behavior 734 C.8.7 Memory Alignment Control 735 C.8.8 Static Assertions 735 C.8.9 Floating-Point Types 735 C.9 Case Study: Performance with Multithreading and Multicore Systems 736 C.9.1 Example: Sequential Execution of Two Compute-Intensive Tasks 739 C.9.2 Example: Multithreaded Execution of Two Compute-Intensive Tasks 741 C.9.3 Other Multithreading Features 745 xviii Contents D Intro to Object-Oriented Programming Concepts 747 D.1 Introduction 747 D.2 Object-Oriented Programming Languages 747 D.3 Automobile as an Object 748 D.4 Methods and Classes 748 D.5 Instantiation 748 D.6 Reuse 748 D.7 Messages and Method Calls 749 D.8 Attributes and Instance Variables 749 D.9 Inheritance 749 D.10 Object-Oriented Analysis and Design (OOAD) 750 Index 751 Online Appendices D Number Systems E Using the Visual Studio Debugger F Using the GNU gdb Debugger G Using the Xcode Debugger Preface An Innovative C Programming Textbook for the 2020s Good programmers write code that humans can understand.1 —Martin Fowler I think that it's extraordinarily important that we in computer science keep fun in computing.2 —Alan Perlis Welcome to C How to Program, Ninth Edition. We present a friendly, contemporary, code-intensive, case-study-oriented introduction to C—which is among the world’s most popular programming languages.3 Whether you’re a student, an instructor or a professional programmer, this book has much to offer you. In this Preface, we present the “soul of the book.” At the heart of the book is the Deitel signature live-code approach—we generally present concepts in the context of 147 complete, working, real-world C programs, rather than in code snippets. We follow each code example with one or more live pro- gram input/output dialogs. All the code is provided free for download at https://deitel.com/c-how-to-program-9-e https://pearson.com/deitel You should execute each program in parallel with reading the text, making your learning experience “come alive.” For many decades: computer hardware has rapidly been getting faster, cheaper and smaller, Internet bandwidth (that is, its information-carrying capacity) has rapidly been getting larger and cheaper, and quality computer software has become ever more abundant and often free or nearly free through the open-source movement. 1. Martin Fowler (with contributions by Kent Beck). Refactoring: Improving the Design of Existing Code. Addison-Wesley, 1999. p. 15. 2. Alan Perlis, Quoted in the book dedication of The Structure and Interpretation of Computer Pro- grams, 2/e by Hal Abelson, Gerald Jay Sussman and Julie Sussman. McGraw-Hill. 1996. 3. Tiobe Index for November 2020. Accessed November 9, 2020. https://www.tiobe.com/ tiobe-index/. xx Preface We’ll say lots more about these important trends. The Internet of Things (IoT) is already connecting tens of billions of computerized devices of every imaginable type. These generate enormous volumes of data (one form of “big data”) at rapidly increas- ing speeds and quantities. And most computing will eventually be performed online in “the Cloud”—that is, by using computing services accessible over the Internet. For the novice, the book’s early chapters establish a solid foundation in program- ming fundamentals. The mid-range to high-end chapters and the 20+ case studies ease novices into the world of professional software-development challenges and practices. Given the extraordinary performance demands that today’s applications place on computer hardware, software and the Internet, professionals often choose C to build the most performance-intensive portions of these applications. Throughout the book, we emphasize performance issues to help you prepare for industry. The book’s modular architecture (see the chart on the inside front cover) makes it appropriate for several audiences: Introductory and intermediate college programming courses in Computer Science, Computer Engineering, Information Systems, Information Technolo- gy, Software Engineering and related disciplines. Science, technology, engineering and math (STEM) college courses with a programming component. Professional industry training courses. Experienced professionals learning C to prepare for upcoming software- development projects. We’ve enjoyed writing nine editions of this book over the last 29 years. We hope you’ll find C How to Program, 9/e informative, challenging and entertaining as you prepare to develop leading-edge, high-performance applications and systems in your career. New and Updated Features in This Ninth Edition Here, we briefly overview some of this edition’s new and updated features. There are many more. The sections that follow provide more details: We added a one-page color Table of Contents chart on the inside front cover, making it easy for you to see the entire book from “40,000 feet.” This chart emphasizes the book’s modular architecture and lists most of the case studies. Some of the case studies are book sections that walk through the complete source code—these are supported by end-of-chapter exercises that might ask you to modify the code presented in the text or take on related challenges. Some are exercises with detailed specifications from which you should be able to develop the code solution on your own. Some are exercises that ask you to visit websites that contain nice tutorials. And some are exercises that ask you to visit developer websites where there may be code to study, but no tutori- als—and the code may not be well commented. Instructors will decide which of the case studies are appropriate for their particular audiences. New and Updated Features in This Ninth Edition xxi We adhere to the C11/C18 standards. We tested all the code for correctness on the Windows, macOS and Linux operating systems using the latest versions of the Visual C++, Xcode and GNU gcc compilers, respectively, noting differences among the platforms. See the Before You Begin section that follows this Preface for software instal- lation instructions. We used the clang-tidy static code analysis tool to check all the code in the book’s code examples for improvement suggestions, from simple items like ensuring variables are initialized to warnings about potential security flaws. We also ran this tool on the code solutions that we make available to instructors for hundreds of the book’s exercises. The complete list of code checks can be found at https://clang.llvm.org/extra/clang-tidy/checks/list.html. GNU gcc tends to be the most compliant C compiler. To enable macOS and Windows users to use gcc if they wish, Chapter 1 includes a test-drive demonstrating how to compile programs and run them using gcc in the cross-platform GNU Compiler Collection Docker container. We’ve added 350+ integrated Self-Check exercises, each followed immedi- ately by its answer. These are ideal for self study and for use in “flipped class- rooms” (see the “Flipped Classrooms” section later in this Preface). To ensure that book content is topical, we did extensive Internet research on C specifically and the world of computing in general, which influenced our choice of case studies. We show C as it’s intended to be used with a rich col- lection of applications programming and systems programming case studies, focusing on computer-science, artificial intelligence, data science and other fields. See the “Case Studies” section later in this Preface for more details. In the text, code examples, exercises and case studies, we familiarize students with current topics of interest to developers, including open-source software, virtualization, simulation, web services, multithreading, multicore hardware architecture, systems programming, game programming, animation, visual- ization, 2D and 3D graphics, artificial intelligence, natural language process- ing, machine learning, robotics, data science, secure programming, cryptography, Docker, GitHub, StackOverflow, forums and more. We adhere to the latest ACM/IEEE computing curricula recommendations, which call for covering security, data science, ethics, privacy and performance concepts and using real-world data throughout the curriculum. See the “Computing and Data Science Curricula” section for more details. Most chapters in this book’s recent editions end with Secure C programming sections that focus on the SEI CERT C Coding Standard from the CERT group of Carnegie Mellon University’s Software Engineering Institute (SEI). For this edition, we tuned the SEI CERT-based sections. We also added secu- SEC rity icons in the page margin whenever we discuss a security-related issue in the text. All of this is consistent with the ACM/IEEE computing curricula docu- xxii Preface ments’ enhanced emphasis on security. See the “Computing and Data Science Curricula” section later in this Preface for a list of the key curricula documents. Consistent with our richer treatment of security, we’ve added case studies on secret-key and public-key cryptography. The latter includes a detailed walk- through of the enormously popular RSA algorithm’s steps, providing hints to help you build a working, simple, small-scale implementation. We’ve enhanced existing case studies and added new ones focusing on AI and data science, including simulations with random-number generation, survey data analysis, natural language processing (NLP) and artificial intelligence (machine-learning with simple linear regression). Data science is emphasized in the latest ACM/IEEE computing curricula documents. We’ve added exercises in which students use the Internet to research ethics and privacy issues in computing. We tuned our mutltithreading and multicore performance case study. We PERF also show a performance icon in the margin whenever we discuss a perfor- mance-related issue in the text. We integrated the previous edition’s hundreds of software-development tips ERR directly into the text for a smoother reading experience. We call out common SE errors and good software engineering practices with new margin icons. We upgraded our appendix on additional sorting algorithms and analysis of algorithms with Big O to full-chapter status (Chapter 13). C programmers often subsequently learn one or more C-based object-oriented languages. We added an appendix that presents a friendly intro to object- oriented programming concepts and terminology. C is a procedural program- ming language, so this appendix will help students appreciate differences in thinking between C developers and the folks who program in languages like C++, Java, C#, Objective-C, Swift and other object-oriented languages. We do lots of things like this in the book to prepare students for industry. Several case studies now have you use free open-source libraries and tools. We added a case study that performs visualization with gnuplot. We removed the previous edition’s introduction to C++ programming to make room for the hundreds of integrated self-check exercises and our new applications programming and systems programming case studies. This new edition is published in a larger font size and page size for enhanced readability. A Tour of the Book The Table of Contents graphic on the inside front cover shows the book’s modular architecture. Instructors can conveniently adapt the content to a variety of courses and audiences. Here we present a brief chapter-by-chapter walkthrough and indicate where A Tour of the Book xxiii the book’s case studies are located. Some are in-chapter examples and some are end-of- chapter exercises. Some are fully coded. For others, you’ll develop the solution. Chapters 1–5 are traditional introductory C programming topics. Chapters 6–11 are intermediate topics forming the high end of Computer Science 1 and related courses. Chapters 12–15 are advanced topics for late CS1 or early CS2 courses. Here’s a list of the topical, challenging and often entertaining hands-on case studies. Systems Programming Case Studies Systems Software—Building Your Own Computer (as a virtual machine) Systems Software—Building Your Own Compiler Embedded Systems Programming—Robotics, 3D graphics and animation with the Webots Simulator Performance with Multithreading and Multicore Systems Application Programming Case Studies Algorithm Development—Counter-Controlled Iteration Algorithm Development—Sentinel-Controlled Iteration Algorithm Development—Nested Control Statements Random-Number Simulation—Building a Casino Game Random-Number Simulation—Card Shuffling and Dealing Random-Number Simulation—The Tortoise and the Hare Race Intro to Data Science—Survey Data Analysis Direct-Access File Processing—Building a Transaction-Processing System Visualizing Searching and Sorting Algorithms—Binary Search and Merge Sort. Artificial Intelligence/Data Science—Natural Language Processing (“Who Really Wrote the Works of William Shakespeare?”) Artificial Intelligence/Data Science—Machine Learning with the GNU Sci- entific Library (“Statistics Can Be Deceiving” and “Have Average January Temperatures in New York City Been Rising Over the Last Century?”) Game Programming—Cannon Game with the raylib Library Game Programming—SpotOn Game with the raylib Library Multimedia: Audio and Animation—The Tortoise and the Hare Race with the raylib Library Security and Cryptography—Implementing a Vigenère Secret-Key Cipher and RSA Public-Key Cryptography Animated Visualization with raylib—The Law of Large Numbers Web Services and the Cloud—Getting a Weather Report Using libcurl and the OpenWeatherMap Web Services, and An Introduction to Building Mashups with Web Services. xxiv Preface Whether you’re a student getting a sense of the textbook you’ll be using, an instructor planning your course syllabus or a professional software developer deciding which chapters to read as you prepare for a project, the following chapter overviews will help you make the best decisions. Part 1: Programming Fundamentals Quickstart Chapter 1, Introduction to Computers and C, engages novice students with intriguing facts and figures to excite them about studying computers and computer programming. The chapter includes current technology trends, hardware and software concepts and the data hierarchy from bits to databases. It lays the groundwork for the C program- ming discussions in Chapters 2–15, the appendices and the integrated case studies. We discuss the programming-language types and various technologies you’re likely to use as you develop software. We introduce the C standard library—existing, reus- able, top-quality, high-performance functions to help you avoid “reinventing the wheel.” You’ll enhance your productivity by using libraries to perform significant tasks while writing only modest numbers of instructions. We also introduce the Internet, the World Wide Web, the “Cloud” and the Internet of Things (IoT), laying the groundwork for modern applications development. This chapter’s test-drives demonstrate how to compile and execute C code with Microsoft’s Visual C++ in Visual Studio on Windows, Apple’s Xcode on macOS, and GNU’s gcc on Linux. We’ve run the book’s 147 code examples using each environment.4 Choose whichever program-development environment you prefer—the book works well with others, too. We also demonstrate GNU gcc in the GNU Compiler Collection Docker con- tainer. This enables you to run the latest GNU gcc compiler on Windows, macOS or Linux—this is important because the GNU compilers generally implement all (or most) features in the latest language standards. See the Before You Begin section that follows this Preface for compiler installation instructions. See the Docker section later in this Preface for more information on this important developer tool. For Windows users, we point to Microsoft’s step-by-step instructions that allow you to install Linux in Windows via the Windows Subsystem for Linux (WSL). This is another way to be able to use the GNU gcc compiler on Windows. You’ll learn just how big “big data” is and how quickly it’s getting even bigger. The chapter closes with an introduction to artificial intelligence (AI)—a key overlap between the computer-science and data-science fields. AI and data science are likely to play significant roles in your computing career. Chapter 2, Intro to C Programming, presents C fundamentals and illustrates key language features, including input, output, fundamental data types, computer mem- ory concepts, arithmetic operators and their precedence, and decision making. 4. We point out the few cases in which a compiler does not support a particular feature. A Tour of the Book xxv Chapter 3, Structured Program Development, is one of the most important chapters for programming novices. It focuses on problem-solving and algorithm development with C’s control statements. You’ll develop algorithms through top-down, stepwise refinement, using the if and if…else selection statements, the while iteration state- ment for counter-controlled and sentinel-controlled iteration, and the increment, dec- rement and assignment operators. The chapter presents three algorithm-development case studies. Chapter 4, Program Control, presents C’s other control statements—for, do…while, switch, break and continue—and the logical operators. A key feature of this chapter is its structured-programming summary. Chapter 5, Functions, introduces program construction using existing and custom functions as building blocks. We demonstrate simulation techniques with random- number generation. We also discuss passing information between functions and how the function-call stack and stack frames support the function call/return mechanism. We begin our treatment of recursion. This chapter also presents our first simulation case study—Building a Casino Game, which is enhanced by end-of-chapter exercises. Part 2: Arrays, Pointers and Strings Chapter 6, Arrays, presents C’s built-in array data structure for representing lists and tables of values. You’ll define and initialize arrays, and refer to their individual elements. We discuss passing arrays to functions, sorting and searching arrays, manipulating mul- tidimensional arrays and creating variable-length arrays whose size is determined at exe- cution time. Chapter 13, Computer-Science Thinking: Sorting Algorithms and Big O, discusses more sophisticated and higher-performance sorting algorithms and presents a friendly introduction to analysis of algorithms with computer science’s Big O notation. Chapter 6 presents our first data-science case study—Intro to Data Sci- ence: Survey Data Analysis. In the exercises, we also present two Game Programming with Graphics, Sound and Collision Detection case studies and an Embedded Sys- tems Programming case study (Robotics with the Webots Simulator). Chapter 7, Pointers, presents what is arguably C’s most powerful feature. Pointers enable programs to accomplish pass-by-reference, pass functions to other functions, and create and manipulate dynamic data structures, which you’ll study in detail in Chapter 12. The chapter explains pointer concepts, such as declaring pointers, initializing point- ers, getting the memory address of a variable, dereferencing pointers, pointer arith- metic and the close relationship between arrays and pointers. This chapter presents our first systems software case-study exercise—Building Your Own Computer with Simulation. This case study introduces an essential modern computer-architecture topic—virtual machines. xxvi Preface Chapter 8, Characters and Strings, introduces the C standard library’s string, character and memory-block processing functions. You’ll use these powerful capabilities in Chapter 11, File Processing, as you work through a natural language processing (NLP) case study. You’ll see that strings are intimately related to pointers and arrays. Part 3: Formatted Input/Output, Structures and File Processing Chapter 9, Formatted Input/Output, discusses the powerful formatting features of functions scanf and printf. When properly used, these functions securely input data from the standard input stream and output data to the standard output stream, respectively. Chapter 10, Structures, Unions, Bit Manipulation and Enumerations, introduces structures (structs) for aggregating related data items into custom types, unions for sharing memory among multiple variables, typedefs for creating aliases for previously defined data types, bitwise operators for manipulating the individual bits of integral operands and enumerations for defining sets of named integer constants. Many C pro- grammers go on to study C++ and object-oriented programming. In C++, C’s structs evolve into classes, which are the “blueprints” C++ programmers use to create objects. C structs contain only data. C++ classes can contain data and functions. Chapter 11, File Processing, introduces files for long-term data retention, even when the computer is powered off. Such data is said to be “persistent.” The chapter explains how plain-text files and binary files are created, updated and processed. We consider both sequential-access and random-access file processing. In one of our case-study exercises, you’ll read data from a comma-separated value (CSV) file. CSV is one of the most popular file formats in the data-science community. This chapter presents our next case study—Building a Random-Access Transaction-Processing System. We use random-access files to simulate the kind of high-speed direct-access capabilities that industrial-strength database-management systems have. This chapter also presents our first artificial-intelligence/data-science case study, which uses Natural Language Processing (NLP) techniques to begin investigating the controversial question, “Who really wrote the works of William Shakespeare?” A second artificial-intelligence/data- science case study—Machine Learning with the GNU Scientific Library—investi- gates Anscombe’s Quartet using simple linear regression.5 This is a collection of four dramatically different datasets that have identical or nearly identical basic descriptive statistics. It offers a valuable insight for students and developers learning some data- science basics in this computer-science textbook. The case study then asks you to run a simple linear regression on 126 years of New York City average January temperature data to determine if there is a cooling or warming trend. 5. “Anscombe’s Quartet.” Accessed November 13, 2020. https://en.wikipedia.org/wiki/ Anscombe%27s_quartet. A Tour of the Book xxvii Part 4: Algorithms and Data Structures Chapter 12, Data Structures, uses structs to aggregate related data items into cus- tom types, typedefs to create aliases for previously defined types, and dynamically linked data structures that can grow and shrink at execution time—linked lists, stacks, queues and binary trees. You can use the techniques you learn to implement other data structures. This chapter also presents our next systems-software case study exercise—Building Your Own Compiler. We’ll define a simple yet powerful high- level language. You’ll write some high-level-language programs that your compiler will compile into the machine language of the computer you built in Chapter 7. The compiler will place its machine-language output into a file. Your computer will load the machine language from the file into its memory, execute it and produce appro- priate outputs. Chapter 13, Computer-Science Thinking: Sorting Algorithms and Big O, intro- duces some classic computer-science topics. We consider several algorithms and com- pare their processor demands and memory consumption. We present a friendly introduction to computer science’s Big O notation, which indicates how hard an algorithm may have to work to solve a problem, based on the number of items it must process. The chapter includes the case study Visualizing the High-Performance Merge Sort. Our recursion (Chapter 5), arrays (Chapter 6), searching (Chapter 6), data structures (Chapter 12), sorting (Chapter 13) and Big O (Chapter 13) coverage provides nice content for a C data structures course. Part 5: Preprocessor and Other Topics Chapter 14, Preprocessor, discusses additional features of the C preprocessor, such as using #include to help manage files in large programs, using #define to create macros with and without arguments, using conditional compilation to specify por- tions of a program that should not always be compiled (e.g., extra code used only during program development), displaying error messages during conditional compi- lation, and using assertions to test whether expressions’ values are correct. Chapter 15, Other Topics, covers additional C topics, including multithreading sup- port (available in GNU gcc, but not Xcode or Visual C++), variable-length argument lists, command-line arguments, compiling multiple-source-file programs, extern dec- larations for global variables in other files, function prototypes, restricting scope with static, makefiles, program termination with exit and atexit, suffixes for integer and floating-point literals, signal handling, dynamic memory-allocation functions calloc and realloc and unconditional branching with goto. This chapter presents our final case study—Performance with Multithreading and Multicore Systems. This case study demonstrates how to create multithreaded programs that will run faster (and often much faster) on today’s multicore computer architectures. This is a nice capstone xxviii Preface case study for a book about C, for which writing high-performance programs is para- mount. Appendices Appendix A, Operator Precedence Chart, lists C’s operators in highest-to-lowest precedence order. Appendix B, ASCII Character Set, shows characters and their corresponding numeric codes. Appendix C, Multithreading/Multicore and Other C18/C11/C99 Topics, covers designated initializers, compound literals, type bool, complex numbers, additions to the preprocessor, the restrict keyword, reliable integer division, flexible array mem- bers, relaxed constraints on aggregate initialization, type generic math, inline func- tions, return without expression, __func__ predefined identifier, va_copy macro, C11 headers, _Generic keyword (type generic expressions), quick_exit function, Unicode® support, _noreturn function specifier, type-generic expressions, Annex L: Analyzability and Undefined Behavior, memory-alignment control, static assertions, floating-point types and the timespec_get function. Appendix D, Intro to Object-Oriented Programming Concepts, presents a friendly overview of object-oriented programming terminology and concepts. After learning C, you’ll likely also learn one or more C-based object-oriented languages—such as C++, Java, C#, Objective-C or Swift—and use them side-by-side with C. Online Appendices Appendix E, Number Systems, introduces the binary, octal, decimal and hexadeci- mal number systems. Appendices F–H, Using the Visual Studio Debugger, Using the GNU gdb Debug- ger and Using the Xcode Debugger, demonstrate how to use our three preferred compilers’ basic debugging capabilities to locate and correct execution-time problems in your programs. C How to Program, 9/e Key Features C Programming Fundamentals In our rich coverage of C fundamentals: We emphasize problem-solving and algorithm development. To help students prepare to work in industry, we use the terminology from the latest C standard documents in preference to general programming terms. We avoid heavy math, leaving it to upper-level courses. Optional mathemat- ical exercises are included for science and engineering courses. C How to Program, 9/e Key Features xxix C11 and C18 Standards C11 refined and expanded C’s capabilities. We’ve added more features from the C11 standard. Since C11, there has been only one new version, C18.6 It “addressed defects in C11 without introducing new language features.”7 Innovation: “Intro-to” Pedagogy with 350+ Integrated Self-Check Exercises This book uses our new “Intro to” pedagogy with integrated Self Checks and answers. We introduced this pedagogy in our recent textbook, Intro to Python for Computer Sci- ence and Data Science: Learning to Program with AI, Big Data and the Cloud. Chapter sections are intentionally small. We use a “read-a-little, do-a-little, test-a-little” approach. You read about a new concept, study and execute the corresponding code examples, then test your understanding of the new con- cept via the integrated Self-Check exercises immediately followed by their answers. This will help you keep a brisk learning pace. Fill-in-the-blank, true/false and discussion Self Checks enable you to test your understanding of the concepts and terminology you’ve just studied. Code-based Self Checks give you a chance to use the terminology and rein- force the programming techniques you’ve just studied. The Self-Checks are particularly valuable for flipped classroom courses— we’ll soon say more about that popular educational phenomenon. KIS (Keep It Simple), KIS (Keep it Small), KIT (Keep it Topical) Keep it simple—We strive for simplicity and clarity. Keep it small—Many of the book’s examples are small. We use more substan- tial code examples, exercises and projects when appropriate, particularly in the case studies that are a core feature of this textbook. Keep it topical—“Who dares to teach must never cease to learn.” 8 (J. C. Dana)—In our research, we browsed, read or watched thousands of current articles, research papers, white papers, books, videos, webinars, blog posts, forum posts, documentation pieces and more. 6. ISO/IEC 9899:2018, Information technology — Programming languages — C, https:// www.iso.org/standard/74528.html. 7. https://en.wikipedia.org/wiki/C18_(C_standard_revision). Also http://www.iso- 9899.info/wiki/The_Standard. 8. John Cotton Dana. From https://www.bartleby.com/73/1799.html: “In 1912 Dana, a Newark, New Jersey, librarian, was asked to supply a Latin quotation suitable for inscription on a new building at Newark State College (now Kean University), Union, New Jersey. Unable to find an appropriate quotation, Dana composed what became the college motto.—The New York Times Book Review, March 5, 1967, p. 55.” xxx Preface Hundreds of Contemporary Examples, Exercises and Projects (EEPs) You’ll use a hands-on applied approach to learn from a broad selection of real-world examples, exercises and projects (EEPs) drawn from computer science, data science and other fields: You’ll attack exciting and entertaining challenges in our larger case studies, such as building a casino game, building a survey-data-analysis program, building a transaction-processing system, building your own computer (using simulation to build a virtual machine), using AI/data-science technologies such as natural language processing and machine learning, building your own compiler, programming computer games, programming robotics simu- lations with Webots, and writing multithreaded code to take advantage of today’s multicore computer architectures to get the best performance from your computer. Research and project exercises encourage you to go deeper into what you’ve learned and explore other technologies. We encourage you to use computers and the Internet to solve significant problems. Projects are often more exten- sive in scope than the exercises—some might require days or weeks of imple- mentation effort. Many of these are appropriate for class projects, term projects, directed-study projects, capstone-course projects and thesis research. We do not provide solutions to the projects. Instructors can tailor their courses to their audience’s unique requirements and vary labs and exam questions each semester. Working with Open-Source Software In those days [batch processing] programmers never even documented their programs, because it was assumed that nobody else would ever use them. Now, however, time-sharing had made exchanging software trivial: you just stored one copy in the public repository and thereby effectively gave it to the world. Immediately people began to document their programs and to think of them as being usable by others. They started to build on each other’s work.9 —Robert Fano, Founding Director of MIT’s Project MAC in the 1960s, which evolved into today’s Computer Science and Artificial Intelligence Laboratory (CSAIL)10 Open source is software with source code that anyone can inspect, modify, and enhance.”11 We encourage you to try lots of demos and view free, open-source code examples (available on sites such as GitHub) for inspiration. We say more about GitHub in the section “Thinking Like a Developer—GitHub, StackOverflow and More.” 9. Robert Fano, quoted in Dream Machine: J.C.R. Licklider and the Revolution That Made Com- puting Personal by Mitchell Waldrop. Penguin Putnam, 2002. p. 232. 10. “MIT Computer Science and Artificial Intelligence Laboratory.” Accessed November 9, 2020. https://en.wikipedia.org/wiki/MIT_Computer_Science_and_Artificial_Intelli- gence_Laboratory. 11. “What is open source?” Accessed November 14, 2020. https://opensource.com/resourc- es/what-open-source. C How to Program, 9/e Key Features xxxi Visualizations We include high-level visualizations produced with the gnuplot open-source visual- ization package to reinforce your understanding of the concepts: We use visualizations as a pedagogic tool. For instance, one example makes the law of large numbers “come alive” in a dice-rolling simulation (see Chapter 10—Raylib Game Programming Case Studies later in this Preface). As this program performs increasing numbers of die rolls, you’ll see each of the six fac- es’ (1, 2, 3, 4, 5, 6) percentage of the total rolls gradually approach 16.667% (1/6th), and the lengths of the bars representing the percentages equalize. You should experiment with the code to implement your own visualizations. Data Experiences In the book’s examples, exercises and projects—especially in the file-processing chap- ter—you’ll work with real-world data such as Shakespeare’s play Romeo and Juliet. You’ll download and analyze text from Project Gutenberg—a great source of free downloadable texts for analysis. The site contains nearly 63,000 e-books in various formats, including plain-text files—these are out of copyright in the United States. You’ll also work with real-world temperature data. In particular, you’ll analyze 126 years of New York City average January temperature data and determine whether there is a cooling or warming trend. You’ll get this data from National Oceanic and Atmospheric Administration (NOAA) website noaa.gov. Thinking Like a Developer—GitHub, StackOverflow and More The best way to prepare [to be a programmer] is to write programs, and to study great pro- grams that other people have written. In my case, I went to the garbage cans at the Com- puter Science Center and fished out listings of their operating systems.12 —William Gates To help prepare for your career, you’ll work with such popular developer web- sites as GitHub and StackOverflow, and you’ll do Internet research. StackOverflow is one of the most popular developer-oriented, question-and- answer sites. There is a massive C open-source community. For example, on GitHub, there are over 32,00013 C code repositories! You can check out other people’s C code on GitHub and even build upon it if you like. This is a great way to learn and is a natural extension of our live-code teaching philosophy.14 GitHub is an excellent venue for finding free, open-source code to incorpo- rate into your projects—and for you to contribute your code to the open- 12. William Gates, quoted in Programmers at Work: Interviews With 19 Programmers Who Shaped the Computer Industry by Susan Lammers. Microsoft Press, 1986, p. 83. 13. “C.” Accessed January 4, 2021. https://github.com/topics/c. 14. Students will need to become familiar with the variety of open-source licenses for software on GitHub. xxxii Preface source community if you like. Fifty million developers use GitHub.15 The site currently hosts over 100 million repositories for code written in an enor- mous number of languages16—developers contributed to 44+ million reposi- tories in 2019 alone.17 GitHub is a crucial element of the professional software developer’s arsenal with version control tools that help teams of developers manage public open-source projects and private projects. In 2018, Microsoft purchased GitHub for $7.5 billion. If you become a soft- ware developer, you’ll almost certainly use GitHub regularly. According to Mic- rosoft’s CEO, Satya Nadella, they bought GitHub to “empower every developer to build, innovate and solve the world’s most pressing challenges.”18 We encourage you to study and execute lots of developers’ open-source C code on GitHub. Privacy The ACM/IEEE’s curricula recommendations for Computer Science, Information Technology and Cybersecurity mention privacy over 200 times. Every programming student and professional needs to be acutely aware of privacy issues and concerns. Students research privacy in four exercises in Chapters 1, 3 and 10. In Chapter 1’s exercises, you’ll start thinking about these issues by researching ever- stricter privacy laws such as HIPAA (Health Insurance Portability and Accountability Act) and the California Consumer Privacy Act (CCPA) in the United States and GDPR (General Data Protection Regulation) for the European Union. Ethics The ACM’s curricula recommendations for Computer Science, Information Technol- ogy and Cybersecurity mention ethics more than 100 times. In several Chapter 1 exer- cises, you’ll focus on ethics issues via Internet research. You’ll investigate privacy and ethical issues surrounding intelligent assistants, such as IBM Watson, Amazon Alexa, Apple Siri, Google Assistant and Microsoft Cortana. For example, a judge ordered Amazon to turn over Alexa recordings for use in a criminal case.19 Performance Programmers prefer C (and C++) for performance-intensive operating systems, real- time systems, embedded systems, game systems and communications systems, so we focus on performance issues. We use timing operations in our multithreading exam- 15. “GitHub.” Accessed November 14, 2020. https://github.com/. 16. “GitHub is how people build software.” Accessed November 14, 2020. https://github.com/ about. 17. “The State of the Octoverse.” Accessed November 14, 2020. https://octoverse.github.com. 18. “Microsoft to acquire GitHub for $7.5 billion.” Accessed November 14, 2020. https:// news.microsoft.com/2018/06/04/microsoft-to-acquire-github-for-7-5-billion/. 19. “Judge orders Amazon to turn over Echo recordings in double murder case.” Accessed November 14, 2020. https://techcrunch.com/2018/11/14/amazon-echo-recordings-judge-murder- case/. C How to Program, 9/e Key Features xxxiii ples to measure the performance improvement we get on today’s popular multicore systems, as we employ an increasing number of cores. Static Code Analysis Tools Static code analysis tools let you quickly check your code for common errors and secu- rity problems and provide insights for improving your code. We checked all our C code using the clang-tidy tool (https://clang.llvm.org/extra/clang-tidy/). We also used the compiler flag -Wall in the GNU gcc and Clang compilers to enable all com- piler warnings. With a few exceptions for warnings beyond this book’s scope, we ensure that our programs compile without warning messages. How We’re Handling C11’s Annex K and printf_s/scanf_s The C11 standard’s Annex K introduced more secure versions of printf (for output) and scanf (for input) called printf_s and scanf_s. We discuss these functions and the corresponding security issues in Sections 6.13 and 7.13: Annex K is optional, so not every C vendor implements it. In particular, GNU C++ and Clang C++ do not implement Annex K, so using scanf_s and printf_s might compromise your code’s portability among compilers. Microsoft implemented its own Visual C++ versions of printf_s and scanf_s before the C11 standard. Its compiler immediately began warning on every scanf call that scanf was deprecated—i.e., it should no longer be used—and that you should consider using scanf_s instead. Microsoft now treats what used to be a warning about scanf as an error. By default, a program with scanf will not compile on Visual C++. Chapter 1’s Visual C++ test-drive shows how to handle this issue and compile our programs. Many organizations have coding standards that require code to compile without warning messages. There are two ways to eliminate Visual C++’s scanf warnings—use scanf_s instead of scanf or disable these warnings. There is some discussion of removing Annex K from the C standard. For this reason, we use printf/scanf throughout this book and show Visual C++ users how to disable Microsoft’s printf/scanf errors. Windows users who prefer not to do that can use the gcc compiler in the GNU GCC Docker container, which we discuss in this Preface’s “Docker” section. See the Before You Begin section that follows this Preface, and see Section 1.10 for details. New Appendix: Intro to Object-Oriented Programming Appendix C’s programming model is called procedural programming. We teach it as struc- tured procedural programming. After learning C, you’ll likely also learn one or more C-based object-oriented languages—such as Java, C++, C#, Objective-C or Swift— and use them side-by-side with C. Many of these languages support several pro- gramming paradigms among procedural programming, object-oriented program- ming, generic programming and functional-style programming. In Appendix D, we present a friendly overview of object-oriented programming fundamentals. xxxiv Preface A Case Studies Tour We include many case studies as more substantial chapter examples, exercises and projects (EEPs). These are at an appropriate level for introductory programming courses. We anticipate that instructors will select subsets of the case studies appropri- ate for their particular courses. Chapter 5—Random-Number Simulation: Building a Casino Game In this case study, you’ll use random-number generation and simulation techniques to implement the popular casino dice game called craps. Chapter 5—Random-Number Simulation Case Study: The Tortoise and the Hare Race In this case study exercise, you’ll use random-number generation and simulation techniques to implement the famous race between the tortoise and the hare. Chapter 6—Visualizing Binary Search In this case study, you’ll learn the high-speed binary-search algorithm and see a visu- alization that shows the algorithm’s halving effect that achieves high performance. Chapter 6—Intro to Data Science: Survey Data Analysis In this case study, you’ll learn various basic descriptive statistics (mean, median and mode) that are commonly used to “get to know your data.” You’ll then build a nice array-manipulation application that calculates these statistics for a batch of survey data. Chapter 7—Random-Number Simulation—Card Shuffling and Dealing In this case study, you’ll use arrays of strings, random-number generation and simu- lation techniques to implement a text-based card-shuffling-and-dealing program. Chapter 7—Embedded Systems Programming: Robotics with the Webots Simulator Webots (https://cyberbotics.com/) is a wonderful open-source, 3D, robotics sim- ulator that runs on Windows, macOS and Linux. It comes bundled with simulations for dozens of robots that walk, fly, roll, drive and more: https://cyberbotics.com/doc/guide/robots You’ll use the free tier of the Webot robotics simulator to explore their dozens of simulated robots. You’ll execute various full-color 3D robotics simulations written in C and study the provided code. Webots is a self-contained development environ- ment that provides a C code editor and compiler. You’ll use these tools to program your own simulations using Webot’s robots. Webots provides lots of fully coded C programs. A great way for you to learn C is to study existing programs, modify them to work a bit differently and observe the results. Many prominent robotics companies use Webots simulators to prototype new products. A Case Studies Tour xxxv Chapter 7—Systems Software Case Study: Building Your Own Computer (Virtual Machine) with Simulation In the context of several exercises, you’ll “peel open” a hypothetical computer and look at its internal structure. We introduce simple machine-language programming and write several small machine-language programs for this computer, which we call the Simpletron. As its name implies, it’s a simple machine, but as you’ll see, a powerful one as well. The Simpletron runs programs written in the only language it directly understands—that is, Simpletron Machine Language, or SML for short. To make this an especially valuable experience, you’ll then build a computer (through the technique of software-based simulation) on which you can actually run your machine-language programs! The Simpletron experience will give you a basic intro- duction to the notion of virtual machines—one of the most important systems- architecture concepts in modern computing. Chapter 8—Pqyoaf X Nylfomigrob Qwbbfmh Mndogvk: Rboqlrut yua Boklnxhmywex This case study exercise’s title looks like gibberish. This is not a mistake! In this exer- cise, we introduce cryptography, which is critically important in today’s connected world. Every day, cryptography is used behind the scenes to ensure that your Inter- net-based communications are private and secure. This case study exercise continues our security emphasis by having readers study the Vigenère secret-key cipher algo- rithm and implement it using array-processing techniques.20 They’ll then use it to encrypt and decrypt messages and to decrypt this section’s title. Chapter 8—RSA Public-Key Cryptography Secret key encryption and decryption have a weakness—an encrypted message can be decrypted by anyone who discovers or steals the secret key. We explore public-key cryptography with the RSA algorithm. This technique performs encryption with a public key known to every sender who might want to send a secret message to a par- ticular receiver. The public key can be used to encrypt messages but not decrypt them. Messages can be decrypted only with a paired private key known only to the receiver, so it’s much more secure than the secret key in secret-key cryptography. RSA is among the world’s most widely used public-key cryptography technologies. You’ll build a working, small-scale, classroom version of the RSA cryptosystem. Chapter 10—Raylib Game Programming Case Studies In this series of five case study exercises and 10 additional exercises, you’ll use the open-source, cross-platform raylib21 game programming library, which supports Win- dows, macOS, Linux and other platforms. The raylib development team provides many C demos to help you learn key library features and techniques. You’ll study two completely coded games and a dynamic animated visualization that we created: 20. “Vigenère Cipher.” Accessed November 22, 2020. https://en.wikipedia.org/wiki/ Vigenère_cipher. 21. “raylib.” Accessed November 14, 2020. https://www.raylib.com. xxxvi Preface The Spot-On game tests your reflexes by requiring you to click moving spots before they disappear. With each new game level the spots move faster, mak- ing them harder to click. The Cannon game challenges you to repeatedly aim and fire a cannon to destroy nine moving targets before a time limit expires. A moving blocker makes the game more difficult. The Law of Large Numbers dynamic animated visualization repeatedly rolls a six-sided die and creates an animated bar chart. Visualizations give you a powerful way to understand data that goes beyond simply looking at raw data. This case study exercise allows students to see the “law of large numbers” at work. When repeatedly rolling a die, we expect each die face to appear approx- imately 1/6th (16.667%) of the time. For small numbers of rolls (e.g., 60 or 600), you’ll see that the frequencies typically are not evenly distributed. As you simulate larger numbers of die rolls (e.g., 60,000), you’ll see the die fre- quencies become more balanced. When you simulate significant numbers of die rolls (e.g., 60,000,000), the bars will appear to be the same size. The games and simulation use various raylib capabilities, including shapes, colors, sounds, animation, collision detection and user-input events (such as mouse clicks). After studying our code, you’ll use the raylib graphics, animation and sound fea- tures you learn to enhance your implementation of Chapter 5’s Tortoise and the Hare Race. You’ll incorporate a traditional horse race’s sounds, and multiple tortoise and hare images to create a fun, animated multimedia “extravaganza.” Then, you’ll use a raylib to enhance this chapter’s high-performance card-shuffling-and-dealing simulation to display card images. Finally, you can select from 10 additional raylib game-programming and simulation exercises. Get creative—have some fun design- ing and building your own games, too! Chapter 11—Case Study: Building a Random-Access Transaction- Processing System In this case study, you’ll use random-access file processing to implement a simple transaction-processing system that simulates the kind of high-speed direct-access capabilities that industrial-strength database-management systems have. This case study gives you both application-programming and some “under-the-hood” systems- programming experience. Chapter 11—Artificial Intelligence Case Study: Natural Language Pro- cessing (NLP) Natural Language Processing (NLP) helps computers understand, analyze and pro- cess text. One of its most common uses is sentiment analysis—determining whether text has positive, neutral or negative sentiment. Another interesting use of NLP is assessing text readability, which is affected by the vocabulary used, word lengths, sen- tence structure, sentence lengths, topic and more. While writing this book, we used A Case Studies Tour xxxvii the paid (NPL) tool Grammarly22 to help tune the writing and ensure the text’s read- ability for a wide audience. Instructors who use the “flipped classroom” format prefer textbooks that students can understand on their own. Some people believe that the works of William Shakespeare actually might have been written by Christopher Marlowe or Sir Francis Bacon among others.23,24 In the NLP case study exercise, you’ll use array-, string- and file-processing techniques to per- form simple similarity detection on Shakespeare’s Romeo and Juliet and Marlowe’s Edward the Second to determine how alike they are. You may be surprised by the results. Chapter 11—Artificial Intelligence Case Study: Machine Learning with the GNU Scientific Library Statistics can be deceiving. Dramatically different datasets can have identical or nearly identical descriptive statistics. You’ll consider a famous example of this phenome- non—Anscombe’s Quartet25—which consists of four datasets of x–y coordinate pairs that differ significantly, yet have nearly identical descriptive statistics. You’ll then study a completely coded example that uses the machine-learning technique called simple linear regression to calculate the equation of a straight line (y = mx + b) that, given a collection of points (x–y coordinate pairs) representing an independent variable (x) and a dependent variable (y), describes the relationship between these vari- ables with a straight line, known as the regression line. As you’ll see, the regression lines for Anscombe’s Quartet are visually identical for all four quite different datasets. The program you’ll study then passes commands to the open-source gnuplot pack- age to create several attractive visualizations. gnuplot uses its own plotting language different from C, so in our code, we provide extensive comments that explain its com- mands. Finally, the case study asks you to run a simple linear regression on 126 years of New York City average January temperature data to determine if there is a cool- ing or warming trend. As part of this case study, you’ll also read comma-separated values (CSV) text files containing the datasets. Chapter 11—Web Services and the Cloud: Getting a Weather Report Using libcurl and the OpenWeatherMap Web Services; Introducing Mashups More and more computing today is done “in the cloud,” using software and data dis- tributed across the Internet worldwide. The apps we use daily are heavily dependent on various cloud-based services. A service that provides access to itself over the Inter- net is known as a web service. In this case study exercise, you’ll work through a com- pletely coded application that uses the open-source C library libcurl to invoke an 22. Grammarly has free and paid versions (https://www.grammarly.com). They provide free plug- ins you can use in several popular web browsers. 23. “Did Shakespeare Really Write His Own Plays?” Accessed November 13, 2020. https:// www.history.com/news/did-shakespeare-really-write-his-own-plays. 24. “Shakespeare authorship question.” Accessed November 13, 2020. https://en.wikipedia.org/ wiki/Shakespeare_authorship_question. 25. “Anscombe’s quartet.” Accessed November 13, 2020. https://en.wikipedia.org/wiki/ Anscombe%27s_quartet. xxxviii Preface OpenWeatherMap (free tier) web service that returns the current weather for a spec- ified city. The web service returns results in JSON (JavaScript Object Notation) for- mat, which we process using the open-source cJSON library. This exercise opens a world of possibilities. You can explore nearly 24,000 web services listed in the ProgrammableWeb26 web services directory. Many are free or provide free tiers that you can use to create fun and interesting mashups that combine complementary web services. Chapter 12—Systems Software Case Study: Building Your Own Compiler In the context of several exercises, you’ll build a simple compiler that translates pro- grams written in a simple high-level programming language to our Simpletron Machine Language (SML). You’ll write programs in this small new high-level lan- guage, compile them on the compiler you build and run them on your Simpletron simulator. And with Chapter 11, File Processing, your compiler can write the gen- erated machine-language code into a file from which your Simpletron computer can then read your SML program, load it into the Simpletron’s memory and execute it! This is a nice end-to-end exercise sequence for novice computing students. Chapter 13—Visualizing the High-Performance Merge Sort A centerpiece of our sorting treatment is our implementation of the high-performance merge sort algorithm. In that case study, you’ll use outputs to visualize the algorithm’s partition and merge steps, which will help a user understand how the merge sort works. Appendix C—Systems Architecture Case Study: Performance with Multi- threading and Multicore Systems Multithreading—which allows you to break a program into separate “threads” that can be executed in parallel—has been around for many decades, but interest in it is higher today due to the availability of multicore processors in computers and devices, including smartphones and tablets. These processors economically implement multiple processors on one integrated circuit chip. They put multiple cores to work executing different parts of your program in parallel, thereby enabling the individual tasks and the program as a whole to complete faster. Four and eight cores are common in many of today’s devices, and the number of cores will continue to grow. We wrote and tested the code for this book using an eight-core MacBook Pro. Multithreaded applications enable you to execute separate threads simultaneously on multiple cores, so that you can take the fullest advantage of multicore architecture. For a convincing demonstration of the power of multithreading on a multicore system, we present a case study with two programs. One performs two compute- inte