100% found this document useful (11 votes)
116 views

Download Introduction to Computing and Programming in Python, Global Edition Mark J. Guzdial ebook All Chapters PDF

Guzdial

Uploaded by

ohsungkreisz
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (11 votes)
116 views

Download Introduction to Computing and Programming in Python, Global Edition Mark J. Guzdial ebook All Chapters PDF

Guzdial

Uploaded by

ohsungkreisz
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 76

Download Full Version ebookmass - Visit ebookmass.

com

Introduction to Computing and Programming in


Python, Global Edition Mark J. Guzdial

https://ebookmass.com/product/introduction-to-computing-and-
programming-in-python-global-edition-mark-j-guzdial/

OR CLICK HERE

DOWLOAD NOW

Discover More Ebook - Explore Now at ebookmass.com


Instant digital products (PDF, ePub, MOBI) ready for you
Download now and discover formats that fit your needs...

Introduction To Computing And Problem Solving Using Python


1st Edition E. Balaguruswamy

https://ebookmass.com/product/introduction-to-computing-and-problem-
solving-using-python-1st-edition-e-balaguruswamy/

ebookmass.com

Introduction to Computation and Programming Using Python,


Third Edition John V. Guttag

https://ebookmass.com/product/introduction-to-computation-and-
programming-using-python-third-edition-john-v-guttag/

ebookmass.com

Python Programming for Beginners: 2 Books in 1 - the


Ultimate Step-By-Step Guide to Learn Python Programming
Quickly With Practical Exercises Mark Reed
https://ebookmass.com/product/python-programming-for-
beginners-2-books-in-1-the-ultimate-step-by-step-guide-to-learn-
python-programming-quickly-with-practical-exercises-mark-reed/
ebookmass.com

Greek and Roman Technology: A Sourcebook of Translated


Greek and Roman Texts 2nd Edition Andrew N. Sherwood

https://ebookmass.com/product/greek-and-roman-technology-a-sourcebook-
of-translated-greek-and-roman-texts-2nd-edition-andrew-n-sherwood/

ebookmass.com
SAP S/4HANA Financial Accounting Configuration: Learn
Configuration and Development on an S/4 System, 2nd
Edition Andrew Okungbowa
https://ebookmass.com/product/sap-s-4hana-financial-accounting-
configuration-learn-configuration-and-development-on-
an-s-4-system-2nd-edition-andrew-okungbowa/
ebookmass.com

(eTextbook PDF) for Healthcare Human Resource Management


3rd Edition

https://ebookmass.com/product/etextbook-pdf-for-healthcare-human-
resource-management-3rd-edition/

ebookmass.com

Racial and Ethnic Groups (14th Edition ) 14th Edition

https://ebookmass.com/product/racial-and-ethnic-groups-14th-
edition-14th-edition/

ebookmass.com

Developments in the Formulation and Reinforcement of


Concrete 2nd ed Edition Mindess

https://ebookmass.com/product/developments-in-the-formulation-and-
reinforcement-of-concrete-2nd-ed-edition-mindess/

ebookmass.com

Tools for Teaching 2nd Edition

https://ebookmass.com/product/tools-for-teaching-2nd-edition/

ebookmass.com
Where Did the Universe Come From? And Other Cosmic
Questions Ferrie Chris

https://ebookmass.com/product/where-did-the-universe-come-from-and-
other-cosmic-questions-ferrie-chris/

ebookmass.com
Introduction to
Computing and
Programming
TM
in Python
A MULTIMEDIA APPROACH

Mark J. Guzdial and Barbara Ericson


College of Computing/GVU
Georgia Institute of Technology

Fourth Edition
Global Edition

Boston Columbus Indianapolis New York San Francisco Hoboken


Amsterdam Cape Town Dubai London Madrid Milan Munich Paris Montreal Toronto
Delhi Mexico City São Paulo Sydney Hong Kong Seoul Singapore Taipei Tokyo
Vice President and Editorial Director, ECS: Marcia J. Horton Senior Manufacturing Controller, Global Edition: Kay Holman
Executive Editor: Tracy Johnson Media Production Manager, Global Edition: Vikram Kumar
Assistant Acquisitions Editor, Global Edition: Aditee Agarwal Global HE Director of Vendor Sourcing and Procurement: Diane Hynes
Executive Marketing Manager: Tim Galligan Director of Operations: Nick Sklitsis
Marketing Assistant: Jon Bryant Operations Specialist: Maura Zaldivar-Garcia
Senior Managing Editor: Scott Disanno Cover Designer: Lumina Datamatics
Production Project Manager: Greg Dulles Manager, Rights and Permissions: Rachel Youdelman
Program Manager: Carole Snyder Associate Project Manager, Rights and Permissions: Timothy Nicholls
Project Editor, Global Edition: K.K. Neelakantan Full-Service Project Management: Kalpana Arumugam, SPi Global

MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS MAKE NO REPRESENTATIONS ABOUT THE SUITABILITY OF THE INFORMATION
CONTAINED IN THE DOCUMENTS AND RELATED GRAPHICS PUBLISHED AS PART OF THE SERVICES FOR ANY PURPOSE. ALL SUCH
DOCUMENTS AND RELATED GRAPHICS ARE PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND. MICROSOFT AND/OR ITS
RESPECTIVE SUPPLIERS HEREBY DISCLAIM ALL WARRANTIES AND CONDITIONS WITH REGARD TO THIS INFORMATION,
INCLUDING ALL WARRANTIES AND CONDITIONS OF MERCHANTABILITY, WHETHER EXPRESS, IMPLIED OR STATUTORY, FITNESS
FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL MICROSOFT AND/OR ITS RESPECTIVE
SUPPLIERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF INFORMATION AVAILABLE FROM THE SERVICES. THE
DOCUMENTS AND RELATED GRAPHICS CONTAINED HEREIN COULD INCLUDE TECHNICAL INACCURACIES OR TYPOGRAPHICAL
ERRORS. CHANGES ARE PERIODICALLY ADDED TO THE INFORMATION HEREIN. MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS
MAY MAKE IMPROVEMENTS AND/OR CHANGES IN THE PRODUCT(S) AND/OR THE PROGRAM(S) DESCRIBED HEREIN AT ANY TIME.
PARTIAL SCREEN SHOTS MAY BE VIEWED IN FULL WITHIN THE SOFTWARE VERSION SPECIFIED.

Pearson Education Limited


Edinburgh Gate
Harlow
Essex CM20 2JE
England

and Associated Companies throughout the world

Visit us on the World Wide Web at:


www.pearsonglobaleditions.com

© Pearson Education Limited 2016

The rights of Mark J. Guzdial and Barbara Ericson to be identified as the authors of this work have been asserted by them in accordance with the
Copyright, Designs and Patents Act 1988.

Authorized adaptation from the United States edition, entitled Introduction to Computing and Programming in Python™ : A Multimedia Approach, Fourth
Edition, ISBN 9780134025544, by Mark J. Guzdial and Barbara Ericson published by Pearson Education © 2016.

All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic,
mechanical, photocopying, recording or otherwise, without either the prior written permission of the publisher or a license permitting restricted copying in
the United Kingdom issued by the Copyright Licensing Agency Ltd, Saffron House, 6−10 Kirby Street, London EC1N 8TS.

All trademarks used herein are the property of their respective owners. The use of any trademark in this text does not vest in the author or publisher any
trademark ownership rights in such trademarks, nor does the use of such trademarks imply any affiliation with or endorsement of this book by such owners.

British Library Cataloguing-in-Publication Data

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

10 9 8 7 6 5 4 3 2 1

ISBN 10: 1-292-10986-6


ISBN 13: 978-1-292-10986-2

Typeset in 10.5/13 Times by SPi Global


Printed and bound in Malaysia.
Dedicated to our first teachers, our parents:
Janet, Charles, Gene, and Nancy
This page intentionally left blank
Contents
Preface for the Fourth Edition 13
Preface to the First Edition 18
About the Authors 24

1 INTRODUCTION 25
1 Introduction to Computer Science and Media
Computation 27
1.1 What Is Computer Science About? 27
1.2 Programming Languages 30
1.3 What Computers Understand 33
1.4 Media Computation: Why Digitize Media? 35
1.5 Computer Science for Everyone 37
1.5.1 It’s About Communication 37
1.5.2 It’s About Process 37
1.5.3 You Will Probably Need It 38

2 Introduction to Programming 42
2.1 Programming Is About Naming 42
2.1.1 Files and Their Names 44
2.2 Programming in Python 45
2.3 Programming in JES 46
2.4 Media Computation in JES 47
2.4.1 Showing a Picture 51
2.4.2 Playing a Sound 54
2.4.3 Naming Values 54
2.5 Making a Program 57
2.5.1 Functions: Real Math-Like Functions That Take
Input 61
6 Contents

3 Creating and Modifying Text 68


3.1 Strings: Making Human Text in a Computer 68
3.1.1 Making Strings from Strings: Telling Stories 70
3.2 Taking Strings Apart with For 73
3.2.1 Testing the Pieces 75
3.2.2 Taking String Apart, and Putting Strings Together 78
3.2.3 Taking Strings Apart with Indices 81
3.2.4 Mirroring, Reversing, and Separating Strings with Index 83
3.2.5 Encoding and Decoding Strings Using a Keyword Cipher 85
3.3 Taking Strings Apart by Words 87
3.4 What’s Inside a String 90
3.5 What a Computer Can Do 91

4 Modifying Pictures Using Loops 98


4.1 How Pictures Are Encoded 99
4.2 Manipulating Pictures 104
4.2.1 Exploring Pictures 108
4.3 Changing Color Values 110
4.3.1 Using Loops in Pictures 110
4.3.2 Increasing/Decreasing Red (Green, Blue) 112
4.3.3 Testing the Program: Did That Really Work? 117
4.3.4 Changing One Color at a Time 118
4.4 Creating a Sunset 119
4.4.1 Making Sense of Functions 119
4.5 Lightening and Darkening 124
4.6 Creating a Negative 125
4.7 Converting to Grayscale 126
4.8 Specifying Pixels by Index 128

5 Picture Techniques with Selection 138


5.1 Replacing Colors: Red-Eye, Sepia Tones, and Posterizing 138
5.1.1 Reducing Red-Eye 142
5.1.2 Sepia-Toned and Posterized Pictures: Using
Conditionals to Choose the Color 144
5.2 Comparing Pixels: Edge Detection 150
5.3 Background Subtraction 153
5.4 Chromakey 156
5.5 Coloring in ranges 161
Contents 7

5.5.1 Adding a Border 161


5.5.2 Lightening the Right Half of a Picture 162
5.6 Selecting without Retesting 163

6 Modifying Pixels by Position 169


6.1 Processing Pixels Faster 169
6.1.1 Looping across the Pixels with Range 171
6.1.2 Writing Faster Pixel Loops 173
6.2 Mirroring a Picture 175
6.3 Copying and Transforming Pictures 182
6.3.1 Copying 183
6.3.2 Copying Smaller and Modifying 189
6.3.3 Copying and Referencing 191
6.3.4 Creating a Collage 193
6.3.5 General Copying 196
6.3.6 Rotation 197
6.3.7 Scaling 200
6.4 Combining Pixels: Blurring 205
6.5 Blending Pictures 208
6.6 Drawing on Images 210
6.6.1 Drawing with Drawing Commands 212
6.6.2 Vector and Bitmap Representations 213
6.7 Programs as Specifying Drawing Process 215
6.7.1 Why Do We Write Programs? 216

2 SOUND 225
7 Modifying Sounds Using Loops 227
7.1 How Sound Is Encoded 227
7.1.1 The Physics of Sound 227
7.1.2 Investigating Different Sounds 230
7.1.3 Encoding the Sound 235
7.1.4 Binary Numbers and Two’s Complement 236
7.1.5 Storing Digitized Sounds 237
7.2 Manipulating Sounds 239
7.2.1 Open Sounds and Manipulating Samples 239
7.2.2 Using the JES MediaTools 242
7.2.3 Looping 243
7.3 Changing the Volume of Sounds 244
8 Contents

7.3.1 Increasing Volume 244


7.3.2 Did That Really Work? 245
7.3.3 Decreasing Volume 249
7.3.4 Using Array Index Notation 250
7.3.5 Making Sense of Functions in Sounds 251
7.4 Normalizing Sounds 251
7.4.1 Generating Clipping 253

8 Modifying Samples in a Range 259


8.1 Manipulating Different Sections of the Sound Differently 259
8.1.1 Revisiting Index Array Notation 260
8.2 Splicing Sounds 262
8.3 General Clip and Copy 269
8.4 Reversing Sounds 271
8.5 Mirroring 273
8.6 On Functions and Scope 273

9 Making Sounds by Combining Pieces 279


9.1 Composing Sounds Through Addition 279
9.2 Blending Sounds 280
9.3 Creating an Echo 282
9.3.1 Creating Multiple Echoes 284
9.3.2 Creating Chords 284
9.4 How Sampling Keyboards Work 285
9.4.1 Sampling as an Algorithm 289
9.5 Additive Synthesis 289
9.5.1 Making Sine Waves 289
9.5.2 Adding Sine Waves Together 291
9.5.3 Checking Our Result 292
9.5.4 Square Waves 293
9.5.5 Triangular Waves 295
9.6 Modern Music Synthesis 297
9.6.1 MP3 297
9.6.2 MIDI 298

10 Building Bigger Programs 302


10.1 Designing Programs Top-Down 303
10.1.1 A Top-Down Design Example 304
10.1.2 Designing the Top-Level Function 305
10.1.3 Writing the Subfunctions 307
Contents 9

10.2 Designing Programs Bottom-Up 311


10.2.1 An Example Bottom-Up Process 312
10.3 Testing Your Program 312
10.3.1 Testing the Edge Conditions 314
10.4 Tips on Debugging 315
10.4.1 Finding Which Statement to Worry About 316
10.4.2 Seeing the Variables 316
10.4.3 Debugging the Adventure Game 318
10.5 Algorithms and Design 321
10.6 Connecting to Data Outside a Function 322
10.7 Running Programs Outside of JES 326

3 TEXT, FILES, NETWORKS, DATABASES,


AND UNIMEDIA 333
11 Manipulating Text with Methods and Files 335
11.1 Text as Unimedia 335
11.2 Manipulating Parts of Strings 336
11.2.1 String Methods: Introducing Objects and Dot Notation 337
11.2.2 Lists: Powerful, Structured Text 339
11.2.3 Strings Have No Font 341
11.3 Files: Places to Put Your Strings and Other Stuff 341
11.3.1 Opening and Manipulating Files 343
11.3.2 Generating Form Letters 344
11.3.3 Reading and Manipulating Data from the Internet 345
11.3.4 Scraping Information from a Web Page 348
11.3.5 Reading CSV Data 349
11.3.6 Writing Out Programs 351
11.4 The Python Standard Library 352
11.4.1 More on Import and Your Own Modules 353
11.4.2 Adding Unpredictably to Your Program with Random 354
11.4.3 Reading CSV Files with a Library 356
11.4.4 A Sampling of Python Standard Libraries 356

12 Advanced Text Techniques: Web


and Information 361
12.1 Networks: Getting Our Text from the Web 361
12.1.1 Automating Access to CSV Data 365
12.1.2 Accessing FTP 367
10 Contents

12.2 Using Text to Shift Between Media 368


12.3 Moving Information Between Media 371
12.4 Using Lists as Structured Text for Media Representations 374
12.5 Hiding Information in a Picture 375
12.5.1 Hiding a Sound Inside a Picture 377

13 Making Text for the Web 383


13.1 HTML: The Notation of the Web 383
13.2 Writing Programs to Generate HTML 388
13.2.1 Making Home Pages 390
13.3 Databases: A Place to Store Our Text 393
13.3.1 Relational Databases 395
13.3.2 An Example Relational Database Using Hash Tables 396
13.3.3 Working with SQL 399
13.3.4 Using a Database to Build Web Pages 401

4 MOVIES 407
14 Creating and Modifying Movies 409
14.1 Generating Animations 410
14.2 Working with Video Source 419
14.2.1 Video Manipulating Examples 419
14.3 Building a Video Effect Bottom-Up 423

15 Speed 430
15.1 Focusing on Computer Science 430
15.2 What Makes Programs Fast? 430
15.2.1 What Computers Really Understand 431
15.2.2 Compilers and Interpreters 432
15.2.3 What Limits Computer Speed? 436
15.2.4 Does It Really Make a Difference? 438
15.2.5 Making Searching Faster 441
15.2.6 Algorithms That Never Finish or Can’t Be Written 443
15.2.7 Why Is Photoshop Faster than JES? 444
15.3 What Makes a Computer Fast? 444
15.3.1 Clock Rates and Actual Computation 445
15.3.2 Storage: What Makes a Computer Slow? 446
15.3.3 Display 447
Contents 11

16 Functional Programming 450


16.1 Using Functions to Make Programming Easier 450
16.2 Functional Programming with Map and Reduce 454
16.3 Functional Programming for Media 457
16.3.1 Media Manipulation without Changing State 458
16.4 Recursion: A Powerful Idea 459
16.4.1 Recursive Directory Traversals 464
16.4.2 Recursive Media Functions 466

17 Object-Oriented Programming 471


17.1 History of Objects 471
17.2 Working with Turtles 473
17.2.1 Classes and Objects 473
17.2.2 Sending Messages to Objects 474
17.2.3 Objects Control Their State 476
17.3 Teaching Turtles New Tricks 478
17.3.1 Overriding an Existing Turtle Method 480
17.3.2 Working with Multiple Turtles at Once 481
17.3.3 Turtles with Pictures 483
17.3.4 Dancing Turtles 484
17.3.5 Recursion and Turtles 487
17.4 An Object-Oriented Slide Show 488
17.4.1 Making the Slide Class More Object-Oriented 491
17.5 Object-Oriented Media 493
17.6 Joe the Box 498
17.7 Why Objects? 499

APPENDIX 506
A Quick Reference to Python 506
A.1 Variables 506
A.2 Function Creation 507
A.3 Loops and Conditionals 507
A.4 Operators and Representation Functions 508
A.5 Numeric Functions 509
A.6 Sequence Operations 509
A.7 String Escapes 509
12 Contents

A.8 Useful String Methods 509


A.9 Files 510
A.10 Lists 510
A.11 Dictionaries, Hash Tables, or Associative Arrays 510
A.12 External Modules 510
A.13 Classes 511
A.14 Functional Methods 511

Bibliography 512

Index 515
Preface for the
Fourth Edition
We started Media Computation in the of Summer 2002, and taught it for the first time
in Spring 2003. It’s now over ten years later, which is a good time to summarize the
changes across the second, third, and fourth editions.
Media Computation has been used successfully in an undergraduate course at Geor-
gia Tech for the last dozen years. The course continues to have high retention rates (over
85% of students complete the class with a passing grade), and is majority female. Both
students and teachers report enjoying the course, which is an important recommendation
for it.
Researchers have found that Media Computation works in a variety of contexts.
The University of Illinois-Chicago had the first Media Computation paper outside of
Georgia, and they showed how switching to MediaComp improved their retention
rates in classes that were much more diverse than those at Georgia Tech [41]. The
University of California-San Diego adopted Media Computation as part of a big change
in their introductory course, where they also started using pair-programming and peer
instruction. Their paper at the 2013 SIGCSE Symposium showed how these changes
led to dramatic improvements in student retention, even measured a year later in the
Sophomore year. The paper also won the Best Paper award at the conference [27].
It’s been particularly delightful to see Media Computation adopted and adapted for
new settings, like Cynthia Bailey Lee’s creation of a MATLAB Media Computation
curriculum [12].
Mark wrote a paper in 2013, summarizing ten years of Media Computation research.
Media Computation does often improve retention. Our detailed interview studies with
female students supports the claim that they find the approach to be creative and engag-
ing, and that’s what keeps the students in the class. That paper won the Best Paper award
at the 2013 International Computing Education Research (ICER) Conference [33].

HOW TO TEACH MEDIA COMPUTATION


Over the last 10 years, we have learned some of the approaches that work best for
teaching Media Computation.

• Let the students be creative. The most successful Media Computation classes
use open-ended assignments that let the students choose what media they use.
For example, a collage assignment might specify the use of particular filters and
compositions, but allow for the student to choose exactly what pictures are used.
These assignments often lead to the students putting in a lot more time to get just
the look that they wanted, and that extra time can lead to improved learning.
14 Preface for the Fourth Edition

• Let the students share what they produce. Students can produce some beautiful
pictures, sounds, and movies using Media Computation. Those products are more
motivating for the students when they get to share them with others. Some schools
provide online spaces where students can post and share their products. Other
schools have even printed student work and held an art gallery.
• Code live in front of the class. The best part of the teacher actually typing in code
in front of the class is that nobody can code for long in front of an audience and
not make a mistake. When the teacher makes a mistake and fixes it, the students
see (a) that errors are expected and (b) there is a process for fixing them. Coding
live when you are producing images and sounds is fun, and can lead to unexpected
results and the opportunity to explore, “How did that happen?”
• Pair programming leads to better learning and retention. The research results on
pair programming are tremendous. Classes that use pair programming have better
retention results, and the students learn more.
• Peer instruction is great. Not only does peer instruction lead to better learning
and retention outcomes, but it also gives the teacher better feedback on what the
students are learning and what they are struggling with. We strongly encourage
the use of peer instruction in computing classes.
• Worked examples help with creativity learning. Most computer science classes
do not provide anywhere nearly enough worked-out examples for students to
learn from. Students like to learn from examples. One of the benefits of Media
Computation is that we provide a lot of examples (we’ve never tried to count the
number of for and if statements in the book!), and it’s easy to produce more
of them. In class, we do an activity where we hand out example programs, then
show a particular effect. We ask pairs or groups of students to figure out which
program generated that effect. The students talk about code, and study a bunch of
examples.

AP CS PRINCIPLES
The Advanced Placement exam in CS Principles1 has now been defined. We have
explicitly written the fourth edition with CS Principles in mind. For example, we show
how to measure the speed of a program empirically in order to contrast two algorithms
(Learning Objective 4.2.4), and we explore multiple ways of analyzing CSV data from
the Internet (Learning Objectives 3.1.1, 3.2.1, and 3.2.2).
Overall, we address the CS Principles learning objectives explicitly in this book as
shown below:
• In Big Idea I: Creativity:
• LO 1.1.1: . . . use computing tools and techniques to create artifacts.
• LO 1.2.1: . . . use computing tools and techniques for creative expression.
1
http://apcsprinciples.org
Preface for the Fourth Edition 15

• LO 1.2.2: . . . create a computational artifact using computing tools and techniques


to solve a problem.
• LO 1.2.3: . . . create a new computational artifact by combining or modifying
existing artifacts.
• LO 1.2.5: . . . analyze the correctness, usability, functionality, and suitability of
computational artifacts.
• LO 1.3.1: . . . use programming as a creative tool.
• In Big Idea II: Abstraction:
• LO 2.1.1: . . . describe the variety of abstractions used to represent data.
• LO 2.1.2: . . . explain how binary sequences are used to represent digital data.
• LO 2.2.2: . . . use multiple levels of abstraction in computation.
• LO 2.2.3: . . . identify multiple levels of abstractions being used when writing
programs.
• In Big Idea III: Data and information:
• LO 3.1.1: . . . use computers to process information, find patterns, and test
hypotheses about digitally processed information to gain insight and knowledge.
• LO 3.2.1: . . . extract information from data to discover and explain connections,
patterns, or trends.
• LO 3.2.2: . . . use large data sets to explore and discover information and knowl-
edge.
• LO 3.3.1: . . . analyze how data representation, storage, security, and transmission
of data involve computational manipulation of information.
• In Big Idea IV: Algorithms:
• LO 4.1.1: . . . develop an algorithm designed to be implemented to run on a
computer.
• LO 4.1.2: . . . express an algorithm in a language.
• LO 4.2.1: . . . explain the difference between algorithms that run in a reasonable
time and those that do not run in a reasonable time.
• LO 4.2.2: . . . explain the difference between solvable and unsolvable problems
in computer science.
• LO 4.2.4: . . . evaluate algorithms analytically and empirically for efficiency,
correctness, and clarity.
• In Big Idea V: Programming:
• LO 5.1.1: . . . develop a program for creative expression, to satisfy personal
curiosity or to create new knowledge.
• LO 5.1.2: . . . develop a correct program to solve problems.
• LO 5.2.1: . . . explain how programs implement algorithms.
• LO 5.3.1: . . . use abstraction to manage complexity in programs.
16 Preface for the Fourth Edition

• LO 5.5.1: . . . employ appropriate mathematical and logical concepts in program-


ming.
• In Big Idea VI: The Internet:
• LO 6.1.1: . . . explain the abstractions in the Internet and how the Internet func-
tions.

CHANGES IN THE FOURTH EDITION


1. We fixed lots of bugs that our crack bug-finders identified in the third edition.
2. We changed most of the pictures in the book – they were getting stale, and our kids
wanted us to not use as many pictures of them.
3. We added more end-of-chapter questions.
4. We added a whole new chapter, on text as a medium and manipulating strings
(to make sentences, koans, and codes). This isn’t a necessary chapter (e.g., we
introduce for and if statements, but we didn’t remove the introductions later in
the book). For some of our teachers, playing with text with shorter loops (iterating
over all the characters in a sentence is typically smaller than the thousands of pixels
in a picture) is a more comfortable way to start.
5. We gave up fighting the battle of inventing a Web scraper that could beat out the
changes that Facebook made, which kept breaking the one we put in the 3rd edition
and then kept updating on the teacher’s website2 . Instead, we wrote examples in
this book for processing CSV (Comma-Separated Values), a common format for
sharing data on the Internet. We parse the CSV from a file using string processing,
then using the CSV library in Python, and then accessing the data by URL.
6. We added some new edge detection code which is shorter and simpler to understand.
7. We added more with turtles: creating dancing turtles (using sleep from the time
module to pause execution) and recursive patterns.
8. We updated the book to use the latest features in JES, which include those that
reduce the need to use full pathnames (a problem identified by Stephen Edwards
and his students in their SIGCSE 2014 paper [43]).

ACKNOWLEDGMENTS
Our sincere thanks go out to all our reviewers and bug-finders:
• At the top of the list is Susan Schwarz of the US Military Academy at West Point.
Susan runs a large course with many instructors, and pays careful attention to
what’s going in all of the sections of the course. She turned that attention on
the third edition of this book. She caught many bugs, and gave us lots of useful
feedback. Thanks, Susan!
2
http://home.cc.gatech.edu/mediaComp and http://www.mediacomputation.org
Preface for the Fourth Edition 17

• Our other bug finders for the book were John Rutkiewicz, U. Massachusetts–
Dartmouth; Brian Dorn, U. Nebraska–Omaha; Dave Largent, Ball State Univer-
sity; Simon, University of Newcastle; Eva Heinrich, Massey University; Peter
J. DePasquale, The College of New Jersey, and Bill Leahy, Georgia Institute of
Technology.
• Matthew Frazier, North Carolina State University, worked with us in the summer
of 2014 to create a new version of JES – fixing many bugs, and improving JES
considerably.
• We are grateful for the feedback from our book reviewers for the 4th edition:
Andrew Cencini, Bennington College; Susan Fox, Macalester College; Kristin
Lamberty, University of Minnesota-Morris; Jean Smith, Technical College of the
Lowcountry; and William T. Verts, University of Massachusetts-Amherst.
• We are grateful for the input from our book reviewers for the 3rd edition, too:
Joseph Oldham, Centre College; Lukasz Ziarek, Purdue University;Joseph
O’Rourke, Smith College; Atul Prakash, University of Michigan; Noah D. Bar-
nette, Virginia Tech; Adelaida A. Medlock, Drexel University; Susan E. Fox,
Macalester College; Daniel G. Brown, University of Waterloo; Brian A. Malloy,
Clemson University; Renee Renner, California State University, Chico.

Mark Guzdial and Barbara Ericson


Georgia Institute of Technology
Preface to the First Edition
Research in computing education makes it clear that one doesn’t just “learn to program.”
One learns to program something [8, 19], and the motivation to do that something can
make the difference between learning and not learning to program [5]. The challenge
for any teacher is to pick a something that is a powerful enough motivator.
People want to communicate. We are social creatures and the desire to communicate
is one of our primal motivations. Increasingly, the computer is used as a tool for com-
munication even more than a tool for calculation. Virtually all published text, images,
sounds, music, and movies today are prepared using computing technology.
This book is about teaching people to program in order to communicate with digital
media. The book focuses on how to manipulate images, sounds, text, and movies as
professionals might, but with programs written by students. We know that most people
will use professional-grade applications to perform these type of manipulations. But,
knowing how to write your own programs means that you can do more than what your
current application allows you to do. Your power of expression is not limited by your
application software.
It may also be true that knowing how the algorithms in a media applications work
allows you to use them better or to move from one application to the next more easily.
If your focus in an application is on what menu item does what, every application is
different. But if your focus is on moving or coloring the pixels in the way you want,
then maybe it’s easier to get past the menu items and focus on what you want to say.
This book is not just about programming in media. Media-manipulation programs
can be hard to write or may behave in unexpected ways. Natural questions arise, like
“Why is the same image filter faster in Photoshop?” and “That was hard to debug—Are
there ways of writing programs that are easier to debug?” Answering questions like
these is what computer scientists do. There are several chapters at the end of the book
that are about computing, not just programming. The final chapters go beyond media
manipulation to more general topics.
The computer is the most amazingly creative device that humans have ever conceived.
It is completely made up of mind-stuff. The notion “Don’t just dream it, be it” is really
possible on a computer. If you can imagine it, you can make it “real” on the computer.
Playing with programming can be and should be enormous fun.

OBJECTIVES, APPROACH AND ORGANIZATION


The curricular content of this book meets the requirements of the “imperative-first”
approach described in the ACM/IEEE Computing Curriculum 2001 standards document
[2]. The book starts with a focus on fundamental programming constructs: assignments,
sequential operations, iteration, conditionals, and defining functions. Abstractions
Preface to the First Edition 19

(e.g., algorithmic complexity, program efficiency, computer organization, hierarchi-


cal decomposition, recursion, and object-oriented programming) are emphasized later,
after the students have a context for understanding them.
This unusual ordering is based on the findings of research in the learning sciences.
Memory is associative. We remember new things based on what we associate them with.
People can learn concepts and skills on the premise that they will be useful some day but
the concepts and skills will be related only to the premises. The result has been described
as “brittle knowledge” [25]—the kind of knowledge that gets you through the exam
but is promptly forgotten because it doesn’t relate to anything but being in that class.
Concepts and skills are best remembered if they can be related to many different
ideas or to ideas that come up in one’s everyday life. If we want students to gain
transferable knowledge (knowledge that can be applied in new situations), we have to
help them to relate new knowledge to more general problems, so that the memories get
indexed in ways that associate with those kinds of problems [22]. In this book, we teach
with concrete experiences that students can explore and relate to (e.g., conditionals for
removing red-eye in pictures) and later lay abstractions on top of them (e.g., achieving
the same goal using recursion or functional filters and maps).
We know that starting from the abstractions doesn’t really work for computing
students. Ann Fleury has shown that students in introductory computing courses just
don’t buy what we tell them about encapsulation and reuse (e.g., [7]). Students prefer
simpler code that they can trace easily and they actually think that such code is better.
It takes time and experience for students to realize that there is value in well-designed
systems. Without experience, it’s very difficult for students to learn the abstractions.
The media computation approach used in this book starts from what many people
use computers for: image manipulation, exploring digital music, viewing and creating
Web pages, and making videos. We then explain programming and computing in terms
of these activities. We want students to visit Amazon (for example) and think, “Here’s
a catalog Web site—and I know that these are implemented with a database and a
set of programs that format the database entries as Web pages.” We want students to
use Adobe Photoshop and GIMP and think about how their image filters are actually
manipulating red, green, and blue components of pixels. Starting from a relevant context
makes transfer of knowledge and skills more likely. It also makes the examples more
interesting and motivating, which helps with keeping students in the class.
The media computation approach spends about two-thirds of the time on giving
students experiences with a variety of media in contexts that they find motivating. After
that two-thirds, though, they naturally start to ask questions about computing. “Why is
it that Photoshop is faster than my program?” and “Movie code is slow—How slow do
programs get?” are typical. At that point, we introduce the abstractions and the valuable
insights from computer science that answer their questions. That’s what the last part
of this book is about.
A different body of research in computing education explores why withdrawal or
failure rates in introductory computing are so high. One common theme is that com-
puting courses seem “irrelevant” and unnecessarily focus on “tedious details” such
as efficiency [21, 1]. A communications context is perceived as relevant by students
20 Preface to the First Edition

(as they tell us in surveys and interviews [6, 18]). The relevant context is part of the
explanation for the success we have had with retention in the Georgia Tech course for
which this book was written.
The late entrance of abstraction isn’t the only unusual ordering in this approach. We
start using arrays and matrices in Chapter 3, in our first significant programs. Typically,
introductory computing courses push arrays off until later, because they are obviously
more complicated than variables with simple values. A relevant and concrete context
is very powerful [19]. We find that students have no problem manipulating matrices of
pixels in a picture.
The rate of students withdrawing from introductory computing courses or receiving
a D or F grade (commonly called the WDF rate) is reported in the 30–50% range or
even higher. A recent international survey of failure rates in introductory computing
courses reported that the average failure rate among 54 U.S. institutions was 33% and
among 17 international institutions was 17% [24]. At Georgia Tech, from 2000 to 2002,
we had an average WDF rate of 28% in the introductory course required for all majors.
We used the first edition of this text in our course Introduction to Media Computation.
Our first pilot offering of the course had 121 students, no computing or engineering
majors, and two-thirds of the students were female. Our WDF rate was 11.5%.
Over the next two years (Spring 2003 to Fall 2005), the average WDF rate at Georgia
Tech (across multiple instructors, and literally thousands of students) was 15% [29].
Actually, the 28% prior WDF rate and 15% current WDF rate are incomparable, since
all majors took the first course and only liberal arts, architecture, and management
majors took the new course. Individual majors have much more dramatic changes.
Management majors, for example, had a 51.5% WDF rate from 1999 to 2003 with the
earlier course, and had a 11.2% failure rate in the first two years of the new course [29].
Since the first edition of this book was published, several other schools have adopted
and adapted this approach and evaluated their result. All of them have reported similar,
dramatic improvements in success rates [4, 42].

Ways to Use This Book


This book represents what we teach at Georgia Tech in pretty much the same order.
Individual teachers may skip some sections (e.g., the section on additive synthesis,
MIDI, and MP3), but all of the content here has been tested with our students.
However, this material has been used in many other ways.
• A short introduction to computing could be taught with just Chapters 2 (intro-
duction to programming) and 3 (introduction to image processing), perhaps with
some material from Chapters 4 and 5. We have taught even single-day workshops
on media computation using just this material.
• Chapters 6 through 8 basically replicate the computer science concepts from
Chapters 3 through 5 but in the context of sounds rather than images. We find
the replication useful—some students seem to relate better to the concepts of
iteration and conditionals when working with one medium than with the other.
Preface to the First Edition 21

Further, it gives us the opportunity to point out that the same algorithm can have
similar effects in different media (e.g., scaling a picture up or down and shifting a
sound higher or lower in pitch are the same algorithm). But it could certainly be
skipped to save time.
• Chapter 12 (on movies) introduces no new programming or computing concepts.
While motivational, movie processing could be skipped to save time.
• We recommend getting to at least some of the chapters in the last unit, in order to
lead students into thinking about computing and programming in a more abstract
manner, but clearly not all of the chapters have to be covered.

Python and Jython


The programming language used in this book is Python. Python has been described as
“executable pseudo-code.” We have found that both computer science majors and non
majors can learn Python. Since Python is actually used for communications tasks (e.g.,
Web site development), it’s a relevant language for an introductory computing course.
For example, job advertisements posted to the Python Web site (http://www.python.
org) show that companies like Google and Industrial Light & Magic hire Python pro-
grammers.
The specific dialect of Python used in this book is Jython (http://www.jython.
org). Jython is Python. The differences between Python (normally implemented in C)
and Jython (which is implemented in Java) are akin to the differences between any
two language implementations (e.g., Microsoft vs. GNU C++ implementations)—the
basic language is exactly the same, with some library and details differences that most
students will never notice.

TYPOGRAPHICAL NOTATIONS
Examples of Python code look like this: x = x + 1. Longer examples look like this:
def helloWorld():
print "Hello, world!"

When showing something that the user types in with Python’s response, it will have
a similar font and style, but the user’s typing will appear after a Python prompt (>>>):
>>> print 3 + 4
7

User interface components of JES (Jython Environment for Students) will be spec-
ified using a small caps font, like Save menu item and the Load button.
There are several special kinds of sidebars that you’ll find in the book.

Computer Science Idea: An Example Idea


Key computer science concepts appear like this.

22 Preface to the First Edition

Common Bug: An Example Common Bug


Common things that can cause your program to fail appear like this.


Debugging Tip: An Example Debugging Tip


If there’s a good way to keep a bug from creeping into your programs in the first place,
it’s highlighted here.


Making It Work Tip: An Example How to Make It Work


Best practices or techniques that really help are highlighted like this.


INSTRUCTOR RESOURCES
The instructor resources are available on the Pearson Education’s Instructor Resource
Center at www.pearsonglobaleditions.com/guzdial:
• PowerPoint Presentation slides

ACKNOWLEDGMENTS
Our sincere thanks go out to the following:
• Jason Ergle, Claire Bailey, David Raines, and Joshua Sklare, who made the initial
version of JES with surprising quality in an amazingly short amount of time. Over
the years, Adam Wilson, Larry Olson, Yu Cheung (Toby) Ho, Eric Mickley, Keith
McDermott, Ellie Harmon, Timmy Douglas, Alex Rudnick, Brian O’Neill, and
William Fredrick (Buck) Scharfnorth III have made JES into the useful and still
understandable tool that it is today.
• Adam Wilson built the MediaTools that are so useful for exploring sounds and
images and processing video.
• Andrea Forte, Mark Richman, Matt Wallace, Alisa Bandlow, Derek Chambless,
Larry Olson, and David Rennie helped build course materials. Derek, Mark, and
Matt created many example programs.
• There were several people who really made the effort come together at Georgia
Tech. Bob McMath, Vice-Provost at Georgia Tech, and Jim Foley, Associate Dean
for Education in the College of Computing, invested in this effort early on. Kurt
Eiselt worked hard to make this effort real, convincing others to take it seriously.
Janet Kolodner and Aaron Bobick were excited and encouraging about the idea
of media computation for students new to computer science. Jeff Pierce reviewed
Preface to the First Edition 23

and advised us on the design of the media functions used in the book. Aaron
Lanterman gave me lots of advice on how to convey the digital material content
accurately. Joan Morton, Chrissy Hendricks, David White, and all the staff of the
GVU Center made sure that we had what we needed and that the details were
handled to make this effort come together. Amy Bruckman and Eugene Guzdial
bought Mark time to get the final version completed.
• We are grateful to Colin Potts and Monica Sweat who have taught this class at
Georgia Tech and given us many insights about the course.
• Charles Fowler was the first person outside of Georgia Tech willing to take the
gamble and trial the course in his own institution (Gainesville College), for which
we’re very grateful.
• The pilot course offered in Spring 2003 at Georgia Tech was very important in
helping us improve the course. Andrea Forte, Rachel Fithian, and Lauren Rich did
the assessment of the pilot offering of the course, which was incredibly valuable in
helping us understand what worked and what didn’t. The first teaching assistants
(Jim Gruen, Angela Liang, Larry Olson, Matt Wallace, Adam Wilson, and Jose
Zagal) did a lot to help create this approach. Blair MacIntyre, Colin Potts, and
Monica Sweat helped make the materials easier for others to adopt. Jochen Rick
made the CoWeb/Swiki a great place for CS1315 students to hang out.
• Many students pointed out errors and made suggestions to improve the book.
Thanks to Catherine Billiris, Jennifer Blake, Karin Bowman, Maryam Doroudi,
Suzannah Gill, Baillie Homire, Jonathan Laing, Mireille Murad, Michael Shaw,
Summar Shoaib, and especially Jonathan Longhitano, who has a real flair for
copyediting.
• Thanks to former Media Computation students Constantino Kombosch, Joseph
Clark, and Shannon Joiner for permission to use their snapshots from class in
examples.
• The research work that led to this text was supported by grants from the National
Science Foundation—from the Division of Undergraduate Education, CCLI pro-
gram, and from the CISE Educational Innovations program. Thank you for the
support.
• Thanks to computing students Anthony Thomas, Celines Rivera, and Carolina
Gomez for allowing us to use their pictures.
• Finally but most important, thanks to our children Matthew, Katherine, and Jennifer
Guzdial, who allowed themselves to be photographed and recorded for Mommy
and Daddy’s media project and who were supportive and excited about the class.

Mark Guzdial and Barbara Ericson


Georgia Institute of Technology
Pearson would like to thank and acknowledge Dheeraj D., REVA Institute of Technol-
ogy and Management Kattigenahalli, Somitra Sanadhya, Indian Institute of Technology
Delhi, and Simon, University of Newcastle, for contributing to the Global Edition, and
Shaligram Prajapat, Devi Ahilya University Indore, Ng Hu, Multimedia University,
Rohit Tahiliani, Renjith S., and Shivani Pandit, for reviewing the Global Edition.
About the Authors
Mark Guzdial is a professor in the School of Interactive Computing in the College
of Computing at Georgia Institute of Technology. He is one of the founders of the
ACM’s International Computing Education Research workshop series. Dr. Guzdial’s
research focuses on learning sciences and technology, specifically, computing education
research. His first books were on the programming language Squeak and its use in
education. He was the original developer of “Swiki” (Squeak Wiki), the first wiki
developed explicitly for use in schools. He is a Fellow and a Distinguished Educator
of the ACM. He is on the editorial boards of the Journal of the Learning Sciences and
Communications of the ACM. He was a recipient of the 2012 IEEE Computer Society
Undergraduate Teaching Award.
Barbara Ericson is a research scientist and the director of Computing Outreach for
the College of Computing at Georgia Tech. She has been working on improving intro-
ductory computing education since 2004.
She has served as the teacher education representative on the Computer Science
Teachers Association board, the co-chair of the K-12 Alliance for the National Center
for Women in Information Technology, and as a reader for the Advanced Placement
Computer Science exams. She enjoys the diversity of the types of problems she has
worked on over the years in computing including computer graphics, artificial intelli-
gence, medicine, and object-oriented programming.
Mark and Barbara received the 2010 ACM Karl V. Karlstrom Award for Outstanding
Computer Educator for their work on Media Computation including this book. They led
a project called “Georgia Computes!” for six years, which had a significant impact in
improving computing education in the US state of Georgia [31]. Together, they Mark
and Barbara are leaders in the Expanding Computing Education Pathways (ECEP)
alliance3

3
http://www.ecepalliance.org
PART

1 INTRODUCTION

Chapter 1 Introduction to Computer Science


and Media Computation
Chapter 2 Introduction to Programming
Chapter 3 Creating and Modifying Text
Chapter 4 Modifying Pictures Using Loops
Chapter 5 Picture Techniques with Selection
Chapter 6 Modifying Pixels by Position
This page intentionally left blank
CHAPTER
Introduction

1 to Computer Science
and Media Computation
1.1 WHAT IS COMPUTER SCIENCE ABOUT?

1.2 PROGRAMMING LANGUAGES

1.3 WHAT COMPUTERS UNDERSTAND

1.4 MEDIA COMPUTATION: WHY DIGITIZE MEDIA?

1.5 COMPUTER SCIENCE FOR EVERYONE

Chapter Learning Objectives


• To explain what computer science is about and what computer scientists are
concerned with.
• To explain why we digitize media.
• To explain why it’s valuable to study computing.
• To explain the concept of an encoding.
• To explain the basic components of a computer.

1.1 WHAT IS COMPUTER SCIENCE ABOUT?


Computer science is the study of process: how we or computers do things, how we
specify what we do, and how we specify what the stuff is that we’re processing. That’s
a pretty dry definition. Let’s try a metaphorical one.

Computer Science Idea: Computer Science Is the Study of Recipes


‘‘Recipes’’ here are a special kind—one that can be executed by a computational device,
but this point is only of importance to computer scientists. The important point overall is
that a computer science recipe defines exactly what has to be done.
More formally, computer scientists study algorithms which are step-by-step proce-
dures to accomplish a task. Each step in an algorithm is something that a computer
already knows how to do (e.g., add two small integer numbers) or can be taught how to
do (e.g., adding larger numbers including those with a decimal point). A recipe that can
run on a computer is called a program. A program is a way to communicate an algorithm
in a representation that a computer can execute.


To use our metaphor a bit more—think of an algorithm as the step-by-step way that
your grandmother made her secret recipe. She always did it the same way, and had a
28 Chapter 1 Introduction to Computer Science and Media Computation

reliably great result. Writing it down so that you can read it and do it later is like turning
her algorithm into a program for you. You execute the recipe by doing it—following
the recipe step-by-step in order to create something the way that your grandmother did.
If you give the recipe to someone else who can read the language of the recipe (maybe
English or French), then you have communicated that process to that other person, and
the other person can similarly execute the recipe to make something the way that your
grandmother did.
If you’re a biologist who wants to describe how migration works or how DNA
replicates, then being able to write a recipe that specifies exactly what happens, in
terms that can be completely defined and understood, is very useful. The same is true
if you’re a chemist who wants to explain how equilibrium is reached in a reaction.
A factory manager can define a machine-and-belt layout and even test how it works—
before physically moving heavy things into position—using computer programs. Being
able to exactly define tasks and/or simulate events is a major reason why computers
have radically changed so much of how science is done and understood.
In fact, if you can’t write a recipe for some process, maybe you don’t really under-
stand the process, or maybe the process can’t actually work the way that you are thinking
about it. Sometimes, trying to write the recipe is a test in itself. Now, sometimes you
can’t write the recipe because the process is one of the few that cannot be executed by
a computer. We will talk more about those in Chapter 14.
It may sound funny to call programs a recipe, but the analogy goes a long way. Much
of what computer scientists study can be defined in terms of recipes.
• Some computer scientists study how recipes are written: Are there better or worse
ways of doing something? If you’ve ever had to separate egg whites from yolks, you
realize that knowing the right way to do it makes a world of difference. Computer
science theoreticians think about the fastest and shortest recipes, and the ones that
take up the least amount of space (you can think about it as counter space—the
analogy works), or even use the least amount of energy (which is important when
running on low-power devices like cell phones). How a recipe works, completely
apart from how it’s written (e.g., in a program), is called the study of algorithms.
Software engineers think about how large groups can put together recipes that still
work. (Some programs, like the ones that keep track of credit card transactions,
have literally millions of steps!) The term software means a collection of computer
programs (recipes) that accomplish a task.
• Other computer scientists study the units used in recipes. Does it matter whether
a recipe uses metric or English measurements? The recipe may work in either
case, but if you don’t know what a pound or a cup is, the recipe is a lot less
understandable to you. There are also units that make sense for some tasks and
not others, but if you can fit the units to the tasks, you can explain yourself more
easily and get things done faster—and avoid errors. Ever wonder why ships at
sea measure their speed in knots? Why not use something like meters per second?
Sometimes, in certain special situations—on a ship at sea, for instance—the more
common terms aren’t appropriate or don’t work as well. Or we may invent new
kinds of units, like a unit that represents a whole other program or a computer, or
Section 1.1 What Is Computer Science About? 29

a network like your friends and your friends’ friends in Facebook. The study of
computer science units is referred to as data structures. Computer scientists who
study ways of keeping track of lots of data (in lots of different kinds of units) and
figuring out how to access the data quickly are studying databases.
• Can recipes be written for anything? Are there some recipes that can’t be written?
Computer scientists know that there are recipes that can’t be written. For example,
you can’t write a recipe that can absolutely tell whether some other recipe will
actually work. How about intelligence? Can we write a recipe such that a computer
following it would actually be thinking (and how would you tell if you got it right)?
Computer scientists in theory, intelligent systems, artificial intelligence, and
systems worry about things like this.
• There are even computer scientists who focus on whether people like what the
recipes produce, almost like restaurant critics for a newspaper. Some of these
are human–computer interface specialists who worry about whether people can
understand and make use of the recipes (“recipes” that produce an interface that
people use, like windows, buttons, scrollbars, and other elements of what we think
about as a running program).
• Just as some chefs specialize in certain kinds of recipes, like crepes or barbecue,
computer scientists also specialize in certain kinds of recipes. Computer scientists
who work in graphics are mostly concerned with recipes that produce pictures,
animations, and even movies. Computer scientists who work in computer music
are mostly concerned with recipes that produce sounds (often melodic ones, but
not always).
• Still other computer scientists study the emergent properties of recipes. Think
about the World Wide Web. It’s really a collection of millions of recipes (programs)
talking to one another. Why would one section of the Web get slower at some
point? It’s a phenomenon that emerges from these millions of programs, certainly
not something that was planned. That’s something that networking computer
scientists study. What’s really amazing is that these emergent properties (that
things just start to happen when you have many, many recipes interacting at once)
can also be used to explain noncomputational things. For example, how ants forage
for food or how termites make mounds can also be described as something that
just happens when you have lots of little programs doing something simple and
interacting. There are computer scientists today who study how the Web allows for
new kinds of interactions, particularly in large groups (like Facebook or Twitter).
Computer scientists who study social computing are interested in how these new
kinds of interactions work and the characteristics of the software that are most
successful for promoting useful social interactions.

The recipe metaphor also works on another level. Everyone knows that some things
in a recipe can be changed without changing the result dramatically. You can always
increase all the units by a multiplier (say, double) to make more. You can always add
more garlic or oregano to the spaghetti sauce. But there are some things that you cannot
change in a recipe. If the recipe calls for baking powder, you may not substitute baking
30 Chapter 1 Introduction to Computer Science and Media Computation

CHICKEN CACCIATORE
3 whole, boned chicken breasts 1 (28 oz) can chopped tomatoes
1 medium onion, chopped 1 (15 oz) can tomato sauce
1 tbsp chopped garlic 1 (6.5 oz) can mushrooms
2 tbsp and later 1 4 c olive oil 1 (6 oz) can tomato paste
1 1 2 c flour 12
of (26 oz) jar of spaghetti
14
c Lawry’s seasoning salt sauce
1 bell pepper, chopped (optional) 3 tbsp Italian seasoning
any color 1 tsp garlic powder (optional)
Cut up the chicken into pieces about 1 inch square. Saute the
onion and garlic until the onion is translucent. Mix the flour and
Lawry’s salt. You want about 1:4–1:5 ratio of seasoning salt to flour
and enough of the whole mixture to coat the chicken. Put the cut up
chicken and seasoned flour in a bag, and shake to coat. Add the coated
chicken to the onion and garlic. Stir frequently until browned.
You’ll need to add oil to keep from sticking and burning; I sometimes
add up to 1 4 cup of olive oil. Add the tomatoes, sauce, mushrooms,
and paste (and the optional peppers, too). Stir well. Add the Italian
seasoning. I like garlic, so I usually add the garlic powder, too. Stir
well. Because of all the flour, the sauce can get too thick. I usually
cut it with the spaghetti sauce, up to 1 2 jar. Simmer 20–30 minutes.

FIGURE 1.1
A cooking recipe—you can always double the ingredients, but throwing in an extra cup
of flour won’t cut it, and don’t try to brown the chicken after adding the tomato sauce!

soda. The order matters. If you’re supposed to brown the chicken and then add tomato
sauce, you won’t get the same result if you add tomato sauce and then (somehow) try
to brown the chicken (Figure 1.1).
The same holds for software recipes. There are usually things you can easily change:
the actual names of things (though you should change names consistently), some of
the constants (numbers that appear as plain old numbers, not as variables), and maybe
even some of the data ranges (sections of the data) being manipulated. But the order of
the commands to the computer, however, almost always has to stay exactly as stated.
As we go on, you’ll learn what can be safely changed, and what can’t.

1.2 PROGRAMMING LANGUAGES


Computer scientists write a recipe in a programming language (Figure 1.2). Different
programming languages are used for different purposes. Some of them are wildly
popular, like Java and C++. Others are more obscure, like Squeak and Scala. Some
others are designed to make computer science ideas very easy to learn, like Scheme or
Python, but the fact that they’re easy to learn doesn’t always make them very popular
or the best choice for experts building larger or more complicated recipes. It’s a hard
balance in teaching computer science to pick a language that is easy to learn and is
popular and useful enough to experts that students are motivated to learn it.
Why don’t computer scientists just use natural human languages, like English or
Spanish? The problem is that natural languages evolved the way they did to enhance
Section 1.2 Programming Languages 31

Python/Jython

def hello():
print "Hello World"

Java

class HelloWorld {
static public void main( String args[] ) {
System.out.println( "Hello World!" );
}
}

C++

#include <iostream.h>

main() {
cout << "Hello World!" << endl;
return 0;
}

Scheme

(define helloworld
(lambda ()
(display "Hello World")
(newline)))

FIGURE 1.2
Comparing programming languages: a common simple programming task is to print the
words ‘‘Hello World!’’ to the screen.

communications between very smart beings—humans. As we’ll explain more in the


next section, computers are exceptionally dumb. They need a level of specificity that
natural language isn’t good at. Further, what we say to one another in natural commu-
nication is not exactly what you’re saying in a computational recipe. When was the
last time you told someone how a video game like Mario Kart or Minecraft or Call of
Duty worked in such minute detail that they could actually replicate the game (say, on
paper)? English isn’t good for that kind of task.
There are so many different kinds of programming languages because there are so
many different kinds of recipes to write and people use these languages. Programs
written in the programming language C tend to be very fast and efficient, but they also
tend to be hard to read, hard to write, and require units that are more about computers
than about bird migrations, or DNA, or whatever else you want to write your recipe
about. The programming language Lisp (and related languages like Scheme, Racket,
and Common Lisp) is very flexible and is well suited to exploring how to write recipes
that have never been written before, but Lisp looks so strange compared to languages
like C. If you want to hire a hundred programmers to work on your project, it will be
32 Chapter 1 Introduction to Computer Science and Media Computation

easier to find a hundred programmers who know a popular language than a less popular
one—but that doesn’t mean that the popular language is the best one for your task!
The programming language that we’re using in this book is Python (visit http://
www.python.org for more information on it). Python is a popular programming lan-
guage, used very often for Web and media programming. The Web search engine
Google uses Python. The media company Industrial Light & Magic also uses Python.
A list of companies using Python is available at http://css.dzone.com/articles/
best-python-companies-work. Python is easy to learn, easy to read, very flexible,
but not as efficient as other programming languages. The same algorithm coded in C
and in Python will probably be faster in C. Python is a good language for writing pro-
grams that work within an application, like the image manipulation language GIMP
(http://www.gimp.org) or the 3D content creation tool Blender (http://www.
blender.org).
The version of Python used in this book is called Jython (http://www.jython.
org).1 Jython is a form of Python that is particularly effective for programming in
multimedia that will work across multiple computer platforms. You can download a
version of Jython for your computer from the Jython Web site that will work for all kinds
of purposes. Most programs written for Jython will work without change in Python.
In this book, we will describe how to program in Jython using a programming
environment called JES (Jython Environment for Students) that has been developed to
make it easier to program in Jython. JES has some features for working with media, like
viewers for sounds and images. JES also has embedded in it some special functions for
manipulating digital media that are made available to you without you doing anything
special. Anything you can do in JES, you can also do in normal Jython, though you
will have to explicitly include the special libraries.
Media Computation special libraries work with other environments and other forms
of Python, too.
• Pythy developed by Stephen Edwards and his colleagues at Virginia Tech is a
browser-based programming environment.2 All programming occurs through a
Web browser with Pythy, and programs and media are stored in the cloud. Programs
that work in JES will work in Pythy.
• A team led by Paul Gries at the University of Toronto has implemented portions
of the special media libraries in JES to work in other forms of Python.3
• The books at http://www.interactivepython.org/ by Brad Miller at Luther
College support manipulation of images in Python in all of their ebooks.
Let’s revisit here two of the most important terms that we’ll be using in this book:
• A program is a description in a programming language of a process that achieves
some result that is useful to someone. A program can be small (like one that imple-
ments a calculator) or huge (like one your bank uses to track all of its accounts).
1
Python is often implemented in the programming language C. Jython is Python implemented in
Java—this means that Jython is actually a program written in Java.
2
See https://github.com/web-cat/pythy for information on installing Pythy.
3
See https://code.google.com/p/pygraphics/ for information on the Pygraphics library.
Section 1.3 What Computers Understand 33

• An algorithm (in contrast) is a description of a process in a step-by-step manner,


not tied to any programming language. The same algorithm may be implemented in
many different languages in many different ways in many different programs—but
they would all be the same process if we’re talking about the same algorithm.

Computer Science Idea: Computer Science is about People


A famous computer scientist, Edsger W. Dijkstra, once said that, ‘‘Computer Science is
no more about computers than astronomy is about telescopes.’’ Computer science is
about people. People think about process in all those different ways (from a data
perspective, to issues of human−computer interfaces, to artificial intelligence). People
use programming languages, and they prefer different ways of communicating and
thinking, so different languages result. People make the programs and the languages.
Most decisions in computer science are not about computers. Most decisions in
computer science are about people.


1.3 WHAT COMPUTERS UNDERSTAND


Computational recipes are written to run on computers. What does a computer know
how to do? What can we tell the computer to do in the recipe? The answer is, “very,
very little.” Computers are exceedingly stupid. They really only know about numbers.
Actually, even to say that computers know numbers is not really correct. Computers
use encodings of numbers. Computers are electronic devices that react to voltages on
wires. Each wire is called a bit. If a wire has a voltage on it, we say that it encodes a 1.
If it has no voltage on it, we say that it encodes a 0. We group these wires (bits) into
sets. A set of 8 bits is called a byte. So, from a set of eight wires (a byte), we have a
pattern of eight 0’s and 1’s, for example, 01001010. Using the binary number system,
we can interpret this byte as a number (Figure 1.3). That’s where we come up with the
claim that a computer knows about numbers.4
A computer has a memory filled with bytes. Everything that a computer is working
with at a given instant is stored in its memory. This means that everything a computer
is working with is encoded in its bytes: JPEG pictures, Excel spreadsheets, Word
documents, annoying Web pop-up ads, and the latest spam email.
A computer can do lots of things with numbers. It can add them, subtract them,
multiply them, divide them, sort them, collect them, duplicate them, filter them (e.g.,
“Make a copy of these numbers, but only the even ones.”), and compare them and
do things based on the comparison. For example, a computer can be told in a recipe,
“Compare these two numbers. If the first one is less than the second one, jump to step
5 in this recipe. Otherwise, continue on to the next step.”
So far, it looks like the computer is a kind of fancy calculator, and that’s certainly why
it was invented. One of the first uses of a computer was to calculate projectile trajectories
during World War II (“If the wind is coming from the SE at 15 mph, and you want to
hit a target 0.5 miles away at an angle of 30 degrees East of North, then incline your
4
We’ll talk more about this level of the computer in the chapter Speed.
34 Chapter 1 Introduction to Computer Science and Media Computation

wires
0 27 = 128* 0 = 0 +
1 26 = 64* 1 = 64 +
0 25 = 32* 0 = 0 +
0 24 = 16* 0 = 0 +
1 23 = 8* 1 = 8 +
0 22 = 4* 0 = 0 +
1
1 2 = 2* 1 = 2 +
0 20 = 1* 0 = 0

interpreted as 74

FIGURE 1.3
Eight wires with a pattern of voltages is a byte, which is interpreted as a pattern of eight
0’s and 1’s, which in turn is interpreted as a decimal number.

launcher to . . .”). Modern computers can do billions of calculations per second. But
what makes the computer useful for general recipes is the concept of encodings.

Computer Science Idea: Computers Can Layer Encodings


Computers can layer encodings to virtually any level of complexity. Numbers can be
interpreted as characters, which can be interpreted in sets as Web pages, which can be
interpreted to appear as multiple fonts and styles. But at the bottom-most level, the
computer only ‘‘knows’’ voltages, which we interpret as numbers. Encodings let us forget
about lower-level details. Encodings are an example of abstraction, which give us new
concepts to use which allow us to ignore other details.


If one of these bytes is interpreted as the number 65, it could simply be the number
65. Or it could be the letter A using a standard encoding of numbers to letters called the
American Standard Code for Information Interchange (ASCII). If the 65 appears in a
collection of other numbers that we’re interpreting as text, and it’s in a file that ends in
“.html” it might be part of something that looks like this <a href=. . ., which a Web
browser will interpret as the definition of a link. Down at the level of the computer, that
A is just a pattern of voltages. Many layers of recipes up, at the level of a Web browser,
it defines something that you can click on to get more information.
If the computer understands only numbers (and that’s a stretch already), how does
it manipulate these encodings? Sure, it knows how to compare numbers, but how does
that extend to being able to alphabetize a class list? Typically, each layer of encoding
is implemented as a piece or layer in software. There’s software that understands how
to manipulate characters. The character software knows how to do things like compare
names because it has encoded that a comes before b and so on, and that the numeric
comparison of the order of numbers in the encoding of the letters leads to alphabetical
comparisons. The character software is used by other software that manipulates text in
files. That’s the layer that something like Microsoft Word or Notepad or TextEdit would
use. Still another piece of software knows how to interpret HTML (the language of the
Section 1.4 Media Computation: Why Digitize Media? 35

Web), and another layer of the same software knows how to take HTML and display
the right text, fonts, styles, and colors.
We can similarly create layers of encodings in the computer for our specific tasks.
We can teach a computer that cells contain mitochondria and DNA, and that DNA
has four kinds of nucleotides, and that factories have these kinds of presses and these
kinds of stamps. Creating layers of encoding and interpretation so that the computer is
working with the right units (recall back to our recipe analogy) for a given problem, is
the task of data representation or defining the right data structures.
If this sounds like a lot of software, it is. When software is layered this way, it
slows the computer down a bit. But the powerful thing about computers is that they’re
amazingly fast—and getting faster all the time!

Computer Science Idea: Moore’s Law


Gordon Moore, one of the founders of Intel (maker of computer processing chips)
claimed that the number of transistors (a key component of computers) would double at
the same price every 18 months, effectively meaning that the same amount of money
would buy twice as much computing power every 18 months. This means that computers
keep getting smaller, faster, and cheaper. This law has held true for decades.


Computers today can execute literally billions of recipe steps per second. They can
hold in memory literally encyclopedias of data! They never get tired or bored. Search
a million customers for an individual cardholder? No problem! Find the right set of
numbers to get the best value out of an equation? Piece of cake!
Process millions of picture elements or sound fragments or movie frames? That’s
media computation. In this book, you will write recipes that manipulate images,
sounds, text, and even other recipes. This is possible because everything in the computer
is represented digitally, even recipes. We would not be able to do media computation if
the media were not represented digitally. By the end of the book, you will have written
recipes to implement digital video special effects that create Web pages in the same
way that Amazon and eBay do, and that filter images like Photoshop.

1.4 MEDIA COMPUTATION: WHY DIGITIZE MEDIA?


Let’s consider an encoding that would be appropriate for pictures. Imagine that pictures
are made up of little dots. That’s not hard to imagine: look really closely at your monitor
or at a TV screen and you will see that your images are already made up of little dots.
Each of these dots is a distinct color. Physics tells us that colors can be described as the
sum of red, green, and blue. Add the red and green to get yellow. Mix all three together
to get white. Turn them all off and you get a black dot.
What if we encoded each dot in a picture as a collection of three bytes, one each for
the amount of red, green, and blue at that dot on the screen? And we collect a bunch
of these three-byte sets to determine all the dots of a given picture? That’s a pretty
reasonable way of representing pictures, and it’s essentially how we’re going to do it
in Chapter 4.
36 Chapter 1 Introduction to Computer Science and Media Computation

Manipulating these dots (each referred to as a pixel or picture element) can take a
lot of processing. There are thousands or even millions of them in a picture that you
might want to work with on your computer or on the Web. But the computer doesn’t
get bored, and it’s very fast.
The encoding that we will be using for sound involves 44,100 two-byte sets (called
a sample) for each second of time. A three-minute song requires 158,760,000 bytes
(twice that for stereo). Doing any processing on this takes a lot of operations. But at a
billion operations per second, you can do lots of operations to every one of those bytes
in just a few moments.
Creating encodings of this kind for media requires a change to the media. Look at the
real world: it isn’t made up of lots of little dots that you can see. Listen to a sound: Do
you hear thousands of little bits of sound per second? The fact that you can’t hear little
bits of sound per second is what makes it possible to create these encodings. Our eyes
and ears are limited: we can only perceive so much, and only things that are just so
small. If you break up an image into small enough dots, your eyes can’t tell that it’s not
a continuous flow of color. If you break up a sound into small enough pieces, your ears
can’t tell that the sound isn’t a continuous flow of auditory energy.
The process of encoding media into little bits is called digitization, sometimes
referred to as “going digital.” Digital means (according to the Longman Dictionaries)
Using a system in which information is recorded or sent out electronically in the form
of numbers, usually ones and zeros.5 Making things digital is about turning things from
continuous and uncountable to something that we can count, as if with our fingers.
Digital media, done well, feel the same to our limited human sensory apparatus
as the original. Phonograph recordings (ever seen one?) capture sound continuously
as an analog signal. Photographs (on film) capture light as a continuous flow. Some
people say that they can hear a difference between phonograph recordings and CD
recordings, but to our ears and most measurements, a CD (which is digitized sound)
sounds just the same, or maybe clearer. Digital cameras at high enough resolutions
produce photograph-quality pictures.
Why would you want to digitize media? Because then the media will be easier to
manipulate, to replicate exactly, to compress, to search, to index and classify (e.g., to
group similar images or sounds together), to compare, and to transmit. For example,
it’s hard to manipulate images that are in photographs, but it’s very easy when the same
images are digitized. This book is about using the increasingly digital world of media
and manipulating it—and learning computation in the process.
Moore’s Law has made media computation feasible as an introductory topic. Media
computation relies on the computer doing lots and lots of operations on lots and lots of
bytes. Modern computers can do this easily. Even with slow (but easy to understand)
languages, even with inefficient (but easy to read and write) recipes, we can learn about
computation by manipulating media.

5
Definition of “digital” from Longman Dictionary of Contemporary English. Copyright © 2009 by
Pearson Education. Reprinted with permission.
Section 1.5 Computer Science for Everyone 37

When we manipulate media, we need to be respectful of the author’s digital rights.


Modifying images and sounds for educational purposes is allowed under fair use laws
(which limit or create exceptions to an owner’s copyright). However, sharing or pub-
lishing manipulated images or sounds could infringe on the owner’s copyright.

1.5 COMPUTER SCIENCE FOR EVERYONE


Why should you learn about computer science by writing programs that manipulate
media? Why should anyone who doesn’t want to be a computer scientist learn about
computer science? Why should you be interested in learning about computation by
manipulating media?
Most professionals today manipulate media: papers, videos, tape recordings, pho-
tographs, and drawings. Increasingly, this manipulation is done with a computer. Media
are very often in a digitized form today.
We use software to manipulate these media. We use Adobe Photoshop for manip-
ulating our images, and Audacity to manipulate our sounds, and perhaps Microsoft
PowerPoint for assembling our media into slideshows. We use Microsoft Word for
manipulating our text, and Google Chrome or Microsoft Internet Explorer for
browsing media on the Internet.
So why should anyone who does not want to be a computer scientist study computer
science? Why should you learn to program? Isn’t it enough to learn to use all this great
software? The following sections provide answers to these questions.

1.5.1 It’s About Communication


Digital media are manipulated with software. If you can only manipulate media with
software that someone else made for you, you are limiting your ability to communicate.
What if you want to say something that can’t be said in software from Adobe, Microsoft,
Apple, and the rest? Or what if you want to say something in a way they don’t support?
If you know how to program, even if it would take you longer to do it yourself, you
have the freedom to manipulate the media your way.
What about learning these tools in the first place? In our years working with com-
puters, we have seen many types of software come and go as the package for drawing,
painting, word processing, video editing, and so on. You can’t learn just a single tool
and expect to be able to use it for your entire career. If you know how the tools work,
you have a core understanding that can transfer from tool to tool. You can think about
your media work in terms of the algorithms, not the tools.
Finally, if you’re going to prepare media for the Web, for marketing, for print, for
broadcast, or for any use whatsoever, it’s worthwhile for you to have a sense of what’s
possible and what can be done with media. It’s even more important as a consumer
of media that you know how the media can be manipulated, to know what’s true and
what could be just a trick. If you know the basics of media computation, you have an
understanding that goes beyond what any individual tool provides.

1.5.2 It’s About Process


In 1961, Alan Perlis gave a talk at MIT in which he argued that computer science, and
programming explicitly, should be part of a liberal education [35]. Perlis is an important
38 Chapter 1 Introduction to Computer Science and Media Computation

figure in the field of computer science. The highest award in computer science is the
ACM Turing Award. Perlis was the first recipient of that award. He’s an important figure
in software engineering and he started several of the first computer science departments
in the United States.
Perlis’s argument can be made in comparison with calculus. Calculus is generally
considered part of a liberal education: not everyone takes calculus, but if you want to
be well educated, you will typically take at least a term of calculus. Calculus is the
study of rates, which is important in many fields. Computer science, as stated earlier
in this chapter, is the study of process. Process is important to nearly every field, from
business to science to medicine to law. Knowing process formally is important for
everyone. Using a computer to automate processes has changed every profession.
Jeannette Wing has argued that everyone should learn computational thinking [23].
She views the types of skills taught in computing as critical skills for all students. This
is what Alan Perlis predicted: that automating computation would change the way we
learn about our world.

1.5.3 You Will Probably Need It


A team of researchers at Carnegie Mellon University did a study in 20056 where they
answered the question, “In the future, where will the programmers be, and how many
will there be?” They predicted that most programmers would not be professional soft-
ware developers. Most people who wrote programs would likely be people who needed
to write little programs to do something that they needed in their daily work. They
estimated that the ratio of professional software to end-user programmers would be as
high as 1:9, i.e., for every professional programmer in the world, there are nine more
people who are programming but just to help them out with their daily work. That result
suggests that many of you now reading this book will likely need to program one day,
even if you never make it your career.
The reality is that many people program today. Scientists and engineers write pro-
grams to create models and test them in simulations, or to analyze data. Graphics
designers write programs to make program tasks in Photoshop or GIMP to save them-
selves time, or to move their designs onto the Web. Accountants program when they
create complex spreadsheets. Many professionals need to store and manipulate process,
and thus learn to program, just as Alan Perlis predicted.

PROBLEMS
1.1 A study performed by a team of researchers at Carnegie Mellon University
in 2005 predicted that most programmers would not be professional software
developers. Use a web browser and a search engine like Google to find out how
the population of programmers is being studied these days. List some possible
areas in which programming could be required in everyday life.
6
See http://dl.acm.org/citation.cfm?id=1083231.1083232&coll=DL&dl=ACM&CFID=347064215&
CFTOKEN=87606004.
Problems 39

1.2 The 2013 Nobel Prize in Chemistry was in some sense a Nobel Prize given for
work in computer science. What was the role of computers in that Nobel Prize?
1.3 Text characters are encoded in different ways. The bottom level is always binary
in bytes, but a different binary pattern can be used to represent different char-
acters. Two of these encodings are ASCII and Unicode. See if you can do Web
searches on ASCII and Unicode. What’s the difference between ASCII and
Unicode? Why would we need Unicode if we already had ASCII?
1.4 Consider the representation for pictures described in Section 1.4, where each
dot (pixel) in the picture is represented by three bytes, for the red, green, and blue
components of the color at that dot. How many bytes does it take to represent a
640 by 480 picture, a common picture size on the Web? How many bytes does
it take to represent a 1024 by 768 picture, a common screen size? (What do you
think is meant now by a “three megapixel” camera?)
1.5 One bit can represent 0 or 1. With two bits you have four possible combinations
00, 01, 10, and 11. How many different combinations can you make with four
bits or eight bits (one byte)? Each combination can be used to represent a binary
number. How many numbers can you represent with 2 bytes (16 bits)? How
many numbers can you represent with four bytes?
1.6 Microsoft Word used to use an encoding of a word-processing document called
“DOC.” Most recent versions of Microsoft Word use a different encoding called
“DOCX.” What’s the difference between them?
1.7 One of the powerful ideas in computer science is that encodings can be layered.
Most of the encodings we’ve talked about so far (e.g., pixels in a picture, char-
acters, floating point numbers) are based on binary. XML is a way of encoding
information in text, which is in turn encoded in binary. What are the advantages
and disadvantages of using XML rather than binary encodings?
1.8 How can you encode a floating-point number in terms of bytes? Do a search
on the Web for “floating point.” You will find that there are different encodings
of floating point numbers. Take a common one like the IEEE Floating Point
Standard as an example. Assuming single precision, what is the largest and
smallest numbers that you can represent in that encoding?
1.9 As we said in the chapter, computer science is about people. Start your explo-
ration of computer science by exploring the people who are computer scientists
and influence computer science. As you do, find Web sites that you believe are
credible for your information, and include the URL in your answers—with your
reasons for believing that source is credible. What general rules do you use to
determine what is a credible Web site?
1.10 What is digitization? Define digital as per Longman Dictionaries. Justify the
need to digitize media. How has Moore’s Law made media computation feasi-
ble? Bring out the difference between phonograph and photograph.
1.11 Search for Gordon Moore on the web. What claim was he making with respect
to computing power? What was Moore’s observation?
Exploring the Variety of Random
Documents with Different Content
The Project Gutenberg eBook of Proper pride :
A novel. Volume 2 (of 3)
This ebook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this ebook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.

Title: Proper pride : A novel. Volume 2 (of 3)

Author: B. M. Croker

Release date: December 27, 2023 [eBook #72519]

Language: English

Original publication: London: Tinsley Brothers, 1882

Credits: MWS and the Online Distributed Proofreading Team at


https://www.pgdp.net (This file was produced from
images generously made available by The Internet
Archive/American Libraries.)

*** START OF THE PROJECT GUTENBERG EBOOK PROPER PRIDE :


A NOVEL. VOLUME 2 (OF 3) ***
PROPER PRIDE.
A Novel.

Life may change, but it may fly not;


Hope may vanish, but can die not;
Truth be veiled, but still it burneth,
Love repulsed—but it returneth.

IN THREE VOLUMES.
VOL. II.

LONDON:
TINSLEY BROTHERS, 8, CATHERINE ST., STRAND.
1882.
[All rights reserved.]
CHARLES DICKENS AND EVANS,
CRYSTAL PALACE PRESS.
CONTENTS.

PAGE
CHAPTER I.
“THE NEILGHERRIES” 1
CHAPTER II.
AFGHANISTAN 20
CHAPTER III.
“MY CAPTAIN DOES NOT ANSWER; HIS LIPS ARE PALE 48
AND STILL”
CHAPTER IV.
MONKSWOOD 80
CHAPTER V.
WAITING FOR AN ANSWER 87
CHAPTER VI.
THE RETURN OF THE NATIVE 105
CHAPTER VII.
“MARY, IT IS MY HUSBAND!” 134
CHAPTER VIII.
ALICE’S OVERTURES ARE DECLINED 163
CHAPTER IX.
“SIR REGINALD’S EYES ARE OPENED” 200
CHAPTER X.
GEOFFREY MANŒUVRES 238
CHAPTER XI.
“MEET ME BY MOONLIGHT ALONE” 245
PROPER PRIDE.
CHAPTER I.
“THE NEILGHERRIES.”
Our hero went to the Neilgherry Hills for the remainder of his two
months’ leave. It is quite beyond my pen to describe that lovely
region, but in common with almost all who have ever been there I
have an admiration amounting to a passion for the Blue Hills. I
declare them to be the most salubrious, delightful, beautiful range in
the whole world. If I were to attempt a detailed description of these
most favoured hills, I should fall so far short of their perfections that
I would only incur the wrath and contempt of their many devoted
admirers, so I shall content myself by merely giving a description of
Sir Reginald’s journey up the Ghaut.
He arrived at the foot of the hills early one morning, having spent
a night of heat, mosquitoes, and consequent madness at
Mettapollium. He rode up by the old road, which is nine miles to
Coonor, in preference to driving up the new ghaut, a detour of
sixteen miles. His thoughts were exceedingly pleasant, and he
whistled uninterruptedly for the first two miles; but after a while the
beautiful scenery he was passing through engaged his attention
entirely, and more than once he stopped his horse and looked about
in amazed admiration. “Oh, if Alice could only see it! If she were
here, what ecstasies she would be in!” was his frequent thought. As
he journeyed steadily up, the close tropical vegetation was gradually
left behind, the trees assumed a more European aspect, the air lost
its thick steamy feel, and became every instant more rarefied and
pure. The path appeared to wind in and out through mountain-sides
clothed with trees and foliage of every description; a foaming river
was tearing headlong down a wide rocky channel and taking frantic
leaps over all impediments. The scenery was splendid. In spite of
hunger and fatigue, Sir Reginald felt as if he could gaze and gaze for
hours, and yet that his eyes would scarcely be satisfied. Wild roses
and wild geraniums abounded on all sides; enormous bunches of
heliotrope were growing between the stones; lovely flowering
creepers connected the trees, and as to the ferns——!
The graves of several engineers who had died when this old ghaut
was being made were passed—poor lonely graves! and yet could
those laid in them, so many thousands of miles away from their
native land, desire to be buried in a more beautiful spot?
At one side towered the “Droog,” crowned by Tippoo’s old fortress.
The “Droog” itself, a bold beetling hill facing south, and most
precipitous, seemed to stand as sentry to this garden of India. From
the top of it you could look sheer down into the plains. It was on the
opposite side of the river to the old ghaut, and a long day’s outing
from Coonor. On its summit were the gray broken walls of the fort,
very old and much dismantled, and from which they say that Tippoo,
when in an angry mood, used to toss his unhappy prisoners down to
the plains below. There it was that the Mahrattas made their last
stand against the British; and as they brought an enormous amount
of treasure up from their strongholds in the plains, which treasure
has never been recovered, the “Droog” is considered a highly
interesting place for more reasons than one. It is said that all the
gold and jewels were thrown down a well somewhere just beyond
the fort walls. One very old man was supposed to know of its
whereabouts, but he would never divulge the secret, as he said the
spot was guarded by the ghosts—devils, he called them—of many
Mahratta warriors, and he was afraid to incur their displeasure.
Sir Reginald arrived in due time at Coonor, and put up at an hotel,
before the windows of which there was a hedge of heliotrope cut like
box at home, and so high and so dense, that you could ride at one
side of it, and someone else at the other, without either being aware
of their mutual proximity. It was one mass of flowers, and smelt like
ten thousand cherry-pies, and was one of the sights of the
Neilgherries. Sir Reginald relaxed somewhat as regarded society,
made friends with the other inmates of the hotel, and joined in
picnics to all the most celebrated views. He was well known on the
Toda Mund as one of the best and most inveterate of tennis-players,
and carried off the first prize in a tournament which took place
during his stay.
Touching the Toda Mund, there were no Todas there then; they
had long removed themselves, with their black ringlets and sheet
clothing, to a more remote region; but years previously the present
lawn-tennis-court ground had been the home of generations of
these extraordinary people.
Sir Reginald returned to his regiment much the better for his trip,
and received the congratulations of his friends on his improved
appearance, and also on the discovery he had made at Cheetapore;
as what had been the talk of all that station naturally came to the
ears of his brother-officers, and they boldly conversed of himself and
his wife as if they had known all along that he had been a married
man. The individual who had been so contemptuously scouted when
he had declared that Fairfax was a Benedict now found himself
looked upon as a man of unusual penetration—in short, a second
Daniel; and for a time his opinions were quoted at at least ten per
cent. above their usual regimental value.
As for Fairfax himself, a change had certainly come over the spirit
of his dream. He was an altered man; no more headlong solitary
rides, no more moping in his own quarters. Attired in faultless garb
of undoubted “Europe” origin, he was led, like a lamb, to make a
series of calls among the chief notabilities of the place. “Better late
than never!” they mentally exclaimed when his card was handed in,
and being assured that “Missus could see,” the hero of the hour
followed. His history was now as well known as if it had been
published in The Pioneer, and the ladies of Camelabad overwhelmed
him with sympathy and condolence, which he accepted with the best
grace he could muster; but he shrank from speaking of his wife,
save in the most distant and general terms; and it was easy to see
that the mock certificate was a very sore, distasteful subject.
As each succeeding mail came in he said to himself, “Surely this
will bring a letter from Alice?” How he looked forward to mail-days
no one knew but himself; how buoyant were his spirits every
Saturday morning, how depressed that same evening, when, tossing
over the newly-arrived letters on the anteroom table, he would find
one from Mark Mayhew, one from his agent, and perhaps one from
his tailor, but not a line from his wife. He heard from the Mayhews
that Alice had received and acknowledged the confessions; and
Mark, Helen, and Geoffrey each sent him a long letter full of
indignation and congratulation. The burden of each of these epistles
was the same, although couched in very different style and
language: it said, “Come home.” “Whenever his wife endorsed their
wishes, he would leave Bombay by the following mail.” This was
what he said to himself over and over again. Two months elapsed
and no letter came—not a line, not even a message. After making
allowance for every conceivable delay, he gradually and reluctantly
relinquished all hopes of the ardently-desired missive, and came to
the conclusion that nothing now remained for him to think but that
she wished their separation to be life-long.
One evening he mounted his horse and galloped out alone to one
of his former favourite haunts, an old half-ruined temple, about six
miles from the cantonment. Here he dismounted and tied his Arab to
a tree, saying to himself as he ascended the steps: “There is no fear
of any interruption here, and I will make up my mind to some
definite plan before I return to Camelabad this evening.” As he
paced up and down the empty echoing ruin, he tried to judge
between Alice and himself as calmly and dispassionately as if he
were a third person. His own motives and actions were easily
explained, but Alice’s were not so readily understood. What could be
the meaning of her extraordinary conduct? His name had been
cleared, and she, who should never have doubted him, and who, at
any rate now, ought to be the first to come forward, had been
dumb. There was but one reasonable solution. “She did not know
her own mind when she was married; she never cared two straws
about me, and she seizes the first pretext to free herself from a
distasteful union. So be it; she shall be free,” he muttered. “I will
hold myself utterly aloof from her for the future. I shall go home and
live at Looton, and surround myself with friends—shoot, hunt, and
lead as gay a bachelor life as if I had no wife in existence. Why
should I expatriate myself for her sake?” he asked himself aloud.
But on second thoughts this scheme did not prove so alluring. At
Looton, every room, every walk, every face would only remind him
of Alice.
“I could not stand it just yet,” he muttered; “it is all too fresh, too
recent; one does not get over a thing like that so soon. In a year or
two, when I am thoroughly hardened and indifferent, I will go;
meanwhile I shall remain in the service.”
The duties of his profession had their charms for him; and the
society of his brother-officers was, he reflected, more welcome and
more necessary to him now than ever. Weak he had always been
where Alice was concerned, but for once he would be firm and be a
man, and no longer an infatuated fool, following the ignis fatuus of a
woman’s caprice.
As he stood on the steps of the temple, watching the crimson sun
that was slowly sinking beyond the horizon and tinting the arid
plains, the distant hills, the old temple, and Reginald himself, with
the gorgeous hues of its departing splendour, “That sun,” he
exclaimed, as he watched the last little red streak utterly disappear,
“has set on my folly and weakness; to-morrow will find me, in one
respect at least, a different man. For the future I will endeavour to
forget that I ever had a wife. I know it will be no easy matter to
banish her from my thoughts, but I shall do my best. As a wife she
is dead to me in all but name; her indifference shall be only rivalled
by mine.” Query: Was he not still thinking of her as he sat for fully
an hour, with his head resting in his hands? He was endeavouring to
dig the grave of his love, and to bury decently all the unfulfilled
hopes he had cherished for so long. The moon arose, owls and bats
made their appearance and flitted to and fro, apparently
unconscious of the silent figure on the temple steps. At length the
pawing and neighing of his horse aroused him. He started up hastily,
pulled himself morally together, and hurried down to the impatient
steed, whom he unfastened and mounted, and in another moment
was galloping away over the moonlit midan, leaving the old temple
to the undisturbed possession of a veteran hyena and a family of
jackals.
The Seventeenth Hussars had expected, as a sequel to his
discovery at Cheetapore, that Sir Reginald would have returned to
his ancestral halls as fast as steam could take him.
But month after month went by, and he still remained a fixture at
Camelabad. He carried out his mental resolution to the letter, and
left himself no leisure to think of Alice or anyone else. He returned
with the greatest energy to all his bachelor amusements, kept a
string of racers, hunted the regimental pack, and made constant
shooting expeditions. He played whist till the small hours, and
entered into everything with the greatest zeal; took a prominent if
somewhat mechanical part in all the entertainments in the station,
and was voted “charming” by the ladies, both young and old.
Notwithstanding his bachelor pursuits, he developed a curious and
Benedict-like interest in babies—a species of humanity that he had
hitherto held in abhorrence. He cast more than one inquisitive
glance on the smaller fry in arms as he went round the married
quarters. And Mrs. Gifford, the wife of the only married captain in
the Seventeenth, was amazed when her ayah informed her that “Sir
Fairfax” had more than once taken notice of her baby, “asking age,
asking boy or girl, how soon walking?” It was most flattering, if a
little mysterious, and he became a greater favourite than ever with
Mrs. Gifford. She was not aware that her boy shone with a borrowed
lustre in Sir Reginald’s eyes for being almost the same age as his
son, and that the toys and presents which were showered on him as
he grew older were not bestowed altogether for his own sake.
A year after his visit to Cheetapore, Sir Reginald received a letter
in Alice’s well-known writing. “It has come at last,” he said to
himself, as with trembling hands he tore it open in his own
bungalow. He drew out the photo of a sturdy dark-eyed cherub,
enclosed in a sheet of blank letter-paper. At first he could hardly
credit his senses; his indignation and his bitter disappointment were
too great for words. His first impulse was to tear the photo into four
pieces, but, mastering this rather insane idea, he took it up and
looked at it closely instead. He was glad he had not obeyed his first
rash notion. The boy was certainly a splendid little fellow. Written in
the corner of the carte was, “Maurice E. Fairfax, aged thirteen
months.” He was something more tangible now, his father thought,
as he minutely studied every feature. He felt a thrill of novel and
very pleasant pride as he looked at the bright eager little face, and
said to himself: “This is my son. He has the Fairfax eyes and brows,
I believe,” he continued, as he still studied the photo critically, “but
no one will deny that he has his mother’s mouth.”
With a sigh he pieced together the torn envelope, and looked in
vain for a word; the blank sheet of paper he scrupulously turned
over; it was really blank indeed. He gazed at it for some time, as if
there were actually something written on it; then, suddenly
gathering himself together, he carefully folded it up and put it along
with the photograph into the envelope, and locked them away in his
desk.

Sir Reginald had been nearly two years at Camelabad when the
outbreak which had been simmering for some time in Afghanistan
came to boiling-point, and the gauntlet of defiance was thrown
down by the Ameer.
Captains Campbell and Vaughan were reposing in long chairs in
front of their mess, much exhausted with lawn-tennis, refreshing
themselves with copious iced pegs, and enjoying a delightful
experience of the dolce far niente as embodied in Bombay—chairs
and brandies-and-sodas.
Suddenly a solitary horseman was seen madly careering across
the midan, in the direction of their lines.
“I say, just look at this fellow; his horse has bolted!” said Captain
Campbell.
“Not a bit of it,” replied his companion serenely; “don’t you see
that it’s Fairfax on his chestnut, riding ventre à terre, as usual?”
“Hallo, Fairfax, what’s up?” they shouted as he approached. “Are
the barracks ablaze, and are you going for the fire-engine?”
“Better than that,” he cried, clattering into the compound. “I have
just come up from the general’s with glorious news—we start for the
front this day week.”
CHAPTER II.
AFGHANISTAN.

True, a new mistress now I chase,


The first foe in the field,
And with a stronger faith embrace
A sword, a horse, a shield.

The Seventeenth Hussars were duly forwarded to the frontier, and


found that their final destination was Dabaule, where there was a
good supply of grass and water for their horses.
Owing to the approach of winter, there was an utter stagnation of
military operations, and in spite of occasional small raids on, and
from, the neighbouring Afridis, the time passed monotonously
enough. The weather was cold and cheerless, but the officers of the
Seventeenth, headed by their junior major, did their very best to
provide exercise and entertainment for their men and for the camp
in general.
Football, hockey, penny readings, and theatricals were set going
with remarkable success, and helped to repel the encroachments of
idleness and ennui. The surrounding scenery was quite different to
the tiresome succession of parallel ridges presented by the ranges
near the frontier. Here hill and valley were thrown together in the
most admirable confusion, and clothed with short stunted shrubs
and wild olives; gloomy pine-woods marked out some of the hills in
bold black relief; the distant mountains were capped with snow, and
the cold at times was most intense. During the suspension of
hostilities there was ample leisure for correspondence, and letter-
writing was a frequent resource on a dull gray afternoon. The
following is one of Sir Reginald’s contributions to the mail-bag,
written on his knee by the light of a small bull’s-eye lantern in the
retirement of his seven-foot tent:
“Camp Dabaule.
“My dear Mark,
“It is not my fault that there has been such a tremendous
gap in our correspondence. I have written to you again and
again, and I once more seize the opportunity of the mail-dâk
passing through to send you a few lines, and hope they will
meet with a better fate than my other effusions, not one of
which appears to have reached you, judging by your
incendiary letter. Doubtless they are in the hands of those
beggars the Afridis, who rob the mails and cut the telegraph-
wires continually. We are all flourishing—men in good spirits,
horses in capital condition; the only thing we ask is to be up
and doing. Cold weather has closed the passes to a great
extent, and there is nothing whatever going on. To come into
our camp you would never dream that you were in an
enemy’s country, we have made ourselves so completely at
home, although our accommodation is not magnificent. We
have all small hill-tents, weighing about eighty pounds, in
which there is just room enough to turn round, and no more.
We all wear thick fur coats, called poshteens, and fur caps,
quite the Canadian style. You would have some difficulty in
recognising me, I can tell you, were you told to pick me out
from among a dozen of fellows sitting round our favourite
rendezvous—the camp-fire. There is snow on the ranges all
round, and we have lots of ice without troubling the ice-
machines, but hot grog is more the fashion than iced
champagne.
“We arrived here six weeks ago, viâ the Khan Pass, and
brought in, among other prisoners, Hadji Khan, a notorious
robber and unmitigated rascal. We have him in camp now. He
has the most diabolical expression I ever beheld;
nevertheless, the length and frequency of his prayers are
absolutely astounding. He spends more than half the day on
his marrow-bones, no doubt consigning us, in all generations,
to Gehenna, if you know where that is?
“The Afghans, take them all in all, are a fine-looking set of
men, with bigger frames and fairer skins than the natives of
sunny Hindostan. Their physiognomy is decidedly of the
Jewish caste—piercing black eyes and hooked noses, set off
by a resolute, not to say savage, expression of death and
extermination to all the Feringhees!
“Now, this cold weather, they are wrapped in poshteens,
with or without sleeves, of very dubious cleanliness. A good
serviceable garment descends from generation to generation.
An enormous dark-blue puggaree encircling a little red cap
forms their turban. But the headman of a village, in a richly-
embroidered poshteen, ‘the woolly side in,’ like the immortal
Brian O’Lynn—magnificent gold and blue turban, and long
silver-mounted matchlock, is as handsome and picturesque a
looking fellow as you could wish to see.
“I have not as yet had an opportunity of beholding an
Afghan lady. Some of the common women labour in the fields
unveiled, a weather-beaten, bold-looking set, but the lady of
the period conceals her charms behind a long white
arrangement, that covers her from head to foot, like a sheet;
two holes cut for her eyes, and covered with white net, give
her a most ghostly and ghastly appearance. She looks like a
she-‘familiar’ of the time of the Inquisition.
“We have a capital mess here, and to find such a dinner as
our head kansamah serves up, after whetting our appetites
by a twenty-mile ride, is a joy no words can express. After the
snows break up we are sure to have a short bout of fighting,
and then the campaign will be over. The English charger I got
in Bombay has turned out first-class—as hard as nails and up
to any amount of work. Many thanks to Helen for the
Cardigan jacket and mittens. My love to her and the Limbs.
“Yours as ever,
“R. M. Fairfax.”
In April there was a general move on. The camp at Dabaule was
broken up, and everyone was delighted to stretch themselves, as it
were, and resume the line of march.
Very shortly afterwards a severe engagement took place between
the brigade and a large body of Afghans. It resulted in the total
defeat of the latter. Their loss amounted to one thousand, whilst the
English force had only three hundred killed and wounded. The
Afghans occupied a large plateau protected by walls of loose stones,
and held an extremely strong position. The English brigade consisted
of the Seventeenth Hussars, Fifth Goorkhas, Twenty-seventh N. I.,
Fortieth Sikhs, and a battery of artillery. The enemy behaved with
the most determined courage, rabble horde as they were; some
merely armed with long knives and yataghans, some carrying the
dear familiar Jazail, and some—oh, proud and happy men!—the
British Enfield rifle. They were led by a man on a powerful black
horse, who wore a prodigious green turban, and had his face
whitened with ashes or some such substance. He was a very holy
moolah, and harangued the multitude with an energy and
vehemence only surpassed by his wild and frenzied gesticulations.
Beside him stood his standard-bearer, carrying a large green flag
with a red border and red inscription; and in spite of a heavy fire
from the infantry, this enormous force of undisciplined fanatics
advanced with the utmost steadiness and resolution. The order to
charge was given to the hussars, who bore down like a whirlwind,
led by Sir Reginald Fairfax—the colonel was hors de combat with
typhoid fever—who, mounted on a gallant English thoroughbred,
cleared the low wall, and was soon laying about him in all directions.
He wrested the standard from the hands of its bearer, and striking
him a tremendous blow with its iron pole, laid him low, but was
speedily surrounded by some furious fanatics, resolved to regain
their colours at any cost. His horse was shot under him; however,
quickly disengaging himself, sword in hand, and still grasping the
green flag, he made a valiant stand against half-a-dozen moolahs,
with his back to some broken masonry. It would have gone hard
with him had not some of his men charged down to his rescue and
beaten off the moolahs, who in another moment would have made a
vacancy in the Seventeenth Hussars and left Lady Fairfax a widow.
Rid of his immediate adversaries, Sir Reginald seized a riderless
horse, and making over the standard to a gunner, was soon pursuing
the flying enemy, who, unable to withstand the cavalry charge, had
wavered, broken, and fled; being, moreover, utterly demoralised by
the loss of their standard, which they looked upon as their
“oriflamme,” and as a kind of holy talisman, the very sight of which
alone would make the hearts of the Feringhees quail. So much had
been promised on its behalf by an aged fakir, who had delivered it
over to his countrymen with many prayers and profound solemnity.
And it was gone—taken from their very midst by a black-hearted
Kaffir, who fought like the Prince of Darkness himself.
The flying Afghans, scattered all over the plain, were pursued and
ridden down by the cavalry; but the prize all sought to capture—the
fakir on the black Turcoman—set every effort at defiance, and,
thanks to his magnificent horse, effected his escape with almost
provoking ease. Yaboos, laden with dead Afghans, were driven off
the field with miraculous celerity, and within an hour from the firing
of the first shot the plain was deserted.
For the capture of the standard “and displaying conspicuous
gallantry on the field of action,” Sir Reginald was recommended for
the Victoria Cross, a distinction his friends granted him ungrudgingly.
He was a born soldier, that was very evident. The Fairfaxes had
always had a drop of wild blood in their veins. With him it took the
form of fighting, instead of—as in his ancestors’ times—dicing,
drinking, and duelling. His men worshipped him, and would willingly
have followed him at any time and to any place, were it to the very
gates of Hades itself.
“It’s the good old blood that tells in the long run,” remarked a
trooper to his comrade over his beer and pipe. “Such a glutton for
fighting as this ’ere major of ours I never did see.”
At any rate, whatever was the reason, such an officer in camp and
such a leader in the field inspired their utmost devotion and
enthusiasm.

Although Hafiz Khan and his hordes were defeated and dispersed,
they speedily rallied sufficiently to be a ceaseless thorn in the flesh
to the brigade now permanently encamped within a few miles of the
late scene of action. Hafiz was a striking illustration of the saying,
“He who fights and runs away will live to fight another day.” He was
a fakir—exceptionally holy, having made the blessed pilgrimage no
less than thrice—notorious alike for his zealous piety as for his
abhorrence of the accursed Kaffir. Scandal whispered that he had
not always been such a devoted servant of the Prophet; that for
years he lived in ill-odour among his neighbours, owing to his
constant appropriation of their flocks and herds. Whatever may have
been the truth, he was now an ardent patriot, and preyed on the
Feringhees instead of on his friends. He was a most daring and
successful raider, and covered himself with glory, notably on one
occasion when he carried off seven hundred head of cattle from
Jellalabad.
He cut off more convoys and slaughtered more grass-cutters and
camel-drivers than any other leader between Cabul and the Khyber;
and his depredations were so secretly and skilfully carried out, that
his very name alone inspired the stoutest-hearted camp-follower
with terror.
Invariably mounted on his superb black Turcoman, he gave chase
or effected his retreat with a speed that set everything at defiance.
His horse was known by the name of “Shaitan,” and was supposed
to be in direct communication with the Evil One, being imported
expressly from the lower regions for the purpose of hunting down
the infidels. The rider of this desirable mount was an elderly thick-
set man, wearing a gigantic green turban, so large as almost to
conceal his features. Still his hooked nose, fierce hawk eye, and
bushy beard were visible; and the treacherous, cruel, malignant
expression of his face was such as a devil might have envied. Armed
with a pair of horse-pistols and a formidable yataghan, he headed a
band of followers varying from fifty to two thousand, and infested an
area of many miles in extent. His patriotic zeal had no bounds; he
was known to have recently butchered an entire village, merely
because the headman had supplied (under strong pressure) cattle
and grain to the English commissariat; in short, his name far and
near was a byword for ferocity and fanaticism.

One evening, Sir Reginald and his two friends, Captain Vaughan
and Mr. Harvey, went for a short ride in the neighbourhood of their
camp, the former mounted on his first charger, an unusually large,
powerful Arab, the two latter on stout Yarkundi ponies. All were clad
in Karki suits, and carried (a most necessary precaution) revolvers in
their belts. The country around was reported clear. Hafiz and his
faction were said to be miles away. Certainly nothing had been heard
of them for two whole days. It was a lovely evening, and tempted by
the odd wild scenery they extended their ride farther than they had
previously intended. At sunset they found themselves close by a
straggling Mohammedan cemetery, whose large square tombs were
thickly crowded together, some of them richly carved, some of them
poor and plain. The graveyard was planted with magnificent
cypresses, now casting long, long shadows in the setting sun. A
solemn melancholy silence hung around the place; even the mud
hovel, usually inhabited by the guardian fakir, was empty—a huge
Afghan dog, with closely-cropped ears and tail, lay in front of the
open doorway, sleeping on his post.
“Do you know that they say there is a Christian grave somewhere
quite close to this?” said Sir Reginald, looking round. “I wonder they
buried him so near to these people,” nodding his head in the
direction of the cemetery.
“Yes,” returned Mr. Harvey; “but it was probably done with an idea
that he would like some company.”
“Defend me from the company of an Afghan, dead or alive,”
returned his brother-officer, walking his horse on to where he
commanded a view of the fourth side of the graveyard. His two
friends followed him, and another second brought in sight a grave
and plain stone cross, about a hundred yards to their right. Standing
beside it was the fakir, in close and earnest conversation with no less
a person than Hafiz himself—Hafiz, mounted as usual on his black
Turcoman, and alone! Both had their backs turned to the cemetery,
and stood facing the setting sun, deeply absorbed in conversation,
which they emphasized from time to time with vehement and almost
frenzied gesticulation. Evidently they were hatching some evil deed.
“Hafiz, by all that is lucky!” exclaimed Sir Reginald, drawing out his
revolver and putting his horse into a sharp canter. But between him
and the fakirs ran a deep nullah, and ere he reached its bank they
were both aware of the presence of the three hussars.
Hafiz paused for a second to glare at the intruders, then raising
one arm to heaven, with a loud invocation to Allah, he turned and
spat on the cross beneath him with a gesture of the utmost
abhorrence and contempt, and wheeling his horse half round, with a
derisive farewell to his foes, he started off at full gallop. This
outrageous insult to their faith and nation affected the three
Englishmen variously. Captain Vaughan, who was of rather full habit,
became absolutely purple with passion; Mr. Harvey relieved his
feelings with several round oaths; Sir Reginald said nothing, but his
lips tightened under his dark moustache in a way that was ominous
enough. With a vicious dig of the spurs he forced his horse down the
rugged sides of the nullah, up the opposite bank, and away across
the plain in hot pursuit of the holy man. The two Yarkundis, urged to
the very top of their speed, joined neck and neck in the chase for a
short distance, but endurance, not pace, was their forte, and they
soon ceased to answer to the repeated applications of their riders’
spurs and Annamullay canes, and began to lag behind the free-going
Arab.
“It’s no use, Fairfax,” shouted Captain Vaughan, pulling up; “you’ll
never overtake him.”
“I will!” he returned, looking back for a second. “I’ll catch him and
kill him, if I follow him to Candahar.”
His friends’ remonstrances were given to the winds; he had
already distanced them by a hundred yards, and soon he and the
far-receding fakir became mere specks in the distance, and rounding
the spur of a hill, were completely lost to sight.
The two officers waited impatiently for the sound of shots, but the
silence that reigned around them remained unbroken, save for the
distant cry of the jackal setting out on his nightly career, and
seeming to say more distinctly than usual: “I smell dead white men,
I smell dead white men.”
The whistle of a kite sailing homewards was the only other sound
that broke the dead surrounding stillness. The sun had set; ten
minutes previously it had vanished below the horizon in the shape of
a little red speck; gray twilight was rapidly spreading her mantle over
hills and plains, and our two friends, finding they had completely lost
sight of their hot-headed companion, reluctantly turned their ponies’
heads homewards, and retailed their adventure to their comrades
round the camp-fire. These listened to it with many interruptions of
surprise and dismay.
“Fairfax was splendidly mounted; that Arab of his was one of the
best horses out of Abdul Rahman’s stables, that’s some comfort,”
remarked one.
“Yes, he was evidently gaining on the Turcoman when we saw the
last of him,” returned Mr. Harvey; “but, for all we know, Fairfax has
galloped straight into the Afghan camp.”
“I had no idea he was such a Quixotic fool,” growled a grizzly-
headed colonel, angrily kicking the logs in front of him. “It would not
surprise me if we never saw him again.”
Some said one thing, some another, but all agreed in feeling very
grave uneasiness on behalf of their brother-officer.
The mess-bugle sounded and was responded to, dinner was
disposed of, and still Fairfax did not appear. Meanwhile Sir Reginald,
once lost to sight, had been, as Mr. Harvey remarked, overtaking
Hafiz at every stride. The Turcoman had done a long day’s march,
and, though urged by his rider to great exertions, was no match for
the well-bred Arab in his wake. The distance between them
diminished gradually but surely. The black horse was only leading by
thirty yards when Hafiz turned and glanced over his shoulder. It was,
as he had fancied, the very selfsame Kaffir who had taken the
sacred standard. They were within half a mile of the Rohilla
headquarters, and Allah had surely given him over for a prey into his
hand. But his horse was failing, and the Feringhee would soon be at
his girths. Best finish the matter at once. Reining up suddenly, he
faced the approaching horseman with astonishing celerity, and
drawing a pistol, which he aimed for half a second, he fired at him
point-blank. The bullet missed its intended destination and buried
itself deep in the brain of the Arab charger, who with one frantic
convulsive bound fell forward dead on the sand, and the fakir, with
drawn yataghan, charged down on the dismounted hussar,
determined to have his life.
But, Hafiz, your evil star was in the ascendant. Had you but
known, you would have been far wiser to have ridden off and left
your foe to find his way back to camp on foot, and to take his
chance of being murdered by your prowling countrymen.
With an expression of fiendish hatred the fakir rode at Sir
Reginald, his uplifted weapon ready to descend with fatal effect. But
he had to contend with a man of half his age and ten times his
activity, who sprang at him and seized his arm, and in so doing
broke the force of the blow, which, instead of sweeping off our
hero’s head, as intended, merely inflicted a flesh wound in his
shoulder, and before Hafiz had time to recover himself, a bullet from
Sir Reginald’s revolver found a lodging in his breast. Swaying heavily
backwards and forwards, his powerless hands dropped reins and
weapon, and he fell from his saddle like a sack; and our hussar,
catching the Turcoman by the bridle and disengaging his late master
from the stirrup, sprang on his back, turned his head in the direction
of the English camp, and rode off at the top of his speed.
His practised ear had caught the sounds of approaching hoofs,
attracted doubtless by the shots; but still he had a start of fully a
quarter of a mile, and made the very most of it. Infuriated Pathans
rode hard upon his track, and it was not till he was well within the
lines of the English picket, and saw their camp-fires blazing, that he
ventured to draw rein and allow the exhausted Turcoman to proceed
at a walk. It does not often happen to a horse to have to carry two
successive riders flying for their lives within the same hour. Shaitan’s
drooping head and heaving sides bore witness to a hard day’s work,
as he was led by his new owner within the bright circle of light
thrown by the officers’ camp-fire.
Exclamations, remonstrances, and questions were volleyed at Sir
Reginald as once more he stood among his friends, bare-headed and
ghastly pale, with the bridle of the notorious black charger hanging
over one arm. Very brief were the answers he vouchsafed to half-a-
dozen simultaneous interrogations.
“Hafiz was badly wounded, if not dead. He was not likely to
trouble them for some time, if ever; his own charger was lying on
the plain with a bullet in his brain, and affording a fine supper for
the jackals. Yes, he had had to ride for it coming back, and the black
was pretty well done.” Here, as he came nearer to the logs, it was
seen that one sleeve of his Karki coat was soaked in blood.
Questions were immediately at an end, and he was hurried off by
the doctor to have his wounds looked to, in spite of his urgent
disclaimers and assurances “that it was a mere scratch.”
The Turcoman, the sight of which acted on the Afghans as a red
rag to a turkey-cock, soon became accustomed to an English bit and
an English rider, and made his new master a most valuable second
charger. Many were the attempts to recover him, to shoot him, to
get him from his abhorred Kaffir owner at any price, but all efforts
were futile, he was much too well guarded. When Sir Reginald was
invalided home, he was sent down to Bombay with his other horses,
and sold for a very high price to a hard-riding Member of Council;
and doubtless the destination of the once feared and honoured “evil
one” will be to end his days in a Bombay buggy.
CHAPTER III.
“MY CAPTAIN DOES NOT ANSWER; HIS LIPS
ARE PALE AND STILL.”

Beyond constant and most wearisome convoy duty, the


Seventeenth Hussars had very little to do. Afghanistan is a country
more adapted for mountaineers than mounted men; and as far as
downright fighting was concerned, the cavalry were, perforce, idle.
Sir Reginald looked upon “baggage guard” as better than nothing.
“Half a loaf was better than no bread,” and he had more than one
exciting little brush with would-be marauding and murdering
Pathans.
Repeatedly successful raids and small skirmishes had given him a
most unenviable notoriety among the tribes of banditti who infested
the various camel-roads and swarmed about the hills. To these he
was a perfect scourge, and hunted them and harried them with
unwearied energy. It is not too much to say that they literally
thirsted for his blood. Although often warned by his brother-officers
that he would be “potted,” his daring and foolhardiness knew no
bounds. He would loiter behind, or canter on in advance of a
squadron, as coolly as if he were riding on an English high-road, and
not through a gloomy Afghan pass, among whose rocks more than
one enemy was sitting patiently behind his Jazail or Snider, waiting
to work off any straggling Kaffirs, and so to earn for himself an
honourable name.
Sir Reginald appeared to bear a charmed life, and thoroughly to
carry out the good old Irish motto, “Where there’s no fear there’s no
danger;” and though he had one or two narrow escapes, he
exemplified another saying in his own person, viz., “That a miss is as
good as a mile.”
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookmass.com

You might also like