C How To Program 9Th Global Edition Deitel Paul Full Chapter PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 69

C How to Program, 9th Global Edition

Deitel Paul
Visit to download the full and correct content document:
https://ebookmass.com/product/c-how-to-program-9th-global-edition-deitel-paul/
More products digital (pdf, epub, mobi) instant
download maybe you interests ...

C How to Program 9th Edition Deitel Paul

https://ebookmass.com/product/c-how-to-program-9th-edition-
deitel-paul/

C How to Program: With Case Studies in Applications and


Systems Programming, Global Edition Paul Deitel

https://ebookmass.com/product/c-how-to-program-with-case-studies-
in-applications-and-systems-programming-global-edition-paul-
deitel/

C++ How to Program: An Objects-Natural Approach, 11e


11th Edition Paul Deitel

https://ebookmass.com/product/c-how-to-program-an-objects-
natural-approach-11e-11th-edition-paul-deitel/

Java how to program. Early objects Eleventh Edition


Deitel

https://ebookmass.com/product/java-how-to-program-early-objects-
eleventh-edition-deitel/
(eTextbook PDF) for Java How to Program, Early Objects
11th Edition by Paul J. Deitel

https://ebookmass.com/product/etextbook-pdf-for-java-how-to-
program-early-objects-11th-edition-by-paul-j-deitel/

C++20 for Programmers (Deitel Developer Series) 3rd


Edition Paul Deitel

https://ebookmass.com/product/c20-for-programmers-deitel-
developer-series-3rd-edition-paul-deitel/

Il linguaggio C - Fondamenti e tecniche di


programmazione 9th Edition Paul J. Deitel

https://ebookmass.com/product/il-linguaggio-c-fondamenti-e-
tecniche-di-programmazione-9th-edition-paul-j-deitel/

C How to Program 8th Edition, (Ebook PDF)

https://ebookmass.com/product/c-how-to-program-8th-edition-ebook-
pdf/

Cómo programar en c++ 9th Edition Harvey Deitel

https://ebookmass.com/product/como-programar-en-c-9th-edition-
harvey-deitel/
GLOBAL
EDITION

C HOW TO PROGRAM
NINTH EDITION

Paul Deitel • Harvey Deitel

with case studies introducing


Applications Programming and
Systems Programming
F01_DEIT8393_09_GE_TTL_final.fm Page 1 Tuesday, April 19, 2022 12:00 PM
Credits and acknowledgments borrowed from other sources and reproduced, with permission, in this textbook appear on the appropriate page of appearance
or in the Credits on pages.

Cover image by Ink Drop/ Shutterstock

Pearson Education Limited


KAO Two
KAO Park
Hockham Way
Harlow
Essex
CM17 9SR
United Kingdom

and Associated Companies throughout the world

Visit us on the World Wide Web at: www.pearsonglobaleditions.com

© Pearson Education Limited 2023

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, 9th Edition, ISBN 978-0-13-739839-3 by Paul Deitel and Harvey Deitel
published by Pearson Education © 2022.

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.
For information regarding permissions, request forms, and the appropriate contacts within the Pearson Education Global Rights and Permissions
department, please visit www.pearsoned.com/permissions/.

This eBook is a standalone product and may or may not include all assets that were part of the print version. It also does not provide access
to other Pearson digital products like MyLab and Mastering. The publisher reserves the right to remove any material in this eBook at any
time.

ISBN 10: 1-292-43707-3 (print)


ISBN 13: 978-1-292-43707-1 (print)
eBook ISBN 13: 978-1-292-43699-9 (uPDF)

British Library Cataloguing-in-Publication Data


A catalogue record for this book is available from the British Library

1 22

Typeset in Times NR MT Pro by B2R Technologies Pvt. Ltd.


F01_DEIT8393_09_GE_TTL_final.fm Page 3 Tuesday, April 19, 2022 12:00 PM

In memory of Dennis Ritchie,


creator of the C programming language
and co-creator of the UNIX operating system.
Paul and Harvey Deitel
F01_DEIT8393_09_GE_TTL_final.fm Page 4 Tuesday, April 19, 2022 12:00 PM

Trademarks
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.


DEIT8393_09_GE_Final.book Page 5 Tuesday, April 12, 2022 3:20 PM

Contents
Appendices E–H are PDF documents posted online at the book’s Companion
Website (located at https://www.pearsonglobaleditions.com).

Preface 17

Before You Begin 49

1 Introduction to Computers and C 53


1.1 Introduction 54
1.2 Hardware and Software 56
1.2.1 Moore’s Law 56
1.2.2 Computer Organization 57
1.3 Data Hierarchy 60
1.4 Machine Languages, Assembly Languages and High-Level Languages 63
1.5 Operating Systems 65
1.6 The C Programming Language 68
1.7 The C Standard Library and Open-Source Libraries 70
1.8 Other Popular Programming Languages 71
1.9 Typical C Program-Development Environment 73
1.9.1 Phase 1: Creating a Program 73
1.9.2 Phases 2 and 3: Preprocessing and Compiling a C Program 73
1.9.3 Phase 4: Linking 74
1.9.4 Phase 5: Loading 75
1.9.5 Phase 6: Execution 75
1.9.6 Problems That May Occur at Execution Time 75
1.9.7 Standard Input, Standard Output and Standard Error Streams 76
1.10 Test-Driving a C Application in Windows, Linux and macOS 76
1.10.1 Compiling and Running a C Application with Visual Studio
2019 Community Edition on Windows 10 77
1.10.2 Compiling and Running a C Application with Xcode on
macOS 81
F02_DEIT8393_09_GE_TOC_final.fm Page 6 Wednesday, April 27, 2022 10:06 AM

6 Contents

1.10.3 Compiling and Running a C Application with GNU gcc


on Linux 84
1.10.4 Compiling and Running a C Application in a GCC Docker
Container Running Natively over Windows 10, macOS
or Linux 86
1.11 Internet, World Wide Web, the Cloud and IoT 87
1.11.1 The Internet: A Network of Networks 88
1.11.2 The World Wide Web: Making the Internet User-Friendly 89
1.11.3 The Cloud 89
1.11.4 The Internet of Things 90
1.12 Software Technologies 91
1.13 How Big Is Big Data? 91
1.13.1 Big-Data Analytics 97
1.13.2 Data Science and Big Data Are Making a Difference: Use Cases 98
1.14 Case Study—A Big-Data Mobile Application 99
1.15 AI—at the Intersection of Computer Science and Data Science 100

2 Intro to C Programming 107


2.1 Introduction 108
2.2 A Simple C Program: Printing a Line of Text 108
2.3 Another Simple C Program: Adding Two Integers 112
2.4 Memory Concepts 116
2.5 Arithmetic in C 117
2.6 Decision Making: Equality and Relational Operators 121
2.7 Secure C Programming 125

3 Structured Program Development 137


3.1 Introduction 138
3.2 Algorithms 138
3.3 Pseudocode 139
3.4 Control Structures 140
3.5 The if Selection Statement 142
3.6 The if…else Selection Statement 144
3.7 The while Iteration Statement 148
3.8 Formulating Algorithms Case Study 1: Counter-Controlled Iteration 149
3.9 Formulating Algorithms with Top-Down, Stepwise Refinement
Case Study 2: Sentinel-Controlled Iteration 151
3.10 Formulating Algorithms with Top-Down, Stepwise Refinement
Case Study 3: Nested Control Statements 158
3.11 Assignment Operators 162
3.12 Increment and Decrement Operators 163
3.13 Secure C Programming 166
F02_DEIT8393_09_GE_TOC_final.fm Page 7 Wednesday, April 27, 2022 10:06 AM

Contents 7

4 Program Control 185


4.1 Introduction 186
4.2 Iteration Essentials 186
4.3 Counter-Controlled Iteration 187
4.4 for Iteration Statement 188
4.5 Examples Using the for Statement 192
4.6 switch Multiple-Selection Statement 196
4.7 do…while Iteration Statement 202
4.8 break and continue Statements 203
4.9 Logical Operators 205
4.10 Confusing Equality (==) and Assignment (=) Operators 209
4.11 Structured-Programming Summary 210
4.12 Secure C Programming 215

5 Functions 231
5.1 Introduction 232
5.2 Modularizing Programs in C 232
5.3 Math Library Functions 234
5.4 Functions 235
5.5 Function Definitions 236
5.5.1 square Function 236
5.5.2 maximum Function 239
5.6 Function Prototypes: A Deeper Look 240
5.7 Function-Call Stack and Stack Frames 243
5.8 Headers 247
5.9 Passing Arguments by Value and by Reference 249
5.10 Random-Number Generation 249
5.11 Game Simulation Case Study: Rock, Paper, Scissors 254
5.12 Storage Classes 260
5.13 Scope Rules 262
5.14 Recursion 265
5.15 Example Using Recursion: Fibonacci Series 269
5.16 Recursion vs. Iteration 272
5.17 Secure C Programming—Secure Random-Number Generation 275
Random-Number Simulation Case Study: The Tortoise and the Hare 294

6 Arrays 297
6.1 Introduction 298
6.2 Arrays 298
6.3 Defining Arrays 300
6.4 Array Examples 300
DEIT8393_09_GE_Final.book Page 8 Tuesday, April 12, 2022 3:20 PM

8 Contents

6.4.1 Defining an Array and Using a Loop to Set the Array’s


Element Values 301
6.4.2 Initializing an Array in a Definition with an Initializer List 302
6.4.3 Specifying an Array’s Size with a Symbolic Constant and
Initializing Array Elements with Calculations 303
6.4.4 Summing the Elements of an Array 304
6.4.5 Using Arrays to Summarize Survey Results 304
6.4.6 Graphing Array Element Values with Bar Charts 306
6.4.7 Rolling a Die 60,000,000 Times and Summarizing
the Results in an Array 307
6.5 Using Character Arrays to Store and Manipulate Strings 309
6.5.1 Initializing a Character Array with a String 309
6.5.2 Initializing a Character Array with an Initializer List
of Characters 309
6.5.3 Accessing the Characters in a String 309
6.5.4 Inputting into a Character Array 309
6.5.5 Outputting a Character Array That Represents a String 310
6.5.6 Demonstrating Character Arrays 310
6.6 Static Local Arrays and Automatic Local Arrays 312
6.7 Passing Arrays to Functions 314
6.8 Sorting Arrays 318
6.9 Intro to Data Science Case Study: Survey Data Analysis 321
6.10 Searching Arrays 326
6.10.1 Searching an Array with Linear Search 326
6.10.2 Searching an Array with Binary Search 328
6.11 Multidimensional Arrays 332
6.11.1 Illustrating a Two-Dimensional Array 332
6.11.2 Initializing a Double-Subscripted Array 333
6.11.3 Setting the Elements in One Row 335
6.11.4 Totaling the Elements in a Two-Dimensional Array 335
6.11.5 Two-Dimensional Array Manipulations 335
6.12 Variable-Length Arrays 339
6.13 Secure C Programming 343

7 Pointers 363
7.1 Introduction 364
7.2 Pointer Variable Definitions and Initialization 365
7.3 Pointer Operators 366
7.4 Passing Arguments to Functions by Reference 369
7.5 Using the const Qualifier with Pointers 373
7.5.1 Converting a String to Uppercase Using a Non-Constant
Pointer to Non-Constant Data 374
F02_DEIT8393_09_GE_TOC_final.fm Page 9 Wednesday, April 27, 2022 10:06 AM

Contents 9

7.5.2 Printing a String One Character at a Time Using a


Non-Constant Pointer to Constant Data 374
7.5.3 Attempting to Modify a Constant Pointer to
Non-Constant Data 376
7.5.4 Attempting to Modify a Constant Pointer to Constant Data 377
7.6 Bubble Sort Using Pass-By-Reference 378
7.7 sizeof Operator 382
7.8 Pointer Expressions and Pointer Arithmetic 384
7.8.1 Pointer Arithmetic Operators 385
7.8.2 Aiming a Pointer at an Array 385
7.8.3 Adding an Integer to a Pointer 385
7.8.4 Subtracting an Integer from a Pointer 386
7.8.5 Incrementing and Decrementing a Pointer 386
7.8.6 Subtracting One Pointer from Another 386
7.8.7 Assigning Pointers to One Another 386
7.8.8 Pointer to void 386
7.8.9 Comparing Pointers 387
7.9 Relationship between Pointers and Arrays 387
7.9.1 Pointer/Offset Notation 387
7.9.2 Pointer/Subscript Notation 388
7.9.3 Cannot Modify an Array Name with Pointer Arithmetic 388
7.9.4 Demonstrating Pointer Subscripting and Offsets 388
7.9.5 String Copying with Arrays and Pointers 390
7.10 Arrays of Pointers 392
7.11 Random-Number Simulation Case Study: Card Shuffling and Dealing 393
7.12 Function Pointers 398
7.12.1 Sorting in Ascending or Descending Order 398
7.12.2 Using Function Pointers to Create a Menu-Driven System 401
7.13 Secure C Programming 403
Special Section: Building Your Own Computer as a Virtual Machine 417
Special Section—Embedded Systems Programming Case Study:
Robotics with the Webots Simulator 424

8 Characters and Strings 441


8.1 Introduction 442
8.2 Fundamentals of Strings and Characters 442
8.3 Character-Handling Library 444
8.3.1 Functions isdigit, isalpha, isalnum and isxdigit 445
8.3.2 Functions islower, isupper, tolower and toupper 447
8.3.3 Functions isspace, iscntrl, ispunct, isprint and isgraph 448
8.4 String-Conversion Functions 450
8.4.1 Function strtod 450
DEIT8393_09_GE_Final.book Page 10 Tuesday, April 12, 2022 3:20 PM

10 Contents

8.4.2 Function strtol 451


8.4.3 Function strtoul 452
8.5 Standard Input/Output Library Functions 453
8.5.1 Functions fgets and putchar 453
8.5.2 Function getchar 455
8.5.3 Function sprintf 455
8.5.4 Function sscanf 456
8.6 String-Manipulation Functions of the String-Handling Library 457
8.6.1 Functions strcpy and strncpy 458
8.6.2 Functions strcat and strncat 459
8.7 Comparison Functions of the String-Handling Library 460
8.8 Search Functions of the String-Handling Library 462
8.8.1 Function strchr 463
8.8.2 Function strcspn 464
8.8.3 Function strpbrk 464
8.8.4 Function strrchr 465
8.8.5 Function strspn 465
8.8.6 Function strstr 466
8.8.7 Function strtok 467
8.9 Memory Functions of the String-Handling Library 468
8.9.1 Function memcpy 469
8.9.2 Function memmove 470
8.9.3 Function memcmp 470
8.9.4 Function memchr 471
8.9.5 Function memset 471
8.10 Other Functions of the String-Handling Library 473
8.10.1 Function strerror 473
8.10.2 Function strlen 473
8.11 Secure C Programming 474
Pqyoaf X Nylfomigrob Qwbbfmh Mndogvk: Rboqlrut yua
Boklnxhmywex 488
Secure C Programming Case Study: Public-Key Cryptography 494

9 Formatted Input/Output 503


9.1 Introduction 504
9.2 Streams 504
9.3 Formatting Output with printf 505
9.4 Printing Integers 506
9.5 Printing Floating-Point Numbers 507
9.5.1 Conversion Specifiers e, E and f 508
9.5.2 Conversion Specifiers g and G 508
9.5.3 Demonstrating Floating-Point Conversion Specifiers 509
9.6 Printing Strings and Characters 510
DEIT8393_09_GE_Final.book Page 11 Tuesday, April 12, 2022 3:20 PM

Contents 11

9.7 Other Conversion Specifiers 511


9.8 Printing with Field Widths and Precision 512
9.8.1 Field Widths for Integers 512
9.8.2 Precisions for Integers, Floating-Point Numbers and Strings 513
9.8.3 Combining Field Widths and Precisions 514
9.9 printf Format Flags 515
9.9.1 Right- and Left-Alignment 515
9.9.2 Printing Positive and Negative Numbers with and without
the + Flag 516
9.9.3 Using the Space Flag 516
9.9.4 Using the # Flag 517
9.9.5 Using the 0 Flag 517
9.10 Printing Literals and Escape Sequences 518
9.11 Formatted Input with scanf 519
9.11.1 scanf Syntax 520
9.11.2 scanf Conversion Specifiers 520
9.11.3 Reading Integers 521
9.11.4 Reading Floating-Point Numbers 522
9.11.5 Reading Characters and Strings 522
9.11.6 Using Scan Sets 523
9.11.7 Using Field Widths 524
9.11.8 Skipping Characters in an Input Stream 525
9.12 Secure C Programming 526

10 Structures, Unions, Bit Manipulation and


Enumerations 535
10.1 Introduction 536
10.2 Structure Definitions 537
10.2.1 Self-Referential Structures 537
10.2.2 Defining Variables of Structure Types 538
10.2.3 Structure Tag Names 538
10.2.4 Operations That Can Be Performed on Structures 538
10.3 Initializing Structures 540
10.4 Accessing Structure Members with . and -> 540
10.5 Using Structures with Functions 542
10.6 typedef 542
10.7 Random-Number Simulation Case Study: High-Performance Card
Shuffling and Dealing 543
10.8 Unions 546
10.8.1 union Declarations 547
10.8.2 Allowed unions Operations 547
10.8.3 Initializing unions in Declarations 547
10.8.4 Demonstrating unions 548
DEIT8393_09_GE_Final.book Page 12 Tuesday, April 12, 2022 3:20 PM

12 Contents

10.9 Bitwise Operators 549


10.9.1 Displaying an Unsigned Integer’s Bits 550
10.9.2 Making Function displayBits More Generic and Portable 551
10.9.3 Using the Bitwise AND, Inclusive OR, Exclusive OR and
Complement Operators 552
10.9.4 Using the Bitwise Left- and Right-Shift Operators 555
10.9.5 Bitwise Assignment Operators 557
10.10 Bit Fields 558
10.10.1 Defining Bit Fields 558
10.10.2 Using Bit Fields to Represent a Card’s Face, Suit and Color 559
10.10.3 Unnamed Bit Fields 561
10.11 Enumeration Constants 561
10.12 Anonymous Structures and Unions 563
10.13 Secure C Programming 564
Special Section: Raylib Game-Programming Case Studies 574
Game-Programming Case Study Exercise: SpotOn Game 580
Game-Programming Case Study: Cannon Game 581
Visualization with raylib—Law of Large Numbers Animation 583
Case Study: The Tortoise and the Hare with raylib—
a Multimedia “Extravaganza” 585
Random-Number Simulation Case Study: High-Performance
Card Shuffling and Dealing with Card Images and raylib 587

11 File Processing 593


11.1 Introduction 594
11.2 Files and Streams 594
11.3 Creating a Sequential-Access File 596
11.3.1 Pointer to a FILE 597
11.3.2 Using fopen to Open a File 597
11.3.3 Using feof to Check for the End-of-File Indicator 597
11.3.4 Using fprintf to Write to a File 598
11.3.5 Using fclose to Close a File 598
11.3.6 File-Open Modes 599
11.4 Reading Data from a Sequential-Access File 601
11.4.1 Resetting the File Position Pointer 602
11.4.2 Credit Inquiry Program 602
11.5 Random-Access Files 606
11.6 Creating a Random-Access File 607
11.7 Writing Data Randomly to a Random-Access File 609
11.7.1 Positioning the File Position Pointer with fseek 611
11.7.2 Error Checking 612
11.8 Reading Data from a Random-Access File 612
DEIT8393_09_GE_Final.book Page 13 Tuesday, April 12, 2022 3:20 PM

Contents 13

11.9 Case Study: Transaction-Processing System 614


11.10 Secure C Programming 620
AI Case Study: Intro to NLP—Who Wrote Shakespeare’s Works? 630
AI/Data-Science Case Study—Machine Learning with GNU
Scientific Library 636
AI/Data-Science Case Study: Time Series and Simple
Linear Regression 642
Web Services and the Cloud Case Study—libcurl and
OpenWeatherMap 643

12 Data Structures 649


12.1 Introduction 650
12.2 Self-Referential Structures 651
12.3 Dynamic Memory Management 652
12.4 Linked Lists 653
12.4.1 Function insert 657
12.4.2 Function delete 659
12.4.3 Functions isEmpty and printList 661
12.5 Stacks 662
12.5.1 Function push 666
12.5.2 Function pop 667
12.5.3 Applications of Stacks 667
12.6 Queues 668
12.6.1 Function enqueue 673
12.6.2 Function dequeue 674
12.7 Trees 675
12.7.1 Function insertNode 678
12.7.2 Traversals: Functions inOrder, preOrder and postOrder 679
12.7.3 Duplicate Elimination 680
12.7.4 Binary Tree Search 680
12.7.5 Other Binary Tree Operations 680
12.8 Secure C Programming 681
Special Section: Systems Software Case Study—Building Your
Own Compiler 690

13 Computer-Science Thinking: Sorting Algorithms


and Big O 711
13.1 Introduction 712
13.2 Efficiency of Algorithms: Big O 713
13.2.1 O(1) Algorithms 713
13.2.2 O(n) Algorithms 713
13.2.3 O(n2) Algorithms 713
DEIT8393_09_GE_Final.book Page 14 Tuesday, April 12, 2022 3:20 PM

14 Contents

13.3 Selection Sort 714


13.3.1 Selection Sort Implementation 715
13.3.2 Efficiency of Selection Sort 718
13.4 Insertion Sort 719
13.4.1 Insertion Sort Implementation 719
13.4.2 Efficiency of Insertion Sort 722
13.5 Case Study: Visualizing the High-Performance Merge Sort 722
13.5.1 Merge Sort Implementation 723
13.5.2 Efficiency of Merge Sort 727
13.5.3 Summarizing Various Algorithms’ Big O Notations 728

14 Preprocessor 735
14.1 Introduction 736
14.2 #include Preprocessor Directive 737
14.3 #define Preprocessor Directive: Symbolic Constants 737
14.4 #define Preprocessor Directive: Macros 738
14.4.1 Macro with One Argument 739
14.4.2 Macro with Two Arguments 740
14.4.3 Macro Continuation Character 740
14.4.4 #undef Preprocessor Directive 740
14.4.5 Standard-Library Macros 740
14.4.6 Do Not Place Expressions with Side Effects in Macros 741
14.5 Conditional Compilation 741
14.5.1 #if…#endif Preprocessor Directive 741
14.5.2 Commenting Out Blocks of Code with #if…#endif 742
14.5.3 Conditionally Compiling Debug Code 742
14.6 #error and #pragma Preprocessor Directives 743
14.7 # and ## Operators 744
14.8 Line Numbers 744
14.9 Predefined Symbolic Constants 745
14.10 Assertions 745
14.11 Secure C Programming 746

15 Other Topics 753


15.1 Introduction 754
15.2 Variable-Length Argument Lists 754
15.3 Using Command-Line Arguments 756
15.4 Compiling Multiple-Source-File Programs 758
15.4.1 extern Declarations for Global Variables in Other Files 758
15.4.2 Function Prototypes 759
15.4.3 Restricting Scope with static 759
15.5 Program Termination with exit and atexit 760
DEIT8393_09_GE_Final.book Page 15 Tuesday, April 12, 2022 3:20 PM

Contents 15

15.6 Suffixes for Integer and Floating-Point Literals 762


15.7 Signal Handling 762
15.8 Dynamic Memory Allocation Functions calloc and realloc 765
15.9 goto: Unconditional Branching 767

A Operator Precedence Chart 773

B ASCII Character Set 775

C Multithreading/Multicore and
Other C18/C11/C99 Topics 777
C.1 Introduction 778
C.2 Headers Added in C99 779
C.3 Designated Initializers and Compound Literals 779
C.4 Type bool 781
C.5 Complex Numbers 782
C.6 Macros with Variable-Length Argument Lists 784
C.7 Other C99 Features 784
C.7.1 Compiler Minimum Resource Limits 784
C.7.2 The restrict Keyword 784
C.7.3 Reliable Integer Division 785
C.7.4 Flexible Array Members 785
C.7.5 Type-Generic Math 786
C.7.6 Inline Functions 786
C.7.7 __func__ Predefined Identifier 786
C.7.8 va_copy Macro 787
C.8 C11/C18 Features 787
C.8.1 C11/C18 Headers 787
C.8.2 quick_exit Function 787
C.8.3 Unicode® Support 787
C.8.4 _Noreturn Function Specifier 788
C.8.5 Type-Generic Expressions 788
C.8.6 Annex L: Analyzability and Undefined Behavior 788
C.8.7 Memory Alignment Control 789
C.8.8 Static Assertions 789
C.8.9 Floating-Point Types 789
C.9 Case Study: Performance with Multithreading and Multicore Systems 790
C.9.1 Example: Sequential Execution of Two
Compute-Intensive Tasks 793
C.9.2 Example: Multithreaded Execution of Two
Compute-Intensive Tasks 795
C.9.3 Other Multithreading Features 799
DEIT8393_09_GE_Final.book Page 16 Tuesday, April 12, 2022 3:20 PM

16 Contents

D Intro to Object-Oriented Programming Concepts 801


D.1 Introduction 801
D.2 Object-Oriented Programming Languages 801
D.3 Automobile as an Object 802
D.4 Methods and Classes 802
D.5 Instantiation 802
D.6 Reuse 802
D.7 Messages and Method Calls 803
D.8 Attributes and Instance Variables 803
D.9 Inheritance 803
D.10 Object-Oriented Analysis and Design (OOAD) 804

Index 805

Online Appendices
E Number Systems

F Using the Visual Studio Debugger

G Using the GNU gdb Debugger

H Using the Xcode Debugger


F03_DEIT8393_09_GE_PREF_final.fm Page 17 Tuesday, April 19, 2022 12:20 PM

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://www.pearsonglobaleditions.com
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/.
F03_DEIT8393_09_GE_PREF_final.fm Page 18 Tuesday, April 19, 2022 12:20 PM

18 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.
F03_DEIT8393_09_GE_PREF_final.fm Page 19 Tuesday, April 19, 2022 12:20 PM

New and Updated Features in This Ninth Edition 19

• 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-
F03_DEIT8393_09_GE_PREF_final.fm Page 20 Tuesday, April 19, 2022 12:20 PM

20 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
F03_DEIT8393_09_GE_PREF_final.fm Page 21 Tuesday, April 19, 2022 12:20 PM

A Tour of the Book 21

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
• Game Simulation—Rock, Paper, Scissors
• 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.
F03_DEIT8393_09_GE_PREF_final.fm Page 22 Tuesday, April 19, 2022 12:20 PM

22 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.
F03_DEIT8393_09_GE_PREF_final.fm Page 23 Tuesday, April 19, 2022 12:20 PM

A Tour of the Book 23

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—Rock, Paper, Scissors, 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.
F03_DEIT8393_09_GE_PREF_final.fm Page 24 Tuesday, April 19, 2022 12:20 PM

24 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.
F03_DEIT8393_09_GE_PREF_final.fm Page 25 Tuesday, April 19, 2022 12:20 PM

A Tour of the Book 25

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
F03_DEIT8393_09_GE_PREF_final.fm Page 26 Tuesday, April 19, 2022 12:20 PM

26 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.

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.
F03_DEIT8393_09_GE_PREF_final.fm Page 27 Tuesday, April 19, 2022 12:20 PM

Key Features 27

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.”
F03_DEIT8393_09_GE_PREF_final.fm Page 28 Tuesday, April 19, 2022 12:20 PM

28 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 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, program-
ming computer games, programming robotics simulations 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.
F03_DEIT8393_09_GE_PREF_final.fm Page 29 Tuesday, April 19, 2022 12:20 PM

Key Features 29

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.
F03_DEIT8393_09_GE_PREF_final.fm Page 30 Tuesday, April 19, 2022 12:20 PM

30 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 Novem-
ber 14, 2020. https://techcrunch.com/2018/11/14/amazon-echo-recordings-judge-
murder-case/.
F03_DEIT8393_09_GE_PREF_final.fm Page 31 Tuesday, April 19, 2022 12:20 PM

Key Features 31

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.
F03_DEIT8393_09_GE_PREF_final.fm Page 32 Tuesday, April 19, 2022 12:20 PM

32 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—Game Simulation: Rock, Paper, Scissors
In this case study, you’ll use random-number generation and simulation techniques
to implement the popular hand game called rock, paper, scissors.
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.
F03_DEIT8393_09_GE_PREF_final.fm Page 33 Tuesday, April 19, 2022 12:20 PM

A Case Studies Tour 33

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.
F03_DEIT8393_09_GE_PREF_final.fm Page 34 Tuesday, April 19, 2022 12:20 PM

34 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
F03_DEIT8393_09_GE_PREF_final.fm Page 35 Tuesday, April 19, 2022 12:20 PM

A Case Studies Tour 35

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.
F03_DEIT8393_09_GE_PREF_final.fm Page 36 Tuesday, April 19, 2022 12:20 PM

36 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-
intensive calculations in sequence. The other executes the same compute-intensive
calculations in parallel threads. We time each calculation and determine the total
execution time in each program. The program outputs show the dramatic time
improvement when the multithreaded version executes on a multicore system.

26. “ProgrammableWeb.” Accessed November 22, 2020. https://programmableweb.com/.


F03_DEIT8393_09_GE_PREF_final.fm Page 37 Tuesday, April 19, 2022 12:20 PM

Secure C Programming 37

Secure C Programming
The people responsible for the ACM/IEEE curricula guidelines emphasize the impor-
tance of security—it’s mentioned 395 times in the Computer Science Curricula
document and 235 times in the Information Technology Curricula document. In
2017, the ACM/IEEE published its Cybersecurity Curricula, which focuses on secu-
rity courses and security throughout the other computing curricula. That document
mentions security 865 times.
Chapters 2–12 and 14 each end with a Secure C Programming section. These are
designed to raise awareness among novice programming students of security issues that
could cause breaches. These sections present some key issues and techniques and pro-
vide links and references so you can continue learning. Our goal is to encourage you to
start thinking about security issues, even if this is your first programming course.
Experience has shown that it’s challenging to build industrial-strength systems
that stand up to attacks. Today, via the Internet, such attacks can be instantaneous
and global in scope. Software vulnerabilities often come from simple programming
issues. Building security into software from the start of the development cycle can sig-
nificantly reduce vulnerabilities.
The CERT Division of Carnegie Mellon’s Software Engineering Institute
https://www.sei.cmu.edu/about/divisions/cert/index.cfm
was created to analyze and respond promptly to attacks. They publish and promote
secure coding standards to help C programmers and others implement industrial-
strength systems that avoid the programming practices that leave systems vulnerable
to attacks. Their standards evolve as new security issues arise.
We explain how to upgrade your code (as appropriate for an introductory book)
to conform to the latest secure C coding recommendations. If you’re building C sys-
tems in industry, consider reading the SEI CERT C Coding Standard rules at
https://wiki.sei.cmu.edu/confluence/display/c

Also, consider reading Secure Coding in C and C++, 2/e by Robert Seacord
(Addison-Wesley Professional, 2013). Mr. Seacord, a technical reviewer for an earlier
edition of this book, provided specific recommendations on each of our Secure C
Programming sections. At the time, he was the Secure Coding Manager at CERT and
an adjunct professor at Carnegie Mellon’s School of Computer Science. He is now a
Technical Director at NCC Group (an IT Security company).
Our Secure C Programming sections discuss many important topics, including:
• Testing for Arithmetic Overflows
• The More Secure Functions in the C Standard’s Annex K
• The Importance of Checking the Status Information Returned by Standard-
Library Functions
• Range Checking
• Secure Random-Number Generation
F03_DEIT8393_09_GE_PREF_final.fm Page 38 Tuesday, April 19, 2022 12:20 PM

38 Preface

• Array Bounds Checking


• Preventing Buffer Overflows
• Input Validation
• Avoiding Undefined Behaviors
• Choosing Functions That Return Status Information vs. Using Similar Func-
tions That Do Not
• Ensuring That Pointers Are Always Null or Contain Valid Addresses
• Using C Functions vs. Using Preprocessor Macros, and More.

Computing and Data Science Curricula


This book is designed for courses that adhere to one or more of the following ACM/
IEEE CS-and-related curriculum documents:
• CC2020: Paradigms for Future Computing Curricula (cc2020.net),27
• Computer Science Curricula 2013,28
• Information Technology Curricula 2017,29
• Cybersecurity Curricula 2017.30

Computing Curricula
• According to “CC2020: A Vision on Computing Curricula,”31 the curricu-
lum “needs to be reviewed and updated to include the new and emerging areas
of computing such as cybersecurity and data science.”32 (See “Data Science
Overlaps with Computer Science” below and this Preface’s earlier “Secure C
Programming” section).
• Data science includes key topics (besides statistics and general-purpose pro-
gramming) such as machine learning, deep learning, natural language process-
ing, speech synthesis and recognition, and others that are classic artificial
intelligence (AI) topics—and hence CS topics as well. We cover machine
learning and natural language processing in the case studies.

https://cc2020.nsparc.ms-
27. “Computing Curricula 2020.” Accessed November 22, 2020.
state.edu/wp-content/uploads/2020/11/Computing-Curricula-Report.pdf.
28. ACM/IEEE (Assoc. Comput. Mach./Inst. Electr. Electron. Eng.). 2013. Computer Science Curric-
ula 2013: Curriculum Guidelines for Undergraduate Degree Programs in Computer Science (New
York: ACM), http://ai.stanford.edu/users/sahami/CS2013/final-draft/CS2013-final-
report.pdf.
29. Information Technology Curricula 2017, http://www.acm.org/binaries/content/assets/
education/it2017.pdf.
30. Cybersecurity Curricula 2017, https://cybered.hosting.acm.org/wp-content/uploads/
2018/02/newcover_csec2017.pdf.
31. A. Clear, A. Parrish, G. van der Veer and M. Zhang, “CC2020: A Vision on Computing Curric-
ula,” https://dl.acm.org/citation.cfm?id=3017690.
32. http://delivery.acm.org/10.1145/3020000/3017690/p647-clear.pdf.
F03_DEIT8393_09_GE_PREF_final.fm Page 39 Tuesday, April 19, 2022 12:20 PM

Data Science Overlaps with Computer Science 39

Data Science Overlaps with Computer Science33


The undergraduate data science curriculum proposal34 includes algorithm develop-
ment, programming, computational thinking, data structures, database, mathematics,
statistical thinking, machine learning, data science and more—a significant overlap
with computer science, especially given that the data science courses include some key
AI topics. Even though ours is a C programming textbook, we work data science topics
into various examples, exercises, projects and case studies.

Key Points from the Data Science Curriculum Proposal


This section calls out some key points from the data science undergraduate curricu-
lum proposal and its detailed course descriptions appendix.35 Each of the following
items is covered in C How to Program, 9/e:
• Learn programming fundamentals commonly presented in computer sci-
ence courses, including working with data structures.
• Be able to solve problems by creating algorithms.
• Work with procedural programming.
• Explore concepts via simulations.
• Use development environments (we tested all our code on Microsft Visual
C++, Apple Xcode, the GNU command-line gcc compiler on Linux and in
the GNU Compiler Collection Docker container).
• Work with real-world data in practical case studies and projects—such as
William Shakespeare’s Romeo and Juliet and Christopher Marlowe’s Edward
the Second from Project Gutenberg (https://www.gutenberg.org/), and 126
years of New York City average January temperatures.
• Create data visualizations.
• Communicate reproducible results. (Docker plays an important role in
that—see the next page.)
• Work with existing software and cloud-based tools.
• Work with high-performance tools, such as C’s multithreading libraries.
• Focus on data’s ethics, security, privacy and reproducibility issues.

33. This section is intended primarily for data science instructors. Given that the emerging 2020
Computing Curricula for computer science and related disciplines is likely to include some key
data science topics, this section includes important information for computer science instruc-
tors as well.
34. “Curriculum Guidelines for Undergraduate Programs in Data Science,” http://www.annual-
reviews.org/doi/full/10.1146/annurev-statistics-060116-053930.
35. “Appendix—Detailed Courses for a Proposed Data Science Major,” http://www.annualre-
views.org/doi/suppl/10.1146/annurev-statistics-060116-053930/suppl_file/
st04_de_veaux_supmat.pdf.
F03_DEIT8393_09_GE_PREF_final.fm Page 40 Tuesday, April 19, 2022 12:20 PM

40 Preface

Get the Code Examples and Install the Software


For your convenience, we provide the book’s examples in C source-code (.c) files for
use with integrated development environments (IDEs) and command-line compilers.
See the Before You Begin section that follows the Preface for software installation
details. See the Chapter 1 test-drives for information on running the book’s code
examples. If you encounter a problem, you can reach us at [email protected] or via
the contact form at https://deitel.com/contact-us.

Docker
We introduce Docker—a tool for packaging software into containers that bundle every-
thing required to execute that software conveniently, reproducibly and portably across
platforms. Some software packages you’ll use require complicated setup and configura-
tion. For many of these, you can download free preexisting Docker containers that help
you avoid complex installation issues. You can simply execute software locally on your
desktop or notebook computers, making Docker a great way to help you get started with
new technologies quickly, conveniently and economically. For your convenience, we
show how to install and execute a Docker container that’s pre-configured with the GNU
Compiler Collection (GCC), which includes the gcc compiler. This can run in Docker
on Windows, macOS and Linux. It’s particularly useful for people using Visual C++,
which can compile C code but is not 100% compliant with the latest C standard.
Docker also helps with reproducibility. Custom Docker containers can be con-
figured with every piece of software and every library you use. This would enable oth-
ers to recreate the environment you used, then reproduce your work, and will help
you reproduce your own results. Reproducibility is especially important in the sci-
ences and medicine—for example, when researchers want to prove and extend the
work in published articles.

Flipped Classrooms
Many instructors use “flipped classrooms.”36,37 Students learn the content on their
own before coming to class, and class time is used for tasks such as hands-on coding,
working in groups and discussions. Our book and supplements also are appropriate
for flipped classrooms:
• We use Grammarly to control the book’s reading level to help ensure it’s
appropriate for students learning on their own.
• In parallel with reading the text, students should execute the 147 live-code C
examples and do the 350+ integrated Self Check exercises, which are imme-
diately followed by their answers. These encourage active participation by

36. https://en.wikipedia.org/wiki/Flipped_classroom.
37. https://www.edsurge.com/news/2018-05-24-a-case-for-flipping-learning-without-
videos.
F03_DEIT8393_09_GE_PREF_final.fm Page 41 Tuesday, April 19, 2022 12:20 PM

Teaching Approach 41

the student. They learn the content in small pieces using a “read-a-little, do-
a-little, test-a-little” approach—appropriate for a flipped classroom’s active,
self-paced, hands-on learning. Students are encouraged to modify the code
and see the effects of their changes.
• We provide 445 exercises and projects, which students can work on at home
and/or in class. Many of the exercises are at an elementary or intermediate
level that students should be able to do independently. And many are appro-
priate for group projects on which students can collaborate in class.
• Section-by-section detailed chapter summaries with bolded key terms help
students quickly review the material.
• In the book’s extensive index, the defining occurrences of key terms are high-
lighted with a bold page number, making it easy for students to find the intro-
ductions to the topics they’re studying. This facilitates the outside-the-
classroom learning experience of the flipped classroom.
A key aspect of flipped classrooms is getting your questions answered when you’re
working on your own. See the “Getting Your Questions Answered” section later in
this Preface for details. And you can always reach us at [email protected].

Teaching Approach
This title contains a rich collection of examples, exercises, projects and case studies
drawn from many fields. Students solve interesting, real-world problems working
with real-world data. The book concentrates on the principles of good software
engineering and stresses program clarity.

Using Fonts for Emphasis


Refer to this section for font style usage. We place the key terms and the index’s page
reference for each defining occurrence in bold text for easier reference. C code uses a
fixed-width font (e.g., x = 5). We place on-screen components in the bold Helvetica
font (e.g., the File menu).

Syntax Shading
For readability, we syntax shade all the code. Our syntax-coloring conventions are as
follows:
comments appear in gray
keywords appear in bold blue
constants and literal values appear in bold light blue
all other code appears in black

Objectives and Outline


Each chapter begins with objectives that tell you what to expect and give you an oppor-
tunity, after reading the chapter, to determine whether it has met the intended goals.
The chapter outline enables students to approach the material in a top-down fashion.
F03_DEIT8393_09_GE_PREF_final.fm Page 42 Tuesday, April 19, 2022 12:20 PM

42 Preface

Examples
The book’s 147 live-code examples contain thousands of lines of proven code.

Tables and Illustrations


Abundant tables and line drawings are included.

Programming Wisdom
We integrate into the text discussions programming wisdom and mistakes we’ve
accumulated from our combined nine decades of programming and teaching experi-
ence, and from the scores of academics and industry professionals who have reviewed
the nine editions of this book over the past 29 years, including:
• Good programming practices and preferred C idioms that help you produce
clearer, more understandable and more maintainable programs.
ERR • Common programming errors to reduce the likelihood that you’ll make them.
• Error-prevention tips with suggestions for exposing bugs and removing them
from your programs. Many of these tips describe techniques for preventing
bugs from getting into your programs in the first place.
PERF • Performance tips highlighting opportunities to make your programs run
faster or minimize the amount of memory they occupy.
SE • Software engineering observations highlighting architectural and design
issues for proper software construction, especially for larger systems.
SEC • Security best practices that will help you strengthen your programs against
attacks.
Section-By-Section Chapter Summaries
To help students quickly review the material, each chapter ends with a detailed bullet-
list summary with bolded key terms and, for most, bold page references to their defin-
ing occurrences.

Free Software Used in the Book


The Before You Begin section following this Preface discusses installing the software
you’ll need to work with our examples. We tested all the examples using the following
popular free compilers:
• GNU gcc on Linux—which is already installed on most Linux systems and
can be installed on macOS and Windows systems.
• Microsoft’s Visual Studio Community Edition on Windows.
• Apple’s Clang compiler in Xcode on macOS.
GNU gcc in Docker
We also demonstrate GNU gcc in a Docker container—ideal for instructors who
want all their students to use GNU gcc, regardless of their operating system. This
F03_DEIT8393_09_GE_PREF_final.fm Page 43 Tuesday, April 19, 2022 12:20 PM

C Documentation 43

gives Visual C++ users a true C compiler option, since Visual C++ is not 100% com-
pliant with the latest C standard.
Windows Subsystem for Linux
The Windows Subsystem for Linux (WSL) enables Windows users to install Linux
and run it inside Windows. We provide a link to Microsoft’s step-by-step instructions
for setting up WSL and installing a Linux distribution. This provides yet another
option for Windows users to access the GNU gcc compiler.

C Documentation
You’ll find the following documentation helpful as you work through the book:
• The GNU C Standard Library Reference Manual:
https://www.gnu.org/software/libc/manual/pdf/libc.pdf
• C Language Reference at cppreference.com
https://en.cppreference.com/w/c
• C Standard Library Headers at cppreference.com
https://en.cppreference.com/w/c/header
• Microsoft’s C Language Reference:
https://docs.microsoft.com/en-us/cpp/c-language/c-language-
reference

Getting Your Questions Answered


Online forums enable you to interact with other C programmers worldwide and get
your questions answered. Popular C and general programming online forums include:
• https://stackoverflow.com
• https://www.reddit.com/r/C_Programming/
• https://groups.google.com/forum/#!forum/comp.lang.C
• https://cboard.cprogramming.com/c-programming/
• https://www.dreamincode.net/forums/forum/15-c-and-c/
For a list of other sites, see
https://www.geeksforgeeks.org/stuck-in-programming-get-the-
solution-from-these-10-best-websites/
Also, vendors often provide forums for their tools and libraries. Many libraries are
managed and maintained at github.com. Some library maintainers provide support
through the Issues tab on a given library’s GitHub page.
F03_DEIT8393_09_GE_PREF_final.fm Page 44 Tuesday, April 19, 2022 12:20 PM

44 Preface

Student and Instructor Supplements


The following supplements are available to students and instructors.
Web-Based Materials
To get the most out of your learning experience, you should execute each code example
in parallel with reading the corresponding discussion. On the book’s web page at
https://www.pearsonglobaleditions.com
we provide the following resources:
• Links to the downloadable C source code (.c files) for the book’s code exam-
ples and exercises that include code in the exercise description.
• Links to our Getting Started videos showing how to use the compilers and
code examples. We also introduce these tools in Chapter 1.
• Blog posts—https://deitel.com/blog.
• “Using the Debugger” appendices for the Visual Studio, GNU gdb and
Xcode debuggers.
For more information about downloading the examples and setting up your C devel-
opment environment, see the Before You Begin section that follows this Preface.
Instructor Supplements
Pearson Education’s IRC (Instructor Resource Center)
http://www.pearsonglobaleditions.com
provides qualified instructors access to the following supplements for this book:
• PowerPoint Slides.
• Instructor Solutions Manual with solutions to most of the exercises. Solutions
are not provided for “project” and “research” exercises. Before assigning a par-
ticular exercise for homework, instructors should check the IRC to ensure
that the solution is available.
• Test Item File with four-part multiple-choice, short-answer questions and
answers. You may also request from your Pearson representative versions of
the Test Item File for use with popular automated assessment tools.
Please do not write to us requesting access to the Pearson Instructor’s Resource
Center (IRC). Access to the instructor supplements and exercise solutions on the IRC
is strictly limited by our publisher to college instructors who adopt the book for their
classes. Instructors may obtain access through their Pearson representatives. If you’re
not a registered faculty member, contact your Pearson representative.
Instructors can request examination copies of Deitel books from their Pearson
representatives.

Communicating with the Authors


For questions, instructor syllabus assistance or to report an error, we’re easy to reach at
[email protected]
Another random document with
no related content on Scribd:
Tuuli on tuima, ankarat aallot,
Ruuhet on rannalla pienoiset;
Ruuhet on aivan pienoiset,
Kultaseni sormet on hienoiset.

Oi, älä lähde aaltojen valtaan!


Aallot ne sun pian pettäisi.
Ei mua murhe heittäisi,
Ennen kuin mun multakin peittäisi.
KULTASENI

(Kansan-laulu)

Minun kultan' kaunis on, sen


suu kun auran kukka;
Silmat on sen siniset
keltanen sen tukka.

Älä sure sorja neitto,


vaikka toisen orja;
Kohta kuluu kuusi vuotta (1),
kyllä sinun korjaan.

(1) Tästä näkyy, että Suomalaisen orjalla oli sama oikeus kun
hebrealaisenkin. Hän sai kuuden palvelus-vuoden perästä lähteä
pois seitsemäntenä, vapaana lunastamata 2 Mos. 21:2.
KULTAANSA SUREWA

(Kansan-laulu)

Itkettää ja surettaa ja
huoleks' tahtoo tulla,
Kuin on muilla kultasensa
eikä ole mulla.

Kultani on kaukana ja
kaukana se kukkuu;
Yksin täytyy maata mennä,
yksin täytyy nukkuu.

Kultani on kaukana, niin


kauas taisi mennä,
Ettei sinne pienet linnut
ijässänsä lennä.

Oi, jos pieni lintunenkin


sanoman nyt toisi,
Suru menis mielestäni,
sydän hyvin voisi.
Lennä, lennä lintu raukka,
puhu kuullakseni! –
Kävitköstä kullan maalla,
näitkö kultaseni?

Sano, kuinka kullan maalla


aamu armas koitti;
Ilossako elettiin, vai
suruko he voitti.

Mitä näit sä muutakin, ja


näitköstä senkin,
Jos ne oli terveena ja
kulta liiatenkin.

Tule kulta tälle maalle,


tule poika kulta,
Ett'ei rientäis turhaan tämä
ikä nuori multa.
TURWATON

(Kansan-laulu) (1)

Onneton olin minä ollessani,


Onneton tähän kylään tullessani;

Onnettomaksi olen minä luotu,


Ei ole minulle ilo-päivää suotu.

Ei ole turvaa siellä eikä täällä,


Enenpää kuin linnulla lentonsa päällä.

Maalima minua nyt paljokin vaivaa,


Kuoppia teilleni eteeni kaivaa.

Ystäväni myöskin on ynsiäksi tullut,


Kuin hän on maailmalta juttuja kuullut.

Kuuleppas kultani, vielä sana yksi:


Kuinkahan näin tulin minä hyljätyksi?

Kuka sinun öksytti rakkauden tiellä?


Tule, tule kertakin luokseni vielä!
Muistakkos muinen kun marjassa käytiin,
Ahosilla istuttiin ja leikkiä lyötiin?

Päivä se paisti, ja pienet kukat loisti;


Kukatkin ne ketosilla iloamme toisti.

Linnut ne laulelivat metsien päällä;


Meistä he lauloivat siellä ja täällä.

Ei ole ajat enää, niinkun olit ennen,


Entiset ajat ovat olleet ja menneet.

Entinen oma kulta ei enää hoida;


Niin se mun heitti kun pienen linnun-pojan.

Toivoni raukesi, meni juuri tyhjään,


Ei ole mulla nyt ilo-päivää yhtään.

Enkä mä itselleni näin luullu käyvän;


Ikäväni kestää nyt kuolema-päivään.

Olen niinkun kyyhkynen vierahalla maalla,


Lentävä lintunen taivahan alla.

Olen niinkuin oksalla varpunen pieni,


En tiedä kuhun otan matkan ja tieni.

Nuoruus-ikä rientää ja aikani kulkee;


Jopa noista vaivoista väsymyskin tulee.

Päiväni päätyy ja elämäni katkee,


Multa se murheeni peittää ja kätkee.

[On enemmiten yhtäläinen kuin Kantelettaressakin.]


SUOSIO

Suosio on soma
Onnen siemen oma,
Josta kasvu kaunis ilmestyy;
Sillä suloisella
Levon laitumella
Kaikki meille hyvin menestyy.

Sydän siivollinen,
Rinta riemullinen
Sulattaavat mielen suosioon;
Mutta viha, vaino,
Kateuskin kaino
Jouduttavat järjen turmioon.

Karhu kontiolla
Woipi vielä olla
Luonto kauhiampi lausuttaa,
Kuin on kulkevalla
Wainon vallan alla,
Joka pahan sisun paisuttaa.
Tunnoton ja tuima,
Päästä hullu, huima
Siis on suotta nurja sovintoon;
Sillä kukin kurja,
Hirmun henki, hurja
Waipunut on itse vahinkoon.

J. Juteini
LEIWOSELLE

Ilon ääni ihanainen


Intohoni ilmestyi,
Kuin tuo lintu laulavainen
Laksohimme lähestyi.

Katsos! kuinka korkialla


Lentelee ja laulelee;
Lempeällä laulamalla
Korkehinta kiittelee.

Koska ensin äänes kuulin,


Wielä varsin nuorena,
Wäinämöisen soitoks' luulin,
Kevähänä kauniina.

Älä väsy veisaamasta!


Korvani sua kaipaavat;
Älä lakkaa laulamasta!
Silmäni sua seuraavat.

Laula, laula lintuseni,


Lennä ylös pilvihin
Kantamahan kiitokseni
Luojan tykö taivaisiin.

Terve sieltä tultuasi


Lohduttamaan luontooni!
Sieltä alas astuissasi
Ilahuttaan intooni!
KIILTO-MATO

Kiilto-mato kukkasissa
Loisti hiljasuudesaan
Yli kedon, tienohissa,
Tietämätön loistostaan.

Sulosesti tätä tähti


Katsoi korkeudestaan.
Kätköstänsä kärme lähti
Myrkkyänsä valamaan.

Sääli madon surkeutta!


Miks’ hän syyttä surmattiin?
Syyttä! sanoi kärme, mutta
Miksikäs hän loisti niin?
LÄHTEELLÄ

Ruotsinkielisestä: "Jag sitter källa vid din rand" (1).

Sua, lähe kaunis, katselen


Likellä vettesi,
Kuin pilven varjot vaeltavat
Kuvastimessasi (2).

Kah tuoll’ on pilvi loistava,


Ihana, kaunoinen;
Jo lähti pois pakenemaan —
Hyvästi varjonen!

Taas tuossa toinen kullallaan


Kuvoaa taivahan;
Se ei pitemp’ – iällinen
Jo lähti matkahan.

Kah vielä muuan (3) hirviä


Hias kulullehen;
Woi siirtyisitkö sievemmin
Jälestä toisien!
Wain näitä katsellessani
Mä muistan mieltäni,
Kuin monta kullan loistoa
Jo siirtyi siltäki.

Kuin pilvet paksut, synkiät,


Sitäi’ pimittivät,
Yhtäkkiähän nousivat,
Hitaasti lähtivät.

Waan jospa kuinkin kulkivat,


Ne eivät outoja:
Ne tyhjiä kuvaamia
Ja pilven varjoja.

Ne mieli raukan kuitenki


Moneksi muuttavat;
Woi koskastapa varjojen
Walehet loppuvat!

E. Lönnrot

(1) Wähän toisellainen on tämä laulu "Maamiehen Ystävässä"


N:o 15, v. 1844.
(2) Peilissäsi.
(3) Muutama, joku, eräs.
JOUTSEN

Ruotsinkielisestä: "Från molnens purpurstänka rand" (1).

Kesäisen illan kullasta


Tuo joutsen tultuaan,
Joen lahelle laskihen,
Ja loihen (2) laulamaan.

Suloa Suomen lauloi hän,


Kesiä pohjolan,
Kuin halkiöisin aurinko
Walaisee maailman.

Kuin varjopuien suojassa


On hetket herttaiset,
Ja aallot uia armahat,
Ja rannat rauhaiset.

Ja kuin suloista siellä on


Syleillä kultoa,
Ja kuinka vilppi, viekkaus,
Siell’ uppo (3) outoja.
Näin souti salmi salmelle
Se joutsen joikuen (4),
Ja kultansa kohattua
Syleili lausuen:

”Wähänpä tuosta, kuinka jo


Ikäni määrän sain –
Olen uinut pohjan aalloilla,
Syleillyt kultoain”.

E. Lönnrot

(1) Toisellainen on tämän laulun käännös "Oulun Wiikko-


Sanomissa"
N:o 5, v. 1834, ja toisellainen "Maamiehen Ystävässä" N:o 33,
v. 1844.
(2) Loi itsensä, rupesi.
(3) Peräti, varsin.
(4) Yksiäänisesti laulaen.
MIES

Mies on maassa oivallinen,


Waivoissakin voimallinen,
Koska konna värisee,
Waaroissaansa vapisee.

Mies on viisas vahingossa,


Tuskan alla, turmioissa;
Onni häntä hyödyttää,
Joka pahan pyörryttää.

Mies ei mieli hoiperella,


Eikä huoli huikennella,
Mutta missä tarvitaan,
Siellä miestä mainitaan.

Tammesta on miehen tahto,


Waan ei höllä, niin kuin vahto,
Walmis töitä täyttämään,
Oikein onnen käyttämään.

Tutkittaissa tuntoansa,
Taikka muuta menoansa,
Miehen tavat tunnetaan,
Joilla arvo ansaitaan.

Miehen jalon, järjellisen,


Retkillänsä rehellisen,
Tie on tietty kunniaan
Avun kautta armiaan.

J. Juteini
TALON-POJAN LAULU

Nuotti: "Ecce novum gaudium" etc.

Talon-poika, taitava
Elon etsinnöissä,
Aina olen alkava
Päivät pellon töissä;
Näissä voiman näytän,
Kaikki hyvin käytän,
Aina työni täytän,
Urhollisena.

Ei omalla pellolla
Aura paljo paina,
Mies on itse ilolla
Ahkera siell’ aina.
Waimo, kuva valon,
Ompi turva talon,
Äiti joukon jalon
Toimellisena.
Tämä sääty suuri on,
Suuri Suomen kansa,
Eikä ole osaton
Perhe pellollansa;
Itse täytän aitan,
Leivän paksun laitan,
Toisellekkin taitan
Riemullisena.

Juhla jalo johdattaa


Kestin keskellemme,
Olu-kannu kuljettaa
Riemun rinnoillemme.
Työ on alku elon,
Itse lähde ilon,
Juotavankin jalon
Herkullisena.

Tavara on tallella
Tämän säädyn tiellä;
Siis on syytä suojella
Wapautta vielä;
Sydämellä, suulla
Esivaltaa kuulla,
Hyvää muista luulla,
Alinomati.

J. Juteini
NUOREN-MIEHEN LAULU

(Ruotsinkielisen johdosta.)

Jos vaikka kaikki järjestänsä


Kerskaisi naima-säädystänsä,
Niin nuoren-miehen elosta,
Sen riemuista ja ilosta,
Nyt laualan ihastuksissani,
Sen aina pitäin muistossani,
Ett' nuoren-miehen paras on.

Kun mies on nuori, naimatonna,


Niin saa hän olla murheetonna
Ja elää huvituksissa,
Waan nainut huokauksissa,
Kateen ja häijyn vaimon kanssa
Hän aina pitää muistossansa,
Ett' nuoren-miehen paras on.

On kyllä naima-sääty kanssa


Myös hohtavainen muodoltansa
Ja loistavasta arvossa,

You might also like