Table Of ContentCOMPUTER SCIENCE
A Structured Programming Approach Using C
Behrouz A. Forouzan & Richard F. Gilberg
—
THIRD EDITION
Operator Description Example * Assoc Pr
Identifiers amount
'Constants 3.14159 N N/A 16
ParentheticalExpressions (a + b)
[ ]. ArrayIndex ary[i] N
ninctionCall doIt(x, y) Y
DirectMemberSelection str.mem N Left-Right 16
-> IndirectMemberSelection ptr->mem N
++ PostfixIncrement(cid:127)Decrement a++ Y
++ PrefixIncrement(cid:127)Decrement ++a Y
sizeof SizeinBytes sizeof(int) N
-
OnesComplement a N
! Not la N Right-Left 15
+ Plus(cid:127)Minus +a N
& Address &a N
* Dereference/Indirection *ptr N
( ) TypeCast (int)ptr N Right-Left 14
* / % Multiply(cid:127)Divide(cid:127)Modulus a * b N Left-Right 13
+ - Addition(cid:127)Subtraction a + b N Left-Right 12
« » BitShiftLeft(cid:127)BitShift Right a << 3 N Left-Right 11
< <= > >= Comparison a < 5 N Left-Right 10
ss != Equal(cid:127)NotEqual a == b N Left-Right 9
& BitwiseAnd a & b N Left-Right 8
A BitwiseExclusiveOr a A b N Left-Right 7
BitwiseOr a b N Left-Right 6
&& LogicalAnd a ScSc b N Left-Right 5
LogicalOr a b N Left-Right 4
? : Conditional a ? x (cid:127)* Y N Right-Left 3
= += -= a = 5
*= /= %=
>>= <<= Assignment a %= b Y Right-Left 2
&= A= a &= c
a |= d
> Comma a, b, c N Left-Right 1
*SideEffects(Yes/No) i
PrecedenceTable
.
>H' ' i -t X \/o.U6
*+'- - Mi | J, - dUe
X AH .v A f\£w \/
Computer Science:
A Structured Programming
Approach Using C,
Third Edition
DATE DUE
Nov o5 rm
LI 2o/H
1ft
March
a ao
/tprtI \(p
3 2-6^6
AA Z7 ^i y
Wt~7IS7 %
JW 30 2(17 <15
im 1o :Qi8 Clb
DEC 17 BtS fa
»
IAUG 0 ! 2012 7
Australia(cid:127)Brazil(cid:127)Japan(cid:127)Korea(cid:127)Mexico(cid:127)Singapore(cid:127)Spam(cid:127)UnitedKingdom(cid:127)UnitedStates
SAN JACIN1U COLLEGE LIBHAHY-SOUTH
Preface to Third Edition
Thistext hastwoprimaryobjectives:toteach thebasicprinciplesol program-
mbaisnigccaosno_sutrtulicntesdofinthteheCALCanMgucaugrer.icOuulurmtexftopruatsCtShe1secloabssjeacntidvetsointetahcehcothne-
text of good software engineeringconcepts that we have developed through
morethan 30yearsof experiencein industryand academia.
Major ChangesinThird Edition
This is a major change from the second edition. In addition to significant-
changes in the presentation and material covered, it also updates the lan
guagetothe ISO/IEC9899(1999),oras it is morecommonlyknown,C99.
While we have made major changes, we have held true to our primary
objectivesasoutlined above. Ihe text remainsa comprehensive introduction
tocomputer programmingin asoftwareengineeringcontext.
Themajorchangesareoutlined in thefollowingsections.
Standard C(1999)
Ihefollowingtopics,inalphabeticalorder,areexplicitlydiscussed in thetext.
(cid:127) the Boolean type
(cid:127) charactersetextensions(including Unicodeand wide-characters)
(cid:127) complexarithmetic
(cid:127) extendedmath library
(cid:127) forstatementdeclarations
(cid:127)
integertypeextensions
(cid:127) linecomments
Extended Chapter Material
In addition to the changes required by the inclusion of the new C99 exten-
sions,severalchaptershavebeen revised or reorganized.
AnewsectioninChapter4, Inter-FunctionCommunication,” providesa
better understandingof howfunctionscommunicate.
IV
PrefacetoThird Edition v
(cid:127) Theconceptof “incremental programdevelopment’ is presented through
an example that starts in Chapter 4 and isextended in C hapter 5.A sec-
ond example in Chapter8completesthediscussion.
(cid:127) The discussion of text and binary files has been reworked to present the
materialsin a morelogical,and less redundant,fashion.
(cid:127) The presentation of structured types is changed to conform to C99 and
.
common usage
(cid:127) Chapter 14. “Bitwise Operators," has been extended and includes more
examples. In particular, we added several applications related to the
Internetand network programming.
(cid:127) Chapter 15,"Lists," hasalso been extended. It now includesan overview
of the basic elements of data structures, including introductory discus-
sionsof stack,queues,lists, trees,and graphs.
(cid:127) Additional flowcharts and structure charts are included throughout the
texttoprovide betterdesignconsiderationsforsomeof the morecomplex
examples.
(cid:127) AppendixD,"NumberingSystems,"providesanexpanded presentation of
the material.
(cid:127) Appendix 1, "Pointers to void and to Functions," has been expanded to
includea discussion of usingpointer tovoid types.
(cid:127) Appendix k. "Program Development,” is a new discussion of program
developmentconcepts.
(cid:127) Appendix L,“UnderstandingComplexDeclarations,"containsthediscus-
sion on reading complex declarations, which has been removed from
Chapter 10.
A C Language Perspective
While C is a complex and professional language, our classroom experience
usingthepreviouseditionsof thisbookhasshown that beginningstudentscan
easily understand it. We believe that if the language is put intoa perspective
thatallowsthestudent tounderstand itsdesign,C is notadifficult language.
There are two aspects of C that separate it from most other languages:
expressionsand pointers.Theconceptof expressions,as used inC, is unique.
Thefirst halfof thistextbuildsafirm understandingofexpressions.Weintro-
duce pointersonlytotheextent necessary7tocover passingthem tofunctions
in Chapter 4and arrays in Chapter8.Our experiences haveshown that with
.
a firm graspof theexpressionconcept, muchof the mysteryof Cdisappears
In Chapters 9, we begin to develop the concept of pointers, which are
further developed in Chapter 10. Chapter 11 provides a discussion of C’s
approach to strings. Finally, Chapter 14 provides an extensive discussion of
bitwiseoperators,asubject that isneeded tomakethebookcomplete.
The last chapter is a simple introduction to data structures. While not
all courses will have time to cover this chapter, those that do will give the
cetoThirdEdition
. Motivated students will find that
sthtuedyecnatns"agehteaadlesgtaurpt”inotnoddaatatasstrturucctutureressover the term break.
Theappendicesat theendofthetextcomprisea rich set of referencesto
subjects required in the complete C language. These w.ill be of use to stu-
dentswhogoontotakeothercoursesin theClanguage
Featuresof the Book
Severalfeaturesof this book make it uniqueand easyfor beginningstudents
tounderstand.
StructureandStyle
Oneof our basic tenets is that good habitsareformed early.Thecorollaryis
that bad habitsare hard to break.Therefore,weconsistentlyemphasize the
principlesof structured programmingand softwareengineering.Throughout
each chapter, short code snippets and programs are used to demonstrate
techniques.
Complete programs, generally found in the last section of the chapter,
are written in a well-document consistent style. As programs are analyzed,
style and standards are further explained. While we acknowledge that there
are manygood styles, our experience hasshown that if students areexposed
to one good style and adopt it, they will be better able to adapt to other
goodstyles.
Principle Before Practice
Wheneverpossible,wedeveloptheprincipleot asubject beforewe introduce
the language implementation. For example, in Chapter 5 we first introduce
theconceptof logicaldataandselectionand thenweintroducetheif...else
and suitch statements.Thisapproach gives the student an understandingof
selection beforeintroducingthe nuancesof thelanguage.
Visual Approach
A brief scan of the hook will demonstrate that ourapproach is visual.1here
are more than 400figures, plus more than 70 tablesand 180 program exam-
pies.While this amount of material tends to create a large hook, the visual
approach makesiteasyforstudentstofollowthe material.
Examples
While the programmingexamplesvary in complexity, each uses a consistent
style.Ourexperience workingwith productional programs that live for 10 to
2to0wyoerakrswciothnvthinacnedpruosgrtahmatsrweraidttaebnleinanadteursned,ecrrsytpatnicdamblaennperor.gFraomrtshaartereeaassoienr,
PrefacetoThirdEdition vii
and to emphasize the structure of the language, we label the sections in a
function with comments.We consistently follow a style that places onlyone
declaration,definition,orstatement onaline.
Ihesourcecodefor theseprogramsisavailableon theCourse Technology
.
Website(see ’WebSiteSupportMaterials”laterinthisPreface) Studentsare
able torun theseprograms and toexplorerelated topics throughmodification
andexperimentation.
Coding Techniques
Throughout the text weincludecodingtechniques that makeprogramsmore
readableandoftenmoreefficient.Forexample,in theanalyTsisof Program 5-4
youwill find the followingdiscussion:
Where do we check for greater than} The answer is that we
default thegreaterthanconditiontotheouterelse....Whencod-
inga two-way selection statement, try to code the most probable
condition first; with nested selection statements, code the most
.
probablefirstandtheleastprobablelast
These techniques are drawn from our extensive industry and classroom
.
experience
Software Engineering
A discussionofsoftwareengineeringprinciplesconcludeseachchapter.Our
.
intent isnot toreplacea separatecourseinsoftwareengineering Rather,we
firmly believe that by incorporating basic software engineering principles
earlyintheir studies,students will bebetterprepared for a formal treatment
of the subject. Even more important, by writing well-engineered programs
from thebeginning,students will not be forced tounlearnandrelearn.Ihey
willbetter understandsoftwarediscussionsintheir subsequent classes.
While the software engineering sections are found at the end of each
chapter,theyaremostsuccessfullytaughtbyintroducingthemasthechapter
unfolds.Then,a short reviewat theendof thechapter summarizes theprin-
ciples that havebeendemonstratedduringthelectures.
These sections are visually distinguishable from the rest of the chapter.
Theyhavebeen set apart for severalreasons.First,theyareinreality a small
bookwithinabook.Whilethesesectionscontainimportantmaterial,thebook
standsonitsownwithout them.Youmay,therefore,decide tocover thesoft-
ware engineering sections as formal lecture topics or informally while the
chapter material is beingcovered.You maydecide toassign them to thestu-
dent as additional reading,or,you may decide toexclude thementirely from
thecourse.
Ingeneral,softwareengineeringsections directlyor indirectlypertain to
the chapter material. Where they don’t, they discuss general software engi-
neeringsubjects,suchascohesion,coupling,andquality.
vjjj PrefacetoThirdEdition
Pedagogical Material
Endchapter material meetstwopedagogicalobjectives:first, it helpsthestu-
dentstorevieworsummarizewhat they havelearned,andsecond, it teststhe
students’masteryof thechapter material.
Review Material
(cid:127) Tips and Common Programming Errors points out helpful hints and
possibleproblemareas.
(cid:127) KeyTermsprovidesa listoftheimportanttermsintroduced in thechapter.
(cid:127) Summarycontains a concise overview of the key points for students to
understand in thechapter.
PracticeSets
(cid:127) Review Questions contain several multiple choice questions that are
similar to thequestionsfound in theexamination database.Theanswers
to the odd-numbered questions are included in the solutions on the
CourseTechnologywebsite.
(cid:127) Exercisesare short questions covering the material in the chapter.The
answerstotheodd-numbered exercisesarealsoincluded in thesolutions
on theCourseTechnologywebsite.
(cid:127) Problemsare short coding problems, generally intended to be run on a
computer. They can usually be developed in two to three hours. Once
again,odd-numberedsolutionsarefound on thewebsite.
(cid:127)
Projectsarelonger, majorassignmentsthat maytake theaveragestudent
sixtoninehourstodevelop.
Appendicesand Cover Material
Ilu appendicesareintended toprovidequickreference material,suchasthe
UnicodeCharacter Set,or toprovidea reviewof material,such asnumbering
systems, usuallycovered in ageneralcomputerclass.
Ihe inside coverscontain t—wo important references that are used con-
tinually throughout the course the Precedence Table and the Formatted
I/OCodes.
WebSiteSupport Materials
'1 <~Hl"St lechn°logy Web site (http://www.course.com) are
twnsetsoff materia|ls,onefor the professorand onefor thestudent.
1
PrefacetoThirdEdition ix
Professor Materials
The professors materials include thesolutions to all review questions, exer-
cises, and problems. Because the projects are more complex assignments lor
which there is nostandardanswer,wedo not providesolutionsfor them.
In addition to the end-material solutions, there are three other sets ol
support materials: (1) Copies of all programs in the text.The programs have
been extensively tested on at least two different computers with different
operatingsystems.Allof themconform totheC99Standard.
(2) PowerPoint materials covering objectives, figures, programs, impor-
tant points,andchaptersummaries.The PowerPoint materialscan beusedas
is oredited tosuit individual class needs.Thisflexibilityallows professors to
argument the text materials with their own. It also allows them to rearrange
the materials tosuit their individual needsand style.
.
(3) New with the third edition is the availability of ExamView® This
objective-based test generator lets the professor create paper, LAN, or Web-
based tests from testhanks designed specifically for this text. Using the
QuickTest Wizard, theycan easilyand quicklycreate true/falseand multiple-
choice tests. It is also possible to add questions that cover supplemental
material provided by the professor.
StudentMaterials
I he student materials include the solutions to the odd-numbered review
questions,exercises,and problems.Theyalsohaveaccess to thecopiesof the
programs used in the text
Acknowledgments
Nobookof thisscopecan hedeveloped without thesupport ol manypeople.
Reviewers
Toanyone who has not been through the process, the value ol peer reviews
cannot heappreciated enough. Writinga text rapidly becomes a myopic pro-
cess.Theimportantguidanceof reviewerswhocanstand hackand review the
text asawholecannot bemeasured.Wewouldespeciallylike toacknowledge
thecontributionsof the reviewersof all threeeditions.
StephenAllen,Utah StateUniversity
MaryAstone, /royStateUniversity
Ali Behforooz,Towson StateUniversity
George Berrv,Wentworth Instituteoj technology
Ernest Carey,UtahValleyStateCollege
PingChu Chu, Fayetteville StateUniversity
r
PrefacetojhirdEdition
ConstanceConner,CityCollegeof San Francisco
JohnS.DaPonte,SouthernConnecticut StateUniversity
Maurice L.Eggen,TrinityUniversity/
PeterGabrovsky,CSU Northridge
RobertGann, HartwickCollege
HenryGordon, KutztownUniversity
RickGraziani,CabrilloCollege
BarbaraGuillott,Louisiana StateUniversity
JerzyJaromczyk,University of Kentucky
John Kinio, HumberCollege
Roberta Klibaner,Collegeof Staten Island
JosephA.Konstan,Universityof Minnesota
Krishna Kulkarni, RustCollege
JohnLowther, MichiganTechnological University
Mike Michaelson, PalomarColle—ge
Kara Nance,University ofAlaska Fairbanks
Ali Nikzad, Huston-TillotsonCollege
Jo.Ann Parikh,SouthernConnecticut StateUniversity
Mark Parker,ShorelineCommunity College
SavithaPinnepalli,Louisiana StateUniversity
Oskar Reiksts, KutztownUniversity
Jim Roberts,Carnegie MellonUniversity
AliSalenia,South Dakota StateUniversity
LarrySells,OklahomaCity University
ShashiShekhar,University of Minnesota
RobertSignorile, BostonCollege
BrendaSonderegger,Montana StateUniversity
DeborahSturm,Collegeof Staten Island
VenkatSubramanian.University of Houston
John B. Iappen,Universityof SouthernColorado
MarcThomasm,California StateUniversity, Bakersfield
John Irono,St. Michael'sCollege
KC.Wong, Fayetteville StateUniversity
CourseTechnologyStaff
Our thanks to our editors,Alyssa Pratt, Senior Product Manager, and Mary
hranz,SeniorAcquisitions Editor, for helping us produce the book. We are
also indebted to the Quality Assurance staff who diligently double-checked
eachc^aP^eranc^ program.Our thanksto Burt LaFountain, Serge Palladino,
andChrisScr’iver. *
W<?U^ a^S° to diank the staff at GEX PublishingServices, espe-
ci(cid:127)allySandra Mitchell,whoablyguided the bookthrough production.
BehrouzA. Forouzan
Richard F.Gilberg