Tải bản đầy đủ - 0 (trang)
Chapter 5. Operators, Expressions, and Statements

Chapter 5. Operators, Expressions, and Statements

Tải bản đầy đủ - 0trang

division.

Anotheraspectofprocessingdataisorganizingyourprograms

sothattheytaketherightstepsintherightorder.Chas

severallanguagefeaturestohelpyouwiththattask.Oneof

thesefeaturesistheloop,andinthischapteryougetafirst

lookatit.Aloopenablesyoutorepeatactionsandmakesyour

programsmoreinterestingandpowerful.



IntroducingLoops

Listing5.1showsasampleprogramthatdoesalittlearithmetic

tocalculatethelengthininchesofafootthatwearsasize9

(men's)shoe.Toenhanceyourappreciationofloops,thisfirst

versionillustratesthelimitationsofprogrammingwithoutusing

aloop.



Listing5.1.Theshoes1.cProgram



/*shoes1.c--convertsashoesizetoinches*/

#include

#defineADJUST7.64

#defineSCALE0.325

intmain(void)

{

doubleshoe,foot;



shoe=9.0;

foot=SCALE*shoe+ADJUST;

printf("Shoesize(men's)footlength\n");

printf("%10.1f%15.2finches\n",shoe,foot);



return0;

}



Hereisaprogramwithmultiplicationandaddition.Ittakesyour

shoesize(ifyouwearasize9)andtellsyouhowlongyourfoot

isininches."But,"yousay,"Icouldsolvethisproblembyhand

morequicklythanyoucouldtypetheprogram."That'sagood

point.Aone-shotprogramthatdoesjustoneshoesizeisa

wasteoftimeandeffort.Youcouldmaketheprogrammore

usefulbywritingitasaninteractiveprogram,butthatstill

barelytapsthepotentialofacomputer.

Whatyouneedissomewaytohaveacomputerdorepetitive

calculationsforasuccessionofshoesizes.Afterall,that'sone

ofthemainreasonsforusingacomputertodoarithmetic.C

offersseveralmethodsfordoingrepetitivecalculations,andwe

willoutlineonehere.Thismethod,calledawhileloop,will

enableyoutomakeamoreinterestingexplorationofoperators.

Listing5.2presentstheimprovedshoe-sizingprogram.



Listing5.2.Theshoes2.cProgram



/*shoes2.c--calculatesfootlengthsforseveralsizes*/

#include

#defineADJUST7.64



#defineSCALE0.325

intmain(void)

{

doubleshoe,foot;



printf("Shoesize(men's)footlength\n");

shoe=3.0;

while(shoe<18.5)/*startingthewhileloop*/

{/*startofblock*/

foot=SCALE*shoe+ADJUST;

printf("%10.1f%15.2finches\n",shoe,foot);

shoe=shoe+1.0;

}/*endofblock*/

printf("Iftheshoefits,wearit.\n");



return0;

}



Hereisacondensedversionofshoes2.c'soutput:



Shoesize(men's)footlength

3.08.62inches

4.08.94inches

......

17.013.16inches

18.013.49inches

Iftheshoefits,wearit.



(Incidentally,theconstantsforthisconversionwereobtained

duringanincognitovisittoashoestore.Theonlyshoe-sizerleft

lyingaroundwasformen'ssizes.Thoseofyouinterestedin

women'ssizeswillhavetomakeyourownvisittoashoestore.

Also,theprogrammakestheunrealisticassumptionthatthere

isarationalanduniformsystemofshoesizes.)

Hereishowthewhileloopworks.Whentheprogramfirst

reachesthewhilestatement,itcheckstoseewhetherthe

conditionwithinparenthesesistrue.Inthiscase,the

expressionisasfollows:



shoe<18.5



The
initializedto3.0,whichcertainlyislessthan18.5.Therefore,

theconditionistrueandtheprogramproceedstothenext

statement,whichconvertsthesizetoinches.Thenitprintsthe

results.Thenextstatementincreasesshoeby1.0,makingit

4.0:



shoe=shoe+1.0;



Atthispoint,theprogramreturnstothewhileportiontocheck

thecondition.Whyatthispoint?Becausethenextlineisa

closingbrace(}),andthecodeusesasetofbraces({})to

marktheextentofthewhileloop.Thestatementsbetweenthe

twobracesaretheonesthatarerepeated.Thesectionof

programbetweenandincludingthebracesiscalledablock.



Nowbacktotheprogram.Thevalue4islessthan18.5,sothe

wholecycleofembracedcommands(theblock)followingthe

whileisrepeated.(Incomputerese,theprogramissaidto

"loop"throughthesestatements.)Thiscontinuesuntilshoe

reachesavalueof19.0.Nowthecondition



shoe<18.5



becomesfalsebecause19.0isnotlessthan18.5.Whenthis

happens,controlpassestothefirststatementfollowingthe

whileloop.Inthiscase,thatisthefinalprintf()statement.

Youcaneasilymodifythisprogramtodootherconversions.For

example,changeSCALEto1.8andADJUSTto32.0,andyou

haveaprogramthatconvertsCentigradetoFahrenheit.Change

SCALEto0.6214andADJUSTto0,andyouconvertkilometers

tomiles.Ifyoumakethesechanges,youshouldchangethe

printedmessages,too,topreventconfusion.

Thewhileloopprovidesaconvenient,flexiblemeansof

controllingaprogram.Nowlet'sturntothefundamental

operatorsthatyoucanuseinyourprograms.



FundamentalOperators

Cusesoperatorstorepresentarithmeticoperations.For

example,the+operatorcausesthetwovaluesflankingittobe

addedtogether.Ifthetermoperatorseemsoddtoyou,please

keepinmindthatthosethingshadtobecalledsomething.

"Operator"doesseemtobeabetterchoicethan,say,"those

things"or"arithmeticaltransactors."Nowtakealookatthe

operatorsusedforbasicarithmetic:=,+,-,*,and/.(Cdoes

nothaveanexponentiatingoperator.ThestandardCmath

library,however,providesthepow()functionforthatpurpose.

Forexample,pow(3.5,2.2)returns3.5raisedtothepowerof

2.2.)



AssignmentOperator:=

InC,theequalsigndoesnotmean"equals."Rather,itisa

value-assigningoperator.Thestatement



bmw=2002;



assignsthevalue2002tothevariablenamedbmw.Thatis,the

itemtotheleftofthe=signisthenameofavariable,andthe

itemontherightisthevalueassignedtothevariable.The=



symboliscalledtheassignmentoperator.Again,don'tthinkof

thelineassaying,"bmwequals2002."Instead,readitas

"assignthevalue2002tothevariablebmw."Theactiongoes

fromrighttoleftforthisoperator.

Perhapsthisdistinctionbetweenthenameofavariableandthe

valueofavariableseemslikehair-splitting,butconsiderthe

followingcommontypeofcomputerstatement:



i=i+1;



Asmathematics,thisstatementmakesnosense.Ifyouadd1

toafinitenumber,theresultisn't"equalto"thenumberyou

startedwith,butasacomputerassignmentstatement,itis

perfectlyreasonable.Itmeans"Findthevalueofthevariable

namedi,add1tothatvalue,andthenassignthisnewvalueto

thevariablei"(seeFigure5.1).



Figure5.1.Thestatementi=i+1;.



Astatementsuchas



2002=bmw;



makesnosenseinC(and,indeed,isinvalid)because2002is

justaconstant.Youcan'tassignavaluetoaconstant;it

alreadyisitsvalue.Whenyousitdownatthekeyboard,

therefore,rememberthattheitemtotheleftofthe=signmust

bethenameofavariable.Actually,theleftsidemustrefertoa

storagelocation.Thesimplestwayistousethenameofa

variable,but,asyouwillseelater,a"pointer"canbeusedto

pointtoalocation.Moregenerally,Cusesthetermmodifiable

lvaluetolabelthoseentitiestowhichyoucanassignvalues.

"Modifiablelvalue"isnot,perhaps,themostintuitivephrase

you'veencountered,solet'slookatsomedefinitions.



SomeTerminology:DataObjects,Lvalues,

Rvalues,andOperands

Dataobjectisageneraltermforaregionofdatastoragethat

canbeusedtoholdvalues.Thedatastorageusedtoholda

variableoranarrayisadataobject,forinstance.Cusesthe

termlvaluetomeananameorexpressionthatidentifiesa

particulardataobject.Thenameofavariable,forinstance,is

anlvalue,soobjectreferstotheactualdatastorage,butlvalue

isalabelusedtoidentify,orlocate,thatstorage.



Notallobjectscanhavetheirvalueschanged,soCusesthe

termmodifiablelvaluetoidentifyobjectswhosevaluecanbe

changed.Therefore,theleftsideofanassignmentoperator

shouldbeamodifiablelvalue.Indeed,thelinlvaluecomes

fromleftbecausemodifiablelvaluescanbeusedontheleftside

ofassignmentoperators.

Thetermrvaluereferstoquantitiesthatcanbeassignedto

modifiablelvalues.Forinstance,considerthefollowing

statement:



bmw=2002;



Here,bmwisamodifiablelvalue,and2002isanrvalue.Asyou

probablyguessed,therinrvaluecomesfromright.Rvaluescan

beconstants,variables,oranyotherexpressionthatyieldsa

value.

Aslongasyouarelearningthenamesofthings,theproper

termforwhatwehavecalledan"item"(asin"theitemtothe

leftofthe=")isoperand.Operandsarewhatoperatorsoperate

on.Forexample,youcandescribeeatingahamburgeras

applyingthe"eat"operatortothe"hamburger"operand;

similarly,youcansaythattheleftoperandofthe=operator

shallbeamodifiablelvalue.

ThebasicCassignmentoperatorisalittleflashierthanmost.



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 5. Operators, Expressions, and Statements

Tải bản đầy đủ ngay(0 tr)

×