Tải bản đầy đủ - 0 (trang)
Chapter 5. LOOPS AND RELATIONAL EXPRESSIONS

Chapter 5. LOOPS AND RELATIONAL EXPRESSIONS

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

Computersdomorethanstoredata.Theyanalyze,consolidate,

rearrange,extract,modify,extrapolate,synthesize,and

otherwisemanipulatedata.Sometimestheyevendistortand

trashdata,butwe'lltrytosteerclearofthatkindofbehavior.

Toperformtheirmanipulativemiracles,programsneedtoolsfor

performingrepetitiveactionsandformakingdecisions.C++,of

course,providessuchtools.Indeed,itusesthesameforloops,

whileloops,dowhileloops,ifstatements,andswitch

statementsthatregularCemploys,soifyouknowC,youcan

zipthroughthisandthenextchapter.(Butdon'tziptoofastyou

don'twanttomisshowcinhandlescharacterinput!)These

variousprogramcontrolstatementsoftenuserelational

expressionsandlogicalexpressionstogoverntheirbehavior.

Thischapterdiscussesloopsandrelationalexpressions,andthe

nextchapterfollowsupwithbranchingstatementsandlogical

expressions.



IntroducingtheforLoop

Circumstancesoftencalluponaprogramtoperformrepetitive

tasks,suchasaddingtogethertheelementsofanarrayoneby

oneorprintingsomepaeantoproductivitytwentytimes.The

C++forloopmakessuchtaskseasytodo.Let'slookataloop

inListing5.1,seewhatitdoes,andthendiscusshowitworks.



Listing5.1forloop.cpp



//forloop.cpp--introducingtheforloop

#include

usingnamespacestd;

intmain()

{

inti;//createacounter

//initialize;test;update

for(i=0;i<5;i++)

cout<<"C++knowsloops.\n";

cout<<"C++knowswhentostop.\n";

return0;

}



Hereistheoutput:

C++knowsloops.

C++knowsloops.

C++knowsloops.

C++knowsloops.

C++knowsloops.

C++knowswhentostop.

Thisloopbeginsbysettingtheintegerito0:

i=0

Thisistheloopinitializationpartoftheloop.Then,intheloop

test,theprogramteststoseeifiislessthan5:

i<5

Ifso,theprogramexecutesthefollowingstatement,whichis

termedtheloopbody:

cout<<"C++knowsloops.\n";



Then,theprogramusestheloopupdatepartoftheloopto

increaseiby1:

i++

Thisusesthe++operator,calledtheincrementoperator.It

incrementsthevalueofitsoperandby1.(Theincrement

operatorisnotrestrictedtoforloops.Forexample,youcan

use

i++;

insteadof

i=i+1;

asastatementinaprogram.)Incrementingicompletesthe

firstcycleoftheloop.

Next,theloopbeginsanewcyclebycomparingthenewivalue

with5.Becausethenewvalue(1)alsoislessthan5,theloop

printsanotherlineandthenfinishesbyincrementingiagain.

Thatsetsthestageforafreshcycleoftesting,executinga

statement,andupdatingthevalueofi.Theprocesscontinues

untiltheloopupdatesito5.Then,thenexttestfails,andthe

programmovesontothenextstatementaftertheloop.

forLoopParts

Aforloop,then,providesastep-by-steprecipeforperforming



repeatedactions.Let'stakeamoredetailedlookathowit'sset

up.Theusualpartsofaforloophandlethesesteps:

Settingavalueinitially

Performingatesttoseewhethertheloopshouldcontinue

Executingtheloopactions

Updatingvalue(s)usedforthetest

TheC++loopdesignpositionstheseelementssothatyoucan

spotthemataglance.Theinitialization,test,andupdate

actionsconstituteathree-partcontrolsectionenclosedin

parentheses.Eachpartisanexpression,andsemicolons

separatetheexpressionsfromeachother.Thestatement

followingthecontrolsectioniscalledthebodyoftheloop,and

itisexecutedaslongasthetestexpressionremainstrue:

for(initialization;test-expression;update-expression

body

C++syntaxcountsacompleteforstatementasasingle

statement,eventhoughitcanincorporateoneormore

statementsinthebodyportion.(Havingmorethanone

statementrequiresusingacompoundstatement,orblock,as

discussedlaterinthischapter.)

Theloopperformsinitializationjustonce.Typically,programs

usethisexpressiontosetavariabletoastartingvalueandthen

usethevariabletocountloopcycles.

Thetest-expressiondetermineswhethertheloopbodygets



executed.Typically,thisexpressionisarelationalexpression,

thatis,onethatcomparestwovalues.Ourexamplecompares

thevalueofito5,checkingtoseeifiislessthan5.Ifthe

comparisonistrue,theprogramexecutestheloopbody.

Actually,C++doesn'tlimittest-expressiontotrue-false

comparisons.Youcanuseanyexpression,andC++will

typecastittotypebool.Thus,anexpressionwithavalueof0

isconvertedtotheboolvaluefalse,andtheloopterminates.

Iftheexpressionevaluatestononzero,itistypecasttothe

boolvaluetrue,andtheloopcontinues.Listing5.2

demonstratesthisbyusingtheexpressioniasthetest

condition.(Intheupdatesection,i--issimilartoi++except

thatitdecreasesthevalueofiby1eachtimeit'sused.)



Listing5.2num_test.cpp



//num_test.cpp--usenumerictestinforloop

#include

usingnamespacestd;

intmain()

{

cout<<"Enterthestartingcountdownvalue:";

intlimit;

cin>>limit;

inti;



for(i=limit;i;i)//quitswheniis0

cout<<"i="<
cout<<"Donenowthati="<
return0;

}

Hereistheoutput:

Enterthestartingcountdownvalue:4

i=4

i=3

i=2

i=1

Donenowthati=0

Notethattheloopterminateswhenireaches0.

Howdorelationalexpressions,suchasi<5,fitintothis

frameworkofterminatingaloopwitha0value?Beforethe

booltypewasintroduced,relationalexpressionsevaluatedto1

iftrueand0iffalse.Thus,thevalueoftheexpression3<5

was1andthevalueof5<5was0.NowthatC++hasadded

thebooltype,however,relationalexpressionsevaluatetothe

boolliteralstrueandfalseinsteadof1and0.Thischange

doesn'tleadtoincompatibilities,however,foraC++program



convertstrueandfalseto1and0whereintegervaluesare

expected,anditconverts0tofalseandnonzerototrue

whereboolvaluesareexpected.

Theforloopisanentry-conditionloop.Thismeansthetest

expressionisevaluatedbeforeeachloopcycle.Theloopnever

executestheloopbodywhenthetestexpressionisfalse.For

example,supposeyoureruntheprograminListing5.2butgive

0asastartingvalue.Becausethetestconditionfailsthevery

firsttimeit'sevaluated,theloopbodynevergetsexecuted:

Enterthestartingcountdownvalue:0

Donenowthati=0

Thislook-before-you-loopattitudecanhelpkeepaprogramout

oftrouble.

Theupdate-expressionisevaluatedattheendoftheloop,

afterthebodyhasbeenexecuted.Typically,it'susedto

increaseordecreasethevalueofthevariablekeepingtrackof

thenumberofloopcycles.However,itcanbeanyvalidC++

expression,ascantheothercontrolexpressions.Thismakes

theforloopcapableofmuchmorethansimplycountingfrom0

to5,thewaythefirstloopexampledid.You'llseesome

exampleslater.

Theforloopbodyconsistsofasinglestatement,butyou'll

soonlearnhowtostretchthatrule.Figure5.1summarizesthe

forloopdesign.



Figure5.1.Theforloop.



Aforstatementlookssomethinglikeafunctioncallbecauseit

usesanamefollowedbypairedparentheses.However,for's

statusasaC++keywordpreventsthecompilerfromthinking

forisafunction.Italsopreventsyoufromnamingafunction

for.



Tip

CommonC++styleistoplaceaspacebetweenforandthefollowing

parenthesesandtoomitspacebetweenafunctionnameandthe

followingparentheses:

for(inti=6;i<10;i++)

smart_function(i);



Othercontrolstatements,suchasifandwhile,aretreatedsimilarlyto

for.Thisservestoreinforcevisuallythedistinctionbetweenacontrol

statementandafunctioncall.Also,commonpracticeistoindentthe

bodyofaforstatementtomakeitstandoutvisually.



ExpressionsandStatements

Aforcontrolsectionusesthreeexpressions.Withinitsselfimposedlimitsofsyntax,C++isaveryexpressivelanguage.

Anyvalueoranyvalidcombinationofvaluesandoperators

constituteanexpression.Forexample,10isanexpressionwith

thevalue10(nosurprise),and28*20isanexpressionwith

thevalue560.InC++,everyexpressionhasavalue.Oftenthe

valueisobvious.Forexample,theexpression

22+27

isformedfromtwovaluesandtheadditionoperator,andithas

thevalue49.Sometimesthevalueislessobvious.Forexample,

x=20

isanexpressionbecauseit'sformedfromtwovaluesandthe

assignmentoperator.C++definesthevalueofanassignment

expressiontobethevalueofthememberontheleft,sothe

expressionhasthevalue20.Thefactthatassignment

expressionshavevaluespermitsstatementssuchasthe

following:



maids=(cooks=4)+3;

Theexpressioncooks=4hasthevalue4,somaidsis

assignedthevalue7.However,justbecauseC++permitsthis

behaviordoesn'tmeanyoushouldencourageit.Butthesame

rulethatmakesthispeculiarstatementpossiblealsomakesthe

followingusefulstatementpossible:

x=y=z=0;

Thisisafastwaytosetseveralvariablestothesamevalue.

Theprecedencetable(AppendixD,"OperatorPrecedence")

revealsthatassignmentassociatesright-to-left,sofirst0is

assignedtoz,andthenthevalueofz=0isassignedtoy,and

soon.

Finally,asmentionedbefore,relationalexpressionssuchasx<

yevaluatetotheboolvaluestrueorfalse.Theshortprogram

inListing5.3illustratessomepointsaboutexpressionvalues.

The<
intheexpressions,sothecodeusesparenthesestoenforcethe

correctorder.



Listing5.3express.cpp



//express.cpp--valuesofexpressions

#include

usingnamespacestd;



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

Chapter 5. LOOPS AND RELATIONAL EXPRESSIONS

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

×