Table Of ContentThe art and science of C
Part One the Basics of C Programming
Part Two Libraries and Modular
Development
Part Three Compound Data Types
OVERVEW
OVERVIEW
OVERVIEW
TTThhheee aaarrrttt aaannnddd sssccciiieeennnccceee ooofff CCC
PPPaaarrrttt OOOnnneee ttthhheee BBBaaasssiiicccsss ooofff CCC PPPrrrooogggrrraaammmmmmiiinnnggg
OOOVVVEEERRRVVVIIIEEEWWW
LearningC,oranyprogramminglanguage,isinmanyrespectslikelearningto
communicateinaforeignlanguage.Youneedtoacquireavocabularytoknowwhatthe
wordsmean. Youneed to studysyntax sothatyoucanassemble those wordsinto
sentences.Andyoumustcometorecognizecommonidiomssothatyoucanunderstand
whatpeopleactuallysay.Therefore,PartOneintroducesyoutothevocabulary,syntax,
andidiomaticstructureofC.Butmasteringtheseconventionsisnotenough.Asinany
language, youmusthavesomethingto say.Theessence ofprogrammingissolving
problems. While knowing howto express themisimportant, learning howto find
solutionsisthegreaterchallenge.Thus,PartOnefocusesonstrategiesforproblem
solving,toenableyounotjusttowritebuttothinklikeaprogrammer.
PPPaaarrrttt TTTwwwooo LLLiiibbbrrraaarrriiieeesss aaannnddd MMMoooddduuulllaaarrr
DDDeeevvveeelllooopppmmmeeennnttt
OOOVVVEEERRRVVVEEEWWW
Ifyousomedaytakeajobinthesoftwareindustry,youwillfindthatyouwrite
veryfewprogramsentirelyonyourown.Inmostcompanies,programmersworkas
termstobuildapplicationsthataremuchlargerthanthoseanypersoncouldmanage
individually. Making it possible for many programmers to work together is a
fundamentalchallenge ofmodernsoftwareengineering. Thefourchapters in Part
Twoteachyouhowtobreaklargeprogramsdownintoindependentmodulesandhow
todesignthosemodulessothattheycanbeusedaslibrariesforotherapplications.
PPPaaarrrttt TTThhhrrreeeeee CCCooommmpppooouuunnnddd DDDaaatttaaa TTTyyypppeeesss
OOOVVVEEERRRVVVIIIEEEWWW
Althoughyouknowthatprogramsmanipulatedata,theearlierpartsofthistext
have focused on the control structures that perform the manipulation, not the
underlyingdata.InChapters11through17,youwillseethat,likecontrolstructures,
datastructuresarecentraltoprogramming.Bylearningtoassembledataintolarger
structures, youcan extend yourprogramming capabilities considerably and write
programsthatarebothmoreusefulandmoreexciting.
A Library-Based Introduction to
Computer Science
About the author
To the Student
In loving memory of Grace E.Bloom (1924-1994) for helping meappreciate the
valueof ideasand theimportanceofwriting clearlyabout them.
AAA LLLiiibbbrrraaarrryyy---BBBaaassseeeddd IIInnntttrrroooddduuuccctttiiiooonnn tttooo
CCCooommmpppuuuttteeerrr SSSccciiieeennnccceee
IIInnn lllooovvviiinnnggg mmmeeemmmooorrryyy ooofff GGGrrraaaccceee EEE...BBBllloooooommm (((111999222444---111999999444))) fffooorrr hhheeelllpppiiinnnggg mmmeeeaaapppppprrreeeccciiiaaattteee ttthhheee
vvvaaallluuueeeooofff iiidddeeeaaasssaaannnddd ttthhheeeiiimmmpppooorrrtttaaannnccceeeooofffwwwrrriiitttiiinnnggg cccllleeeaaarrrlllyyyaaabbbooouuuttt ttthhheeemmm...
AAAbbbooouuuttt ttthhheee aaauuuttthhhooorrr
I first began teaching introductory computer science more than 20 yearsago while I
was still astudent at Harvard. Since receiving my Ph.D. in 1980,I havetaught computer
science at Harvard, Wellesley, andStanford, whereI am Associate Chair of the Computer
Science Department. In that capacity, I am responsible for the undergraduate program in
computer science.Although I havetaught advancedcoursesin computer science andhave
alsoworkedintheresearch industry, mygreatestjoy comesfrom openinguptheenormous
power of computers to students who are just beginning to learn about them. In their
excitement,my ownloveforcomputerscienceis constantlyrenewed.
In addition to my teaching at Stanford, I have servedsince 1990 as the president of
ComputerProfessionals forSocialResponsibility,apublic-interestassociation ofcomputer
professionals with2000 membersin 22chapters throughout the United States. Computers
affect our society in many different ways. Just as it is important to learn about the
technology, it is critical that wealso take the responsibility to ensure that computers are
usedforthebenefit ofall. Ifyouhavesuggestions as tohowI might makethe presentation
more clear,or you encounter errors in this text, please let me know. You can reach me by
electronic mailat ericr@aw.com.
Eric S.Roberts
Department ofComputerScience
StanfordUniversity
TTTooo ttthhheee SSStttuuudddeeennnttt
Welcome! By picking upthis book, youhavetakenastep into theworld of computer
science—afield ofstudy that hasgrownfrom almost nothinghalf acenturyagotobecome
one ofthemost vibrant andactivedisciplines ofourtime.
Over thattime, thecomputer hasopenedupextraordinary possibilities inalmost every
areaofhumanendeavor.Businessleaders todayareable tomanageglobal enterprisesonan
unprecedented scale becausecomputersenable them to transfer informationanywherein a
fraction of asecond. Scientists can nowsolve problems that werebeyond their reach until
the computer made the necessary calculations possible. Filmmakers use computers to
generate dramatic visual effects accurately what is going on inside a patient because
computershaveenabled amassivetransformation inthepracticeofmedicine.
Using the Art and Science of C
For Chapter Review
objectives
Computers area profoundly empowering technology.The advances wehaveseen up
to now aresmall comparedto what wewill see in thenext century.Computerswill play a
major rolein shaping that century,just astheyhavethelast 50years.Those ofyouwhoare
students today will soon inherit the responsibility of guiding that progress. As you doso,
knowinghowto usecomputerscanonly help.
Like most skills that are worth knowing, learning how computers work and how to
control their enormous power takes time. You will not understand it all at once. But you
must start somewhere. Twenty-five centuries ago the Chinese philosopher Lao-tzu
observed that the longest journey begins with a single step. This book can be your
beginning.
Formanyofyou,however,thefirststep canbe thehardesttotake.Many studentsfind
computers overwhelming and imagine that computer science is beyond their reach.
Learning thebasicsof programming, however,doesnot requireadvancedmathematicsora
detailed understanding of electronics. What matters in programming is whether you can
progress fromthestatement ofaproblem to itssolution. Todoso,youmust be abletothink
logically. You must havethe necessary discipline to express your logic in a form that the
computer can understand. Perhaps most importantly, you must be able to see the task
through to its completion without getting discouragedby difficulties and setbacks. If you
stick withtheprocess, you willdiscover that reaching thesolution is so exhilarating thatit
morethanmakesupforanyfrustrations youencounteralong theway.
This bookisdesignedtoteachyouthefundamentalsof programming andthebasicsof
C, which is the dominant programming language in the computing industry today.It treats
the whys of programming as well as the hows, to give you a feel for the programming
processas awhole. It alsoincludesseveral featuresthatwill helpyou focusontheessential
points and avoid errors that slow youdown. Thenext few pagessummarize these features
and explain how to use this book effectively as you begin your journey into the exciting
world ofcomputer science.
UUUsssiiinnnggg ttthhheee AAArrrttt aaannnddd SSSccciiieeennnccceee ooofff CCC
To makethebest possible useof this textbook forlearning the Clanguage, be sureto
takeadvantageofthetools it provides.
FFFooorrr CCChhhaaapppttteeerrr RRReeevvviiieeewww
Each chapter includes easily accessible material to guide your study and facilitate
review ofthecentraltopics.
The list of ooobbbjjjeeeccctttiiivvveeesss previews the key topics covered by the chapter. Because each
objective identifies aconcreteskill, thechapter objectives help you to assess your mastery
oftheessential material.
The Summarydescribes, in moredetail, what you should have learned in connection
withtheObjectives.
To the Instructor
Learning to Program
To Avoid Errors
After the Chapter
Program examples
Syntax boxes
CommonPitfalls
Review Questions
ProgrammingExercises
LLLeeeaaarrrnnniiinnnggg tttooo PPPrrrooogggrrraaammm
Programming is both a science and an art. Learning to program well requires much
more than memorizing a set of rules. You must learn through experience and by reading
otherprograms.This text includesseveralfeaturestoaid inthisprocess.
Thetext includes a largenumber of PPPrrrooogggrrraaammm eeexxxaaammmpppllleeesssthat illustratehow individual
Ccomplete areusedtocreatecomplete programs. Theseexamples also serveas models for
yourownprograms; inmanycases, youcansolveanewprogramming problem bymaking
simplemodifications toaprogramfrom thetext.
SSSyyynnntttaaaxxx bbboooxxxeeesss summarize key rules of C syntax, for an at-a-glance review of key
programming concepts.
TTTooo AAAvvvoooiiiddd EEErrrrrrooorrrsss
All programmers, eventhebest ones,makemistakes. Finding thesemistakes,orbugs,
in your programs is a critically important skill. The following features will help you to
buildthis skill.
To help you learn to recognize and correct bugs, this text includes several buggy
programs that illustrate typical errors. To make sure you do not use thes3 programs as
models,such incorrectprogramsaremarkedwithasuperimposedimageof abug.
CCCooommmmmmooonnnPPPiiitttfffaaallllllsssprovide handyremindersaboutmistakesall beginning programmers
arelikely to make, andhowto avoid them. Faultylines of code arehighlighted witha bug
imageandannotatedincolor.
AAAfffttteeerrr ttthhheee CCChhhaaapppttteeerrr
Learning to program requires considerable practice. To make sure that you get the
necessaryexperience,eachchapter includesanextensiveset ofexercisesandquestions that
test yourmasteryofthematerial.
Each chapter concludes with a wealth of RRReeevvviiieeewww QQQuuueeessstttiiiooonnnsss, which require brief
answerstochapter contentquestions, codeadoptions,or debuggingexercises.
PPPrrrooogggrrraaammmmmmiiinnngggEEExxxeeerrrccciiissseeessscall foryouto tryyourhandat moreextensiveprogramming
projects.
TTTooo ttthhheee IIInnnssstttrrruuuccctttooorrr
In 1991-92, Stanford decided to restructure its introductory computer science
curriculum to useANSICinstead ofPascal. WechosetoadoptANSI Cin ourintroductory
coursesforthefollowing reasons:
Studentsdemandedamorepractical language. Futureemployers wantstudentstohave
moredirectexperiencewiththetools industry uses,whichtodayare principally C and
C++. With few employment opportunities listed for Pascal programmers in the
The library-based approach
newspaper employment section, our students began to questionthe relevanceof their
education.
OurPascal-based curriculum taughtstudentstoprogramin alanguage thattheywould
never again use. We discovered that many of those students, when they abandoned
Pascal for more modern languages, often forgot everything they had learned about
programming style and the discipline of software engineering. Having now taught
these skills in the context of a language that the students continue to use, we have
found thattheyendupwrithing muchbetterprograms.
Many of our advanced computer science courses, particularly in the systems area,
require students to program in C. Workingwith C from the beginning gives students
muchmoreexperiencebythetimetheyreachtheadvancedcourses.
Learning C early paves the wayto learning C++ and the object-oriented paradigm.
Becauseour studentshaveastrong backgroundinCprogramming after their first year
ofstudy,wehavebeenableto offerour courseonobject-oriented systemdesignmuch
earlier in thecurriculum.
C makes it possible to cover several important topics, such as modular development
andabstract datatypes,thatarehardtoteachin aPascalenvironment.
In the last five years, Chas makesignificant headwaytoward replacing Fortranas the
Lingua Francaofprogramming fortheengineeringsciences.
Given our experience over the last threeyears, I am convinced that the choice was a
goodone andthatour programisstrongerbecauseofthechange.
At thesametime, it is important to recognize that teaching Cin thefirst programming
course is not always easy. C was designed for programmers, not introductory students.
Many of its features make sense only when understood in terms of a larger conceptual
frameworkthat newstudentsdonotrecognize. Inmanyrespects,Cis acomplex language.
Toteachit attheintroductory level, wemust findawaytocontrol itscomplexity.
TTThhheee llliiibbbrrraaarrryyy---bbbaaassseeeddd aaapppppprrroooaaaccchhh
One of the central goals of this text is to enable teachers to manage C’s inherent
complexity. Managing complexity, however, is precisely what we do as programmers.
Whenwearefacedwithaproblem thatis too complex forimmediate solution, wedivide it
into smaller pieces andconsider each one independently. Moreover, whenthe complexity
of one of thosepieces crosses acertain threshold, it makes senseto isolate that complexity
bydefining aseparateabstraction that hasasimple interface. Theinterface protects clients
from theunderlyingdetails oftheabstraction, therebysimplifying theconceptualstructure.
Thesame approachworksforteaching programming. To makethematerial easier for
students to learn, this text adoptsalibrary-based approachthat emphasizes theprinciple of
abstraction. The essential character of that approach is reflected in the following two
featuresthat setthis bookapartfrom otherintroductory texts:
1. Libraries andmodular development—essential conceptsin modernprogramming
—are covered in considerable detail early in the presentation. Part II focuses
entirely on the topics of libraries, interfaces, abstractions, and modular
The order of presentation
development. Students learn how to usethese techniques effectively before they
learnabout arrays.
2. Thetext demonstrates thepowerof libraries byusingthem.It is one thing totell
students that libraries make it possible to hide complexity. It is quite another to
demonstrate that concept. This text introduces several new libraries that hide
details fromthestudentsuntil theyarereadytoassimilate them.Thelibraries give
students thepower to writeuseful programsthat they could not develop ontheir
own. Later chapters reveal the implementation of those libraries, thereby
allowing studentstoappreciatethepowerofabstraction.
In 1992, I attemptedto teach the introductory course using only the ANSI libraries.
The results were not encouraging. Each new topic required that the student understand so
much about the rest of C that there was no effective way to present the material. For
example, students had to understand the mechanics of arrays, pointers, and allocation
beforetheycould usestring datain and\yinterestingway,eventhough string manipulation
is simpler conceptually.My best students managedto understand whatwasgong onbythe
endof thequarter.Most,however,did not. Sinceweintroducedthe library-basedapproach
in early 1993, students have assimilated the material more easily and learned much more
aboutcomputerscience.
Thelibrary interfaces andassociatedimplementations used in thistext arereprinted in
Appendix B, which also gives instructions for obtaining the source code electronically
throughanonymousFTP(File TransferProtocol).
TTThhheee ooorrrdddeeerrr ooofff ppprrreeessseeennntttaaatttiiiooonnn
This bookpresents topics in the sameorder as Stanford’s introductory course, except
for the material in Chapter 17, which wecover in the second course. Depending on your
audienceandthe goals ofyour course, youmaywantto vary theorder ofpresentation. The
following notes provide an overview of the chapters and indicate some of the more
important dependencies.
Chapter1tracesthehistoryof computinganddescribes theprogramming process.The
chapter requiresnoprogramming perse butprovides thecontextual backgroundfor therest
ofthetext.
I have designed Chapter 2 and 3 for students with little or no background in
programming. These chapters are conceptual in their approach and focus on problem
solving rather than on the details of the C language. When new students are faced with
detailed rules of syntax andstructure, they concentrateonlearning the rules instead of the
underlying concepts,whichare vastlymoreimportant atthis stage.If your studentsalready
knowsomeprogramming, youcouldmovemuchmorequickly throughthismaterial.
Chapters 2 and 3 are informal in their approach and concentrate on developing the
student’s problem-solving skills. Along the way, they introduce several basic statement
forms and control structures, but only as idioms to accomplish a specific task. Chapter 4
adds formal structure to this topic by describing each statement form in turn, detailing its
syntaxandsemantics.Thechapter alsoincludes anextensivediscussionofBoolean data.
Chapter 5 introduces functions and procedures. It begins with simple examples of
functions andthencontinues withincreasingly sophisticated examples. Themechanicsof
parameter passing are discussedin aseparatesection that includes many diagrams to help
students follow the flow of data from one function to another. The chapter ends with a
significantprogramming examplethatillustratestheconcept ofstepwiserefinement.
Thealgorithmic conceptspresentedin Chapter 6arefundamentalto computer science
but maynot be required for all students. If your audienceconsists of engineers or potential
computer science majors the material will prove extremely valuable. For less technical
audiences,however,youcaneliminate muchofthis material withoutdisturbingtheflow of
thepresentation.
I have found that integrating graphics in the introductory course is a great way to
increase student interest in the material. Chapter 7 exists for that reason. At this stage,
students havelearned the mechanics of functions but haveno burning need to writethem.
Letting students draw complex pictures on the screen gives them that incentive. The
graphics library is implemented for several of the major programming environments and
canthereforebe used inmostinstitutions.
Chapter8 has two themes, which are in some sense separable. The first part of the
chapter discusses design criteria for interfaces and is essential for anyone who needs to
understand howmodern programming works.Thensecondpartof thechapterapplies those
principles to build a random number library. Therandom.h interface itself is less important
thanthegeneralprinciples, althoughuseofthe randomnumberlibrary is required forafew
oftheexerciseslater inthetext.
Chapter 9introduces strings as anabstract typeandrepresents, to acertainextent, the
cornerstone of the library-based approach. By usingadynamic string library,students can
easily writeprograms that perform sophisticated string manipulation, eventhough theydo
not yet understand the underlying representation, which is covered in Chapter 14.
Introducing strings at this point in the presentation enables students to write much more
excitingprogramsthantheycouldotherwise.
Onafirst reading, it is easytomissthe purposeof Chapter10,which appearstobe an
extension of the discussion of strings begun in Chapter 9. The fundamental value of
Chapter 10doesnotlie in thePig Latin program,whichis morefunthanit ispractical. The
entirereason for theexampleis thatit provides themotivation to build thescanner interface
used toseparatewordsontheinput line. Thescanner module proves itsusefulness over and
over again, not only in the first course but in subsequent courses as well. It is the most
practical tool students createin the courseandthereforeserves as acompelling exampleof
thevalueformodularity.
Chapter 11 through 16 introduce the fundamental compound structures—arrays,
pointers, files, andrecords—in anorder that hasworkedwellin practice.Becausethe base
language is C, it is important to resent pointers as soon as possible afterintroducing arrays
so that you can emphasize the connections between them. Moreover, having established
theseconcepts,it is thenpossible inChapter14toconsiderstring datamoreclosely,thereby
revealing the underlying representation that was concealed by the abstract definition.
Chapter 16integratesthefundamentaldatastructureswiththeconstruction ofadata-driven
teaching machine, which isthe most sophisticatedexample ofprogramming resented inthe
Acknowledgments
Instructor’s Manual
test.
Chapter 17 includes threeimportant topics that often appear in thefirst programming
course: recursion,abstract datatypes, andanalysis of algorithms.At Stanford,which is on
the quarter system weteach all these topics in the second souse. If you decide to teach
recursion in the first course, I strongly recommend that you doso early enough to allow
students time to assimilate the material. One possibility is to discuss recursive functions
immediately afterChapter 5and recursive algorithms after Chapter6. Another approachis
tocoverecursionandanalysis ofalgorithms together attheendofChapter 12.
IIInnnssstttrrruuuccctttooorrr’’’sss MMMaaannnuuuaaalll
TheInstructor’s Manual Contains supplemental materials including acoursesyllabus,
suggestions for lecturedesign, sample assignments and examination, and solutions to all
programming exercises. In addition to the printed manual, instructors whoadopt this text
canretrieveelectronic copies ofsolution setsandrelated materials. For detailsonobtaining
solutions, pleasecontractyour localAddison-Wesleyrepresentative. All other supplemental
material isavailable on-line. For explicit instructionsseeAppendix B.
AAAccckkknnnooowwwllleeedddgggmmmeeennntttsss
The text has come a long wayfrom its initial stages as class notes, in largemeasure
because of suggestions from people who have worked with the text in one capacity of
another. I am particularly grateful to the Stanford lecturers—Jon Becker, Katie Capps,
Stephen Clausing, Todd Feldman, Allison Hansen, Margaret Johnson, Jim Kent, Andrew
Kosoresow, Mehran Sahami, and Julie Zelenski—who have taught this material in 14
different sections of theintroductory courseover the past threeyears. I am alsoindebted to
all the section leaders and teaching assistants as well as the coordinators of the student-
teaching program—Felix Baker, John Lilly, Sandy Nguyen, Bryan Rollins, and Scott
Wiltamuth—whoprovidedmuchneededlogisticalsupport.
Many of the best ideas for the text came from a seminar on teaching introductory
computer sciencethat I conducted beginning in 1992-93. It provided aforum for thrashing
out the hard issues and madeasignificant differencein the text.I wantto thank everyone
whoparticipated: PerryArnold, Jon Becker,Tom Bogart, Karl Brown,BryanBusse, Katie
Capps,Peter Chang,ScottCohen,StaceyDoerr,JeffForbes,StephenFreund,Jon Goldberg,
TagueGriffith,Matt Harad, LindsayLack,ChristineLee, TriciaLee, JohnLilly,Albert Lin,
Mara Mather, Hugh McGuire, Jeffrey Oldham, David O’Keefe, Bryan Rollins, Samir
Saxena, Nikhyl Singhal, Eric Tucker, Garner,Garner Weng,HowardWong-Toi, andJohn
Youn.
I also want to thank all the studentswho haveused andcritiqued the draft versionof
thetext:AdjoAmekudzi, EricAnderson,AndrewArnold, Kevin Berk, Kevin Carbajal, Ajit
Chaudhari, Alida Cheung, Hye-won Choi, Elisabeth Christensen, Ralph Davis, Joel
Firehammer,PeterFrelinghuysen, Trevor Gattis,TeddyHarris, Heather Heal, EnochHuang,
Ann Lee, Ted Lee, Daphne Lichtensztajn, Lisa Maddock,Allan Marcus, Brad McGoran,
Forrest Melton, Adrienne Osborn, Masatoshi Saito, Anne Stern, Ricardo Urena, and
Nichole Wilson.
In 1993-94, several faculty members at other universities tested this material in draft
form and made several valuable suggestions. I especially want to thank Margo Seltzer at
HarvardUniversity,robLangsnerat theUniversity ofNevada(Reno),RichardChangat the
University of Maryland (Baltimore County), Jane Turk at La Salle University, and Kim
KihlstromatWestmont College forhelping to refinethetextfromits earlystages.
Iam alsoindebtedtomyreviewers:
StephenAllan UtahStateUniversity
JamesSchmolze TuftsUniversity
DonGoelman VillanovaUniversity
Michael Skolnick Renseelaer Polytechnic
StanKolasa RutgersUniversity
JefferyA.Slomka SouthwestTexasStateUniversity
HarryR.Lewis HarvardUniversity
KevinSmith EmoryUniversity
Bill Muellner Elmhurst College
PhilTromovitch SUNY-StonyBrook
RayonNiemi RochesterInstitute ofTechnology
JohnA. trono St.Michaels’College
RobertG.Plantz SonomaStateUniversity
RobertWalker Rensselaer Polytechnic
DavidRosenthal SetonHall
RichardWeinand WaynestateUniversity
In addition, I have received useful advice along the way from several friends and
colleagues, including Josh Barnes, Pavel Curtis, Kathleen Kells, James Finn, and Steve
Lewin-Berlin.
The final version of this text owes much to my editors at Addison-Wesley, whohave
beenhelpful throughout theprocess. In particular,I thankLynneDoranCote, SueGleason,
Peter Gordon, Laura Michaels, Jim Rigney, Karen Stone, andAmy Willcutt for all their
work.AndI am extremely fortunateto haveLauren Ruskas both mydevelopmental editor
andmypartner;withouther,nothing wouldevercomeoutas wellas it should.