You are on page 1of 67

Introduction to Computing Systems:

From Bits & Gates to C & Beyond -


eBook PDF
Visit to download the full and correct content document:
https://ebooksecure.com/download/introduction-to-computing-systems-from-bits-gate
s-to-c-beyond-ebook-pdf/
third edition

introduction
to computing
systems
from bits & gates to
C/C++ & beyond

yale n. patt
sanjay j. patel
introduction to
computing systems
third edition

introduction to
computing systems
from bits & gates to C/C++ & beyond

Yale N. Patt
The University of Texas at Austin

Sanjay J. Patel
University of Illinois at Urbana-Champaign
INTRODUCTION TO COMPUTING SYSTEMS: FROM BITS & GATES TO C/C++ & BEYOND, THIRD EDITION

Published by McGraw-Hill Education, 2 Penn Plaza, New York, NY 10121. Copyright 2020 c by McGraw-Hill Education. All rights
reserved. Printed in the United States of America. Previous editions 2004,
c and 2001. No part of this publication may be reproduced
or distributed in any form or by any means, or stored in a database or retrieval system, without the prior written consent of McGraw-Hill
Education, including, but not limited to, in any network or other electronic storage or transmission, or broadcast for distance learning.

Some ancillaries, including electronic and print components, may not be available to customers outside the United States.

This book is printed on acid-free paper.

1 2 3 4 5 6 7 8 9 LCR 24 23 22 21 20 19

ISBN 978-1-260-15053-7 (bound edition)


MHID 1-260-15053-4 (bound edition)
ISBN 978-1-260-42474-4 (loose-leaf edition)
MHID 1-260-42474-X (loose-leaf edition)

Executive Portfolio Manager: Suzy Bainbridge


Product Developer: Heather Ervolino
Senior Marketing Manager: Shannon O’Donnell
Content Project Manager: Jeni McAtee
Buyer: Sandy Ludovissy
Designer: David Hash
Content Licensing Specialist: Melissa Homer
Cover Image: Front Cover Computing art Yale c N. Patt; Abstract image in green, orange and yellow Design
c Pics/Tim Antoniuk;
Abstract image in orange, green and yellow Design
c Pics/Tim Antoniuk; Computer laptops on a blue abstract background loops7/
c
Getty Images; Illustration of streams of binary code Shutterstock/Tavarius
c
Compositor: Aptara R
, Inc.

All credits appearing on page or at the end of the book are considered to be an extension of the copyright page.

Library of Congress Cataloging-in-Publication Data


Names: Patt, Yale N., author. Patel, Sanjay J., author.
Title: Introduction to computing systems : from bits & gates to c/c++ &
beyond / Yale N. Patt, The University of Texas at Austin, Sanjay J. Patel,
University of Illinois at Urbana-Champaign.
Description: Third edition. New York, NY : McGraw-Hill, 2020.
Identifiers: LCCN 2018050089 ISBN 9781260150537 (acid-free paper) ISBN
1260150534 (acid-free paper)
Subjects: LCSH: Computer science. C (Computer program language)
Classification: LCC QA76 .P367 2019 DDC 004–dc23 LC record available at
https://lccn.loc.gov/2018050089

The Internet addresses listed in the text were accurate at the time of publication. The inclusion of a website does not indicate an endorse-
ment by the authors or McGraw-Hill Education, and McGraw-Hill Education does not guarantee the accuracy of the information presented
at these sites.

mheducation.com/highered
To the memory of my parents,
Abraham Walter Patt A"H and Sarah Clara Patt A"H,
who taught me to value “learning”
even before they taught me to ride a bicycle.

To my loving family,
Amita, Kavi, and Aman.
Contents

Preface xv 2.4 Conversion Between Binary and Decimal 31


2.4.1 Binary to Decimal Conversion 31
2.4.2 Decimal to Binary Conversion 32
2.4.3 Extending Conversion to Numbers with
1 Welcome Aboard 1 Fractional Parts 33
1.1 What We Will Try to Do 1
2.5 Operations on Bits—Part I: Arithmetic 34
1.2 How We Will Get There 1
2.5.1 Addition and Subtraction 34
1.3 Two Recurring Themes 3
2.5.2 Sign-Extension 36
1.3.1 The Notion of Abstraction 3
2.5.3 Overflow 36
1.3.2 Hardware vs. Software 5
2.6 Operations on Bits—Part II: Logical
1.4 A Computer System 7
Operations 38
1.4.1 A (Very) Little History for a (Lot)
2.6.1 A Logical Variable 38
Better Perspective 8
2.6.2 The AND Function 38
1.4.2 The Parts of a Computer
2.6.3 The OR Function 39
System 10
2.6.4 The NOT Function 40
1.5 Two Very Important Ideas 11
2.6.5 The Exclusive-OR Function 40
1.6 Computers as Universal
2.6.6 DeMorgan’s Laws 41
Computational Devices 12
2.6.7 The Bit Vector 42
1.7 How Do We Get the Electrons to Do
2.7 Other Representations 43
the Work? 14
2.7.1 Floating Point Data Type (Greater Range,
1.7.1 The Statement of the Problem 14
Less Precision) 43
1.7.2 The Algorithm 16
2.7.2 ASCII Codes 47
1.7.3 The Program 16
2.7.3 Hexadecimal Notation 48
1.7.4 The ISA 17
Exercises 49
1.7.5 The Microarchitecture 18
1.7.6 The Logic Circuit 19
1.7.7 The Devices 19
Exercises 20 3 Digital Logic Structures 59
3.1 The Transistor 59
3.2 Logic Gates 61
3.2.1 The NOT Gate (Inverter) 61
2 Bits, Data Types, 3.2.2 OR and NOR Gates 62
and Operations 25 3.2.3 Why We Can’t Simply Connect P-Type
2.1 Bits and Data Types 25 to Ground 64
2.1.1 The Bit as the Unit of Information 25 3.2.4 AND and NAND Gates 65
2.1.2 Data Types 26 3.2.5 Gates with More Than Two Inputs 66
2.2 Integer Data Types 26 3.3 Combinational Logic Circuits 67
2.2.1 Unsigned Integers 26 3.3.1 Decoder 67
2.2.2 Signed Integers 27 3.3.2 Mux 68
2.3 2’s Complement Integers 29 3.3.3 A One-Bit Adder (a.k.a. a Full Adder) 69
viii Contents

3.3.4 The Programmable Logic 5.1.3 The Instruction Set 147


Array (PLA) 71 5.1.4 Opcodes 149
3.3.5 Logical Completeness 72 5.1.5 Data Types 149
3.4 Basic Storage Elements 73 5.1.6 Addressing Modes 150
3.4.1 The R-S Latch 73 5.1.7 Condition Codes 150
3.4.2 The Gated D Latch 74 5.2 Operate Instructions 151
3.5 The Concept of Memory 75 5.2.1 ADD, AND, and NOT 151
3.5.1 Address Space 75 5.2.2 Immediates 152
3.5.2 Addressability 76 5.2.3 The LEA Instruction (Although Not Really
3.5.3 A 22 -by-3-Bit Memory 76 an Operate) 154
3.6 Sequential Logic Circuits 78 5.3 Data Movement Instructions 155
3.6.1 A Simple Example: The 5.3.1 PC-Relative Mode 156
Combination Lock 79 5.3.2 Indirect Mode 158
3.6.2 The Concept of State 80 5.3.3 Base+offset Mode 159
3.6.3 The Finite State Machine and Its 5.3.4 An Example 160
State Diagram 82 5.4 Control Instructions 161
3.6.4 The Synchronous Finite 5.4.1 Conditional Branches 162
State Machine 85 5.4.2 Two Methods of Loop Control 165
3.6.5 The Clock 86 5.4.3 The JMP Instruction 169
3.6.6 Example: A Danger Sign 87 5.4.4 The TRAP Instruction 169
3.7 Preview of Coming Attractions: The Data Path 5.5 Another Example: Counting Occurrences
of the LC-3 93 of a Character 170
Exercises 95 5.6 The Data Path Revisited 173
5.6.1 Basic Components of the
Data Path 175
4 The von Neumann Model 121 5.6.2 The Instruction Cycle Specific
4.1 Basic Components 121 to the LC-3 176
4.1.1 Memory 122 Exercises 177
4.1.2 Processing Unit 123
4.1.3 Input and Output 124
4.1.4 Control Unit 125 6 Programming 203
4.2 The LC-3: An Example von 6.1 Problem Solving 203
Neumann Machine 125 6.1.1 Systematic Decomposition 203
4.3 Instruction Processing 127 6.1.2 The Three Constructs: Sequential,
4.3.1 The Instruction 127 Conditional, Iterative 204
4.3.2 The Instruction Cycle (NOT the 6.1.3 LC-3 Control Instructions to Implement
Clock Cycle!) 130 the Three Constructs 205
4.3.3 Changing the Sequence of 6.1.4 The Character Count Example from
Execution 132 Chapter 5, Revisited 206
4.3.4 Control of the Instruction Cycle 134 6.2 Debugging 210
4.3.5 Halting the Computer (the TRAP 6.2.1 Debugging Operations 211
Instruction) 136 6.2.2 Use of an Interactive Debugger 212
4.4 Our First Program: A Multiplication Exercises 220
Algorithm 137
Exercises 139
7 Assembly Language 231
7.1 Assembly Language Programming—Moving
5 The LC-3 145 Up a Level 231
5.1 The ISA: Overview 145 7.2 An Assembly Language Program 232
5.1.1 Memory Organization 146 7.2.1 Instructions 233
5.1.2 Registers 146 7.2.2 Pseudo-Ops (Assembler Directives) 236
Contents ix

7.2.3 Example: The Character Count Example 9.2 Input/Output 317


of Section 5.5, Revisited Again! 238 9.2.1 Some Basic Characteristics
7.3 The Assembly Process 240 of I/O 317
7.3.1 Introduction 240 9.2.2 Input from the Keyboard 320
7.3.2 A Two-Pass Process 240 9.2.3 Output to the Monitor 322
7.3.3 The First Pass: Creating the 9.2.4 A More Sophisticated Input
Symbol Table 241 Routine 325
7.3.4 The Second Pass: Generating the 9.2.5 Implementation of Memory-Mapped
Machine Language Program 242 I/O, Revisited 326
7.4 Beyond the Assembly of a Single Assembly 9.3 Operating System Service Routines
Language Program 243 (LC-3 Trap Routines) 327
7.4.1 The Executable Image 244 9.3.1 Introduction 327
7.4.2 More than One Object File 244 9.3.2 The Trap Mechanism 329
Exercises 245 9.3.3 The TRAP Instruction 330
9.3.4 The RTI Instruction: To Return
Control to the Calling
8 Data Structures 263 Program 331
8.1 Subroutines 263 9.3.5 A Summary of the Trap Service
8.1.1 The Call/Return Mechanism 265 Routine Process 331
8.1.2 JSR(R)—The Instruction That Calls 9.3.6 Trap Routines for Handling I/O 333
the Subroutine 266 9.3.7 A Trap Routine for Halting
8.1.3 Saving and Restoring Registers 267 the Computer 335
8.1.4 Library Routines 269 9.3.8 The Trap Routine for Character Input
8.2 The Stack 273 (One Last Time) 336
8.2.1 The Stack—An Abstract Data Type 273 9.3.9 PUTS: Writing a Character String to
8.2.2 Two Example Implementations 273 the Monitor 338
8.2.3 Implementation in Memory 274 9.4 Interrupts and Interrupt-Driven I/O 339
8.2.4 The Complete Picture 278 9.4.1 What Is Interrupt-Driven I/O? 339
8.3 Recursion, a Powerful Technique When Used 9.4.2 Why Have Interrupt-Driven I/O? 340
Appropriately 280 9.4.3 Two Parts to the Process 341
8.3.1 Bad Example Number 1: Factorial 280 9.4.4 Part I: Causing the Interrupt to
8.3.2 Fibonacci, an Even Worse Occur 341
Example 285 9.4.5 Part II: Handling the Interrupt
8.3.3 The Maze, a Good Example 288 Request 344
8.4 The Queue 294 9.4.6 An Example 347
8.4.1 The Basic Operations: Remove from 9.4.7 Not Just I/O Devices 349
Front, Insert at Rear 295 9.5 Polling Revisited, Now That We Know
8.4.2 Wrap-Around 295 About Interrupts 350
8.4.3 How Many Elements Can We Store 9.5.1 The Problem 350
in a Queue? 296 9.5.2 The Solution 351
8.4.4 Tests for Underflow, Overflow 297 Exercises 352
8.4.5 The Complete Story 298
8.5 Character Strings 300
Exercises 304
10 A Calculator 379
10.1 Data Type Conversion 380
9 I/O 313 10.1.1 Example: A Bogus Program:
9.1 Privilege, Priority, and the Memory 2 + 3 = e 381
Address Space 314 10.1.2 Input Data (ASCII to Binary) 381
9.1.1 Privilege and Priority 314 10.1.3 Display Result (Binary
9.1.2 Organization of Memory 316 to ASCII) 385
x Contents

10.2 Arithmetic Using a Stack 387 12.3.7 Logical Operators 438


10.2.1 The Stack as Temporary Storage 387 12.3.8 Increment /Decrement Operators 439
10.2.2 An Example 388 12.3.9 Expressions with Multiple
10.2.3 OpAdd, OpMult, and OpNeg 389 Operators 441
10.3 The Calculator 395 12.4 Problem Solving Using Operators 441
10.3.1 Functionality 395 12.5 Tying It All Together 444
10.3.2 Code 396 12.5.1 Symbol Table 444
Exercises 402 12.5.2 Allocating Space for Variables 445
12.5.3 A Comprehensive Example 447
12.6 Additional Topics 449
12.6.1 Variations of the Basic Types 450
11 Introduction to C/C++ 12.6.2 Literals, Constants, and Symbolic
Programming 405 Values 451
11.1 Our Objective 405 12.6.3 Additional C Operators 452
11.2 Bridging the Gap 406 12.7 Summary 453
11.3 Translating High-Level Language Exercises 453
Programs 410
11.3.1 Interpretation 410
11.3.2 Compilation 411 13 Control Structures 457
11.3.3 Pros and Cons 411 13.1 Introduction 457
11.4 The C/C++ Programming Languages 411 13.2 Conditional Constructs 457
11.4.1 The Origins of C and C++ 411 13.2.1 The if Statement 458
11.4.2 How We Will Approach C 13.2.2 The if-else Statement 460
and C++ 412 13.3 Iteration Constructs 464
11.4.3 The Compilation Process 413 13.3.1 The while Statement 464
11.4.4 Software Development 13.3.2 The for Statement 466
Environments 415 13.3.3 The do-while Statement 471
11.5 A Simple Example in C 415 13.4 Problem Solving Using Control
11.5.1 The Function main 415 Structures 472
11.5.2 Formatting, Comments, and Style 417 13.4.1 Problem 1: Approximating the
11.5.3 The C Preprocessor 418 Value of 𝜋 472
11.5.4 Input and Output 419 13.4.2 Problem 2: Finding Prime Numbers
11.6 Summary 422 Less Than 100 474
Exercises 422 13.4.3 Problem 3: Analyzing an E-mail
Address 477
13.5 Additional C Control Structures 480
13.5.1 The switch Statement 480
12 Variables and Operators 425 13.5.2 The break and continue
12.1 Introduction 425
Statements 482
12.2 Variables 425
13.5.3 An Example: Simple
12.2.1 Four Basic Data Types 426
Calculator 482
12.2.2 Choosing Identifiers 429
13.6 Summary 484
12.2.3 Scope: Local vs. Global 429
Exercises 484
12.2.4 More Examples 431
12.3 Operators 432
12.3.1 Expressions and Statements 433
12.3.2 The Assignment Operator 433 14 Functions 491
12.3.3 Arithmetic Operators 434 14.1 Introduction 491
12.3.4 Order of Evaluation 435 14.2 Functions in C 492
12.3.5 Bitwise Operators 436 14.2.1 A Function with a Parameter 492
12.3.6 Relational Operators 437 14.2.2 Example: Area of a Ring 495
Contents xi

14.3 Implementing Functions in C 497 16.3.6 Problem Solving: Insertion Sort 556
14.3.1 Run-Time Stack 497 16.3.7 Common Pitfalls with Arrays in C 559
14.3.2 Getting It All to Work 500 16.3.8 Variable-Length Arrays 559
14.3.3 Tying It All Together 505 16.3.9 Multidimensional Arrays in C 561
14.4 Problem Solving Using Functions 507 16.4 Summary 563
14.4.1 Problem 1: Case Conversion 507 Exercises 563
14.4.2 Problem 2: Pythagorean Triples 508
14.5 Summary 510
Exercises 511 17 Recursion 569
17.1 Introduction 569
17.2 What Is Recursion? 570
15 Testing and Debugging 517 17.3 Recursion vs. Iteration 571
15.1 Introduction 517 17.4 Towers of Hanoi 572
15.2 Types of Errors 518 17.5 Fibonacci Numbers 576
15.2.1 Syntactic Errors 519 17.6 Binary Search 581
15.2.2 Semantic Errors 519 17.7 Escaping a Maze 583
15.2.3 Algorithmic Errors 521 17.8 Summary 586
15.2.4 Specification Errors 522 Exercises 587
15.3 Testing 523
15.3.1 Black-Box Testing 524
15.3.2 White-Box Testing 524 18 I/O in C 593
15.4 Debugging 525 18.1 Introduction 593
15.4.1 Ad Hoc Techniques 526 18.2 The C Standard Library 593
15.4.2 Source-Level Debuggers 526 18.3 I/O, One Character at a Time 594
15.5 Programming for Correctness 528 18.3.1 I/O Streams 594
15.5.1 Nailing Down the Specifications 529 18.3.2 putchar 595
15.5.2 Modular Design 529 18.3.3 getchar 595
15.5.3 Defensive Programming 530 18.3.4 Buffered I/O 595
15.6 Summary 531 18.4 Formatted I/O 597
Exercises 532 18.4.1 printf 597
18.4.2 scanf 599
18.4.3 Variable Argument Lists 601
16 Pointers and Arrays 537 18.5 I/O from Files 602
16.1 Introduction 537 18.6 Summary 605
16.2 Pointers 537 Exercises 605
16.2.1 Declaring Pointer Variables 539
16.2.2 Pointer Operators 540
16.2.3 Passing a Reference Using 19 Dynamic Data Structures in C 607
Pointers 541 19.1 Introduction 607
16.2.4 Null Pointers 543 19.2 Structures 608
16.2.5 Demystifying the Syntax 543 19.2.1 typedef 610
16.2.6 An Example Problem Involving 19.2.2 Implementing Structures in C 611
Pointers 544 19.3 Arrays of Structures 611
16.3 Arrays 545 19.4 Dynamic Memory Allocation 614
16.3.1 Declaring and Using Arrays 546 19.4.1 Dynamically Sized Arrays 616
16.3.2 Examples Using Arrays 547 19.5 Linked Lists 618
16.3.3 Arrays as Parameters 550 19.5.1 Support Functions 620
16.3.4 Strings in C 552 19.5.2 Adding a Node to a Linked List 622
16.3.5 The Relationship Between Arrays and 19.5.3 Deleting Node from a Linked List 625
Pointers in C 554 19.5.4 Arrays vs. Linked Lists 626
xii Contents

19.6 Summary 628 C The Microarchitecture of


Exercises 629 the LC-3 699
C.1 Overview 699
C.2 The State Machine 701
20 Introduction to C++ 633 C.3 The Data Path 703
20.1 Essential C++ 633 C.4 The Control Structure 706
20.2 Going from C to C++ 634 C.5 The TRAP Instruction 710
20.2.1 Compiling C++ Code 634 C.6 Memory-Mapped I/O 711
20.2.2 Namespaces 636 C.7 Interrupt and Exception Control 712
20.2.3 Input and Output 636 C.7.1 Initiating an Interrupt 714
20.2.4 Pass by Reference 637 C.7.2 Returning from an Interrupt or Trap
20.2.5 Function Overloading 638 Service Routine, RTI 717
20.2.6 Dynamic Allocation 639 C.7.3 Initiating an Exception 717
20.2.7 Compilation to Machine C.8 Control Store 719
Version 639
20.3 Classes 639
20.3.1 Methods 640
20.3.2 Access Specifiers 642
20.3.3 Constructors 644 D The C Programming
20.3.4 Advanced Topics 645 Language 721
20.4 Containers and Templates 647 D.1 Overview 721
20.4.1 Vectors 647 D.2 C Conventions 721
20.4.2 Templates 649 D.2.1 Source Files 721
20.5 Summary 649 D.2.2 Header Files 721
Exercises 650 D.2.3 Comments 722
D.2.4 Literals 722
D.2.5 Formatting 724
A The LC-3 ISA 653 D.2.6 Keywords 724
A.1 Overview 653 D.3 Types 725
A.2 The Instruction Set 655 D.3.1 Basic Data Types 725
A.3 Interrupt and Exception Processing 675 D.3.2 Type Qualifiers 726
A.3.1 Interrupts 676 D.3.3 Storage Class 728
A.3.2 Exceptions 676 D.3.4 Derived Types 728
D.3.5 typedef 731
D.4 Declarations 731
B From LC-3 to x86 679 D.4.1 Variable Declarations 731
B.1 LC-3 Features and Corresponding x86 D.4.2 Function Declarations 732
Features 680 D.5 Operators 733
B.1.1 Instruction Set 680 D.5.1 Assignment Operators 733
B.1.2 Memory 685 D.5.2 Arithmetic Operators 734
B.1.3 Internal State 687 D.5.3 Bit-Wise Operators 734
B.2 The Format and Specification of D.5.4 Logical Operators 735
x86 Instructions 690 D.5.5 Relational Operators 735
B.2.1 Prefix 691 D.5.6 Increment/Decrement Operators 736
B.2.2 Opcode 691 D.5.7 Conditional Expression Operators 736
B.2.3 ModR/M Byte 692 D.5.8 Pointer, Array, and Structure
B.2.4 SIB Byte 693 Operators 737
B.2.5 Displacement 693 D.5.9 sizeof 738
B.2.6 Immediate 693 D.5.10 Order of Evaluation 738
B.3 An Example 695 D.5.11 Type Conversions 739
Contents xiii

D.6 Expressions and Statements 740 D.9 Some Standard Library Functions 747
D.6.1 Expressions 740 D.9.1 I/O Functions 747
D.6.2 Statements 740 D.9.2 String Functions 749
D.7 Control 741 D.9.3 Math Functions 750
D.7.1 If 741 D.9.4 Utility Functions 750
D.7.2 If-else 741
D.7.3 Switch 742
D.7.4 While 743 E Useful Tables 753
D.7.5 For 743 E.1 Commonly Used Numerical Prefixes 753
D.7.6 Do-while 744 E.2 Standard ASCII codes 754
D.7.7 Break 744 E.3 Powers of 2 755
D.7.8 continue 745
D.7.9 return 745
D.8 The C Preprocessor 746
D.8.1 Macro Substitution 746 F Solutions to Selected
D.8.2 File Inclusion 747 Exercises 757
Preface

Finally, the third edition! We must first thank all those who have been pushing
us to produce a third edition. Since the publication of the second edition was so
long ago, clearly the material must be out of date. Wrong! Fundamentals do not
change very often, and our intent continues to be to provide a book that explains
the fundamentals clearly in the belief that if the fundamentals are mastered, there
is no limit to how high one can soar if one’s talent and focus are equal to the task.
We must also apologize that it took so long to produce this revision. Please
know that the delay in no way reflects any lack of enthusiasm on our part. We are
both as passionate about the foundation of computing today as we were 25 years
ago when we overhauled the first course in computing that eventually became
the first edition of this book. Indeed, we have both continued to teach the course
regularly. And, as expected, each time we teach, we develop new insights as to
what to teach, new examples to explain things, and new ways to look at things.
The result of all this, hopefully, is that we have captured this in the third edition.
It is a pleasure to finally be writing this preface. We have received an enor-
mous number of comments from students who have studied the material in the
book and from instructors who have taught from it. It is gratifying to know that
a lot of people agree with our approach, and that this agreement is based on real
firsthand experience learning from it (in the case of students) and watching stu-
dents learn from it (in the case of instructors). The excitement displayed in their
correspondence continues to motivate us.

Why the Book Happened


This textbook evolved from EECS 100, the first computing course for computer
science, computer engineering, and electrical engineering majors at the Univer-
sity of Michigan, Ann Arbor, that Kevin Compton and the first author introduced
for the first time in the fall term, 1995.
EECS 100 happened at Michigan because Computer Science and Engi-
neering faculty had been dissatisfied for many years with the lack of student
comprehension of some very basic concepts. For example, students had a lot
of trouble with pointer variables. Recursion seemed to be “magic,” beyond
understanding.
We decided in 1993 that the conventional wisdom of starting with a high-
level programming language, which was the way we (and most universities) were
xvi Preface

doing it, had its shortcomings. We decided that the reason students were not get-
ting it was that they were forced to memorize technical details when they did not
understand the basic underpinnings.
Our result was the bottom-up approach taken in this book, where we contin-
ually build on what the student already knows, only memorizing when absolutely
necessary. We did not endorse then and we do not endorse now the popular
information hiding approach when it comes to learning. Information hiding is a
useful productivity enhancement technique after one understands what is going on.
But until one gets to that point, we insist that information hiding gets in the way of
understanding. Thus, we continually build on what has gone before so that nothing
is magic and everything can be tied to the foundation that has already been laid.
We should point out that we do not disagree with the notion of top-down
design. On the contrary, we believe strongly that top-down design is correct
design. But there is a clear difference between how one approaches a design prob-
lem (after one understands the underlying building blocks) and what it takes to get
to the point where one does understand the building blocks. In short, we believe
in top-down design, but bottom-up learning for understanding.

Major Changes in the Third Edition


The LC-3
A hallmark of our book continues to be the LC-3 ISA, which is small enough to
be described in a few pages and hopefully mastered in a very short time, yet rich
enough to convey the essence of what an ISA provides. It is the LC “3” because
it took us three tries to get it right. Four tries, actually, but the two changes in the
LC-3 ISA since the second edition (i.e., changes to the LEA instruction and to the
TRAP instruction) are so minor that we decided not to call the slightly modified
ISA the LC-4.
The LEA instruction no longer sets condition codes. It used to set condition
codes on the mistaken belief that since LEA stands for Load Effective Address,
it should set condition codes like LD, LDI, and LDR do. We recognize now that
this reason was silly. LD, LDI, and LDR load a register from memory, and so
the condition codes provide useful information – whether the value loaded is
negative, zero, or positive. LEA loads an address into a register, and for that, the
condition codes do not really provide any value. Legacy code written before this
change should still run correctly.
The TRAP instruction no longer stores the linkage back to the calling pro-
gram in R7. Instead, the PC and PSR are pushed onto the system stack and popped
by the RTI instruction (renamed Return from Trap or Interrupt) as the last instruc-
tion in a trap routine. Trap routines now execute in privileged memory (x0000 to
x2FFF). This change allows trap routines to be re-entrant. It does not affect old
code provided the starting address of the trap service routines, obtained from the
Trap Vector Table, is in privileged memory and the terminating instruction of
each trap service routine is changed from RET to RTI.
As before, Appendix A specifies the LC-3 completely.
Preface xvii

The Addition of C++


We’ve had an ongoing debate about how to extend our approach and textbook
to C++. One of the concerns about C++ is that many of its language features
are too far abstracted from the underlying layers to make for an easy fit to our
approach. Another concern is that C++ is such a vast language that any adequate
coverage would require an additional thousand pages. We also didn’t want to drop
C completely, as it serves as a de facto development language for systems and
hardware-oriented projects.
We adopted an approach where we cover the common core of C and C++
from Chapters 11 through 19. This common core is similar to what was covered
in the second edition, with some minor updates. Chapter 20 serves as a transition,
which we aspired to make very smooth, to the core concepts of C++. With this
approach, we get to explore the evolution between C and C++, which serves as
a key learning opportunity on what changes were essential to boost programmer
productivity.
In particular, we focus on classes in C++ as an evolution from structures in
C. We discuss classes as a compiler construct, how method calls are made, and
the notion of constructors. We touch upon inheritance, too, but leave the details
for subsequent treatment in follow-on courses.
An important element of C++ is the introduction of container classes in the
Standard Template Library, which is a heavily utilized part of the C++ language.
This provides an opportunity to dive deep into the vector class, which serves as
a continuation of a running example in the second half around the support for
variable-sized arrays in high-level languages, or in particular, C’s lack of support
for them.

Other Important Updates


Although no chapter in the book has remained untouched, some chapters have
been changed more than others. In Chapter 2, we expanded the coverage of the
floating point data type and the conversion of fractions between decimal and
binary numbers in response to several instructors who wanted them. We moved
DeMorgan’s Laws from Chapter 3 to Chapter 2 because the concept is really about
AND and OR functions and not about digital logic implementation. In Chap-
ter 3, we completely overhauled the description of state, latches, flip-flops, finite
state machines, and our example of a danger sign. We felt the explanations in the
second edition were not as clear as they needed to be, and the concepts are too
important to not get right. We revised Chapter 4 to better introduce the LC-3,
including a different set of instructions, leading to our first complete example of
a computer program.
Our organization of Chapters 8, 9, and 10 was completely overhauled in order
to present essentially the same material in a more understandable way. Although
most of our treatment of data structures waits until we have introduced C in the
second half of the book, we felt it was important to introduce stacks, queues,
and character strings as soon as the students have moved out of programming in
machine language so they can write programs dealing with these data structures
xviii Preface

and see how these structures are actually organized in memory. We moved our dis-
cussion of subroutines up to Chapter 8 because of their importance in constructing
richer programs.
We also introduced recursion in Chapter 8, although its main treatment is still
left for the second half of the book. Both the expressive power of recursion and
its misuse are so common in undergraduate curricula that we felt dealing with
it twice, first while they are engrossed in the bowels of assembly language and
again after moving up to the richness of C, was worthwhile.
Chapter 9 now covers all aspects of I/O in one place, including polling and
interrupt-driven I/O. Although the concept of privilege is present in the second
edition, we have put greater emphasis on it in the third edition. Our coverage
of system calls (the trap routines invoked by the TRAP instruction) appears in
Chapter 9. All of the above reduce Chapter 10 to simply a comprehensive example
that pulls together a lot of the first half of the book: the simulation of a calculator.
Doing so requires 12 subroutines that are laid out in complete detail. Two con-
cepts that are needed to make this happen are stack arithmetic and ASCII/binary
conversion, so they are included in Chapter 10.
We reworked all the examples in Chapters 11 through 19 to use the latest
ANSI Standard C or C18. We also added more coding examples to further empha-
size points and to provide clarity on complex topics such as pointers, arrays,
recursion, and pointers to pointers in C. In Chapter 16, we added additional
sections on variable-sized arrays in C, and on multidimensional arrays.

Chapter Organization
The book breaks down into two major segments, (a) the underlying structure
of a computer, as manifested in the LC-3; and (b) programming in a high-level
language, in our case C and C++.

The LC-3
We start with the underpinnings that are needed to understand the workings of a
real computer. Chapter 2 introduces the bit and arithmetic and logical operations
on bits. Then we begin to build the structure needed to understand the LC-3.
Chapter 3 takes the student from an MOS transistor, step by step, to a “real”
memory and a finite state machine.
Our real memory consists of four words of three bits each, rather than
16 gigabytes, which is common in most laptops today. Its description fits on a
single page (Figure 3.20), making it easy for a student to grasp. By the time stu-
dents get there, they have been exposed to all the elements needed to construct the
memory. The finite state machine is needed to understand how a computer pro-
cesses instructions, starting in Chapter 4. Chapter 4 introduces the von Neumann
execution model and enough LC-3 instructions to allow an LC-3 program to be
written. Chapter 5 introduces most of the rest of the LC-3 ISA.
Preface xix

The LC-3 is a 16-bit architecture that includes physical I/O via keyboard
and monitor, TRAPs to the operating system for handling service calls, con-
ditional branches on (N, Z, and P) condition codes, a subroutine call/return
mechanism, a minimal set of operate instructions (ADD, AND, and NOT), and
various addressing modes for loads and stores (direct, indirect, Base+offset).
Chapter 6 is devoted to programming methodology (stepwise refinement)
and debugging, and Chapter 7 is an introduction to assembly language program-
ming. We have developed a simulator and an assembler for the LC-3 that runs on
Windows, Linux, and Mac0S platforms. It can be downloaded from the web at
no charge.
Students use the simulator to test and debug programs written in LC-3
machine language and in LC-3 assembly language. The simulator allows online
debugging (deposit, examine, single-step, set breakpoint, and so on). The sim-
ulator can be used for simple LC-3 machine language and assembly language
programming assignments, which are essential for students to master the concepts
presented throughout the first ten chapters.
Assembly language is taught, but not to train expert assembly language pro-
grammers. Indeed, if the purpose was to train assembly language programmers,
the material would be presented in an upper-level course, not in an introductory
course for freshmen. Rather, the material is presented in Chapter 7 because it
is consistent with the paradigm of the book. In our bottom-up approach, by the
time the student reaches Chapter 7, he/she can handle the process of transform-
ing assembly language programs to sequences of 0s and 1s. We go through the
process of assembly step by step for a very simple LC-3 Assembler. By hand
assembling, the student (at a very small additional cost in time) reinforces the
important fundamental concept of translation.
It is also the case that assembly language provides a user-friendly notation
to describe machine instructions, something that is particularly useful for writing
programs in Chapters 8, 9, and 10, and for providing many of the explanations in
the second half of the book. Starting in Chapter 11, when we teach the semantics
of C statements, it is far easier for the reader to deal with ADD R1, R2, R3 than
to have to struggle with 0001001010000011.
Chapter 8 introduces three important data structures: the stack, the queue,
and the character string, and shows how they are stored in memory. The sub-
routine call/return mechanism of the LC-3 is presented because of its usefulness
both in manipulating these data structures and in writing programs. We also intro-
duce recursion, a powerful construct that we revisit much more thoroughly in the
second half of the book (in Chapter 17), after the student has acquired a much
stronger capability in high-level language programming. We introduce recursion
here to show by means of a few examples the execution-time tradeoffs incurred
with recursion as a first step in understanding when its use makes sense and when
it doesn’t.
Chapter 9 deals with input/output and some basic interaction between the
processor and the operating system. We introduce the notions of priority and
privilege, which are central to a systems environment. Our treatment of I/O is
all physical, using keyboard data and status registers for input and display data
and status registers for output. We describe both interrupt-driven I/O and I/O
xx Preface

under program control. Both are supported by our LC-3 simulator so the student
can write interrupt drivers. Finally, we show the actual LC-3 code of the trap ser-
vice routines that the student has invoked with the TRAP instruction starting in
Chapter 4. To handle interrupt-driven I/O and trap service routines, we complete
the description of the LC-3 ISA with details of the operation of the Return from
Trap or Interrupt (RTI) and TRAP instructions.
The first half of the book concludes with Chapter 10, a comprehensive exam-
ple of a simple calculator that pulls together a lot of what the students have learned
in Chapters 1 through 9.

Programming in C and C++


By the time the student gets to the second part of the textbook, he/she has an
understanding of the layers below. In our coverage of programming in C and
C++, we leverage this foundation by showing the resulting LC-3 code generated
by a compiler with each new concept in C/C++.
We start with the C language because it provides the common, essential
core with C++. The C programming language fits very nicely with our bottom-
up approach. Its low-level nature allows students to see clearly the connection
between software and the underlying hardware. In this book, we focus on basic
concepts such as control structures, functions, and arrays. Once basic program-
ming concepts are mastered, it is a short step for students to learn more advanced
concepts such as objects and abstraction in C++.
Each time a new high-level construct is introduced, the student is shown
the LC-3 code that a compiler would produce. We cover the basic constructs of
C (variables, operators, control, and functions), pointers, arrays, recursion, I/O,
complex data structures, and dynamic allocation. With C++, we cover some basic
improvements over C, classes, and containers.
Chapter 11 is a gentle introduction to high-level programming languages. At
this point, students have dealt heavily with assembly language and can understand
the motivation behind what high-level programming languages provide. Chapter
11 also contains a simple C program, which we use to kick-start the process of
learning C.
Chapter 12 deals with values, variables, constants, and operators. Chapter 13
introduces C control structures. We provide many complete program examples
to give students a sample of how each of these concepts is used in practice. LC-3
code is used to demonstrate how each C construct affects the machine at the lower
levels.
Chapter 14 introduces functions in C. Students are not merely exposed to the
syntax of functions. Rather they learn how functions are actually executed, with
argument-passing using a run-time stack. A number of examples are provided.
In Chapter 15, students are exposed to techniques for testing their code, along
with debugging high-level source code. The ideas of white-box and black-box
testing are discussed.
Chapter 16 teaches pointers and arrays, relying heavily on the student’s
understanding of how memory is organized. We discuss C’s notions of fixed size
and variable-length arrays, along with multidimensional array allocation.
Preface xxi

Chapter 17 teaches recursion, using the student’s newly gained knowledge of


functions, stack frames, and the run-time stack. Chapter 18 introduces the details
of I/O functions in C, in particular, streams, variable length argument lists, and
how C I/O is affected by the various format specifications. This chapter relies on
the student’s earlier exposure to physical I/O in Chapter 8. Chapter 19 discusses
structures in C, dynamic memory allocation, and linked lists.
Chapter 20 provides a jump-start on C++ programming by discussing its
roots in C and introducing the idea of classes as a natural evolution from struc-
tures. We also cover the idea of containers in the standard template library, to
enable students to quickly jump into productive programming with C++.
Along the way, we have tried to emphasize good programming style and cod-
ing methodology by means of examples. Novice programmers probably learn at
least as much from the programming examples they read as from the rules they
are forced to study. Insights that accompany these examples are highlighted by
means of lightbulb icons that are included in the margins.
We have found that the concept of pointer variables (Chapter 16) is not at all
a problem. By the time students encounter it, they have a good understanding of
what memory is all about, since they have analyzed the logic design of a small
memory (Chapter 3). They know the difference, for example, between a memory
location’s address and the data stored there.
Recursion ceases to be magic since, by the time a student gets to that point
(Chapter 17), he/she has already encountered all the underpinnings. Students
understand how stacks work at the machine level (Chapter 8), and they understand
the call/return mechanism from their LC-3 machine language programming expe-
rience, and the need for linkages between a called program and the return to the
caller (Chapter 8). From this foundation, it is not a large step to explain functions
by introducing run-time stack frames (Chapter 14), with a lot of the mystery about
argument passing, dynamic declarations, and so on, going away. Since a function
can call a function, it is one additional small step (certainly no magic involved)
for a function to call itself.

The Simulator/Debugger
The importance of the Simulator/Debugger for testing the programs a student
writes cannot be overemphasized. We believe strongly that there is no substi-
tute for hands-on practice testing one’s knowledge. It is incredibly fulfilling
to a student’s education to write a program that does not work, testing it to
find out why it does not work, fixing the bugs himself/herself, and then see-
ing the program run correctly. To that end, the Simulator/Debugger has been
completely rewritten. It runs on Windows, Linux, and MacOS while present-
ing the same user interface (GUI) regardless of which platform the student is
using. We have improved our incorporation of interrupt-driven I/O into the Sim-
ulator’s functionality so students can easily write interrupt drivers and invoke
them by interrupting a lower priority executing program. ...in their first course in
computing!
xxii Preface

Alternate Uses of the Book


We wrote the book as a textbook for a freshman introduction to computing. We
strongly believe that our motivated bottom-up approach is the best way for stu-
dents to learn the fundamentals of computing. We have seen lots of evidence
showing that in general, students who understand the fundamentals of how the
computer works are better able to grasp the stuff that they encounter later, includ-
ing the high-level programming languages that they must work in, and that they
can learn the rules of these programming languages with far less memorizing
because everything makes sense. For us, the best use of the book is a one-semester
freshman course for particularly motivated students, or a two-semester sequence
where the pace is tempered.
Having said that, we recognize that others see the curriculum differently.
Thus, we hasten to add that the book can certainly be used effectively in other
ways. In fact, each of the following has been tried, and all have been used
successfully:
Two Quarters, Freshman Course
An excellent use of the book. No prerequisites, the entire book can be covered
easily in two quarters, the first quarter for Chapters 1–10, the second quarter for
Chapters 11–20. The pace is brisk, but the entire book can be covered easily in
two academic quarters.
One-Semester, Second Course
Several schools have successfully used the book in their second course,
after the students have been exposed to programming with an object-oriented
programming language in a milder first course. The rationale is that after expo-
sure to high-level language programming in the first course, the second course
should treat at an introductory level digital logic, basic computer organization,
and assembly language programming. The first two-thirds of the semester is spent
on Chapters 1–10, and the last third on Chapters 11–20, teaching C programming,
but also showing how some of the magic from the students’ first course can be
implemented. Coverage of functions, activation records, recursion, pointer vari-
ables, and data structures are examples of topics where getting past the magic is
particularly useful. The second half of the book can move more quickly since the
student has already taken an introductory programming course. This model also
allows students who were introduced to programming with an object-oriented
language to pick up C, which they will almost certainly need in some of their
advanced software courses.
A Sophomore-Level Computer Organization Course
The book has been used to delve deeply into computer implementation in
the sophomore year. The semester is spent in Chapters 1 through 10, often
culminating in a thorough study of Appendix C, which provides the complete
microarchitecture of a microprogrammed LC-3. We note, however, that some
very important ideas in computer architecture are not covered in the book, most
notably cache memory, pipelining, and virtual memory. Instructors using the
book this way are encouraged to provide extra handouts dealing with those top-
ics. We agree that they are very important to the student’s computer architecture
Preface xxiii

education, but we feel they are better suited to a later course in computer
architecture and design. This book is not intended for that purpose.

Why LC-3, and Not ARM or RISCV?


We have been asked why we invented the LC-3 ISA, rather than going with ARM,
which seems to be the ISA of choice for most mobile devices, or RISCV, which
has attracted substantial interest over the last few years.
There are many reasons. First, we knew that the ISA we selected would
be the student’s first ISA, not his/her last ISA. Between the freshman year and
graduation, the student is likely to encounter several ISAs, most of which are in
commercial products: ARM, RISCV, x86, and POWER, to name a few.
But all the commercial ISAs have details that have no place in an introductory
course but still have to be understood for the student to use them effectively. We
could, of course, have subset an existing ISA, but that always ends up in questions
of what to take out and what to leave in with a result that is not as clean as one
would think at first blush. Certainly not as clean as what one can get when starting
from scratch. It also creates an issue whenever the student uses an instruction in
an exam or on an assignment that is not in the subset. Not very clean from a
pedagogical sense.
We wanted an ISA that was clean with no special cases to deal with, with as
few opcodes as necessary so the student could spend almost all his/her time on
the fundamental concepts in the course and very little time on the nuances of the
instruction set. The formats of all instructions in the LC-3 fit on a single page.
Appendix A provides all the details (i.e., the complete data sheet) of the entire
LC-3 ISA in 25 pages.
We also wanted an instruction set that in addition to containing only a few
instructions was very rich in the breadth of what it embraced. So, we came up
with the LC-3, an instruction set with only 15 four-bit opcodes, a small enough
number that students can absorb the ISA without even trying. For arithmetic, we
have only ADD instead of ADD, SUB, MUL, and DIV. For logical operations,
we have AND and NOT, foregoing OR, XOR, etc. We have no shift or rotate
instructions. In all these cases, the missing opcodes can be implemented with
procedures using the few opcodes that the LC-3 provides. We have loads and
stores with three different addressing modes, each addressing mode useful for a
different purpose. We have conditional branches, subroutine calls, return from
trap or interrupt, and system calls (the TRAP instruction).
In fact, this sparse set of opcodes is a feature! It drives home the need for
creating more complex functionality out of simple operations, and the need for
abstraction, both of which are core concepts in the book.
Most importantly, we have found from discussions with hundreds of students
that starting with the LC-3 does not put them at a disadvantage in later courses.
On the contrary: For example, at one campus students were introduced to ARM in
the follow-on course, while at another campus, students were introduced to x86.
xxiv Preface

In both cases, students appreciated starting with the LC-3, and their subsequent
introduction to ARM or x86 was much easier as a result of their first learning the
fundamental concepts with the LC-3.

A Few Observations
Having now taught the course more than 20 times between us, we note the
following:

Understanding, Not Memorizing


Since the course builds from the bottom up, we have found that less memorization
of seemingly arbitrary rules is required than in traditional programming courses.
Students understand that the rules make sense since by the time a topic is taught,
they have an awareness of how that topic is implemented at the levels below
it. This approach is good preparation for later courses in design, where under-
standing of and insights gained from fundamental underpinnings are essential to
making the required design tradeoffs.

The Student Debugs the Student’s Program


We hear complaints from industry all the time about CS graduates not being able
to program. Part of the problem is the helpful teaching assistant, who contributes
far too much of the intellectual content of the student’s program so the student
never has to really master the art. Our approach is to push the student to do the
job without the teaching assistant (TA). Part of this comes from the bottom-up
approach, where memorizing is minimized and the student builds on what he/she
already knows. Part of this is the simulator, which the student uses from the day
he/she writes his/her first program. The student is taught debugging from his/her
first program and is required from the very beginning to use the debugging tools
of the simulator to get his/her programs to work. The combination of the simulator
and the order in which the subject material is taught results in students actually
debugging their own programs instead of taking their programs to the TA for
help ... with the too-frequent result that the TAs end up writing the programs for
the students.

Preparation for the Future: Cutting Through Protective Layers


Professionals who use computers in systems today but remain ignorant of what
is going on underneath are likely to discover the hard way that the effectiveness
of their solutions is impacted adversely by things other than the actual programs
they write. This is true for the sophisticated computer programmer as well as the
sophisticated engineer.
Serious programmers will write more efficient code if they understand what
is going on beyond the statements in their high-level language. Engineers, and not
just computer engineers, are having to interact with their computer systems today
Preface xxv

more and more at the device or pin level. In systems where the computer is being
used to sample data from some metering device such as a weather meter or feed-
back control system, the engineer needs to know more than just how to program
in MATLAB. This is true of mechanical, chemical, and aeronautical engineers
today, not just electrical engineers. Consequently, the high-level programming
language course, where the compiler protects the student from everything “ugly”
underneath, does not serve most engineering students well, and it certainly does
not prepare them for the future.

Rippling Effects Through the Curriculum


The material of this text clearly has a rippling effect on what can be taught in
subsequent courses. Subsequent programming courses can not only assume the
students know the syntax of C/C++ but also understand how it relates to the
underlying architecture. Consequently, the focus can be on problem solving and
more sophisticated data structures. On the hardware side, a similar effect is seen
in courses in digital logic design and in computer organization. Students start the
logic design course with an appreciation of what the logic circuits they master are
good for. In the computer organization course, the starting point is much further
along than when students are seeing the term Program Counter for the first time.
Faculty members who have taught the follow-on courses have noticed substan-
tial improvement in students’ comprehension compared to what they saw before
students took our course.

Acknowledgments
It’s been 15 years since the second edition came out, and about 20 years since we
first put together a course pack of notes that eventually morphed into the first edi-
tion. Through those years, a good number of people have jumped in, volunteered
help, adopted the book, read through drafts, suggested improvements, and so on.
We could easily fill many pages if we listed all their names. We are indebted to
each of them, and we deeply appreciate their contributions.
Still, there are some folks we feel compelled to acknowledge here, and we
apologize to all those who have helped immeasurably, but are not mentioned here
due to space limitations.
First, Professor Kevin Compton. Kevin believed in the concept of the book
since it was first introduced at a curriculum committee meeting that he chaired at
Michigan in 1993. Kevin co-taught the course at Michigan the first four times it
was offered, in 1995–1997. His insights into programming methodology (inde-
pendent of the syntax of the particular language) provided a sound foundation for
the beginning student. The course at Michigan and this book would be a lot less
were it not for Kevin’s influence.
Several colleagues and students were our major go-to guys when it came
to advice, and insights, on the current version of the book and its future.
Wen-mei Hwu, Veynu Narasiman, Steve Lumetta, Matt Frank, Faruk Guvinilir,
xxvi Preface

Chirag Sakuja, Siavash Zanganeh, Stephen Pruett, Jim Goodman, and Soner
Onder have been particularly important to us since the second edition.
McGraw-Hill has been an important partner in this undertaking, starting with
Betsy Jones, our first editor. We sent the manuscript of our first edition to several
publishers and were delighted with the many positive responses. Nonetheless, one
editor stood out. Betsy immediately checked us out, and once she was satisfied,
she became a strong believer in what we were trying to accomplish. Throughout
the process of the first two editions, her commitment and energy, as well as that
of Michelle Flomenhoft, our first development editor, were greatly appreciated.
Fifteen years is a long time between editions, and with it have come a whole new
collection of folks from McGraw-Hill that we have recently been privileged to
work with, especially Dr. Thomas Scaife, Suzy Bainbridge, Heather Ervolino,
and Jeni McAtee.
Our book has benefited from extensive comments by faculty members from
many universities. Some were in formal reviews of the manuscript, others in
e-mails or conversations at technical conferences. We gratefully acknowledge
input from Professors Jim Goodman, Wisconsin and Aukland; Soner Onder,
Michigan Tech; Vijay Pai, Purdue; Richard Johnson, Western New Mexico; Tore
Larsen, Tromso; Greg Byrd, NC State; Walid Najjar, UC Riverside; Sean Joyce,
Heidelberg College; James Boettler, South Carolina State; Steven Zeltmann,
Arkansas; Mike McGregor, Alberta; David Lilja, Minnesota; Eric Thompson,
Colorado, Denver; Brad Hutchings, Brigham Young; Carl D. Crane III, Florida;
Nat Davis, Virginia Tech; Renee Elio, University of Alberta; Kelly Flangan,
BYU; George Friedman, UIUC; Franco Fummi, Universita di Verona; Dale
Grit, Colorado State; Thor Guisrud, Stavanger College; Dave Kaeli, North-
eastern; Rasool Kenarangui, UT, Arlington; Joel Kraft, Case Western Reserve;
Wei-Ming Lin, UT, San Antonio; Roderick Loss, Montgomery College; Ron
Meleshko, Grant MacEwan Community College; Andreas Moshovos, Toronto;
Tom Murphy, The Citadel; Murali Narayanan, Kansas State; Carla Purdy, Cincin-
nati; T. N. Rajashekhara, Camden County College; Nello Scarabottolo, Universita
degli Studi di Milano; Robert Schaefer, Daniel Webster College; Tage Stabell-
Kuloe, University of Tromsoe; Jean-Pierre Steger, Burgdorf School of Engi-
neering; Bill Sverdlik, Eastern Michigan; John Trono, St. Michael’s College;
Murali Varansi, University of South Florida; Montanez Wade, Tennessee State;
Carl Wick, US Naval Academy; Robert Crisp, Arkansas; Allen Tannenbaum,
Georgia Tech; Nickolas Jovanovic, Arkansas–Little Rock; Dean Brock, North
Carolina–Asheville; Amar Raheja, Cal State–Pomona; Dayton Clark, Brooklyn
College; William Yurcik, Illinois State; Jose Delgado-Frias, Washington State;
Peter Drexel, Plymouth State; Mahmoud Manzoul, Jackson State; Dan Con-
nors, Colorado; Massoud Ghyam, USC; John Gray, UMass–Dartmouth; John
Hamilton, Auburn; Alan Rosenthal, Toronto; and Ron Taylor, Wright State.
We have continually been blessed with enthusiastic, knowledgeable, and car-
ing TAs who regularly challenge us and provide useful insights into helping us
explain things better. Again, the list is too long – more than 100 at this point.
Almost all were very good; still, we want to mention a few who were particularly
helpful. Stephen Pruett, Siavash Zangeneh, Meiling Tang, Ali Fakhrzadehgan,
Sabee Grewal, William Hoenig, Matthew Normyle, Ben Lin, Ameya Chaudhari,
Preface xxvii

Nikhil Garg, Lauren Guckert, Jack Koenig, Saijel Mokashi, Sruti Nuthalapati,
Faruk Guvenilir, Milad Hashemi, Aater Suleman, Chang Joo Lee, Bhargavi
Narayanasetty, RJ Harden, Veynu Narasiman, Eiman Ebrahimi, Khubaib, Allison
Korczynski, Pratyusha Nidamaluri, Christopher Wiley, Cameron Davison, Lisa
de la Fuente, Phillip Duran, Jose Joao, Rustam Miftakhutdinov, Nady Obeid,
Linda Bigelow, Jeremy Carillo, Aamir Hasan, Basit Sheik, Erik Johnson, Tsung-
Wei Huang, Matthew Potok, Chun-Xun Lin, Jianxiong Gao, Danny Kim, and
Iou-Jen Liu.
Several former students, former colleagues, and friends reviewed chapters in
the book. We particularly wish to thank Rich Belgard, Alba Cristina de Melo,
Chirag Sakhuja, Sabee Grewal, Pradip Bose, and Carlos Villavieja for their
help doing this. Their insights have made a much more readable version of the
material.
We have been delighted by the enthusiastic response of our colleagues at
both The University of Texas at Austin and the University of Illinois, Urbana-
Champaign, who have taught from the book and shared their insights with us:
Derek Chiou, Jacob Abraham, Ramesh Yerraballi, Nina Telang, and Aater Sule-
man at Texas, and Yuting Chen, Sayan Mitra, Volodymyr Kindratenko, Yih-Chun
Hu, Seth Hutchinson, Steve Lumetta, Juan Jaramillo, Pratik Lahiri, and Wen-mei
Hwu at Illinois. Thank you.
Also, there are those who have contributed in many different and often unique
ways. Space dictates that we leave out the detail and simply list them and say
thank you. Amanda, Bryan, and Carissa Hwu, Mateo Valero, Rich Belgard, Aman
Aulakh, Minh Do, Milena Milenkovic, Steve Lumetta, Brian Evans, Jon Valvano,
Susan Kornfield, Ed DeFranco, Evan Gsell, Tom Conte, Dave Nagle, Bruce
Shriver, Bill Sayle, Dharma Agarwal, David Lilja, Michelle Chapman.
Finally, if you will indulge the first author a bit: This book is about developing
a strong foundation in the fundamentals with the fervent belief that once that is
accomplished, students can go as far as their talent and energy can take them.
This objective was instilled in me by the professor who taught me how to be a
professor, Professor William K. Linvill. It has been more than 50 years since I
was in his classroom, but I still treasure the example he set.

A Final Word
We are hopeful that you will enjoy teaching or studying from this third edition of
our book. However, as we said in the prefaces to both previous editions, we are
mindful that the current version of the book will always be a work in progress,
and both of us welcome your comments on any aspect of it. You can reach us by
email at patt@ece.utexas.edu and sjp@illinois.edu. We hope you will.
Yale N. Patt
Sanjay J. Patel
September, 2019
CHAPTER

1 Welcome Aboard

1.1 What We Will Try to Do


Welcome to From Bits and Gates to C and Beyond. Our intent is to introduce
you over the next xxx pages to the world of computing. As we do so, we have
one objective above all others: to show you very clearly that there is no magic to
computing. The computer is a deterministic system—every time we hit it over the
head in the same way and in the same place (provided, of course, it was in the same
starting condition), we get the same response. The computer is not an electronic
genius; on the contrary, if anything, it is an electronic idiot, doing exactly what
we tell it to do. It has no mind of its own.
What appears to be a very complex organism is really just a very large, sys-
tematically interconnected collection of very simple parts. Our job throughout
this book is to introduce you to those very simple parts and, step-by-step, build the
interconnected structure that you know by the name computer. Like a house, we
will start at the bottom, construct the foundation first, and then go on to add layer
after layer, as we get closer and closer to what most people know as a full-blown
computer. Each time we add a layer, we will explain what we are doing, tying the
new ideas to the underlying fabric. Our goal is that when we are done, you will be
able to write programs in a computer language such as C using the sophisticated
features of that language and to understand what is going on underneath, inside
the computer.

1.2 How We Will Get There


We will start (in Chapter 2) by first showing that any information processed by
the computer is represented by a sequence of 0s and 1s. That is, we will encode
all information as sequences of 0s and 1s. For example, one encoding of the letter
a that is commonly used is the sequence 01100001. One encoding of the decimal
number 35 is the sequence 00100011. We will see how to perform operations on
such encoded information.
2 chapter 1 Welcome Aboard

Once we are comfortable with information represented as codes made up of


0s and 1s and operations (addition, for example) being performed on these repre-
sentations, we will begin the process of showing how a computer works. Starting
in Chapter 3, we will note that the computer is a piece of electronic equipment
and, as such, consists of electronic parts operated by voltages and interconnected
by wires. Every wire in the computer, at every moment in time, is at either a high
voltage or a low voltage. For our representation of 0s and 1s, we do not specify
exactly how high. We only care whether there is or is not a large enough voltage
relative to 0 volts to identify it as a 1. That is, the absence or presence of a rea-
sonable voltage relative to 0 volts is what determines whether it represents the
value 0 or the value 1.
In Chapter 3, we will see how the transistors that make up today’s micro-
processor (the heart of the modern computer) work. We will further see how
those transistors are combined into larger structures that perform operations,
such as addition, and into structures that allow us to save information for later
use. In Chapter 4, we will combine these larger structures into the von Neumann
machine, a basic model that describes how a computer works. We will also begin
to study a simple computer, the LC-3. We will continue our study of the LC-3 in
Chapter 5. LC-3 stands for Little Computer 3. We actually started with LC-1 but
needed two more shots at it before (we think) we got it right! The LC-3 has all
the important characteristics of the microprocessors that you may have already
heard of, for example, the Intel 8088, which was used in the first IBM PCs back
in 1981. Or the Motorola 68000, which was used in the Macintosh, vintage 1984.
Or the Pentium IV, one of the high-performance microprocessors of choice for
the PC in the year 2003. Or today’s laptop and desktop microprocessors, the Intel
Core processors – I3, I5, and I7. Or even the ARM microprocessors that are used
in most smartphones today. That is, the LC-3 has all the important characteristics
of these “real” microprocessors without being so complicated that it gets in the
way of your understanding.
Once we understand how the LC-3 works, the next step is to program it, first
in its own language (Chapter 5 and Chapter 6), and then in a language called
assembly language that is a little bit easier for humans to work with (Chap-
ter 7). Chapter 8 introduces representations of information more complex than a
simple number – stacks, queues, and character strings, and shows how to imple-
ment them. Chapter 9 deals with the problem of getting information into (input)
and out of (output) the LC-3. Chapter 9 also deals with services provided to a
computer user by the operating system. We conclude the first half of the book
(Chapter 10) with an extensive example, the simulation of a calculator, an app on
most smartphones today.
In the second half of the book (Chapters 11–20), we turn our attention
to high-level programming concepts, which we introduce via the C and C++
programming languages. High-level languages enable programmers to more
effectively develop complex software by abstracting away the details of the under-
lying hardware. C and C++ in particular offer a rich set of programmer-friendly
constructs, but they are close enough to the hardware that we can examine
how code is transformed to execute on the layers below. Our goal is to enable
you to write short, simple programs using the core parts of these programming
1.3 Two Recurring Themes 3

languages, all the while being able to comprehend the transformations required
for your code to execute on the underlying hardware.
We’ll start with basic topics in C such as variables and operators (Chapter 12),
control structures (Chapter 13), and functions (Chapter 14). We’ll see that these are
straightforward extensions of concepts introduced in the first half of the textbook.
We then move on to programming concepts in Chapters 15–19 that will enable
us to create more powerful pieces of code: Testing and Debugging (Chapter 15),
Pointers and Arrays in C (Chapter 16), Recursion (Chapter 17), Input and Output in
C (Chapter 18), and Data Structures in C (Chapter 19).
Chapters 20 is devoted to C++, which we present as an evolution of the
C programming language. Because the C++ language was initially defined as
a superset of C, many of the concepts covered in Chapters 11–19 directly map
onto the C++ language. We will introduce some of the core notions in C++ that
have helped establish C++ as one of the most popular languages for developing
real-world software. Chapter 20 is our Introduction to C++.
In almost all cases, we try to tie high-level C and C++ constructs to the
underlying LC-3 so that you will understand what you demand of the computer
when you use a particular construct in a C or C++ program.

1.3 Two Recurring Themes


Two themes permeate this book that we as professors previously took for granted,
assuming that everyone recognized their value and regularly emphasized them
to students of engineering and computer science. However, it has become clear
to us that from the git-go, we need to make these points explicit. So, we state
them here up front. The two themes are (a) the notion of abstraction and (b) the
importance of not separating in your mind the notions of hardware and software.
Their value to your development as an effective engineer or computer scien-
tist goes well beyond your understanding of how a computer works and how to
program it.
The notion of abstraction is central to all that you will learn and expect to
use in practicing your craft, whether it be in mathematics, physics, any aspect of
engineering, or business. It is hard to think of any body of knowledge where the
notion of abstraction is not critical.
The misguided hardware/software separation is directly related to your
continuing study of computers and your work with them.
We will discuss each in turn.

1.3.1 The Notion of Abstraction


The use of abstraction is all around us. When we get in a taxi and tell the driver,
“Take me to the airport,” we are using abstraction. If we had to, we could probably
direct the driver each step of the way: “Go down this street ten blocks, and make
a left turn.” And, when the driver got there, “Now take this street five blocks and
make a right turn.” And on and on. You know the details, but it is a lot quicker to
just tell the driver to take you to the airport.
4 chapter 1 Welcome Aboard

Even the statement “Go down this street ten blocks …” can be broken down
further with instructions on using the accelerator, the steering wheel, watching
out for other vehicles, pedestrians, etc.
Abstraction is a technique for establishing a simpler way for a person to inter-
act with a system, removing the details that are unnecessary for the person to
interact effectively with that system. Our ability to abstract is very much a pro-
ductivity enhancer. It allows us to deal with a situation at a higher level, focusing
on the essential aspects, while keeping the component ideas in the background.
It allows us to be more efficient in our use of time and brain activity. It allows us
to not get bogged down in the detail when everything about the detail is working
just fine.
There is an underlying assumption to this, however: when everything about
the detail is just fine. What if everything about the detail is not just fine? Then,
to be successful, our ability to abstract must be combined with our ability to
un-abstract. Some people use the word deconstruct—the ability to go from the
abstraction back to its component parts.
Two stories come to mind.
The first involves a trip through Arizona the first author made a long time
ago in the hottest part of the summer. At the time he was living in Palo Alto,
California, where the temperature tends to be mild almost always. He knew
enough to take the car to a mechanic before making the trip and tell him to check
the cooling system. That was the abstraction: cooling system. What he had not
mastered was that the capability of a cooling system for Palo Alto, California,
is not the same as the capability of a cooling system for the summer deserts of
Arizona. The result: two days in Deer Lodge, Arizona (population 3), waiting for
a head gasket to be shipped in.
The second story (perhaps apocryphal) is supposed to have happened during
the infancy of electric power generation. General Electric Co. was having trouble
with one of its huge electric power generators and did not know what to do. On
the front of the generator were lots of dials containing lots of information, and
lots of screws that could be rotated clockwise or counterclockwise as the operator
wished. Something on the other side of the wall of dials and screws was malfunc-
tioning and no one knew what to do. As the story goes, they called in one of the
early giants in the electric power industry. He looked at the dials and listened to
the noises for a minute, then took a small screwdriver from his pocket and rotated
one screw 35 degrees counterclockwise. The problem immediately went away. He
submitted a bill for $1000 (a lot of money in those days) without any elaboration.
The controller found the bill for two minutes’ work a little unsettling and asked
for further clarification. Back came the new bill:

Turning a screw 35 degrees counterclockwise: $ 0.75


Knowing which screw to turn and by how much: 999.25

In both stories the message is the same. It is more efficient to think of entities
as abstractions. One does not want to get bogged down in details unnecessarily.
And as long as nothing untoward happens, we are OK. If there had been no trip
to Arizona, the abstraction “cooling system” would have been sufficient. If the
1.3 Two Recurring Themes 5

electric power generator never malfunctioned, there would have been no need for
the power engineering guru’s deeper understanding.
As we will see, modern computers are composed of transistors. These tran-
sistors are combined to form logic “gates”—an abstraction that lets us think in
terms of 0s and 1s instead of the varying voltages on the transistors. A logic cir-
cuit is a further abstraction of a combination of gates. When one designs a logic
circuit out of gates, it is much more efficient to not have to think about the inter-
nals of each gate. To do so would slow down the process of designing the logic
circuit. One wants to think of the gate as a component. But if there is a problem
with getting the logic circuit to work, it is often helpful to look at the internal
structure of the gate and see if something about its functioning is causing the
problem.
When one designs a sophisticated computer application program, whether it
be a new spreadsheet program, word processing system, or computer game, one
wants to think of each of the components one is using as an abstraction. If one
spent time thinking about the details of each component when it was not neces-
sary, the distraction could easily prevent the total job from ever getting finished.
But when there is a problem putting the components together, it is often useful to
examine carefully the details of each component in order to uncover the problem.
The ability to abstract is the most important skill. In our view, one should
try to keep the level of abstraction as high as possible, consistent with getting
everything to work effectively. Our approach in this book is to continually raise
the level of abstraction. We describe logic gates in terms of transistors. Once we
understand the abstraction of gates, we no longer think in terms of transistors.
Then we build larger structures out of gates. Once we understand these larger
abstractions, we no longer think in terms of gates.

The Bottom Line Abstractions allow us to be much more efficient in dealing


with all kinds of situations. It is also true that one can be effective without under-
standing what is below the abstraction as long as everything behaves nicely. So,
one should not pooh-pooh the notion of abstraction. On the contrary, one should
celebrate it since it allows us to be more efficient.
In fact, if we never have to combine a component with anything else into a
larger system, and if nothing can go wrong with the component, then it is perfectly
fine to understand this component only at the level of its abstraction.
But if we have to combine multiple components into a larger system, we
should be careful not to allow their abstractions to be the deepest level of our
understanding. If we don’t know the components below the level of their abstrac-
tions, then we are at the mercy of them working together without our intervention.
If they don’t work together, and we are unable to go below the level of abstraction,
we are stuck. And that is the state we should take care not to find ourselves in.

1.3.2 Hardware vs. Software


Many computer scientists and engineers refer to themselves as hardware people
or software people. By hardware, they generally mean the physical computer and
6 chapter 1 Welcome Aboard

all the specifications associated with it. By software, they generally mean the pro-
grams, whether operating systems like Android, ChromeOS, Linux, or Windows,
or database systems like Access, MongoDB, Oracle, or DB-terrific, or applica-
tion programs like Facebook, Chrome, Excel, or Word. The implication is that
the person knows a whole lot about one of these two things and precious little
about the other. Usually, there is the further implication that it is OK to be an
expert at one of these (hardware OR software) and clueless about the other. It is
as if there were a big wall between the hardware (the computer and how it actu-
ally works) and the software (the programs that direct the computer to do their
bidding), and that one should be content to remain on one side of that wall or
the other.
The power of abstraction allows us to “usually” operate at a level where we
do not have to think about the underlying layers all the time. This is a good thing.
It enables us to be more productive. But if we are clueless about the underlying
layers, then we are not able to take advantage of the nuances of those underlying
layers when it is very important to be able to.
That is not to say that you must work at the lower level of abstraction and not
take advantage of the productivity enhancements that the abstractions provide.
On the contrary, you are encouraged to work at the highest level of abstraction
available to you. But in doing so, if you are able to, at the same time, keep in
mind the underlying levels, you will find yourself able to do a much better job.
As you approach your study and practice of computing, we urge you to take
the approach that hardware and software are names for components of two parts
of a computing system that work best when they are designed by people who take
into account the capabilities and limitations of both.
Microprocessor designers who understand the needs of the programs that
will execute on the microprocessor they are designing can design much more
effective microprocessors than those who don’t. For example, Intel, AMD, ARM,
and other major producers of microprocessors recognized a few years ago that a
large fraction of future programs would contain video clips as part of e-mail,
video games, and full-length movies. They recognized that it would be impor-
tant for such programs to execute efficiently. The result: most microprocessors
today contain special hardware capability to process those video clips. Intel
defined additional instructions, initially called their MMX instruction set, and
developed special hardware for it. Motorola, IBM, and Apple did essentially
the same thing, resulting in the AltiVec instruction set and special hardware to
support it.
A similar story can be told about software designers. The designer of a large
computer program who understands the capabilities and limitations of the hard-
ware that will carry out the tasks of that program can design the program so it
executes more efficiently than the designer who does not understand the nature of
the hardware. One important task that almost all large software systems need to
carry out is called sorting, where a number of items have to be arranged in some
order. The words in a dictionary are arranged in alphabetical order. Students in
a class are often graded based on a numerical order, according to their scores
on the final exam. There is a large number of fundamentally different programs
one can write to arrange a collection of items in order. Donald Knuth, one of the
1.4 A Computer System 7

top computer scientists in the world, devoted 391 pages to the task in The Art
of Computer Programming, vol. 3. Which sorting program works best is often
very dependent on how much the software designer is aware of the underlying
characteristics of the hardware.

The Bottom Line We believe that whether your inclinations are in the direction
of a computer hardware career or a computer software career, you will be much
more capable if you master both. This book is about getting you started on the
path to mastering both hardware and software. Although we sometimes ignore
making the point explicitly when we are in the trenches of working through a
concept, it really is the case that each sheds light on the other.
When you study data types, a software concept, in C (Chapter 12), you will
understand how the finite word length of the computer, a hardware concept,
affects our notion of data types.
When you study functions in C (Chapter 14), you will be able to tie the rules
of calling a function with the hardware implementation that makes those rules
necessary.
When you study recursion, a powerful algorithmic device (initially in
Chapter 8 and more extensively in Chapter 17), you will be able to tie it to the
hardware. If you take the time to do that, you will better understand when the
additional time to execute a procedure recursively is worth it.
When you study pointer variables in C (in Chapter 16), your knowledge of
computer memory will provide a deeper understanding of what pointers pro-
vide, and very importantly, when they should be used and when they should be
avoided.
When you study data structures in C (in Chapter 19), your knowledge of com-
puter memory will help you better understand what must be done to manipulate
the actual structures in memory efficiently.
We realize that most of the terms in the preceding five short paragraphs may
not be familiar to you yet. That is OK; you can reread this page at the end of the
semester. What is important to know right now is that there are important topics
in the software that are very deeply interwoven with topics in the hardware. Our
contention is that mastering either is easier if you pay attention to both.
Most importantly, most computing problems yield better solutions when the
problem solver has the capability of both at his or her disposal.

1.4 A Computer System


We have used the word computer more than two dozen times in the preceding
pages, and although we did not say so explicitly, we used it to mean a system
consisting of the software (i.e., computer programs) that directs and specifies the
processing of information and the hardware that performs the actual processing
of information in response to what the software asks the hardware to do. When
we say “performing the actual processing,” we mean doing the actual additions,
multiplications, and so forth in the hardware that are necessary to get the job
8 chapter 1 Welcome Aboard

done. A more precise term for this hardware is a central processing unit (CPU),
or simply a processor or microprocessor. This textbook is primarily about the
processor and the programs that are executed by the processor.

1.4.1 A (Very) Little History for a (Lot) Better Perspective


Before we get into the detail of how the processor and the software associated
with it work, we should take a moment and note the enormous and unparalleled
leaps of performance that the computing industry has made in the relatively short
time computers have been around. After all, it wasn’t until the 1940s that the
first computers showed their faces. One of the first computers was the ENIAC
(the Electronic Numerical Integrator and Calculator), a general purpose electronic
computer that could be reprogrammed for different tasks. It was designed and built
in 1943–1945 at the University of Pennsylvania by Presper Eckert and his colleagues.
It contained more than 17,000 vacuum tubes. It was approximately 8 feet high, more
than 100 feet wide, and about 3 feet deep (about 300 square feet of floor space). It
weighed 30 tons and required 140 kW to operate. Figure 1.1 shows three operators
programming the ENIAC by plugging and unplugging cables and switches.
About 40 years and many computer companies and computers later, in the
early 1980s, the Burroughs A series was born. One of the dozen or so 18-inch
boards that comprise that machine is shown in Figure 1.2. Each board contained
50 or more integrated circuit packages. Instead of 300 square feet, it took up
around 50 to 60 square feet; instead of 30 tons, it weighed about 1 ton, and instead
of 140 kW, it required approximately 25 kW to operate.

Figure 1.1 The ENIAC, designed and built at University of Pennsylvania, 1943–45.

c Historical/Getty Images
1.4 A Computer System 9

Figure 1.2 A processor board, vintage 1980s. Courtesy of Emilio Salguerio

Fast forward another 30 or so years and we find many of today’s computers on


desktops (Figure 1.3), in laptops (Figure 1.4), and most recently in smartphones
(Figure 1.5). Their relative weights and energy requirements have decreased
enormously, and the speed at which they process information has also increased
enormously. We estimate that the computing power in a smartphone today (i.e.,
how fast we can compute with a smartphone) is more than four million times the
computing power of the ENIAC!

Figure 1.3 Figure 1.4 A laptop. 


c Rob Figure 1.5 A smartphone. 
c Oleksiy
A desktop computer. Monk/Future/ Maksymenko/

c Joby Sessions/ REX/Shutterstock imageBROKER/REX/Shutterstock
Future/REX/
Shutterstock
10 chapter 1 Welcome Aboard

Figure 1.6 A microprocessor. 


c Peter Gudella/Shutterstock

The integrated circuit packages that comprise modern digital computers have
also seen phenomenal improvement. An example of one of today’s microproces-
sors is shown in Figure 1.6. The first microprocessor, the Intel 4004 in 1971,
contained 2300 transistors and operated at 106 KHz. By 1992, those numbers
had jumped to 3.1 million transistors at a frequency of 66 MHz on the Intel
Pentium microprocessor, an increase in both parameters of a factor of about 1000.
Today’s microprocessors contain upwards of five billion transistors and can oper-
ate at upwards of 4 GHz, another increase in both parameters of about a factor
of 1000.
This factor of one million since 1971 in both the number of transistors and
the frequency that the microprocessor operates at has had very important impli-
cations. The fact that each operation can be performed in one millionth of the
time it took in 1971 means the microprocessor can do one million things today
in the time it took to do one thing in 1971. The fact that there are more than a
million times as many transistors on a chip means we can do a lot more things at
the same time today than we could in 1971.
The result of all this is we have today computers that seem able to understand
the languages people speak – English, Spanish, Chinese, for example. We have
computers that seem able to recognize faces. Many see this as the magic of artifi-
cial intelligence. We will see as we get into the details of how a computer works
that much of what appears to be magic is really due to how blazingly fast very
simple mindless operations (many at the same time) can be carried out.

1.4.2 The Parts of a Computer System


When most people use the word computer, they usually mean more than just
the processor (i.e., CPU) that is in charge of doing what the software directs.
1.5 Two Very Important Ideas 11

They usually mean the collection of parts that in combination form their computer
system. Today that computer system is often a laptop (see Figure 1.4), augmented
with many additional devices.
A computer system generally includes, in addition to the processor, a key-
board for typing commands, a mouse or keypad or joystick for positioning on
menu entries, a monitor for displaying information that the computer system has
produced, memory for temporarily storing information, disks and USB memory
sticks of one sort or another for storing information for a very long time, even after
the computer has been turned off, connections to other devices such as a printer
for obtaining paper copies of that information, and the collection of programs
(the software) that the user wishes to execute.
All these items help computer users to do their jobs. Without a printer, for
example, the user would have to copy by hand what is displayed on the monitor.
Without a mouse, keypad, or joystick, the user would have to type each command,
rather than simply position the mouse, keypad, or joystick.
So, as we begin our journey, which focuses on the CPU that occupies a small
fraction of 1 square inch of silicon and the software that makes the CPU do our
bidding, we note that the computer systems we use contain a lot of additional
components.

1.5 Two Very Important Ideas


Before we leave this first chapter, there are two very important ideas that we
would like you to understand, ideas that are at the core of what computing is all
about.
Idea 1: All computers (the biggest and the smallest, the fastest and the
slowest, the most expensive and the cheapest) are capable of comput-
ing exactly the same things if they are given enough time and enough
memory. That is, anything a fast computer can do, a slow computer can
do also. The slow computer just does it more slowly. A more expensive
computer cannot figure out something that a cheaper computer is unable
to figure out as long as the cheaper computer can access enough mem-
ory. (You may have to go to the store to buy more memory whenever it
runs out of memory in order to keep increasing memory.) All computers
can do exactly the same things. Some computers can do things faster,
but none can do more than any other.
Idea 2: We describe our problems in English or some other language
spoken by people. Yet the problems are solved by electrons running
around inside the computer. It is necessary to transform our problem
from the language of humans to the voltages that influence the flow of
electrons. This transformation is really a sequence of systematic trans-
formations, developed and improved over the last 70 years, which
combine to give the computer the ability to carry out what appear to
12 chapter 1 Welcome Aboard

be some very complicated tasks. In reality, these tasks are simple and
straightforward.
The rest of this chapter is devoted to discussing these two ideas.

1.6 Computers as Universal


Computational Devices
It may seem strange that an introductory textbook begins by describing how
computers work. After all, mechanical engineering students begin by studying
physics, not how car engines work. Chemical engineering students begin by
studying chemistry, not oil refineries. Why should computing students begin by
studying computers?
The answer is that computers are different. To learn the fundamental prin-
ciples of computing, you must study computers or machines that can do what
computers can do. The reason for this has to do with the notion that computers
are universal computational devices. Let’s see what that means.
Before modern computers, there were many kinds of calculating machines.
Some were analog machines—machines that produced an answer by measuring
some physical quantity such as distance or voltage. For example, a slide rule is
an analog machine that multiplies numbers by sliding one logarithmically graded
ruler next to another. The user can read a logarithmic “distance” on the sec-
ond ruler. Some early analog adding machines worked by dropping weights on a
scale. The difficulty with analog machines is that it is very hard to increase their
accuracy.
This is why digital machines—machines that perform computations by
manipulating a fixed finite set of digits or letters—came to dominate comput-
ing. You are familiar with the distinction between analog and digital watches. An
analog watch has hour and minute hands, and perhaps a second hand. It gives
the time by the positions of its hands, which are really angular measures. Digital
watches give the time in digits. You can increase accuracy just by adding more
digits. For example, if it is important for you to measure time in hundredths of
a second, you can buy a watch that gives a reading like 10:35.16 rather than just
10:35. How would you get an analog watch that would give you an accurate read-
ing to one one-hundredth of a second? You could do it, but it would take a mighty
long second hand! When we talk about computers in this book, we will always
mean digital machines.
Before modern digital computers, the most common digital machines in the
West were adding machines. In other parts of the world another digital machine,
the abacus, was common. Digital adding machines were mechanical or elec-
tromechanical devices that could perform a specific kind of computation: adding
integers. There were also digital machines that could multiply integers. There
were digital machines that could put a stack of cards with punched names in
alphabetical order. The main limitation of all these machines is that they could
do only one specific kind of computation. If you owned only an adding machine
1.6 Computers as Universal Computational Devices 13

and wanted to multiply two integers, you had some pencil-and-paper work
to do.
This is why computers are different. You can tell a computer how to add num-
bers. You can tell it how to multiply. You can tell it how to alphabetize a list or
perform any computation you like. When you think of a new kind of computation,
you do not have to buy or design a new computer. You just give the old computer
a new set of instructions (a program) to carry out the new computation. This is
why we say the computer is a universal computational device. Computer scien-
tists believe that anything that can be computed, can be computed by a computer
provided it has enough time and enough memory. When we study computers, we
study the fundamentals of all computing. We learn what computation is and what
can be computed.
The idea of a universal computational device is due to Alan Turing. Turing
proposed in 1937 that all computations could be carried out by a particular kind of
machine, which is now called a Turing machine. He gave a mathematical descrip-
tion of this kind of machine, but did not actually build one. Digital computers
were not operating until several years later. Turing was more interested in solv-
ing a philosophical problem: defining computation. He began by looking at the
kinds of actions that people perform when they compute; these include making
marks on paper, writing symbols according to certain rules when other symbols
are present, and so on. He abstracted these actions and specified a mechanism that
could carry them out. He gave some examples of the kinds of things that these
machines could do. One Turing machine could add two integers; another could
multiply two integers.
Figure 1.7 shows what we call “black box” models of Turing machines that
add and multiply. In each case, the operation to be performed is described in
the box. The data elements on which to operate are shown as inputs to the box.
The result of the operation is shown as output from the box. A black box model
provides no information as to exactly how the operation is performed, and indeed,
there are many ways to add or multiply two numbers.

TADD TMUL
a, b a+b a, b a×b
(Turing machine (Turing machine
that adds) that multiplies)

Figure 1.7 Black box models of Turing machines.

Turing proposed that every computation can be performed by some Turing


machine. We call this Turing’s thesis. Although Turing’s thesis has never been
proved, there does exist a lot of evidence to suggest it is true. We know, for exam-
ple, that various enhancements one can make to Turing machines do not result in
machines that can compute more.
Perhaps the best argument to support Turing’s thesis was provided by Turing
himself in his original paper. He said that one way to try to construct a machine
more powerful than any particular Turing machine was to make a machine U
that could simulate all Turing machines. You would simply describe to U the
14 chapter 1 Welcome Aboard

particular Turing machine you wanted it to simulate, say a machine to add two
integers, give U the input data, and U would compute the appropriate output,
in this case the sum of the inputs. Turing then showed that there was, in fact,
a Turing machine that could do this, so even this attempt to find something that
could not be computed by Turing machines failed.
Figure 1.8 further illustrates the point. Suppose you wanted to compute
g ⋅ (e + f ). You would simply provide to U descriptions of the Turing machines
to add and to multiply, and the three inputs, e, f , and g. U would do the rest.

TADD, TMUL
U
g × (e + f )

e, f, g (Universal
Turing machine)

Figure 1.8 Black box model of a universal Turing machine.

In specifying U, Turing had provided us with a deep insight: He had given us


the first description of what computers do. In fact, both a computer (with as much
memory as it wants) and a universal Turing machine can compute exactly the
same things. In both cases, you give the machine a description of a computation
and the data it needs, and the machine computes the appropriate answer. Comput-
ers and universal Turing machines can compute anything that can be computed
because they are programmable.
This is the reason that a big or expensive computer cannot do more than a
small, cheap computer. More money may buy you a faster computer, a monitor
with higher resolution, or a nice sound system. But if you have a small, cheap
computer, you already have a universal computational device.

1.7 How Do We Get the Electrons to


Do the Work?
Figure 1.9 shows the process we must go through to get the electrons (which
actually do the work) to do our bidding. We call the steps of this process the
“Levels of Transformation.” As we will see, at each level we have choices. If we
ignore any of the levels, our ability to make the best use of our computing system
can be very adversely affected.

1.7.1 The Statement of the Problem


We describe the problems we wish to solve in a “natural language.” Natural lan-
guages are languages that people speak, like English, French, Japanese, Italian,
and so on. They have evolved over centuries in accordance with their usage.
They are fraught with a lot of things unacceptable for providing instructions to a
1.7 How Do We Get the Electrons to Do the Work? 15

Problems

Algorithms

Language

Machine (ISA) Architecture

Microarchitecture

Circuits

Devices
Figure 1.9 Levels of transformation.

computer. Most important of these unacceptable attributes is ambiguity. Natural


language is filled with ambiguity. To infer the meaning of a sentence, a listener is
often helped by the tone of voice of the speaker, or at the very least, the context
of the sentence.
An example of ambiguity in English is the sentence, “Time flies like an
arrow.” At least three interpretations are possible, depending on whether (1) one is
noticing how fast time passes, (2) one is at a track meet for insects, or (3) one is
writing a letter to the Dear Abby of Insectville. In the first case, a simile; one
is comparing the speed of time passing to the speed of an arrow that has been
released. In the second case, one is telling the timekeeper to do his/her job much
like an arrow would. In the third case, one is relating that a particular group of
flies (time flies, as opposed to fruit flies) are all in love with the same arrow.
Such ambiguity would be unacceptable in instructions provided to a com-
puter. The computer, electronic idiot that it is, can only do as it is told. To tell it to
do something where there are multiple interpretations would cause the computer
to not know which interpretation to follow.
16 chapter 1 Welcome Aboard

1.7.2 The Algorithm


The first step in the sequence of transformations is to transform the natural lan-
guage description of the problem to an algorithm, and in so doing, get rid of the
objectionable characteristics of the natural language. An algorithm is a step-by-
step procedure that is guaranteed to terminate, such that each step is precisely
stated and can be carried out by the computer. There are terms to describe each
of these properties.
We use the term definiteness to describe the notion that each step is precisely
stated. A recipe for excellent pancakes that instructs the preparer to “stir until
lumpy” lacks definiteness, since the notion of lumpiness is not precise.
We use the term effective computability to describe the notion that each step
can be carried out by a computer. A procedure that instructs the computer to “take
the largest prime number” lacks effective computability, since there is no largest
prime number.
We use the term finiteness to describe the notion that the procedure termi-
nates.
For every problem there are usually many different algorithms for solving
that problem. One algorithm may require the fewest steps. Another algorithm
may allow some steps to be performed concurrently. A computer that allows
more than one thing to be done at a time can often solve the problem in less
time, even though it is likely that the total number of steps to be performed has
increased.

1.7.3 The Program


The next step is to transform the algorithm into a computer program in one of the
programming languages that are available. Programming languages are “mechan-
ical languages.” That is, unlike natural languages, mechanical languages did not
evolve through human discourse. Rather, they were invented for use in specify-
ing a sequence of instructions to a computer. Therefore, mechanical languages do
not suffer from failings such as ambiguity that would make them unacceptable for
specifying a computer program.
There are more than 1000 programming languages. Some have been designed
for use with particular applications, such as Fortran for solving scientific calcula-
tions and COBOL for solving business data-processing problems. In the second
half of this book, we will use C and C++, languages that were designed for
manipulating low-level hardware structures.
Other languages are useful for still other purposes. Prolog is the language of
choice for many applications that require the design of an expert system. LISP
was for years the language of choice of a substantial number of people working
on problems dealing with artificial intelligence. Pascal is a language invented as
a vehicle for teaching beginning students how to program.
There are two kinds of programming languages, high-level languages and
low-level languages. High-level languages are at a distance (a high level) from
the underlying computer. At their best, they are independent of the computer on
which the programs will execute. We say the language is “machine independent.”
Another random document with
no related content on Scribd:
The justice glanced at the superintendent who seemed
uncomfortable. I suspect that glance deterred the man from offering
to pay the fine. Alas, he was paying the penalty that every man who
dealt with Hervey had to pay; he was feeling contemptible for doing
what was right.
“Oh bimbo, that’s a lot for a feller to have,” said Hervey. “Will you
please not send me to jail—please?”
The justice studied him. It was perfectly evident that he was
resolved to make him an example, but also that was disposed to
temper his judgment with consideration. “No, it don’t need that you
go to jail, I guess,” he drawled: “not if you’re honest. I’ll parole you till
twelve o’clock to-morrow. If you don’t come and pay your fine then,
we’ll have to send for you. You have parents, I suppose?”
“Y—yes—I have.”
“Very well then, you come here to-morrow not later than twelve
o’clock and pay your fine. And I think then you’ll have had your
lesson.” The official glanced significantly at General Pond’s man as if
to say he thought that was the best solution.
And General Pond’s man made a wry face, as if to say that he
supposed so.
As for Hervey, he was so thankful to go free that he did not for the
moment concern himself about the fine. His captor did not
accompany him, but stayed behind to look at the justice’s radio set.
He went out into the road with Hervey, however, and showed him
how he could get back to the ball field without crossing the Pond
estate.
“Does parole mean that you’re—sort of—not free yet?” he asked.
“That’s it, sonny,” said the superintendent. “Long as you don’t fail
you’re all right. You just tell your father. Every kid is entitled to one
flop I suppose; they say every dog is entitled to one bite. And now
you get your lesson. Scoot along now and I hope your team wins.”
CHAPTER XIX
THE COMEBACK
That was all very well but, you see, this was not Hervey’s first flop.
It was his second one in three days. He was very subdued going
home in the bus, and refrained from telling any one of his adventure
beyond the fence. It was important that his father should not hear of
it.
Not that his father would think the affair so terrible, considered by
itself. It was against the background of his father’s mood that it
seemed so bad. At all events it was very unfortunate. His father was
in no humor to consider all the circumstances. If he knew that
Hervey had been arrested and fined, that would be enough. Hervey
could not tell him after the warning he had so recently received.
But he must get five dollars, and he knew not what to do. Five
dollars seemed a good deal of money to get without giving a pretty
good reason. And he had to get it within a brief, specified time.
Failing, he had visions of an official from Farrelton Junction coming
to get him.
He was very quiet at the supper table that evening and afterward
asked Mr. Walton if he might go out for a while. He had thought that
he might confide in his stepfather and take a chance on the
consequences, but he could not bring himself to do that. He thought
of his stepmother, always kind and affectionate, but he was afraid
she would be agitated at the knowledge of his predicament and take
counsel with her husband. Here again Hervey did not quite dare to
take a chance. He thought of Myra, the hired girl. But Myra was
spending the night with her people and Hervey did not like to seek
her there.
He went down in the cellar and got out his bicycle, the only thing
of value that he possessed. He took it out the cellar way and rode it
downtown to Berly’s Bicycle Shop. It would probably be some days
before either Mr. or Mrs. Walton would ask about the bicycle, and
Hervey’s thought, as usual, did not reach beyond the immediate
present. He did not like the idea of selling his bicycle; it had never
seemed quite so dear to him as on that very ride downtown. But this
was the only solution of his problem.
Mr. Berly looked the machine over leisurely. “How much do you
want for it?” he asked.
It had never occurred to Hervey to ask for more than the sum he
needed, but now he realized that he might sell the bicycle and be a
millionaire in the bargain. “Would you give—twelve dollars for it?” he
ventured timorously.
Mr. Berly scrutinized him. “Your parents want you to sell it?” he
asked.
“Don’t it belong to me?” said Hervey uncomfortably.
“Well, I think you better ask your folks about it first,” the dealer
said. “See what they say, then if everything is all right you come back
here and I’ll give you the right price for it.”
Hervey’s hopes were dashed. He rode his bike down the street
with an odd feeling of being both glad and sorry. But mainly he was
worried, for time was precious and he knew he must do something.
He stopped in front of the home of Harlem Hinkey and gave his
familiar call. He hoped Hinkey would come out, yet somehow he
hoped he wouldn’t come out. He hardly knew how he would
approach the subject with Hinkey.
The Hinkeys had a great deal of money and supplied their son
rather too liberally with it. They had lately moved from New York, and
since Hinkey was unpopular and Hervey was an odd number, they
had struck up acquaintance. Hinkey was a devotee of the practical
joke and his joy was always in proportion to the discomfort of his
victims. He boasted much of his imperial status in Harlem where he
had held sway until his father took over a motion picture theatre in
Farrelton. He came sauntering out in response to Hervey’s call. And
all inadvertently he made it easy for Hervey to begin.
“You want to go down to the show?” Hinkey asked.
“I would except for this blamed old bike,” said Hervey. “Bimbo, I’d
sell the darned thing for five dollars, it’s such a blamed nuisance.”
“What are you riding it for then?”
“I’m just bringing it home from Berly’s Bicycle Shop,” said Hervey.
“I never use it much. Places where I go, you couldn’t ride a bike. If
you should meet any one that wants to buy a bike, let me know, will
you?”
“Sure,” said Hinkey, uninterested.
“Do you want to buy it?” Hervey asked, emboldened.
“What would I want to buy it for when I drive a car?” Hinkey asked.
That was Hervey’s last hope. He rode his bike home, put it in the
cellar and went upstairs to his room. He had many times disregarded
the law, but he had never before found himself at grips with it like
this. And all because he had been just a little heedless in pursuing a
ball. He thought that the whole business was monstrously unfair.
What had he done that was so bad? It never occurred to him that
the whole trouble was this— that he had got himself into a position
where he could not move either way. He could not run the risk of
making a confident of Mr. Walton in this small matter because of
other matters. This matter was serious only because he had made it
so. He was in a predicament, as he always was. Once he had hung
from a tree by his feet and could not let go nor yet regain hold with
his hands. And there you have Hervey. Mental quandaries or
physical quandaries, it was all the same.
Well, there was one thing he could do which he had many times
thought of doing; he could run away from home. That seemed to be
the only thing left to do. He had many times made unauthorized
excursions from home, but he had never run away. Happy-go-lucky
and reckless as he was, he could not think of this without a tremor.
But it was the only thing to do. He would not go to jail even for a day,
he could not pay his fine, and he dared not tell his stepfather of his
predicament. He resolved to run away.
Once resolved to do a thing, Hervey was never at a loss. He
would go away and he would never return. He would go that very
night. Since he was unable to meet the situation he had a feeling
that at any moment something might happen. Yet he did not know
where to go. Well, he would think about that after he got in bed and
would start off early in the morning; that would be better. There was
a circus in Clover Valley. Why wouldn’t it be a good idea to hike there
and join the circus? Surely they could give him a job. And pretty
soon he would be miles and miles distant. He had had enough of
Farrelton and all this business....
He started to undress, but he was not altogether happy. Suppose
everything did not go right? He had no money—oh well, a lot he
cared! He sat on the edge of the bed unlacing his shoes. No
promptings of sentiment stood in the way of his resolve. But running
away from home without any money was a serious business and he
wondered just how he was going to manage it. He would like to go to
sea, only in this inland city⸺
He was startled by the banging of the front door knocker
downstairs. The sound broke upon his worried cogitations like a
hundred earthquakes. Who could that be at half past nine at night?
He heard footfalls in the hall below, then muffled voices. He crept to
his door, opened it a little, and listened. He was trembling, he knew
not why. That justice man had given him till the next day; if⸺ Why
it wouldn’t be fair at all.
Yet he distinctly heard the word punished uttered by a strange
voice. His heart was in his mouth. Should he climb out through the
window and jump from the roof of the kitchen shed, and then run?
What were they talking about down there? He heard the word police.
Perhaps they knew he could not get the money and were taking no
chances. Then he heard the gentle voice of his stepmother saying,
“The poor boy.” That was himself. He rushed to the window, threw up
the screen, put one foot out. He heard footfalls on the stairs. They
seemed to come half way up, then paused.
“Hervey, dear,” Mrs. Walton called.
He did not answer, but in a sudden impulse sprang back into the
room and grabbed his outlandish, rimless hat from one of the posts
of his old-fashioned bed.
“Hervey, dear?”
She opened the door just as he sat straddling the window-sill
ready to slide off the little shed roof.
“Here’s a letter for you, Hervey; a young fellow just left it. What on
earth are you doing, my dear boy? You’ll have the room full of flies
and moth millers.”
He came back into the room, tore open the envelope which his
astonished stepmother handed him, and the next thing he knew he
was reading a note, conscious all the while that part of it had
fluttered to the floor.

Dear Hervey:—
I was mighty sorry to learn that you’ve given us up. Craig
Hobson told me and he seems to think it wouldn’t be worth while
talking to you. Of course, it’s better to be out of the Scouts than
to be in and not interested. He says you can’t be in anything and
maybe after all he’s right.
You care so little about our thriving troop that I dare say you
have forgotten about the Delmore prize of five dollars to every
boy that introduces another boy to scouting. Chesty McCullen
went to give your message to Craig and Warner this morning
and stayed at their lawn camp and ate spaghetti and begged to
be allowed to take your place in the patrol. Of course, nobody
can take the place of Hervey Willetts, but Chesty is all dolled up
with a clean face and we’ve taken him in and of course, we feel
that you’re the fellow that wished him onto us.
So here’s the five dollars, Herve, for introducing a new
member into the troop and please accept my thanks as your
scoutmaster, and the thanks of all these scouts who aren’t smart
enough to make heads or tails of you. And good luck to you,
Hervey Boy. You’re a bully little scout missionary anyway.
Your scoutmaster,
Ebin Talbot

Hervey groped around under the bed and with trembling hand
lifted the crisp, new five dollar bill. And there he stood with a strange
feeling in his throat, clutching the bill and the letter while gentle Mrs.
Walton lowered the wire screen so that the room wouldn’t be full of
flies and moth millers.
“Well! Now aren’t you proud?” she asked.
He did not know whether he was proud or not. But he knew that
the crazy world was upside down. He had sent Chesty to denounce
the Scouts and Chesty had remained and joined. And the Scouts
had sent five dollars and called him a missionary.
“A missionary! Think of that!” said Mrs. Walton.
“It’s not so bad being a missionary,” said Hervey. “That isn’t calling
names. Bimbo, they go to Africa and Labrador—it’s not so bad being
called one.”
“Well, you’d better take your hat off and go to bed now,” said his
stepmother.
“You don’t think I’d let ’em call me names, do you?” Hervey
demanded. “That’s one thing.”
“I don’t see how you can hit them,” laughed Mrs. Walton, “they
seem to have such a long reach. It’s hard to get away from them.”
It certainly was a knockout.
CHAPTER XX
OMINOUS
“Well, that’s a pretty good joke,” said Mr. Walton at the breakfast
table. “You take my advice and save it for next summer up at camp,
Herve. I think after this we’ll call you the missionary, eh mother?
Shall we call him the missionary? The scout worker! Toiler in the
scout vineyard!” Contrary to his custom, Mr. Walton leaned back and
laughed.
“The boy who brought the letter,” said Mrs. Walton, “told me Mr.
Talbot thought it was fine that Hervey went to the police and saved
an innocent boy from being punished. Poor little Chesty McCullen
⸺”
“I can only hope he proves worthy of the young missionary who
converted him,” Mr. Walton interrupted.
So that was the sense in which those appalling words, overheard
by Hervey, had been used.
“I was going to take him and give him a good time,” said Hervey.
“I think you’re giving him the time of his life,” said his stepfather.
When Hervey went forth after breakfast the world looked bright. A
few days were still to elapse before the opening of school and he
was never at a loss for something to do. He did not keenly feel
Chesty McCullen’s desertion to the enemy’s camp. And I am sorry to
say that he was not deeply touched by the receipt of the much
needed five dollars from the Scouts. Hervey could never be won by
sentiment. He said he was lucky and there was an end of it as far as
he was concerned. Here he had recognition for doing a clean,
straightforward thing (for he had not one streak of yellow in him), but
he took no pride in it. And when they were thrilled at his essential
honor, he was not even grateful. He went upon his way rejoicing. He
did not know anything about honor because he never did anything
with deliberation and purpose. He had the much needed five dollars
and that was all he thought about.
He went to Farrelton Junction that morning and paid his fine, and
on the way back he drove a frightened cat up a tree and climbed up
after it. It may be observed in passing that he was the sworn enemy
of cats. To get one at bay and poke his stick at it and observe its
thickened tail and mountainous back was his idea of high adventure.
The frantic hissing was like music to his ears. He might have had the
stalker’s badge, the pathfinder’s badge, and half a dozen other
badges for the mileage and ingenuity wasted on cats.
On that very day he made a discovery which was to keep him
right side up for several days. During that time Farrelton and his
home saw but little of him. It was the calm preceding the storm. He
discovered along the railroad tracks near Clover Valley, a crew of
workers engaged in lengthening a siding. They had been brought
from distant parts and made their home in a freight car which was
converted into a rolling camp. It had a kitchen with an old-fashioned
stove in it and pots and pans hanging all about. Partitioned off from
this was a compartment with delightfully primitive bunks. The
workers hung out their washing on the roof of the car.
Best of all there was a little handcar at their disposal, which was
worked by pumping a handle up and down. By this means they could
move back and forth from the village of Clover Valley, about two
miles up the line. Between two o’clock and five-nineteen each day,
this little car was safe on the line and they used it to get provisions
from the village. Hervey loved this handcar as no mortal ever before
loved an inanimate thing. To propel it by its creaky pump handle was
a delight. And the old freight car in which those half-dozen men fried
bacon and played cards approximated nearer than anything he had
ever seen to his idea of heaven.
IT WAS HERVEY’S DELIGHT TO HELP PROPEL THE LITTLE HANDCAR.

These rough, burly men accepted him as they would have


accepted a stray dog and called him a mascot. He hiked to their
camp each day and stayed among them till sunset. He wandered
about and climbed trees and ate with them and fetched saw or
sledge-hammer, and was always on the handcar when it went down
the line to Clover Valley for provisions. When he told the men his
name was Hervey, they dubbed him Nervy and he was fated to
deserve the name. Of course, they liked him. He was serviceable
when he wanted to be and it was all right when he elected to beguile
himself in the dense woods that bordered the tracks.
It was unfortunate that Hervey could not have continued this
harmless pastime which was interrupted by Harlem Hinkey. On a
certain fateful evening he went to the second show with this young
magnate who treated him to ice cream soda on the way home. This
delayed his arrival till about eleven o’clock, and Mr. Walton was
greatly annoyed. He had an old-fashioned idea that a boy should be
home early at night, though occasionally he relaxed in this respect
provided Hervey asked permission. But asking permission was a
thing that Hervey did not know how to do. He breezed into the living
room on this particular night presenting an amusing contrast to the
ominous deliberation of his stepfather who leisurely folded his paper,
laid it down precisely and addressed him.
“Where have you been, Hervey?”
“I went to the second show with a feller—some picture! Bimbo, all
about ranches. That’s where I’d like to go—out west.”
“I wish you wouldn’t throw your cap in a chair, Hervey, dear,” said
Mrs. Walton. “Can’t you hang it in the hall as you come in?”
He disappeared into the hall, and as he did go, Mr. Walton with a
quietly determined look said, “I want to talk to Hervey alone a few
minutes.” Mrs. Walton, with a gentle show of apprehension, went
upstairs.
CHAPTER XXI
DISTANT RUMBLINGS
“Now Hervey, where have you been?”
“Gee, didn’t I tell you? I went to the second show.”
“It’s after eleven o’clock,” said Mr. Walton, “and you know you
musn’t stay out till that time without our knowing where you are. If
you want to go to the movies you must go to the first show. Wasn’t
that understood? Now school is beginning⸺”
“In New York the fellers stay out till twelve, even one,” said
Hervey. He had up-to-date information from Harlem Hinkey on this
point.
“Well, they don’t here,” said Mr. Walton crisply; “not in this house
anyway.”
“Isn’t it my house—when I grow up?” demanded Hervey.
This was high-handed to the point of insolence, but Mr. Walton
was not angered. Instead he seemed thoughtful. He would have
been justified in feeling hurt, for he had always been generous to this
boy whose own mother had left just nothing except the house which
would be Hervey’s some day. Mr. Walton had improved it and
cleared it of a mortgage, thinking only of its future owner.
“I’m sorry you said that, Herve,” he remarked, “for it makes it hard
for me to deal with you as I’m sure I ought to—as I promised I would.
That is, with the single thought of your own welfare. Somehow I
always feel that I have not full authority over you. I feel I have the
right to help you and guide you, but not to punish you.”
“Sure, I don’t blame you,” said Hervey.
“Of course, this place is to be yours. But you want to be worthy of
it, don’t you?”
“Believe me, I want to get away from it and go out west,” said
Hervey; “there’s no fun in this berg. A feller I know says so too. And I
know how I’m going to get the money too—I do.”
He was probably thinking of employment in the circus which was
doing a three day stand in Clover Valley. Perhaps he had also some
idea of identifying himself professionally with that camp of railroad
workers whose duties sometimes took them far afield.
“Bimbo, you can have the place if you want it,” he said flippantly.
“What’s the use of having it if I can’t stay out of it nights. Anyway,
you’re not my father, are you?”
Still Mr. Walton kept his composure. “I think some boy has put that
idea into your head,” said he. “You never said that before. I don’t
think that comes from your heart, Herve.”
“Well, I’m not going to start going to school anyway. Lots of fellers
my age do other things. Jiminies, I can’t stand that old four-eye
Keller; he razzed me all last term. You say the Scouts and fresh air
are good. Is it good to keep a feller in school till five o’clock. Bimbo,
do you call that fresh air? Good night!”
Still Mr. Walton, unruffled, patient, reasonable, seemed to be
trying to understand this boy and to be fair with him. He watched him
with a keen scrutiny in his kindly, tired eyes. His forbearance seemed
inexhaustible.
“Hervey,” said he finally, “why did you try to sell your bicycle?”
Hervey was quite taken by surprise. “M—my—why did I try to—
when did I try to sell it?” he stammered.
“You tried to sell it to Mr. Berly,” said Mr. Walton. “I met him to-day
and he told me so.”
“He—he said that?” Hervey was right on the edge of a lie, but he
sidestepped it. “Gee, what good is it?” he said.
“You said only last week you were going to take a long ride on it.
Don’t you remember—at the supper table—when Mrs. Tennet was
here?”
“As long as I can’t go anywhere and stay out, what’s the good of
it? Riding around the green isn’t any fun.”
Mr. Walton disregarded this insincerity. “And that’s why you tried to
sell it? The bicycle that your mother promised you when you reached
fifteen, and which I gave you in memory of her—to carry out her
wish?”
Hervey was silent. For a moment he seemed to be reached.
“You didn’t think you could get enough for it to take you out west,
did you? When you’re old enough if you want to go out west, I’ll give
you the money to go. I’m afraid you’ll never find what you want out
there, but if you want to go, I will be willing—when you get through
school. I can’t make you stay in the Scouts⸺”
“Good night on that outfit,” Hervey interrupted.
“But of course, you must finish school—and high school.”
“Goooood night!”
“And I want you to think about what you’ve said to me to-night,”
said Mr. Walton soberly; “about this being your house and about my
not being your father. And about trying to sell your bicycle that was
really like a present from your own mother—her wish. I want you to
ask yourself whether you—I think you call it playing a game, don’t
you⸺? Whether you’re playing the game right with me, and with
Mumsy, who worries so much about you. But whether you think of
these things or not you must be ready to go to school when it opens.
And you must be in the house each night at half past nine. You must
pay as much attention to what I tell you as to what some chance
acquaintance tells you. You see, Hervey, I’m giving you credit for not
originating some of these things you have said to me. Good night.”
Hervey did not move away. He was just embarrassed enough to
avoid drawing attention to himself by leaving the room. He did not
feel like saying good night, and he did not like to go without saying
good night. It was not an unworthy embarrassment and Mr. Walton
respected it. He rose, a gaunt, bent form, and went out into the
kitchen. Hervey could hear him winding the old-fashioned clock that
stood on the shelf over the stove. Then he could hear the woodshed
door being bolted. Still he stood just where he was. Mr. Walton came
slowly through the hall and Hervey could count his slow footfalls on
the stair. When the coast was clear he went upstairs himself.
CHAPTER XXII
WORDS AND ACTIONS
Hervey did not ponder upon any of those matters. There was no
action in pondering, and he believed in action. He had never
intended to rebel against going back to school; his remarks along
that line had been quite casual. First and last, he had a good deal of
fun in school. I suppose you might call playing hooky part of the fun
of going to school.
Nor did he have any serious intentions at that time of going west.
His remarks on that score had also been quite casual. The thought
that did linger with him was that New York (especially Harlem) must
be a wonderful place. For the honor of Farrelton and Massachusetts,
he was resolved that Harlem Plinkey’s face should be washed with
the very first dare he offered. Harlem Hinkey was all that was left
now before the opening of school.
For several days Hervey walked the straight and narrow path, and
though he roamed at large in the evenings, he was always home on
time. He was a deft performer on the harmonica and could play
Home Sweet Home in funeral time, in march time and in waltz time.
He would sit on the counter in his father’s store on evenings when
Mr. Walton was at home and play for the two salesgirls to dance.
They liked him immensely and adored his outlandish hat.
He was on his way home from one of these impromptu affairs one
night when he encountered Harlem Hinkey standing in front of the
Hinkey million dollar theatre.
“Want to go in to the second show?” Hinkey asked.
“Nope, I’ve got to be home before ten,” said Hervey.
They walked up the street together and turned into Milligan Street
which ran through to Hart Street on which Hervey lived. Another
block and he would have been safely at home. Milligan Street was
but one block long; it was dominated by the big square wooden
Congregational church which had stood there a good hundred years
before any of the chain of Hinkey million dollar theatres had been
dreamed of. Its white bulk and the massive roof-high pillars before its
spacious portal loomed in the darkness.
“Is that where the kids meet?” Hinkey asked. He meant the
Scouts, but he never paid them the compliment of calling them by
that name.
“Yop,” said Hervey, “only they’re not meeting there to-night. It’s the
Farrelton band. They practise in the Sunday School room. There go
a couple of them now.”
As he spoke a couple of young men hastened along the board
walk beside the church and into the lighted extension.
“Oh, listen to the band,” Hinkey sang rather aggressively. “Come
on, let’s sit down; you don’t have to go home yet,” he said.
Adjacent to the church was a long, ramshackle shed, reminiscent
of a time when people sheltered their horses and carriages during
service. Near this was a rail where horses had once been tied. In
days gone by many were the sermons punctuated by the restive
stamping of these horses from near and far about the countryside.
“I bet you I can walk on that,” said Hervey. “I bet you I can go the
whole length of it on one foot. Do you say I can’t?” After a stumble or
two, he proved that he could. “Come on, let’s sit on the rail; I don’t
have to get in till ten.” Nine-thirty was the limit set, but Hervey had
made it ten and Mr. Walton had not taken official notice.
“Me, I can stay out all night,” said Hinkey. “You’re lucky. I bet when
you went to Coney Island you stayed that late.”
“They were lucky if they saw me back the next day,” said Hinkey.
“Did you go on the boat? I bet you wouldn’t stand on the rail of
that.”
“I bet I did.”
“Not when it was going?”
“Sure I did.”
“Oh bimbo. Let’s see you walk this rail—on one foot.”
“I wouldn’t be bothered,” said Hinkey.
“I bet you were never up in the tower of that Woolworth Building.”
“I bet I was. I bet I know the man that owns it.”
“I bet you wouldn’t stand on the rail up there—oh boy!”
“I bet I would.”
“I bet you wouldn’t.”
“I bet I would only there’s a man that won’t let you.”
“I bet I could do it when he didn’t see me,” said Hervey. “Will they
let you walk through that tube under the river?”
“Sure, and Election Day is a holiday over there too. This is no
good of a state.”
“I bet you don’t get forefathers’ Day over there,” said Hervey. “So
that proves you’re a fool.”
“I bet if you saw Coney Island you’d want to stay there.”
“Oh bimbo!” said Hervey. “Do they have loop-the-loops there?”
“Suuure they do, and I looped them too.”
“Not without being strapped in, I bet you didn’t.”
“I bet I did.”
“I bet you can’t prove it.”
“I bet I can only the feller is in New York.”
“When you stayed away at night, I bet you didn’t stay with gipsies.
I did.”
“I bet I helped to arrest gipsies,” Hinkey said.
“That’s nothing, I bet I got arrested,” said Hervey.
“I bet you never did.”
“What do you bet?”
“I bet you a ride in my car.”
“Where to?”
“You got arrested! I have to laugh.”
“You think only fellers that live in New York can get arrested?”
“Here comes another band player,” Hinkey said, and raising his
voice in a way of mockery, he paraphrased the familiar song.
“Oh listen to the band,
Oh don’t you think it’s punk.”
“He walks cissified,” he concluded. “Look, he’s got a satchel.”
“He’s got a cornet or some kind of a trumpet in it,” said Hervey.
“One of them has a long bag with a saxaphone in it—I saw it once.”
“Oh listen to the village band
Oh merrily they make a noise like tin pans.”
sang Harlem Hinkey, and he whistled a kind of insolent
accompaniment as the young man came tripping diagonally across
the street. It must be confessed that this late arriving member had a
decidedly effeminate trip as he came hurrying along and there was a
crude humor to Hinkey’s accurately timed mockery.
“He doesn’t see us,” whispered Hinkey. “I tell you what let’s do;
let’s sneak up behind and trip him up and grab the bag and then we’ll
beat it around the side and we’ll blow the trumpet good and loud
through the window. Hey? We’ll give them a good scare. See them
jump, hey?”
This was a crude enough practical joke, to be sure. It was
characteristic of Hinkey; it was his particular style of mischief. It had
not any of the heroic quality of a stunt. It was not in the class with
Hervey’s deeds of glory. To do our hero credit, to give the devil his
due as they say, he would never have originated this silly joke. But it
was not in his nature to back out of anything. He always moved
forward.
“You trip him up and I’ll grab the bag,” he said. “Then I’ll beat it
around and climb up on the window sill and I’ll give it a good loud
blow. I can climb up there better than you can, I bet you.” It was
amusing how in this wanton enterprise his thought focused upon the
one really skilful feature of it—the vaulting on to the high window
ledge. “Oh bimbo,” he added with relish.
There was something inviting in the thought of tripping up a young
fellow with such a mincing gait. If it were ever justifiable to trip
anybody up he would be the sort of fellow who ought to be tripped.
The two boys made a masterful and silent flank move to the rear of
the hurrying figure. But when it came to tripping him, Harlem Hinkey
fell back and it was Hervey who, dextrously projecting his foot, sent
the young musician sprawling.
Things happened with lightning rapidity. Aghast at the magnificent
execution of his inspired plan, Harlem Hinkey withdrew precipitately
from the scene. Hervey’s ready skill and promptness and the
thudding descent of the victim had exhausted his courage. And there
was Hervey, already around the corner with the bag. He had not
advanced to the wing of the church for the very good reason that the
rumpus had attracted attention within and already a young man with
a flute in his hand was emerging from the doorway. He and his
companions had been waiting for their dilatory member and now
they beheld him sitting on the pavement nearby, nursing a bleeding
knee while Harlem Hinkey went scooting down the street.
Around the corner, safe from the excited group, Hervey Willetts
walked quickly with a simulated air of unconcern. He was good at
this sort of thing and could adopt a demeanor of childlike innocence
immediately after any stunt which had not the sanction of the law. A
doctor hurrying with his little black bag, intent on an errand of mercy,
could not have been more unconcerned than was our hero as he
hastened along Hart Street. He could not afford to run because
Cartwright, the night cop, was sauntering along on the other side of
the way.
CHAPTER XXIII
DIPLOMACY
Instead of making the big noise our hero, deserted by his
confederate, was using all his finesse not to attract the attention of
the sauntering cop. At the corner Cartwright paused, glanced about,
then crossed and strolled along a few yards behind Hervey. The
official was quite unconcerned, but Hervey’s guilty conscience told
him that he was pursued. If he looked around or started to run,
disaster might ensue. So he kept up the air of a respectable home-
going citizen and did it to perfection.
He might have been a Boy Scout carrying some one’s satchel as
a good turn. He heard a voice behind him and feared it might be the
outraged band member heading a posse to recover his instrument.
Whoever it was, the person walked with the policeman and spoke of
the weather.
Coming to his own house, Hervey opened the gate and felt
relieved to be within the fenced enclosure. The gravel walk with its
bordering whitewashed stones seemed to welcome him to safety. It
was characteristic, oh how characteristic of Hervey, that he was not
in the least troubled about how he was to return the satchel to its
unknown owner. His only concern was his immediate safety. He
would not lay it down to be lost to its owner. And he could not seek
the hapless victim without giving himself away. So he entered the
house cautiously, went upstairs and laid the satchel in his own
apartment, then descended to the living room where his step-parents
sat reading beside the marble center table. He had overstepped his
time by about fifteen minutes, but Mr. Walton seemed never
disposed to quibble about small infringements.
“I was at the store,” said Hervey.
“They busy?”

You might also like