P. 1
5. Selection Statements

5. Selection Statements

|Views: 78|Likes:
Published by yaazel

More info:

Published by: yaazel on Aug 08, 2010
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less

05/12/2014

pdf

text

original

Pro:grammefS afie naif to be Imeasured' by ,their Ingenull;Y ,and their Ja,9'ic but by the completeness Df 'l1le~T case analysis

.

~~ JtbOU}l1 C ha rnany operas rs H h~ I, relari ely < I W - atements. We \/1 .ene un-

.retur s1atRmenrl ""2.2 red ju lit .~: far: theze u,rn l - t ment md the' . '. -, I I si rr stateme n'L_ , osl t

e:qJl'eSSlon saiamen .'.5 's rem "Ding II er ='01 ~,11 UllO thr .' c' t - , I pending I n hi _"-- lh:.

til old. r i [J wh· b st tements aJ~I-' ex · u red:

" ,e',,I'le',I(I. Tb _ if,' _ 8.-wi oh tateme It tcula executi '0. path [rom a I. et of alterns ti :-., '~I.

lr"mtW" ,tR,'efIWlt .. The while,. do, looping .'

I. Jump ,tat_,"""I'",., The hr,eak., eonti.nue, and 'Q'o·t.o'la'~1 ments cause an

nne -nilitio,aj jump '0 '.1 _ 'ID .d er -1 ice in th .-. rogra I. Th return· tan -

men belongs in his (;'atI_, Iry " _'~ ,- U.)

The onlv other s ,·te'ml. ,~t~ in t I are' th, comp u d .

...

,~ [n- I 'ml flt I lnt - . inale ISnlal[ _ m~ nt ~ n d lb· null

-' hich grl IUp, ~ 'ie' ~ raj

whi:h ~:.. rms DO

,

IIC'tl. 11",

Thi, ·b P'·I disc U.',' ,"' th .. elec ti n ' ta emen - an _ the _ und tateme nt.

(Chap~; r 6 (l vers the i~erlti,o'n :- tatemen E , rh ~ jump tatements and tile null tateIn _ t, Be~-' I I:. 'W C,U) wri ' 'M f I a Dl_'O~', . e 11 D ed k si _ ~ .. 1' e ,in .:: I_- ndi ...

'i-,1\5 thai if statem ·.nt· can test. Section 5.1 explalm h' logiealexpresaion at

uilt frt m the r rlational operat -, <: <=_ e-, and >=. tbe quality .. perators :::,~

.... !::-,' nd rh - logical iP en lore' ,&,&" I [ , a d ,~ . ,.1.,,_ t:'U' . __ "",,: c rve .. the if ,"_ re-

m nt and compound tatern nt, 3;,,' well as imrodn -lug the I ndition J opera or -? ::.hl_'h can IL~ l ,8 eonditi -n __ ithin an p ..'" tio __ I, .... ' des ribes . lie

ewl. teh staternen ..

Seve ral 0;: C '. , atement - in Inding the ifla[,_m nt must test the value of an e '~pre.s, ill n to '. " if it L I ~, rue I . I'r' f Ise, '~'Oll - npl 8J1 if, . ~m ntmi h n . I

'0' " CI.t the expres '_ . .11011 i -c j'; ~. true alue would indican that ii, 1-" . than j" In man programming I· D~Iia~ e .' _ pr ssi n uch ,2 i <: j W uid h- ,

rs ': lean I r I gical typ .'ueh a _ ,e "Quid h· _ '.' 'nly' w values id

tru "In ho', , . en a comparison I. ueh as i < j i I .. ' . n intege : eith -r 0 (tid, )1 or.' UlJII',I. ~- db thi .in mind, tet's 11:- k at the' I; I . r tor· lb IL are' _ " d to build I giC~ 1 expression.' 0'

5.1 Logic-I Exprsslns

,abl- :J Relational Oper _ tor',

" ,11l __ IOIIi.11 ,(JpBrai~r. (Table .. J) corres -ond to tho -c, >. ~, and 2: n _"r,a! ors of

mat-If! . 3: ic " e·· .'pl tb l tbe· p'r duce 0 . f. lse I or I I' r ue wh n used in ~ x Jii. '1- ~ ions, F ir example, rh '. III a.o 'c:, 11i I ~ the value of 11 0< 10 is 0,.

Ie than

:> .. ' lerll.D:-

<: - Ie.' ,,,I than r equal to

>= greater than or equal 0,

The relation' operators C:'D b. user t compare integers and floating-p mt numb ers, ~, iLh Oi - erands of mix d ' ~ pe all ".' d _ hus, 1 -c :2 . 5 h the - 2I11ue while 5 ~,.6 ,< 4 ha tJL II] ue J,

h"- preced n e 0_' th r I ti ne l oper or, is l er than th [.-- th arhhrnetic operators: forexample i + j < k ~ means (i + j) < (k ~ 1), The r lad '11,_] .. per, ·10['" ar-e left ass. cis tive,

Tbe expl'"

i <: j <: k

i }. al m C but do', In I I~_a- e the me .'~ g ths t,'DU mi

at r i iative, this expr .. sion i,. equi alent to

(i <: j) e k

In r ther o~n '. thee pre 'i n rrt· It tes '.' . h ether i L 11._'.'., than j: the I or 0 p'rl - U I d b- -hi' I, mpari " 11 ~' .. th -n _ otnpared to k Ihe ". Pile I,i n doe 'Inl. 1.'( whether j lies between i and k, (Wi ... ll . e later in thi. . 1 ction that the corre ct ,_-' pr sion would be i -< j && j < k.)

Tabl,e 5.2 ~qu,3Iily 'Operator

_c-able 5.3, Lo ical Op raters

Equality Opera ,'- 0 -~

" I - ,,_ ' ,.- ~,I~" I " ,I

Although tile relational operators are denoted by the same symbol 31' in In,8I1Y

other programming languages the B'llJllality 'PBr- ,'0'7.. h - . ,I unique pearance

Table 5;,2)~ The 'equal to" operator i_ two adj,,_cent ::, charar ters not one sine a single =, character represents th assignm t operator, The "not equal to" oper tor is at '0 l W'O characr _ rs: 1 and =.

!=

equal to

not equal to

Li ke the relational operators the, qualit - op '. r tors are lef a soci ative ~ nd produce either 0 (false or 1 (tru 'a th ir re ,01" : 'e'. _ [ the ,~qu,lir . - " ran have lowe" precedence than the relational operators, for example, th,e e pression

III iii • k

~ <: J == J <'_

i " equn '31 nt to

(i < j) ~= (j < k)

which i: tru - if i « j and j ,< k . ore b '

Clever programmers som 'times e~r plolt he fact £hal the 'tiel a, ional and equality op raft rerum integer' " alues .. .' rei ample th,~ val e of the ICXP ~ . ssion 'i :>= j ) + (' i = = j)1 h' I itb,eJ" 0" 1 Dr 2 depending OD '-, h nher i i" Ie th n ,: 1 at _'f than . or equal to j, respectively, Trick- codin like thi' generally in"t a ,~,od ide n~ h. ever; it makes program hard to under ts n· .

Lo .~ cal Operators

More complicated logical expre ',~on I _ an 1 WIt fl -rn simpler I· ne b,y usin:o the lo,gI~cal 0p'le'lYIto,s: and. or and not ,Tabl 5,.1). Tb, ~ op nt. r i, unary, wbil && and I II are binary.

! ~&

I I

1,1 gical ~le~r ti iU Iogical (J, ILl

I, Jilcalor

The logical operators produce either 10 or. 1 Ir-_: thCDf result, Oft "]]'1 the operands will have -~ alues ol 0 . r 1 but this lsn' a re _uiremDt~ the- Jogi al operators IT',_ t ,any nonz _ ra operand a a 'tree 'value and any zero op . rand a ,3 false valu ~ '.

TJ~e] gical op fat ,r, behav I as ollow ,::

• ! expr has the valu _ lif eX1Jr bas, the value O,~

., exprl && expr2 hi the value ] if thevalue: exprl nd : pr2 an b tb non-

zero.

1[1 at ~I other cas . ""'e, the :le operators proc u '= th, va H, O.

BI' nh && and I I perform I, short circuit evalunti n of their' perands, Th,~.lt il."

rh . ,- open tor If' tie aluate tl e left pll"r~ nd I _ en th ri.',ht I 'PC[ nd, f the valu .

tho expre , on t an be' ,_,. uc d Irom the - alue ' the lef peran al n .. th nth.' right, peran c' i sn't e' , alua I' "~I. ,on i· ,er the olle ." .

~i 1= C) ~& (j Ii> 0)

]" find" . "'e mns trs '. IU~ re (i ! = 0). fiLm; . , 1U.a] t 01. tbl. n we' ll __ u - 10 levi lu," :[, I( j Ii> 0) LO d, t~ rmine ~ he her the f'n . "

., I f:~.·11 H .' r- I oj _II o !ilL b " "

e Pf-e" 0 I· true GIIr aise, '0 'ever, _ ~ J . e lJw tou men It ' entire express: _ 1]

rnus fa] -' 01 (here: n need I . e aluate I{ j Ii:> (1), ., Th· ad. antage of sh rtith 'u~ it ralu __ tin- the expres i D " ou d b '-

Be 'w,m-y of ide etfects ln l . , lea] .. , prF' :'. i .'~ Than .... It the bon-circuit nature lof tbl 1&1& an I I operators, sid effect in operan ' m c. n t alwzr . I iccur, C msi .1-[ h.' follo ingexpre sion;

± ~ 0 && ++j' :> 0

-ltbQub:h ]I t, pparen tl remented ,8 R ide f!.ffect f . xprle -"" ian

that is n 't al ,. 1 I the ca . _ i :> 0 .:, f· L then « r > 10 is n. :' d. 10 j isn' ~

increment d ITIl P -ob}. m can be fixed bv chs ns i ig I-', ondition to ++j >, ,01 1&& i :> 0 or even bet ~1'" by U1C[I, . mien ting j '_ paraf . ly.

Th" ! op. rator has the same _ r cede u ...... _

tors, he p ecedence of && and I II il l·operat rs: . or example i < j && k == m man", I{ i < J ) operator i " light associ tiv . "", && and I I ate left 8, soci tive,

i ,f :slll:ement

The if· tat -me,nt allov .' a ~~:r l_gram ,[hl ose bet I' en : wo alltematL I I by L ,tin.-

fan expression. In i'l , simpl .. st erm, the Lf . tatement ha form

, .' ere tha ,'th, parenthe ....... tLa~""II tb . if tat me nt, Blot p'_ rt 0 c . me after th parentbes ,., a it would in. me progr rnrning langu :_. '"

I, he n an i f'tat ~ ment j' Ie - pre I~ii 11 ill th p: _ " nthese , i~ 1,-" alu-

at d: if the ,ilu_ ' f the exoression is n:"'D_,'1 r ~w'hic'b ," inl nprets ',' tme~ tatemenr after th - parenthese ," x' uted, Here an example:

if (l.ine __ num :- MAX~LINES)

line_num =: 0;

The I,t~ mot line_nu'm=- 0; j" e tecuted i_- the I onditi n line num ._""" M1\X L lNES .'. true has a nun " ro alue),

. " n Il " I,' '[Jill ,e == equalit '

l.f ('1"1 .:;:;;_;:: 0') .-

- . . ~~~

if (i = 10) n~

_I IIiiIIiI

assi ,0' to i~ tb:en tests u hetln rt 'r :,u,lr is nonz r ),. In this . ~ " the te always fil.

lei: nfusing ~~ 'with :; I, perhaps the mest ccmmon programming e1T'~,

prob bly becau = m 30'" "is I, qual Ito'," ill mathematlcs Iand in ertain pn '-rammlng language ~ Some c, mpiler '. u,' a 'warning if they Ilo,jlce ~ whe:r,e =,= ould

n- orn n,""'U appear

, ,u&,B.ILt:: t_·"" ar,

Often tb e expre sion in an i,f tatement will t ':t 'whe her a ariable fall , ifuIn a range' . <- alues, To test', beth,' 0 ~.; <: n lor example,v e'd s ,',

ildialm if (0 <;;;;. i && i <: n) ~ ..

Ildllom ~ f I( i <: a I Ii:>=- n)

Note lite u '_, of the II ~ operator inst" ad fthe && p. -ator.

Clo,mp" und ", tat, 'mle' . Itsl

In our if, taternent templat 'I' otice tho 1 statemet t ~" sin ular n, t plural:

,at ~ , e want an if I' remenr t c ntrr I ,h '-0 or more . uatem 0',. Tha I' where the IC,Ofl,,,OUI,'-:, . Ita ement come in" A " omp nmd . ,~J ~ m _ nl has be' ~ um

co'mpound statement

{ tatem tJnt }

13,,! putting bn ~ ~'I aroum a group 0' '[3,[ me it al,' a si ogle statement,

_i.f ,stale:ment, wah

_. - .. --

,e,ls€! cllause

{ 1; ne_Dum = 10; p.ag;e_Dum+-i-·;' }

For I '~,ar~ ty I' u usn ally put a. compound statement on several lines, with ODe stme.w mem per line:

{

lJLIo n- - ,D. n- -'urn-; ~, In, ~

11."""",_" _' .. ' - u~,

page _ num.""r+ i

'}

Notice '[bat each inner ~" tatement still ends w'i th a_, semicolon but 'the ,c'omponnd state me nt itsel f do not,

Here's what a compound statement woukl look like when used inside an if statement:

i ,f I~' 1 iDIt:!~num =!i: MAX LINE'S) { line_num .: 0;

Pat"f,e num+ + ~,

~ - ' ,

}

Compound statements are also corn rnon in loops, and other places where the sYllrlL."{ of C requires a single statement. but we want more 'than one.

The e' ,'le- IS,' Cla 0-5 •. 0

_', ,. ,I _ ~,I", .~

'The i' ,tate'~nlel1ll that follows the word e 1 S fa is, executed if the expression in parentheses bias the value O~

Here's an example of an if statement with Wl. el.ae clause:

1.£ (i > ]1)

max ;;;;;; i; eLse

"

max ~ Ji

Notice that both "inner" statements lend with a semicolon.

'Wb,oo an if statement contains an el,s!e clause, a la,yout issue arises: where shonld the else b~ placed? Muny C programmers align it with [be if at the beginning of the statement as in the previous example, The inner ,'. tatements are usually indented bLIl if they're short they can be put 00 the same lime as 'be if and else:

.i. f I( i ~ j) mJax el:ti;9 max ~ 'j ii

"

- 1.;

There are D... res rrictions I. .. h It kind . f · tatement I can a.PP'ClaI j n side an if natement, In ·3, t, i j 110' unu ual r if' atemen s t be nes 'te_ in i . other if

statements. onsid ibe "1 UI' ing :If stat ment, . bleb fin -' th tar:' es h

numbers st red in i j .and k nd t res that v _L lJ:1Je in max:

if (i ~ j) .if (i ~ k)

max eLee max

~

-. 1"

II

else

if I~ j > k.)

max

ma.x - k;

if: ,e (I' m ,_t ian b D sn d to any depth. N ti .. 1-1 I' alignm . lea .'b e.lse with the

matching if m kes [he ne tin,.· .' .'. j. 'r to see, w-r:" au till fin. the ne sting confusl ra, don't besitat ... 1 'to' add braces:

.if ('i :> j) { if (i }t k)

"

max ,_ JL;'

lels:e

max - k,7 J e l ae {

if (jl ~ k)

I

max~];

elise

max - k,;

}

Addins braces 0 statements even when they re not n ,c·: ary-i lik - ILL Ii Db parentheses in expres .•.. ira I ~ b . th techniq lIe b -} P make a. progr 1m rnUiJn~ 1'11:=' d ble

hile ar ti . "d' h "b"'I" I b- iler wo ,.

, e a: le same lim' ~·'Oll'Jn,'. t ie p "\,11 fld Y t ',' 1.1 - e 'mp, e - .n t on iers an

Lh pr gram the IW,y -, th uzht i Idil'l _

_ ~ m,1 Pf1' gr," rnrne I u:_ I many bn ,~er possible mil if st 't, nnents and

J - rali n tatem nts -,.~ 'en" A :pr grammer wh. adopt ~ thls convenri ',11 . uld

inclu e It pair of bra c' for e·.' cry if IC]I3Lu·e and every else clan se:

if 't i :>. j) {

if '(i :> k) {

~

m .. a,x :::::: 1.;'

} e,ls,e {

max = k;

}

} e1SIe {

if (j ~ k) {

I

max ~ ];.

} else { max = k;

}

}

Uslng braees even when they're D~oL required bas two advantage ·.Fij;'l~ the program become .' easier to modify, bC'C3JUSf' more l tatements can easily be added to any if or eLse clause. Second, it helps avoid ermn that can result from forget ... ring to use braces, when adding statements to ani.f 01~ e l se cl u, '.,

We"II often need to test a . eries of condirions. s'~iOppiDg as suon as, one of them is true, ,A "cascaded ' if statement is of en tJ11e 'be_ r wa to wri e ,Deh a series oJ tests, For example, IDe f:. llowing cascaded i fl'lt81tenllcnrttes't whether n 1 les than O~, equal to Olr., or greater than 0':

if (n < 0],

cp,r' ntf ,( lin a s les,s than O'\n ~ '~I 'f el:se

it (n == D)

p'rintf ( lin is ~qu',alt:o '0 \n 'Ii) ;' ,e,·l,s'e

plrint,f (lin is Igre:at.er than Ol\n~~) ,:

Although the' second if statement is nest d inside the, first C programmer don ~ os'uaD_y indem it, Instead, they aligneach else 'with the original if,:

if (n -c 0)

:pr.intf (~rn,n, is Leas 'than 'D\n II) i ,els,e;· if (n ~~. OJ

pri,ntf (fl'n, i,e equa.l to a\nl! }I; else

prin·tf (i'in is Igr'e,ater t.han Oi\D"~);

This arrangement gives the cascaded if' a di tinctive appearance;

if ( expression ) statemen:

el.ae if ( e.:(p.re·~~si'{JJ1 ) a ta fe,ni.!'R t

Ie: ,1 s;, e i ,fit expression .) s tat e'~'lent

,~15e

stateme n l'

The last two line I (else statement) aren't always present" of ICO'Ufse,. Thi: way of indenting the cascaded if··. tatement avoids tl11 proble·m of excessive indentation when the number oftests is large .. M oreover, it assures the reader 'that tbe statement is nothing more than I, series of tests.

Keep, in mind tbsr a cascaded if statement ,ISO 't some new kind of stat ment: if, , just an ordinary .i f statement that hopp~n·, to DEJ'v,e another if statement las, its el se clause (and that if statement has another if uarement as irs. else clause, ad i,'rJl,ni,tum' ),.

Wh~n'ock.,. areal or purchased tbrouzh a br .-r'-, c j' : ssion i'

otten I ompure using __ diding ale IUl·, fepend upon he ue IOf the ,.,il.,

tr Id - ," Let ,~; say tb'at . _ br ·k -r charg e'· tbe __ -_lll_un " ~ hn D in the 'OU, 'lng t:. bl "

n lD'UQCtiOI1' sizt, . Inder .'" 51 .0 ~'~2 S,O()....· ·6 ~50

Commi .sion rate

: _ 0 + 1.7%

$-'15 66'

'. " '

. + ..... 1'" '1

'7'~ n- m 'I U' + \1.-" .'7(

~, lO + IO~:',,' '''15~'- + IO~ I 1 % ';-"255" + 0 a m

1,li' ,'=- ,1,,,,",, 7-.·'7t

. ,e mJn~:mum h,'- gil ~- ,;,-:, . . ur D

th trs de, then disple ,,' ,h e amount 'f ILb-

• i

mml' s., _liD::

Ent,er va Lue of tr'a,Ci,e; J 00 01 () Conunission- $,161IS .. IOO

Th . h -, ,0· 'the progn m is ' cascaded if st tement that d -l,-Jrmlne which th tra I -all jl nto,

,I t · ( , .a] l.n _ rna~n VOl.,U I

{

printf (1lIIBnter va.l.ue 0', tr,ade ~ aoanf I( III tf ~ Ii &v'alue).,

11') !!!'

~'

if (value < 2500~OO, 1

Icommission == 30" 00£ ~. ,,017f .. vaf.ue i ,e-ISle if (v,alue <: 6250,~IOIO~)

commd.esi.c I. ~ 5,6 .. 0,0£ + ., 0016,6f * value;

else i£ (value < 20000~OOf'

co'mmi,s,sion = 76 ~ OOf + ,,01034 * va.l.ue , e Lae i£ (value' c; 500'00 'I OOfJ'

clommission := lOO~OOf -+ .,Q022f * va Lue , else i£ (value < SOOOOO.OO )

eommis:si,on ~ lS5" OOf ,"OOllf '* :v-a,lu,IB;

elSie

if i(c,ommisaion ,~ 39"" OI,Of). comm.Ls e Lon = 3'91" Olaf;

r~tu

The cascaded if mrement could have been written this way ius: ead (tbe changes are indicated in bo-d),:

if (value <.: 25010 ~ OC'f)

commisalion :: 310 ~ OCf + ,.017£ :* value ~

el'se if fval:ue>,~ 2500~, IlDlf lui v-alue <: 62,501• Oaf)' c,ommission ;~ 56 .. QOf + ~ 006'6,£ * va l.ue,

else if (value '>,:= 525D 0; IDClf &Ii value -e 2100101(1 .. OQ,f) c-ommisaio,n ~ "6;" O'Of + .,0034£' * value,;

Although the prio·gl1l'1l1 will still worl the ,Idded conditions aren't neces ary, Fa,r example, the first if clause. h~s,t~ whl£ther value LS, less than 25001 and, if SQ- com'PU[I~ the commisalon. When we reach 'the' second if ·te'~ t (va Lue ~=- ,2 5 Cl'O .. 00£ && value < 62501 .. '0 0 f)" we know that value can't be less than 2500 ,W1d therefore must greater than Dr equal to 2500,,, The condition va Iue >.;;;; :2 5 101 to ;! 0: [1 f 'will always be true, so there 's no point inchecklng it"

'Ib,e ""D,&ugling e,l,sei" .• n oblem

When if statements ate nested, we ve got to' WPl~ch uul for the nu·torious. ' dangling el.ae" problem, Consider tile following ex amp le:

if (y ,[:= C,)

if (x J~ Qt) re,!Sult = x / 'y,~ e,ls,e

prlntf (~I'IError: y is e'quall:"o D\n'l~);

To, which if statement does tile ,else clause belons? The indentation suggesn that it belong to 'Ul.e outer if statement, However, C1 follows, 'tile rule [b,al 3D el.ae clause belong JIO the nearest if staremenrthsr ba1,11 t aiready been paired with an e Lae. In this example, the elEe clause, actually belongs to the inner if statement, Sin a Icorr-ecUy i_nd)en~E!d version would look like this:

i_f (y 1= 0)1

if (,X, ~= a) re,sult == x I y; e'lse

printf ( ~~Error: y i.s equal to ID\n~m);

T() make the elae clause part of the outer if . tatement~we can enclose the inner if statement in braces:

if I(Y ~. ~ 01) {

,if (x 1:= 0)

r'e~su.lt = x I Y i }- ela,e'

prin't.f ('HErr'of" ~ y i,g lequ.,al t.OI O\nll) ;

This example illustmtes tbe value to f brace :". if ul,c"-'d used them in the original if statement.we wouldn' have gotten into this situation hI the fil'. t place,

Ican'diltiana,1 e~ ,-resl 'on

5.2 The if Statem,snt 83

,- 1. f st __ Ime:nt allow, a . 100: ram t p n rmnlc I : value ,of a. condition. I 81.0 pro·- ide~- cD operator dh

du' ne nt two value dependin n , In lh, . value r con jri 111 ..

Tb C .I-tii ii fUllop ill or co -1-j".,1 .. 0 .~ ,01 I ymbol '? _ 0'-1 : 1,- which - - 11. be '~ '., :,d tog - Lbr in 'lit ' folk - , ing wa,·

dependin - on he

. xprl e 1Jlr - nd I_ prs iO,,-I: 0 , __ n' r - .~, The t, \~-ul in,l.- xpr

, __ "d to b - '. I.~, ,fld~ ·0_,_ ~_I eq( -e I,sli, ,The IC'D iti .......... "" .. op . rata . in that ~t require tlu~f!.p. ' __ nds in. [131 ' 10 i' 0 ~ten r - f rred 0 ill '1;' rIa· .. perator,

The conditional ~ rpressi ti exprl » rl"~: r3 '-"111 uk li ad "if exp. 1

then-xpll·2 else exprl ' The e rpression v lu ted in srae -jl: e,; P' J ts ev _ uate __

fir. t· i 'it -'aID i n't zero then. pr2 is. e . lu'-. t ' ~I I_d, it"alUI_ i b value ofth

I· n hi 'C nditi nal _- ~Ir _, ssion, " th . alue of emrfis zero. then the' ale .f eplJr .' ~I, the - alu -1 tb, -' C'D _iti . nat,

'The fol! '-. ina xam le illu rr te

i - 1 '"
~
I 2
J - 0;
f
k , I ') i ,
- a. >- J ,. J ..
- OJ '. ~
k (i 0 '" • 0] j
- ~= ,. + ..
W I~ , /* k I, :2 I
191 now
I k ~ 3 I
.. 18 now he eonditic nal IXP'f' " sion i :> j ?I ~ ~ j in tb fir ~t as i. omen' I,· k fl: [urn, th _

- alu . D' lei her i lor J II de pendln 'no - hich :' ne I L -_'. L Sin ~ ha I lb' 'I' tlu . I

and j ha th alue 2,- the i >1 j , '0 mpar i Ion f ". I d the c-;" U:.('Jl i . Iwhil '~1 i 'I a isigne t k. In the con as i ~ nment to k, the i >= 0.'01 '~_ ari 'Ion ,: ncr ,el- d ,. the con i ional e tpression (i >= 01 ? i " G) h the .- , Jue J wbi h i

h -0 _ did, d to j . . - r odu _ e .. I • h P'" r - nth ~ 'e', Dr' n, ' ~ I he

den ~ , 'f lh, conditi D') , '. .than rh'l _' the '- r - rilt e

if (i ~ jl) ret.urn i-

"

els"e

suld

e urn i > j ? i : j;

84

Calls f pr i.nt.f can s metimes en ~'t fr. m I .nditin ',. ~. 're . ion. Inste dof if (1 > j)

printf (" %d\ II I' i) i elSie

pr int f ( 'II %d \n t~ J j);.

printf ( If %d\n n, i >, j ? i : j);

C 'ndt ~i n· expre ssions are 1811·. I cornrn . n in c rtaiu kin

Fir many ears, the CIani u ge L." 'd a proper Bool 'n t, p _ ,and th re i none d 'fine: l in the' C89' s ,and~ d. Thi ' 0111"<)1011' min r ann an e since In,_ n programs "need variable that can sto __ lither false o: true, One a,' t " work und rhi Iimiration of I 89 it, de ~ Iar c an Lnt; variab 1 ' and tb _ n a is n ite 'i the r 0 or I:

:int. flag;

fla'9 0' •
~ - "
!"-.oJ
flag ~ 1 ~,
, ': Jthough this s b me works, it oesn't IC, ntribu ':_ much to pr gram read ,bUlty. It· not obvious that fla'g is t. be assigned onl Boc lean valU~I~. and that '. an ' ~ r jpl". 'DU "a..! _,e 'od true"

To m'·,· .' programs more' un er n - :abl , e89 programmers . ften define n1a1Cros with names ','LI 11 as TRUE' and FALSE:'

-~define TRUE 1 ftdefine' P:ALSE 01

As· ignm 'ot· 0 f 121'9 n _ h_ V' 'a m re natural app earance: f l,a.g ~ FALSE;

fla.g ~ TRUE;

To test whether flag i true" we can writ,

if (flag ::~ TRUE) " ..

. '

or just

if ( fl,c£,g ) .~.

The latter ,', rm is bette :. not I, In] becaus il" m

still ork 01T1~" til ~ if' fl,ag hs . .. b ''f than 0 I, r ~.

110 to l vhether flag i, _ 'W _ an '~, rite

if ( fl ag := FALSE)I .•. ,

u also becaui I. i' will

5,~2 The if Sta·ement 851

or

Carrying [III.· idea one step furthe '. . e might " '" define macro that ell n e used tI'· "._ type:

It' now I· lear that £ lag i,n'i[ an ordinar integer vii ble, bu j0"'4'1 'f_ad. pre enn u Boolean condition, (T:he mpiler still t ~, at flag as an Lnt; variable, . f cours .

t~~fH:te -rri1ions "'7_5 In talc}" clu pter " we 11 dt J -, ·T better \ . y to . r U ,B oleao l3'1 e in . :9 by

enIJmeratione ~'fI6~5 U ing tyPI- d flnition r , -. I numer ti· ns,

18 Boole: m ··BlDe··[ in C991

The loft. tanding la '_ of [~ Bool , m 't,' P '.. ha , been rernedh d U) leg I, W hich pro- id ~ '.' til· _B"o·o 1 type, In thi· version of C" a Bot lie 11 vari abl c· [1 b -d cle l!,d. by writing

_lB,ool flag;

UJ1S1 ned In~ger typas .7.1 _Bool is an integer type I' m are pr ci -. J.', tn ~'nlil~ued in: - gl Pl_ ~

Bool ariable Is really just an in ez r . ariahl - ~ FI di - gui~ . U §, " n ordin

integer variable h . "~r' 0 Boal ariabl can I nly be ass igned Or or ~., In general, artemptin] too' or' a 110ll11er-1 value int a Bool ariahle will c ,U~_ the variabl ' to b assigned I:

flag ~ 5,

1* flag is assigne,n 1 1rr /

It': legal (although not _·d isable t. ierforrn arithme 'ie on ~Bool ari bl s; 'EfL legal to prin a _BO'ol vari '1, ith r 0 or [,HI re dis 13 ·-Ied.. _nd-, olf CUTi '.~ . aoel. ariable can be te t [_I in an if c ta em'_:_ nt;

'!<'!.

in ,ad,' i iOll to d~ fining be _ Boo1 ty .. ! I I. a10 P_[I id sane. b a er

<~tdbool.h> hRadM~211.& < s,td:.bc[ollol ~ h:> that mak i e . il r to won \. ith Boolean ' tue .. Til 'I: .. h ad r pre vide a macrc bool that .. tand ~ - Boal. J ~ <::stdbool "h> i ill Iud sd,

I" same as Bool ,fl,ag; it I

. =-=-

The <:st,dblo',ollOh=" header dso xupplies macros named trule and faLae. which stand Of' i · n .01 re .. p ·ti e~ making it po ,"ibt l write

:E-lag ..... fa 1 s,e ;

Ii:.~·

,fl,ag ~ 't,ru,a t

B eeen se the ,<,s t dbco l . h:> header i ,'j ;S,O handy" [~11 use it in subseq uem programs when ver Boolean variabEes are needed,

In everyday prrogr,amming. we'Il often need to compare HD expression against a . erie" ofvalues to see which one it cUIT1enUy matches .. We saw in Section 52 '[hat a cascaded if starement can be used for this purpose, ROrr example, the following cascaded i-f statement prints the, English w,rd d181t corresponds to a numerical grade:

if (grade =.:;:- 4)

pri,n,tf {'II E'xcellent II) ;

else if (grade == J) printf ( tI Go'od m~ ) ;

'else' if (gr,ad,e == :r) printf ( U Av,e rage 'II ) ;

e l.ae if (g:rad,e ==, 1) pr,i,nt.,f ( HP,QorJ1) ;,

e.Lse if (gracle ='= 0)

prin't:f ( fII Fai 1 in~;J' ii )0 ;

.e Lae

~:)oJ:'intf [ IIII Ille'g:al IgrQde~l) ;

A, an alrernarive to lb.i kind of cascaded if statement, C provide the s'wi tc,h statement TIle' fallow ing swi t ch i~ equivalent ,0 our cascaded if:

liwitch I(grade) {

eaoe ,4: prin'tf ( HExcell'ent ~I!I ~I ,: bre_,aUt,:'

eaae 31: prin"tf ( MIGolC)d II ]1 ;

br'eak i

c:as€!:, :2: print,'f ( U Ave r',age II~) i

b;reak;'

C!,a,se, 1:' prin.'t f ( 'n P,oor 1iI1]1 ;

bre,ak;

11:::&6'1: 0 ~ ~Irinrtf ( JJ Fa,lling ~ ) i break;

defa,ult,: printf I( II Illeg',al gr,adell) ; b,r,eak;

}

When thi ' statement W" executed, the value 'Of the varia ",Ie gra.,de i tested against • 3, 2", I and O. H it mat:ch, " ,,4 ~ , 'or example, the 'message Exc: e LLent; is prin!ed, ~break sla1:emefll ,,,",,64 then the b,re:ak s'- aternent trans fen control (0 the statement following the switch" If the value of 'Q'rade doesn't match any af the choice listed, the def au.l t; case applies and the message Illegal Q'rade is printed,

A BW± beh statem nr is often easier 10 read than a cascaded i Moreover, 'switch la.eem- ats are often falter Ithan if statements 'when there are more than a hsndful of cases ..

In its most common form, the 6,'wit!c'1~ sta ementhas the form

statemen t. especially

awi, ch ( ,exp~"essiolt ) I

c'a"se eonstam-espression II, statemem«

..

caae constant-expresnon : suuemetus

,ae'! auf t : statements

}

The S'W it.€h statemenr lsfairly complex: let's 1,0 Ik at ] '- components nne b:Y' Q1J1II::

• rC",,_tTtJlli,u'g ,expresl,ioll. Tbe word s,wi t.ch must be fotlowed 'by an integer e;, pression m parentheses, Characters am treated a ' ~int:e,g:er", in C and thus IC',aD be tested inswi: ch statements, Floating .... point numbers and strings dOD It qualify, however ..

• Cas« ,lD:IJ'els',., Each case bezins with a label of the 10rm

- ,~'.

A ICO"I~Q'Jlt tJ%f'r-ess,i:o',n' is much like an ordinary expression except that it can't

'ontain variables or function calls, Thu ; ,5 is a constant expres ion, and S! + 1 a its a constant express ~ on, bot n + 1 C isn' '[ a eonstan l expre - sjon (unles ~ n is a macro that repre en ts a constan l).. The constant .. xpression in .3. case label mu t evaluate to au integer (characters are also aecepn ble) .

• Ststeme'II;Is'.After each ease label comes --ny number of ·':,arL-em,ent .. No braces are required around the statements, (EnjfY it-this i-' one of the "few' places in Cwber1e braces Men t required.jThe last statement in each group is Il'ornlaJly b,rleak,.

Duplicate cue label aren't allowed, The order of the cases doesn t rna ter; in particular" the de fa ul t Cit se oesn' t need to come las t.

Only one constant expres don mal' follow the word case: however, several case labels 'may precedethe same group of statements:

switch ilg''rade) [

caae 4 '::

c,ase 3::

caae :2"

case 1:: printf (III P,a,ssi-ng"j) :

blr'B1aki'

caae 0 ~ printf ( '1I'F81ilin.g'll) ;,

'blre,aki

,de_fau~t;: p,rint.f' ~ 'hln Il~eg'a.1 g~ad,e~i) ,;

bl'!l""£:i!I .... ,'l.. .. ·Jlii.IIO-::;i'~1

)

11 i save space, progr nnmei ;, ' om time put, sWJi t'[ch (lgr,ade) f

caae 4 ,: caee 3': case 2,: case 1. pr' "ntf ( 'P'a,s[singml) ; b.reaki

caae o! p,rin f ( III Fa i1 ing III) i

br~a.ki

de,fJatult: prin,tf' (IlIllegal g'rad,ell) ; break;

}

_' " write a .- ,I' . la :] at s i _ jfi I', r·o·, I ',. aiue: I~

as there is m som prog amming I ngnage .

A sw[i tch st ',' . m nt i ~Ef requin d to' have a de f au I t case, H de fau I t i , i ing s 0, tbe alee of th e mrc IILn _. e ~'[ i D do ',,'D' t match any of the c[_ se

label c mtr ] imply po" t ' th " ne l st tement rter the awi t[ch~

'Tb " Role ofthe br'e.aJ eSn rt ment

Now, 1 t" ak -' til closer ~ook t the mysterious b,r'eak ' stement, A'I we VI! seen, e tecuting a break.£, ." en ICRu':e-, he ,. "gr,um ,: break' OIJJlt of th ' switch

~ , __ tement: execution _ ontinue lilt tb -' " ext s atem nt after' the B'Wl t.ch,

The eason that : I. nee breakh~~lodo'wi~hthe_'·-llhat'tbl[s.-wit:leh'[ "'''''

m nt i&c re ill a form ," , put -d Jump. ,-;hen he, mtr 1 lin , - , __ pt1. ., u

e aluated, control jump t [be case ~I bel matching the valu of the switch

I <·pre· . in. ,C,'S" lab 'I is othing m ' ' th n a m rker in icatin _ positi n· it I'

th s wit en, hen ' he last sn te m ' ' n l in rbi, caseh ~ " b en executed, e'l ntrol fall:

thr ugh" r " th' first st temcnt in-the ~]], . ~ in _ c _ "., :~, ' I lab-lor --I nex t c ·e

is ignored. ltb ut bz eak ( r om '.,' mr .1 wUJ flo' frorn

one case into, ihe next, Consi _f th

switlch l(grad1e) {

ca.-ae.: pr,tntf ("Excellen't II) ,; case, 3,,~ p[rintf ( I Good II ) ;

cas e 2:: P'I' in t f ( H' Average 1Ii)1 ;

caae 1,: prl.ntf I( ~'proo 'II') ;

eai!Sle 01: ,prirrtf I( I Fai11ng'!1 ) i de'fault; priIltfl"~I.l1egal gradell) I

}

If th, .: In ' of grade i 3~ the me ' ago print d >

Goo~verag,epoorFa,ilingll1Ie9a[1 gr,ade

-'0 getting 0 U.·I- Dlre'ak i~., H, commo .error, Alth ugh I mitring b:re_ak is '"11- time dome inte ntionally tc allov everal cas to shar ·0 e ,1'1 usn ll iust __ n o er 'igllt~

no D,~

Since deliberately falling hrough from one case into the next is rare it' a good idea 'to point ont any de iberate omission ofbr ealc:

,s,'w'itch (Igrade) {

caae 4: "eas,e 3, ~ ,ea,iS,e :2 ,: c,a,s~ 1·:

I

nu,m_P'QSSl,ng++ :

/ * F'AL,L THROIOG,H 'Ill 'case 0: tctal_grad~s++; b,reak-;

}

Without the comrn nt, someone might later fix the "error" by addin ,an unwanted bre,a.k tatement ..

Although tbe Ia --L case in I. sW'i t.ch statement never nee r a break starement if': common prlal tiee t pU'1 I ne there anyway to guard against a "mi sing break;; problem if cases should later b ,add~" d ..

PROIGIAAMI ~ nolin,' " Date 'in Lega Form

Let's write a program than di plays dat s ill thi ' fa - -., We "11 have the user enter the Ida', e in fll,ontb/day/year form. hen w:~"11 display the' date in "legal" form:

E-nte'r dace '(mm/dd/yy):' 7'/1.91/14 Dat.ed this 19t:,h day' of July" 2CJi14 ..

- /e can .glet printf to do mo: t nt the formaning. However we're left '~ ith two problems: how 'to add "th" (or "st' Of "nd" or "rd") 0 the d'~Y'~1 and bow to print the month ~. - I 13 word instea - uf a number, Fortunately, the s,wi t.ch tatement i id afor boll! situations: we'Il have one s,witch print the day suffix and 13.110fbel" print the month R,aIU '.

cla".,il: 1* Prints a dat,e in, legal fQrm * I

#include cBtdio~h>

p,rin,'tf (~E'nter dat;e (mm!dd/yy), ~ II):

aoanf I( 1II1·,ld I %d I %d mm, &m,on·th, ,&day" &ye .: ar)';

print! (~mDatled this ld~~" day); swi,tch (day) {

case 1: case 21: ~ase 31: p,rintf ( ~m st"~) ;b,r,eak; caSIe. 2:: caae 22~,

p,rintf I( nnd.U); b_re,ak;

]V ue,

'or _ m,a't'~~y" ,many eompil 'r we cap ,bl~ of che iking f r suspe "t us" 1'1'- the = IQrP .a 0 in if ICI_ ndi i, "D' '. The IG~ ,~rn,pi~ler or e: amp e. will perform L "

ca,Eua 3: case :2],:

p,rin,tf {Urd ~) i b17e,ak'i default:, p,rin,tf ( 11th'll), i br,eak,;

}

print f (III d,ay of 11);

switch I('month) {
caB,e ~: print! uJanuarym~ ) .. bre,akj
,
C,BB'e 2 .' Ilrintf ( " Fe:bruary~f ) .' break;
'. I'
:3 . f ( rIMa_ch'l )1 hreakw
ca,s,e, .. p r i.rr -
- Ii " I - ,f
Icas~ 4: ~ prin,tf ( ~~Ap, :--il'" ) '. brleak:
.. ,"
case 5 10 print III1 May I I ) ii break~'
~ ~' ,
case 6 I~ prill·t,f ( .1 Jt1n,e ~~ ) • break;
.. ,
caslle 7 ,jj prin,tf ( III Ju , v iw ) bre,ak;
,. ,
case 8 • printf ( 'II Augus ' I~ )1 .. br'e,ak;
,~ ~'
Ca,5U!, 9 printf ( IIIS:,eptember~1 ) '" break,
.. ,
., -tf ~ "Oc -cberlll ) break;
lease lOI"" plr~ ~
, ., 'I
CraBle 11: print: - ~ nN'oventb'er III , ~ break;
I:
case 12 . prin'tf ( II Del,cenlblerII ) .. brei Ik"
,. t ' -,
} P in,tf (U I return Or-

'1ln:~ 2-,d- '\nn y'e- a, 'I!"') ;0

,& !.ill "i:I! "' ' • " ,. " I ...... I

NQr't~1 the use of % ~ 2:d 0 dLplay the last 'two diglt 0 the ye~r.( we bit used

%d in I e I~ ~ ingle-digit - ould b - di I la I d in 'O:~ re tl 105" 'I, ',ut b

printer ,-'1205 ..

Q&A,

Q::

- , th - r-:- , om,e

'filin

if (i =: =: 0' ,) ~ .• 'hey h ibitualf w--'~~.",

',. ow' _- UPIP , " that the = = erst ~- f (,~ :. 1")

~ U ~i!!

The 1_'001 -, iler ;-',: ill pr I, U ae am error m ~~ae" " "'in,, i ' ' value to O~ I on t UI' e U1i' triek, because I think if 11],- - "Ie ' I ...... "'-"Oi it can b UI - only x -hen

di . . i!iI

-,n lUI', n n t _

Q&"A

1;'.:' .,_:_

check if the -Wp,ar,entheses non i· used If if -Wall I all warnln i

sele ted. Gee allo be prograi arne r t uppr . ,. tb,. t,. amine in a PI- ~ti!cular case

by .. nclo ing the if condition in a . ~', end ..... '. 'I, parenth s:

i.f ((i = ,j)) ...

Q: C' bo -: seem 10 U:,', everal d~fL'_,_r nt It, Ies .", indenta i.o a- d ,--:I.~'I: place-

ment flor compound statements, ichtyl. Is be t?

A: Aceerdin _ to, The New Hacker s Dictionary (Cambridge, as .: MlT Press, 19'96),

th ,e _ _our common ,tyle' .. , of inden arion and bi a,ee pla em ent:

• TIl_I{ &R "; l u "'. m ' rnigh LD an 1 Ritchie's Th, ' ,e Programs __ 'iI, 'Lan~ guc ge, i,·~ the n I' .' cho n tor the pr , am m this b· ok. In the K&R I lyle, th ). ft brace appear·.·· £1 he nd of ,9 line:

if (line num == :MAX: LINE,S) {

li e num :;;: 0; page __ num++;'

1 h .. " & < ,t~ I I I P I program: compact b not puttin'. th left bra." .' n a line b_ il"" If. A i,~ '. lvs t, .Ig ~ :: - 1'~" brace can be hard tOI find, (I don t consid r tbi a problem since the indentation 0' ' the i ner l term nts make it clear where the left br ce should be.) The K&Rotyl,'j "is, th 1010- most often used in JI8va by the '-ay.

• I- 'll',,,,antvle, named arter Eric Allman I the autl __ 'r of aendmad I anc

'"'

oth .. r '. u tiliti 'I)' put . the left brace on a s eparate [in e:

if (line num _,_ MAX L,INES)

{

line_num ;: 0; page_num+: ,i'

}

Thi s style makes it easy . ,0 che c thalt brae :,,' come in rna' hing pair· ..

• I h . hite mims '!.' le, popt lari: ed b· the Whltesmiths 1'_Jom ,il, '[that

if (lin,e rrum

{,

line num :; 0; p,a'gle num I ;

} ~

• The G.NUsiJl,(~ used in sof . are Ide. eloped by the GNU Project, iod In('··· the brae s, then further indent the iune-' . tate menu :

if (line num ==' MAX. LINES)

{

Ld.ne num = 01; pa'ge~Illlm++ ;

}

r;'h- ~ -I-r 5 W',' lr:API.,fiJi s- :'_.'

-which ·:tyle' you use !', mainly ,8 matter of taste; there's no proof that one style is cl arly better than the 0 ers, In any event, choosing "the r~8htt style is Iss important than applyinu it consistently,

IQI: If i i' 13,D i,nt, vnrialb,lc and 'f'i,11 .1 flo,ilt, Va:_ri,. lie,,' 11,3 I bil, 'I - typ' ,"~.' th' leo '"'

diti -QaJ expr'iio, (i > 01 I' i :: f)?

A-

,~

A'"

- .".

Q'IIII

~I

A'",

J~!

'.~Q' _

l!fllf!lj,. _. ,1~1

.. ' I'

A:

When int and f Loat; zalue are mixed in ,8 conditional expressien, as they are here the expres ion I type fl,oat., If i > (] i true .. the value :~-'tbe expression will b _ the value of.i after conversion to float type .

. hy d ,eJ;n ,,_ C99' lui, 'e a' ett~lr name fOJ' it: Baol,elln t -e,t,~ [PI'~1 ,8~]

_B,ocI isn't ,3 cry elegant nam ~ is if? Mor _ common name", uch III ,b,o'ol or bOnole,an~ weren' ,'ho' en becaus existi 11 C programs might aine'mdy define these names, caus ing older code not to c. mpile,

10K I ,so b'" D'Wda;t the name _Ba'e'l br __ ' ... ~ old,er program a. "~ 'll?

The C89 standard specifics that na1116' , beginning with . n unde score followed by an uppercase letter are reserved for future use and shoukl nol b used by program .. mers,

The template ,m¥'en nr thswi, te"h, ' .. ': ,teo' eD't ,d,esibed i'i as 'the ,,1, ost eomI 1011 If arm " ' .' ,- ,-' there 0 b, r :- H' ,,? [p, IS,,]

'The srw'i t ch statement is a bit mor-e~I_!CT~d than described in this chapter, although thedescriptir n given here is general enough fer virtually ,all programs. For example a swi tch statement can contain labels tbat aren't preceded by Lbe word c,a,se" 'which leads -,0 an amusing (1) trap, Suppose that v e accidentally mis,"pleU the word def au Lt.:

·t h I ) {.'

,SW11'~'- \ , •••

}

The compiler may nor detect the error since it as umes that de fua I t i-, an ordi .. nary label,

I've I een ',ve'ral met lod ' oif 01 Ide' ti -; tlu s'witlch Ist-I'te'ment., Wlucb be' .. t'1

.A: There 1M;' ,al least two Clomm'D methods. IOn e is ~o put J'le statemen S in each c,ase lift~". the case label:

D,Y II

switch (coin) {

case 1: p,ri-ntf( IICen,tmm) ~ break;

ca,se 5: pr'i'n"tf ( ,1"Nick,elll )1 ;

b1reak;

caae 10: px i.nt.f (uDime" } i br'eak;

case 25: prrintf (ru"Quarter II.) ; bzeak ,

}

If . ch c -Ie consi _' of;' jueJ a . I 3. call Ol_ printf. in this example '(be b,re:ak statementcould . "-0 go' n the same nne" '. the action:

ewi en (cod.n) {

case 1: p~intf("CeDt~) i break; c:asle 5.~ printf I{ U J .l.,ckelll )1; b,r'e,ak;

.... a ge 10' " - L: t - r ill D- '1.'" me 1111). ~ b~"'e"~k ~

I,.,.,' .' :Q' r I, : pr _ D" I~ J.." ,,;L' IliA. - "

case :2 5: printf I( '~Oruart:.ern ); br1eak i

}

Th other method -m, 'to put the statements under th I ~a~e label, jndenting the' r to make th ,:,cLbl'ut

s,'w'i tlc,h I~ CIOin ') { case 1:

prin-tf r( 'II Cen t ~I , ,;'

break;'

'case 51:

printf ( IlINickel") ;

b -'e,ak;

cane 10 =

plrintf ( !"IDime U)I ;

bre,ak;

case: 25:

printf ( uQuarterU) ; break;

}

In on .variationof this chem .. ach case Iabel is alignedunder the 1l~ s,witch,.

The firs method i fin . hen Lb state men - in ea n I.~ -'- - e all -hi .- 'I L and th 're

are relati ' ly " w of th ~ rn, - he . nd m th ld ~ I. ne , r Jar 1_ I swi t.ch sts e-

ment in-' hi b tbe statement in each cas are complex nd/ornumerou .

1.. The fon 'in_ pfl sram rr~lgnl"l illu I ate the relational ',' d e qu_ Ul' outpull- . Ll~ db, · .'11 i1'" nuning that L, j ~I and k ,ate' in,t, ariabl .

I(ia) i :: .2;: j =. J;.

k ~ 1. '* j =~ 6; printf (U %d II I' k)1

(b i _, 5 ,; j = 10; k_ ::: 1; p'rintf(m'%,du~. k ::> i -c. j) i

~_)I .; ~ 3'· ]. - "'1lij ,_.. ,_ 1,·

!j,. ..b - _ If - ~,t n.. _. "

printf ('II %"d~', i < j == j -e k);

(~ i = 3; j = ~,. k = 5

prin,t'f ( H %d!"', i % J ~!- i 0(' k):

- the

"he fun - ina - ~ro ram rr m D'I' illu "I'I-~ lh·· Ab rt ... : j.., uit beha ior f II' gilL: ' I . ore Show the output pmdu db, each a .. urning tha ,i j, 1110 karl tnt' riables,

(a) i ~ J r j -- 4; k = S;

pr in t ( u ld ", i < j I t j <: k) ; pr.intf " III %:d td! 'tdmt,~ i ,j I k):

b) i == 7; j = 8; k = 9 i

printf(·'d ~, i - 7 &. j + c k), p,rintf ( 'II t.d td ~,d II ~ iii j I kJ;

( ) i = 7; j = B; k =- 9~

pr in t f ( II %d II ,f ( i - j)1 I II (j = k)) ;

prin tf ( II' %:d %Id %d 1,1, L, jl" k)I;'

d 1 i= 1; j = 1;' k :;:;, 1;:

prin t. f I( fl %d U ~ , - - i ~ I ++ j & + -, k) f

prin,tf (~, %,d%d %dl'~ 1 i, j, k_) I;

94 Ch',apter 5 Belection Statements

2~ The full .ing pr', gram . ragrnent illui _ ate the l ;gi al P raters. Sbo the· '0.' put pt due d by leach _'" uming that i j '. and k an mt v,· ri,~bl ' ..

hi) i = 10 i j ~ 5;

p,r.1:nrr ( U %d I"i, J, i <. j) I

I(b f ~ ,2 ,;' j == 1;

print'f (U%d,'·, 1 ~ i . !j) I

i ; s~ j = 0; k = -5: prin.tf ( ~"%d, iii, i ~& j ~. I k);' d, i ~ :t; j = .2; k ~ 3;:

pr in tf I( III %,d II t i < j I II }tJ I)

I" the ~oUOi\-'Yjn, if 'nlle.ment I ,t';.I.: if (0 ,= 1 c= 10)

pr1n'tf (N1a is hetween 1 and 10\;, m~), ;

If so, what do· H do Wb,D n i equal t· to'?

., 1 *1- ~ 1· tbe foUo: in ~ f . tatemeut lie all

7. 'Wb'~lt de" the . II, value -11l1'

pr,l.ntf (u td\nUl,

*~

.]' ...

*4

_ i(

*'

, .

- rile a 'i,ogil- - -, pr,. -j 'D who,' . alue i . either -L 0,1' r -+ t dep endi ng 01] whether i Is I ' .

LbfU'L. 11-' a~ to, or greater 'rhan j, respi :cti- ,ely.

if' (n ec 110)

pr~ntf (lin is be ween 1 and 10\nll J ;

]1"':'0, what does 11 do when n l equaJ to . '.

h print jJ i 11" '., dl-

. t Lemen' rint if i ha the - -aJu . 11 .

>= 10 '? i :

i) ·

- l!'

8. The fonowing i f statement Is unneces 'arily ciomlpUcatJ d, SimpHJ"!t h much as pes ible

Hlnt: The entire loa em rn an re l ced by . .single -,1i!Rm en ~.

if (age >~ 13.)

if (ag'e <:;;;;. 19')1

te'enag,er - true,

e Lae

teenager - false; else if [age < 13) teenager = false;

Are the fellowlng if statements Icq i' ah 0'(",

n t wb-' n f'

'-

if' ( ,Be,ore' >= 51 0' ) pz Lnt.f ( IIAIII!)r ;'

else 1f (score >= 80) printf ( U EII'~ ') J

else if (score ~= 70) p'r i,n,tf { IIIII c I') i

else if (score >= 60) printf (I~DII) ;

els,e

p'r intf ( II' F''II ) ;

i~f I{ SClore < 6' 0 J prl.D.'tf {u'Fml} ;

else ~f (score c 70) p:rint...f' { m~D jl) ,;

else if (score <: BO) ]printf (III au ) ;

else if (score ~ 90) printf ,,"B 'I ,) ~

else

p'rint f ( IIA 111)1 :

.*,_01. What output does the following program fragment produce?' (- ssume that i j an integer variable.)

JIj

1. ~, 1;

s'witch (1 %: 3)1 (

case Ol'~ printf (iii z,ero") ; eaae 1: p,rintf ( II'a,n,elllll)1 ;

case 2: print:! ( II two III 1 ;

}

'~ 1,. 'he following 'labIle ShrrJI\¥~,' telephon area code ,~- In the ,tat' 1,-' Geon ia all 'R,o ' i b the larg-

est city in 1- ach area ~

A,fa code; 229 404 4701 478: '678 706 762 770 1'12

Mo,j(Jr ellY Albany Atlanta Atlanta

, a OJ]

Atlanta Columbus Colum us Atlanta 8.,3:, , nnah

Write a ISlwitch tatement who, l(;ontnoUmg expres ion l the vadabille atre,a~crOd"e. If the value of axea _ code i:, in the tabl tit switch tat m nl win print the' corre ·panding city Dame. Otherwise, the awi t.ch sun, ,m, f~.IL will display the me Tag, 'IIArea code n-ot re"co'gni z ad ''. Use the technique dis __: uss d ill Slecdon5 3 'IDo make the swi tch sta ... m, nt,", imple _ I possible.

I. Wri'le a program that calculates how many digits ill number contain 'I':

E:nter a numbez : 374

The number 374 bas, 3 dilg'il's

, ou may as UIDe th t the nu mber ba no mute lbarn four dlai ~ 'ii Hiiu: U ' I if, a ,'. meat t

,t est the number, For example, i 01' umb . r is between 0 and . it h '" I n digit, II the .number is between mo and '99 h has 'two di j~ '.

WrJt,_ a program that ask I ~l U·' r for a 24-h, ur time I then dl 'p~uy~ the time in n2-bOLIT

·nn.

Ent'e'x a ,24-hour timl9: 2,1 ~11 Equiva.lent 12-=hour time:: .9:1l PM

Be earelu 1 tun to dL pia l I :00 ,it

3.. ill rJi'_ 11 broker '. C program of I ection 5,~2. h, mukin - both of the ~ 11,

(a) sk the U8{ r to enter [be number of 1 har-es and nh pnce per share .. lnstead of th' value . the Lr1: de.

Il -)~dd latem, nu that compuu the commission charged c. a ri' ,B.I bro r ($3 plus ' per share for fC\¥1 r than 20nU·ba~ est $3 II plus 21~ per I' hare rorOO shares Or~ more) .. DisIlia' III ri al " comrni: t [on ,a.. \l ell a the '(J ommi sion char j b i the rigi n 1 broker;

..

Speed (kH t.) Less than I 1-

4-,_7

:!&=41 · 8-63

,,' iove 1,;]3

,(tSI 'ripl'ifJl'l alm

Lisht au

.._..'

Breez

IGale

I , I~I, 'I1"'1"II"'I _ L " .111,1;

Hurric ne

- Til . u program rh u ask tb I .'" [0 . n r . wind 'p. d ill knot ,)~ then III pla " the cnrre-

non in ~ d icription

, "n,tJunt.o.l tax

. 1750 1 fI~ r mcom '.

Il . . '1 ~I pi 'I _1% ' amount

1'37,50 pl u _ % of' aruau nt over, 'I ~SO

$82. ';0 :Iu. -,~ ul amount' ver .'1,75Q

'"1142.50 plu 5· 01 amount over,' , '::!,_IO.IOO plu 6'% Dr m lull 0' er7 ~OOO

rite a prn zram th ( a ' ~.' Ilh, U·. r I, . ent he amount if taxabl. in orne, Ih en dm pla ... '. the

Li;l- du I.

I I

I

upc ~ C progr un ,,""e= ti :0 4..1 Sf' that it It:b t.:k wh nher a - CI i tlid,

. P 't th . pr gram will r j "lpLay . ith r VALID or NOT VAL 1:D:.

7. - rite (1 pr gram tal !10d1 the largest an mall ,:"11 f four im ';;_r mered by the user:

Enter £our intege':r:ra ,:21 43 10 351 Llargl@,s: 43

IS~nal1e6t ~ 10

U _ if as f "~ if.: I ; temenn ,IS POI iible. Hint: Four if ','tal, menti are sufficlcnt.

Deparutn time " ':00 a.m, (:43 a.rn,

I : It . . 12:47 p.m,

I' r"it 0,1 rim .. [0: III a.rn, u !52 a.m.

I =_ J 1_ .D1", 3:00 p.m~

A, "7 Ii

-:0,8 p .. ITIl. 5: ss p.m,

9" ", TI m

,,~ _r" '"

I, ] :;, _: ,I p.m,

Writ· a program tb~t asks us" r til enter ~ rim (expre· ' .. ed in 110m.· and minute .~ u .·ing the 24- hour clo ,,_). he program then dl pla I I the 11_ pa ure nd urival tim -', 10r lh. Iliaht 'wbo" :' departure '_ ime is '. I, est 11'1 that entered b lh ILt·-, r:

Ent:.er at -2 I: -Irour- _tim,~ ~ .tl ~ 1,5

(~llose,st dep,ariure, t~me i,s l2:_,,7 p .. m .. " arriving at ],:00 p.,m ..

Hi'''r,~ .'. I nvert the lnput inu a time :' xpre sed ill] minutes sine ~ midaiaht, and cmpar _, it t . the departure time ,p-Il- ., ecJ in minute .... sin .. - midnigh r, or example, 1.- ::,] ~ L,. ] 3 X I' 01 + ] 51 == 79~ minute: . inc ~ midni ht WID h ~, _lo .. _r to m ,...::47' p,.m' 1'7 minute In midni ~'hU (barn to any u~ the other departure ime '.

tite a pn gt-. m that prompts the user to enter I t11 date, and then Indicate whi -'b date come s earlier . n th - i I dar:

Enter fir~t dat;e (mm/dd/yy): 3/6/08 Enter second date (mm/ldd/yy),: 5/11/07 .5/11'/07 is ear1ier than 3/6/0,B

10.. U·.,ing th - s'witch taletnenL --r'i'l a pr ]l,~ .~ rn tha con er . '_ namerj at ,at, in I a letter grade:

Enter numez i ca.L gra,de: 8,4

~

Let tez 'gra,de ,: B

U the' ollowing grading sc Ie: . = 90=100, B -:' I 0-;'.'· I = 10-7'9, DI--0--6,9 P = 0··-5' '., Print an emn messase 1 lh_. grad W' larger than )1 0 or ~~. s ' han 0,. HI",.· 1·I'eal. the gr " int ,t'NO digits, then u e a sr'wi tch sratement [0 te ,t the ten diait,

ll. "" rit a programthat asks the user fOr ,I two ... digi number, then piJi,nt. the l nali -111 word for

Lb - number:

'Enter a two-digit nurnbez; 4S

You ente.redthe numce r fo,r y ... f1v,e.,

Hhu: Bre kli e _ umbe r int .. r 01 dbjl I. '. e or e s -i tcb t ~temeD' to p - t ihe .,' rd (01- 'b.' fir ~ digit I( '[w~nty,~' ·"tbirty " and SOl forth). , 'Sf! U second swi . ch ~ - '(,e:mnl rlu print the word or the , nd _ i it, 0 fi '_ -I rge thai u numbers between I ~ and 1 r[~. uj]i_ . p. ·ial 'treatment.

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->