Download as pdf or txt
Download as pdf or txt
You are on page 1of 22

Or_

"n

As Will Ra,g'e~s' would ha~e said. '7rh'e,l'te Is "ID such thing ISS IS frrsle varieb~,,~ 'I

I-Ia- ina. C I I. cr.-d function I in h,~' pl_ r \ e - ~ r _ .r y to 'e _ nfront everal issues that aris . wtu n pr gram _nntaill more than, e fun -j. n. 1]18 chapter be ins with a

di <'.' _ ·i n of the dl erence , I. - .= ='0 1_ .a1 ' aria bl I S' -I'~ on J 01,.,1 ) , , ,- d extern .

. ariable Section] 0.2. ,.,~: eetion I O~ ~ lben· liD ide .... I bl ck c mr . nnd. statements con nining del, -l rati ns . S, ' 'ion 11,,, t ~I' 'e, he s ~'OP1- ru] . th,~_ t appl to I cal names, .' t, mal names and names d clared in blocks, Fmally'~~llection 10,.5 . U:' _, , .~. ,( a WI',' 'j I ~._ ani e fun _-til' - pr')to',' p " funeti n defimtions -'arm. hle d .. tara ... ti -D': an the oth ~r pan'. f a .. ' rogr m.

ana' l decl ired in Ute be d f func ion i I " c: id ' 0 be ,local' ; Lb, unction,

the foHowi-ng unction. aum j a local varit

. t d I'· t· t )

l.D sum _' J.9 1. t.s '.l.n·~' n

{

int sum ~ 0;'

1* local va~iable *1

whille (n >, 0) { sum += ri t 10; n 1= 1.0;

ret.u.rn sumr

}

2'19

y defaul local 'ariable, h . e tb follo in~ pr pertie ,,:

• 'uio", 'tlU: !I , " llgfl Itill ntlon. The I ,to -Jtl.Il' ,,' - ratis _ I ' r 11/ __ . '_lItl! a", riab lie i ' rh " portion of program execution during -- hich I rage ~' r til[ , variahle.e ~L rs, '" ~ rage tor , II . oJ' ri ble L "- utome ii' all,' all' .ate d ' h n the, '",_1[0,i ns

unction is called and deall cate hen the function returns sc the variable i

laid L h [' - IfJlltumati[_ sto,rag,6 i o,.fion, . '" 10 ,.' aru bl ~' [I n t retain " "

alue whs fI it,'! enclosing fun non return -,. When e Iuncti l1 is called again there' no guarantee fh~ t the variable " ill I. till ha . it: . I value,

I. is the _ onion I'· thl -:r' gr m text in

[ '" nl varia rle 11 - "I b -ock l'lcop,el,; it i

I om L, pint of ,"1 ui I the en 0 tb, encf sing function

body, Since the ,;'cope of ' __ loc - ariable doesn 'l extend beyond the function

, which it belongs other '·unci,' Chi sam name 'or other pur-

",~, . 'til n 1" .. " iove I"~ the e ; in m "', d etail,

."iDlc'e C ,I d iesn "t requ ire vs ri ble I leclar (on' £0 come all tile beginning of ~, un tion, if I po sible _' r a local vari bl [I hav -, verv small ',C, p' In th foll , ing e rample, lh scope 1_ i _' ,e ,n _ b - in un il th - lin ,'11 which if : dec 1 are ,_I , 'rub could -, e 01 ar the lend of the function lv:

void f (vo-id~'

{

LIlli.

int

}

u tin ~ th - ,rlid stat i c in - I .larati ,n I, - ,c j -_ 'art, I Ie ause it to b' .-

staue {t'tOFtRgfJ' Ilr,,·.' ·'01) .- stead of automatic lora, e duration. variable with

I,tal~ ~, ," or' ,I:_ duration hi s u oerm In nt 51 ra I locu ion ,'0 it retuim i, "" U fur u.. hout the executlonof th -pr gram, " am lder the following functi. n:

VOId f(V01d)

{

1* at.a ic Locaf ariable I

}

inee. the local '1" triabl i hs ieen t , "I· ed at.at Lc. it occupies he '_,_I, mmor)! lcention throughout the Ie " ," ution if lbl progn l1. " ben f ,r\ .nrn " on "t los H -_ nlu· '.

, tatic Iccal variable t tiU has block sc ip'~:O i,'t' ~ not visibh tor oth ~r funcion ~~ In a nut hell '_ '_ .ti_ ~_ ; I' 1_' " " I_I pi 0 I bid! data [rom til r fun ction UI r tain it for future c .no' of the t un func tion ..

Parame .ers

Parameters have the same properties-c-autornatic .[lorage duration-and block scope as local varlables. In fact, the only real difference between parameters and local variables is that each parameter l~~ initialized auromatically when a function is called: (by being assigned the value of me corresponding argument),

Passing argument 'is one w,ay to transmit information Ito ~. function. Functions can also communicate through 'Ixt"flIRI ';Rri4'b',"e;'i~~varimbhes that are declared u tside the body of any function,

111t pro pie rti es n'f external variables (or global 'f,Q',ialj,les, as 'lhey!re sometimes called) are different from those of local variables:

• Stutic' Itolr~Qlle dU"tlrio"il .. External variables have static storage duration, Ju t like local variables that have been declared at.at Lc. A v\alue stored in at] external 'Variable' 'will stay [here' indefinitely .

• File scope~ An ex ternal variable has,/i'le .!flCflP6,o"' H is vi iible from its point of declaration 'to [be clod of the enclos ing file. As a result, an external variable can be accessed (and potentially modifiedl y al I function , th,Jt follow j."'. deeIaration.

Example: USing External Variables to 1n1P, ement a Stack

To illustrate how external variables miaht be used, ler' look at a data structure

-

k..nown a! a. Itu,ckj (Stuck. are an abstract C'lonC'ept~ not a C leature: (hey can be

implemented in most programming languages." A stack, like an BIT,ay., can store multiple data items of the same 'type. However, tile operatione on a stack are tirnired; we C~Ul either pi !,ll,an item ion, 0, the ... tack "add it to one eud-s-rhe "stack top") . T P'lo.P lit from the stack (remove ·iIl from Ute same lend). Bxamining or 'rna ify· ng an

item that ~I not a.t the top of the stack is forbidden"

One w~y 0' implemem a stack in C '~ .. t 'lore H.~ items in 1M array, wb-ich we'll call corrt.errt.a. A separate integer variable named 'cop marks the position ofthe stack Lop. When the stack is empty, top ha the value O. Jib posh. an item IOn the tack we simplystore tile item in contents ar the position indicated by top," then inCl"enlenl t.cp, plop.ping an 1 em requires decrlementi'ngtop (hen u 'in,g 'i~ as iCtD index into cont ent.s to fetchthe item thaf s being popped,

BI,. '. ed on. this outline. bere 's a program fn gment I( not ,I complete program) that declares the eonbent.s and top variables for " stack and, provides a set of functions that represent operatiom I on the stack, AJJ five functions need access to the t.op variable ... and two functions need access ro ccmt.eri t.a, SiC.!1 we: U make oont.ent s and top, external,

#define STACK_SIZE ~oa

/ * ext.ezna I var'iab 1 e,s .. I tnt d~ontents [STAICK SIZE] :

inlt t.op = 0 i

voLd makle_empty (void)

-{

}-

top = 0;

re:turn top == 0;

boo I

{

}

voia puah (int ,i)

{

if (is full ( ) )1 St,;2,C,k. o,'v,erflo'w (,) ,;' e l.ae

cont ent s [t,op++] = i;

}

inl:: PlOP (vS'i,d,)

{

if (i9, lempty(») r~rtack un.derflclw () ;

ret'llICn contents [- -'top] ;

}

Pros and Cons, of External Vari,ables

Ext mal variables are convenient when ,many functions must share a variable or when a f~' functions share a large number of variables. In most cases, however; it's b-etter I functions 'to communicate rhronghparameten rath r than bl)' sharing variables, Here's why':

• If·, Ie change an ~ xrernal variabh during program m 'irdenance (by altering it! type, say) ,we:1 'I] need t.IOt check e'VIf!'11' function in the' same file' to see how the change affects it,

223,~

l ,".'

• If an e temal variable is D", i~ed an mcerrect value, it m,B,)' be d'ifB,cuJl "0 identify the guilty f-UDJCtiOD,. 1(!', like trying to solve a murder committed at it crowded parly~tbere' "'~ no easy w,sY to narrow 'the Iist of . .0 spects,

'. Function" that rely on e rternal v ali , bles are hard [0 reuse ill otherprograms. A function tha:t depend OIl external variable iSD t self-comained; to reuse tbe fU1IC tJ on .. , 'Wit 'Il have to drag along any external variables that 'it need .,

,,', any C programme rs rely fat' teo much Ion external variables, ODe common abuse: using the s,am, , extemal variable 'or different pUrpO:SCI in different funclions. Suppose that I, everal fUDCOO'IlS, need a variable named i to control a for' statement Instead of declaring i in ea ~b function that us es it, some programmers declare i~ at 'the "top of 'the P[IQg:[aJD., thereby making the variable vi,' dble to all func'tio'- .'" This practice is poor not only for the reasons lis led earlier, bUI~ also, because It s misleading: someone reading theprogram later ~m,a:! ' think, that the use of the variable are related, when in fact rtbreY'lle' not.

When YOLl use e rernal variables, make slum tbley have meaningful names, (Local variables don't always Diced meaningful names: jtt~. often hard '~Q think fa better name than i for the control variable in II -for JOOp~)1 If you find yourself using names, like i and temp for external variables, Lb!' t' " il clue that perhaps they should really be. local variables,

Making variables esternal I ben they , .. ho Id be ]IOCal C'!IO Jead to some rath,er frustrating bugs, Consider We ~oJowin.g ex:amp[,e~ which is ~upp'os,ed to clispl~~' a ] 0 x "10 arrangernentof asterisks:

.int i,;

vod d print onerC)w (void)

( -.-

for (~ ~ 1; i c= 10; i++' pr 1 nt; f ( II * ~r) ~

}

voa d px'int~all~rows (void)

'f

for {i :: 1; i <~ 10; i++} {

print one row() ;

~ iiiiiiiiioE

printf (1111\nl'I!) ;'

}

Instead of printing lO! rows, print ........ all_...row;s prints only one row. When print_on,e ....... ,ro'w return after being called the first time, i, will have the value I I I The for tatement in, plrint_,al1~.r'o'w'stbeD: increments i an. tests whether it's less than or equal tc I 0" It's not so, the loopterminates and the function return .. ~

224 Chapter '10 Prag'ram Q'rg:anizatlon

To gel In ore experience with external variables. we'"U 'write ,8 simple game ... playing program, The program generates 8 random number between I and r OO~ which the user attempts to! gue .. 5 'ill as few tries ,lt~, posaible, Here's what the user will . ee when the program is roo:'

A new Dumber has been chosen 'I Ent.er g.u,ess: 5S

:To,c lO'N;' tr-y' ag·a.in. Ent,er q,1..l€S,s:: 651

Too high; try agiain. Ent,ex guess: 60

Too high; try ·ag'ain. Enter g'uesB: 59,

You w'on in 4 gu!essee!

Pla~y an~·l..~n? (Y'~/'N' v

- - " '::::J'~ --"_' ~I - . J L

A newnumbJer llG(ls, bB'~n ehoaen ,. &nte'r guess,~. 78

~oo high; try again. Enter g'u,e,ss i 34

y,ou W'OD in2 guesB.e;s,~

Play aga~n? (yiN) g

This, program will need to carry out several different tasks: iniLiaUzJn,g the f,8J1- dom number generator; choosing a secret number, and interacting with the 8ge,r umil the correct number is picked. U" we write a separate function to handle e;u)ch task we might end up with the following program,

#in61ude <stdio~h> linalude cstdlih.h> #in,clUdllt! <t.ime.h;,

Mdl f" - '&111" 'V kn,"oIn'ED .'1' ~ 0

ff,'" e'~ ~ne J.'I'~ L" UJ'!!,a,Ll), ~ lUI

1* external variable */ int. -a,ecr,et_number;

1* prot'ot'YPea * I

void initia~iZ'e_nu'mber_g·enlera.\tQr (void) i

void choose new s,e'C:r'et nUlnhe.r (voi,d) r

- - -

-vo Ld r',sad,_gu.eSiH3€S (vo,i,d) ;

i"ntma,in (voi.dJ

{

c ha r command;'

prin'tf (~I!Gues,s t.he s,e!cret Du1Tlher 'b,etw'le1en 1, and \d,., \n,\n~I'" JI4AX NTIM<BER) ;

~ .

initializ's_numb@l"=.9,enerator();

do {

choose new ,secret numhex () ~

~ ~ -

printf (I'IIA new nun1.ber has been .ehoaen , \nll~) ~'

read gu,e;sses () ;'

_I

printf ,(: IIIPlay ,ag'ain? (Y'/N') m~I);'

acanf (ill 'C 'II ~ &comm'and)l;

pL-intf ( Ii \nlill) ;

} w'hile (,co'mmand,:= 1'1',11 III cc'mmand

I yt ') ;

retu.m 0 l'

1** *** it .'k'k*,*'**!It '* t., '* ".* 'It'it * * ** *' **'*,. * 1( ':It **, ,it 'iIr. '. * 'k,ft '* . * 'I: * *1t***+k' •• ' *

T' initialize nu'm.ber ge-ne~ator: rnit ializes the zandom lit

~ .........

_,k I.

nUULUer gener,at.or uSlng

t~l:ime of day.

**. '***.*.***** *.**.* *-Ir ******** :l:lhtldll" **,,, '"Ill *'*. ,i:".".1

voi'd in! tializlez-. nu,mbe:r_gener.a tor (v,oid,J

{

s rand ('(unsi,gn:ed) time (NULL) ) ;

}

I*******·******·***~**************·***~~~·*~***·****·*****~ ok c"1~ilDose n,~w secret numbler ': "Randomly selE!c' s a riumbe r *. * betwe,en 1 and MAX NUMBER and i:'

store,s it Ln se"cre't number, .

••• *.* •••• **** .• **.** •• ~** •• ** •• ~.*.*~ •• ***.*.**~* •• *******1 voi:d cho'ose_new_secret_number ('-v;oi,d)

{

}

/****** **.** •• *** ••• ***~*************.**.~**.~************ * zead guesses:~ R,epe,at,edl.y re,ad,suaer guesBles and, tell,s '*

_.

*th,e UBer whe'the..r ea.ch gu,esa i9: ta,a low," :t, t.oo b': eh ~V' r"i '0· r"'il'"',e· ~ t 'r.Th· ·en·· '. .~ he 'g. -" oj leiL!i~i '" el '*

~". ~ Ji.L..~ "~I Ll!.Il.. ~. ..L:;. ~J •• 111 "_ t, "--I _I!L;IiIi '_,.I~. ~.~ .....d-.~

'* corr,ect J prints the t.ot a.l, number' of *

'*' 91:iu:!'ssea and returns ;; •

***.***+*~********~*.*****.*****.****.********************/

v,oid read guef;ses (v!oi.d)

{ -

int 'gue,r:u~ I num_. guess,es= (];

for <; ,;)0 {

num guess:,12s+ -I- ;

~

printf (mq~nter gUles,s: II);

acanf ( ~!I fod i1' Ii &gurea B ')1 ;

if (,guess =-~ EU3C,ret_numberl {

p:rintf (llyou won in %,d guesEh9s:! \n\nll IW n.um_gueSS9S) ,i re·tllrn~

} e Lse if {guess -< aecret numcez l

p'rint-f I~ II~ T'DO lo'w i t!IC'Y Ei'gai..n ~ \n II ) i e.ls~

:pr,in,t.f (1'~T'O,o hilgh; t:ry aga,in .. \n~ ) ,~

}

)

·t if:DlU~ ~1~l'flCn0f1 )J.,,2§ .. 9 For random number generation, the gu,le S 51 " c program relle on the t Lme ~1

,sraud ~]Jnclion.26 .. 2 s rand, and ra,nd functions, which we first used in dea L " 12 (Section 8,,,2)., 'This, rand ~'nJ.ndion __ ,SS;2J time, we're s,caH~[]:g the return value of ra.nd so that 11 fails between Wand, MAX ,mrMBER'1

Although gue s IS .,e works fine, it relies on an external van. abl e. We wade ,se·,cret number' external 0 that both chooae new' secret. number and

_- _' '-, -

r,ea'd_guB:ss,e:s could access it. If we alter chooa,e_ne:w_' secret_numb'le:r

and res,d guess,es, ~ust a lirue'l we I~h\ou]d be able l1Q move aecret+ number

,-- ~ -

into the main function, Wc"'ll modify 'ChIOIO·I~e. -=-- new~sHE!C!ret~nulflber so

that it returns the new number, and we'Il rewrite read~gu,essles ;01 that se!cret number can, be' p. assed to it as, ;W1 a_r!:ument

_ I 1!Ii.E"

Here's our new program, with changes in bul,d:

#i.nC'l nne -c stdi,o ~ b> 'include <stdlib '. h':;" #in,clude <,tim.e."h:>

t= protoltype,s, */

vO'id initial i,:;.'te numb'efr_'gener'(id:'Cll: (vloid) ,; i,n,1:, Daiw~Bec,r:et,~D'ilil'nbar (void) ;

vod.d r,e,ad_. 'guess,es (i.B,it. B:,ecret~,Du:mber);

in,tmain (voi,d)'

{

cha.r ,c.ommand if

int 8'I!Cr'E!·t D'lI"Qjb,sr ,if

...... -

printf (mwGuessr t.he secrer.:.numbe'r between 1 and %d. \n\n~1 f IVIAX_NUMIfER) ;

initialize numloe-r ,gene.rat'or () ;

Id,Q { -- --

s:ecret nUlllb,er =' 'DeW sec'r'Bot Dumber (:) ,~.

- ,--

pl,rint'f ( 11'1 A new numbar haa been chosen i \0 mil]1 i

r,ead_guesses (s:ec:ret_D'Dmblsr) "

p'rintf ( II Pl,ay again? (Y IN') I~I)I;'

acanf (III %'JC'~II I ,&coimm,an,d);

p'rintf (U\n'l," ;

} whi~E!' (c,o'mm,and ~~ ~ Y' ,II command ~I Y II) i

rerturn 0.;

}

B ~nl~'f..;rs-.c: 'UI~nl' .

I~*****~·*******~*~****·····*·***-··**·*·**·w*~*~****.*****

'ok ini tialize_DtllT:Lhex_genIB,rat;Or: Ini'tial izes' 'the z'andom "I'

1; *

numbez gene.ratar using "the time of day.

* 1.1:

*******.** •• *~ •• *~***.**.**.*********.*** •• ********.**** /'

I'

vod.d i'nitiali,ze~n,umher~elner,ator (vloid)

{

errand, ((uDBigned) "time (NUL,L) } i

}

I '* .. '* * '* * 11-: ''k* ''It '* '* *' * it 'IIi *" '1:1t iI' *' '* * 'jiI:' 't!f. ok ~ , . *. *-* w * '* * '* -N '* *' "H' * if: *' * ... ' * 1t '* 7.l' .... W .' 'if .'

*' :new' e:lelc:r:elt number:1 .,et,urns a E"and_Dmly a'hos·eDI Dl1mhlie,:r' *

"* betw'e:en 1 ,and 'MAl[ !lDIIBBD.,~ *

~~~~~~~~~~LL~~~~~~~~~~.~~L£~_~~~~**~_~~~~~~*~ lI!IJ'~ -U!S:' ~ 'K' "':II' '!K' "" 'K ':is"",,' "ft"?* ':JIj ':1Si~' "'!'!r'"~ Z" ~ W '-P;-'1JIr ~ lI'f'_' ~"lJIf W T ,.., ~ ~, . =-]!If 'iJ.!!I' ~~; ~"'J!f ~- _', ')If'

,iIl't nSWIJ,e,c.r,e.t n'tUntuin.~ (void)

{ ~ --

,J:'leturn z'and ( ) t MAX muMBER + 1 f'

}

I**··*********·*****·~*·*****-···**~·~******·*·******* •• *** • 'r'e,ad_gues;'ses: 'Replea;l;~lldly reads uae r 'gu,9SSe!"S and tells .. if the u,~er wheth,er each 'gue-ss is, t,OO low, *

I h - .1,

* t.oo hl.g .~, or cOlrr'Eu:!'t,~ When E.he guess, l,S

* CIOZ!CII!'Ct., prillts the t.ot.a L numbez of

I: d t ~

g'ue,sses an· .l:18Ur,n,;s ji,

**** .. '**.'.**.'1t ".wit. -,,,, ** ** 1'*****'**.1; ** -1:'***'. ***,,**",,*'"t..* /

void r1ead gu-ess,eds ('i:n.t ,lIalOrStt D'llBbe:r)

(- -

il1t Iguess I num gues,ses, 0::;;:' a i

-

f,or (;;) { nu,m~gue!j"BeB++ ;

printf It 111',En.ter gu.e,e; S, :: 11)1 i

s canf ( Ii %d111i, I&gue:,s,s);

if ('gue,iHil: == selcre,t~nurrrlbiler) (

pr Lnt.f (11~Y'c:)uwon, in~ld guesses! \n.\nmt, num_, g-u.,ess,'es) ; r.e·turn,;

} el~"e if (lguleEH~~ <: sec,r,e't numllber') print·f (1i1'T'o'o .low'; try ag'ai.n '.' \nn) ,; ,else

pz Lnt.f (UT!OiQl hilgh; try again '. \n II l ;

}

}

In Section 51.2, I we encountered compound I tatement of the form ( st(Jlelne'1~ti' }

block

"I'll use tbe term b,lolc1t: La describe such ,8 compound s tatement. Here's an example ofa block:

if (i ~ j) {

1* swap values of i and j */ int tempi :; i;'

,~ ~

1 - ];

I

JI.I .-. tenro III

. ""r'

}

By default, the filurage duration of ,I variable-declared in 3. block is automatic: S,' Ofage for the variable is allecated when the block is entered and deallocated when the block is exited" The variable has block ! cope; it can't be referenced outside the block. A variable that belong. tel a block can be declared at.at Lc to give ii static storm, . e' duration.

The body of a function is a block, Blo cks are al 0 u seful i nside a ill nction body when we need variables for temporary use. In our lastexample, we needed a variable temporarily so that w,e could swap rhe values of i and j i' Putting temperacy - ariables in blocks has WOi advantage s: l) lL a voids clmtering the declarat" ons at the beginning of' the function body with variables that are U8Cld onlybrietly (~) It reduces name conflicts. In our e tarnple, the name t.emp can b used els c_~ where in the same fu:]1.ICtiOD for different purpose ·~tbe t.emp variable is e;:lricUy local to nile block in which It" declared,

,., 'C'99i allows .. ariables to he declared anywhere within a, block, just as it allows

variables to bedeclared anywhere within 18 function.

In a C program" the same identifier may have several different meaning '. C'~s, scope rules enable the programmer (and the compiler) to determine which meaning hi, relevant at a g,~'"e:1rn' point in: the program.

Here's the 11108 important scope rule: When a declaration inside ~ block names un identi fier that's already visible (because it has file scope or becau e k - s declared in an enclosing block), the new- declaration rempcrarily "hide .~~ rhe old one, and rue' identifier takes on 3 new meaning. At the end of tb block, the id~ntj"" fier regains its, old meaning,

Consider the (sornewhat extreme) example s'l the top of the next page,~ in which the identifier i has four different meanings:

'. III Declaration J ~ i is a variable with. static torage duration and file 'ICOJJ'C~;"

1* Declarat,i,on 1 'if
/11. De;c 1 ar,a t.Lon 2 *' }

,2 ;
0) ,{
'"
, r= DEH:;l_aration 4 .. I

, '~,

.1. :::::; ~ "

}

.1 10 Declaration 2 i is a param ter with block ·,cope.

· 1 1111 Declaration 3,~ i is an automaricvariahle with b~1 'c:k_ scope,

.1 In Declaration - i is also auromaric aa~t hml' block ~c' pe,

i 1~ used five times, C~'s, s,cope rules allow us to determine the m .aning of i in each case:

_ The i. = l,Q';igJllD1e.Dl refen to the parameter in Deelaration 2, not the variable in Declaration I, since Declaration 2 hide, Declaration ] ,II

• 'The i ~ IQ 'lei t refer EO the vari ab le in Declaration 3 since Declaration .3 hides Declaration 1 and Deelaration 2 ~i'i. ou of scope.

• ~_ be i ~ .3 assignment refer. to the variable in Declaration 4,c, wInch hide sDecIaration 3.

• The i = 4: assignment refersto the ariable ln Declaration 3., It can't refer '~o Declaration ·4, which is our of scope .

• TheI == 5 as ignment refers to the variable in Declaration I '.

-1 0.,5 Org,anizing a C Pr'og am

N,ow that we've seen the major elements tl~,a;t make up a C program it's tim '[0 develop a strategy or their arrangement, For DOW~, we'Il assume lth r a program

aJ ay fit into a ~ lingle file .. Cha iter ] 5.ol,o,w. h w t ' organize .3, program that': , plit over s veral file '.

I 0 far, we'v __ seen that a program may contain th - following:'

Preproce sing di ecti -Ie .sueh as #include and #define Type definitions

Declarations of external variabh 'I Function prototypes,

Function definitions

C imposes only a few rules on th order II' these item: A prl processing directiv d~ " n't take effect until the line Ion wbich it appears, A type' n 1 can t be u: ed until i' I . been d _' ned. A variable can't be 1U8e~ until it': declared, Although C i m't a pi ky about fun tions I trongly recommend that every functi n b,e defined or

(I" declared rior (0 its fir .' call. (C919 makes this a requir men' an' ay,

There ,W"IC . everal wayi 0 orgamze a program SOl that thle~, rul . are ,,' beved,

Here's one pos ibl' ordering:

#includ,e directi' #defin,e directives Typ ,- definitions

Declarations of -x' I 'mal variable '

Prl t type, for function' other than main Definition of ma i.n

Definition', I of other function

IL rnak _ sense to put #. i nc 1 ude dire ctives ,]r ,,' t-inoe tb, y bring in informati n

, ' at wil] likJ ly be n ed d in I" ~ ral pl 1(", within the pr gra . #def Lne direc ...

tives create macros which Brie '_ en rally used throughout the pl., gram. Puttin typd finitions a "love the declarations of exte rnal variables is ]1: gical, sin' e the declaralions of th sc V'J iable may refer to the type names Just defined. Declaring ext rna] variable next make them available .' all the functions that follow, ·',ec~,a:rill,n aU functions exc ~ pt for main avoids the problem th l arise w.h n ,£1 fum tion i called before th compiler has seen its prototype, This eractice al Or make, it possi-

hle to arrange th _ un tion ' .• efinitions in any ord ~r what' I. '-'. el': alphabetically by

unction name If with related function, grouped together, for example. Definina main before tbe other unction make' it: asier for a reader u locate th pf-~O-' gr,Wll ~ S starting point,

A final suggestion: reced each function definition b a bo: ed comment th:·_ 't I~ves the name of 'th, fun - tion .. exph jn.. it- purpo e, di ,CUI ses the meaning of leal fu pan meter describes it return v, Ju·· . if any) and n sts any . ide effects it bar- uch as modifying eli. mal ariables),

To show 11 :w a C program might be organiz d, let's attempt a programthat's a littile more complex than our previous example c. _ he program will read and clas ify

"0 .. 5 Org:a,nizing a C Progra.,m 231

a poker hand, Each card in rhe hand will have both 3 sult ( 'lubsL' diamonds, heart ", or spades,. and a rank (two.jhree, four [I've .. iix, seven, eight nine, ten, jack, qu '0. king, or ace), We won't allow 'the use of jokers .. and we'll assume that aces rule. high, "heprogram will read a hand of five .. :.u-d, . then C),f.lssL(y [bl hane milo one 101' the following categories (listed in order from best to, W'Of t):

stralght flush (both a straisht and 3 flush) four-of-a-kind (four cards; 0_ the . arne rank) full house (a three-of ... a-kind and a p,air) flush (five cards of the I, arne suit)

s'[raigbl (five cards 'with consecutive ranks ) three-of -a-kl nd (three card of the' same rank)' two pairs

pair (two cardsof the same rank) high card (any other h,and)

If a hand falls into two or more categories the program will cboo iethe be [one.

For input purposes, we'l1 ~brbrevia[,e ranks and suit- a" follows (letters may be' either upper- ,or lower-case):

Ranks: :2 3 4· .5 6 7 8 9 t j q k a Suits: c d h 8,

If the user enters an illegal c'ard or tries to enter the " ame IC'8Jid tw ice, the p10:8r8J11 will ignore the card, 'issue an error m ssage, and l11en request another card, Entering the number a instead IOf ,I card win cause the program 'to terminate.

A .' SSiODWitlJ, the program will have the following appearance:

Ente.r a card ~ ,2--s En,te-"'" IQ card: 8s Enter ,e, card: 4,9 En te.r a a,ar'd;: :3 sEnter a ca,rd~, b,s

~

Straight flush

En,ter a ea.rd: lie

Enter a card~ as

Enter a card:: :Bc Duplica.te card,f' ig,nore"d,~. En'ter a ca_r,d ~ "l«:

Enter a card: ad

-

Enter a card:' 3h

Plair

Ent'er a cardl:' 169 E1Tt"er acarid: d2 B,ad card; igno'r,e·d ... Ent"e.r a car,a: 2d Enter ,a c'ardl~: sc Ent.'Br ,a ea~rd= 4h Enter a ,card:: tEl:

Erigh c·a~l-d

From this descrip jon of 'the program we see that it has three tasks:

Read a hand of five cards.

Analyze the hand for pairs, straights and so forth. Print theclassification of the hand,

We. 1] dividJe the program into three funcfiO'l1.·-read_lcarda, analyze_han,a" and 'p:r.·int,_rlesult~tl1,a't perform these three tasks.ma i.n doc .. nothing but call these functions inside an. endless loop, The functions "MHl need 'to share a fairly large amount of information, so we' U have them communicate through external variables, re,ad cards wil] ,tOJ~ informadon about the hand into several external variables, analy,z@:_hand will then examine these variablesstoring it findings into other external variable for the bene ~ 0-( plr in t.~ resul!:.",

B,8S~d onthis preliminary design, we can begin 1(0' ketch [1:0 outline of 'be pro= gram:

1* prototypes *1

'\lo,i-d, reald cards, (vl()id) i

......... -

void anaIyzE!:_. hand ('v'o,ild) ;

void pr~nt,_,resul t (voilcU ,~

I*******·****·~*·***···********·****··********************'* main:: ,calls r!ead=c::ard:s[" anialY"z>e_hand, .and prinl:_r,esul.t:. " "* r- ~-p. ·~'·~tr~d' Iy" '*

-.~' -!'CaL' ~ .. _. _. __ ' !!

******************.~*.-***,***.*** ••• * ••• ***.******.******1

. . ·t . i { "' d-" a.nt ma n.VOl.··i

{

fen:,' (;;- JI {

rea.,d~icards () ;' analy'ze hand ,{)I ,~

, ~

print ...... ,r,esult ()I ;

]

}

I 'it **'***'J!f'k:w',***,****'it.lt*'*'.'It** *.*,~(-***** ** *.* **'~Icw _,It * ** * 'I.: .'*"** ilrot * *- ok

'I: read caxde ~ Re',ads the caz-ds Lnt.e extlernal varia.hle9,: *

* ,check,~' for ba.,d ca.rds vand du.pllica.,t.e oar'ds. *

't*** *W'***' •• '**********.*' _******.~* -kit **.". **** 'ki"#li *'*** *: *'**._-, 'It .~-,** I

{ '}

I~·********·-********·***·~*·****·***··**·*·*·******·*****

'" an.a,lyz,e_hand,:, DI1e-t'ermine's whether t.he hand cont aans ill to

* ertraig,h,t f a_ fLuah., 'four-af-a";kind, ..

'It land/or three·~of-a-kl.ndl: determ,in~e.s· th,e ~

* number of pa.,irs; Is,t-orles the r.Eus:ultI5 into *

!I!r lextlexna' va.r.i.ab,l e,9 ~ *

* _ *' *: * _ '* * ' , * '* '* *'.. , 'W: '* ''It '* 'I: ''If ** '* '** ** '*' ;I; * *" -!Jc "* '* w * ,*- i: * ,* * -* * '* ~ ~ '* w --. '* *, * * *' '* * I

void[ analyze_hand(void)

{

}

/'* '* * 'I: '* * *' * *' .. * *,,* * *' * *' *' *' * * * ~ '* 1f .• " * 1ii '* '" " '* )\: '*' '1J *"*:1 '* * * *' * :* • *' .... *K *' ,.. -:It ... w 'I:

"print:_r.esult! Notili.e·8 the 'u:se.r c,f ·the re!sult ~ u,s~n,g ..

* th,@ ex'tlerna1 vaIiahl~"s se;E_b,y '*

* .ana lyze~hand .' *

•••••••••••• *********.** .**.** •••••••••• ****.*****.**.**/

void pri.nt~.Jj,e~Bult l(v'o,id)

{

}-

Themost pr- c ·1 .~- i ng question Itha;~ remains is how to.represent the band of cards, Let s see' what operationsxead cazds and ana.Lvae hand will perform 01"

,~ -

'[he hand, .. During [he analysis of the bandit! aDalyze~h,an,d will meed to kno\y

how m?lOOY card are in each rank and each suit. This suggests that 'we II e two arrays, nun in rank, and num in aud t. The valu or num in rank[r]

. -- ~~ ~-

~IHJ' be the number of cards wirth rank, z, and the value of nu,m_in_sllit [5] will

be the number ofcardi with suit :9., We"Ulencolde ranks as numbers between to and 1.2". and,lti' as numbers between 0 and 3,,,) We 11 1110 need a, tbird arr-ay ca,r,d_, exdst s, so that rle,ald~cards Clan detect duplicate cards, Each time .read ca rds reads a card with rank r land suit B~ it checks whether the value of car,d,_exis,ts [r] [s] i t.ru.e. If so, the cam was previously entered: i ,- not

- - -

re,ad_cards assigns tru,e to card=,exists [r] l sl .

Sloth the :r'ead_, cards function and tbe an,alyze~hand function will [le.· .. d access tOI tbenum d n rank and rrum in au it; arrays, SOl I' U make them exter-

~ .~ ....... ~ -

DEd variables, The card_exi.s,t,s array i~ used only by r1e,ad,_,c"ards,!, SID it Clan

be local to that function, As ,8 rule, variables should be made external '. nly if'neces .... sary,

-HaVU1g decided on the major data, structures we can DOW finish the program:

~'include -e :~rtdbooll ~ 'h~, #inc'lude <stdio· .,h,>, 'jinclu,de <stdlib., h>

#defin1e NtJM. RANKS 13 #definel NUM: SUITS ,4 #de'finle NrJ'M' CARDS 5

I 1 e,xt'erna,l variah~les 'It I int num~in_rank [NUM_RANKS]' I;" in,t num in sui I:. [NUM StJITS) ;

............... ~ ~,

boo I, ,straight ~ f1us,h, ,four" t:hreu:! 1

';n~' oa l' ..r CI' '. I * c ian be 01 IJ' '0' , r' ~ '* I

..L IlL., C"'-' ',..;II, , ,I, "", "I' I I ' .4. '

I it p1rat,otype,s -I

vc],id, read cazds (void) :

~

void analy,ze~hand (void), ;

void print~r,es,ult (va;1 0.)1 ;

I*'* .'W'*,**,*"'* *' .. ***.'W* '* *'*** !ft'**'. ****'** .'.****"*' '* - ''It *'. 'Iht'** ****** ***'* -I: 'main: Calls read~car'd,B, a.nalyze,_ha'nd, and print._'res'ult *'

*' r1e'plsateld.1,Y i 'If

*.********.*******.**********~*********** **************/

int main I(V10i__O)

{

for L:;) { r'EI8Ld_cardl.s ( ) ; anal YZ'8_h,8!nd (I) i print I'esult ~ ) ;

"'='

}

}

'**.****** •• ******.***.*~.***.**********~****.*******.* *

i' 'read cazda : Rleadstbe cards into the ex:ternal *

'* ~ar'iables nu'm~i-n~Iank and num~in_:suit,; ..

w c:hleC:K,Si fo,r had ,carde emd duplicBt'f! caJ:'dsl. ...

* * w * * * "" *' w.' '" * * " it' ok 'It, '* • * tt" - 'W' <N *'." ",'. w, '* * Il' it, "8 !It '* ; '.JG '* '* " ' ,:It ..... -It, .. "* *', ~ '* ,ok, ." I

void read_car,ds (void,)

[

boo l, c-a,rd if:,xists [NllM_RANKS] [NOM_SUITS]. ; char ch , rank~ch,. Buit==chi

.i.nt, rank I' Bui'~;

bool b,ad_car,d;

in,t cards rea .. d- a i

for' ('rank = (Ji; x'ank <'. N01'4~~~; rank~+') {

'" . ....:-11 .. [ . c ~ ... ] 1M

num _1n _ ra.1l.A rann.., ="= U;

for Csuil: ~ 0; eu,; t; <: NlJN1 ......... SUITS,; ;suit:+-+) e,a:rd existsl [rank] [s:uitJ ~ fa,ls,e;

fo,r ( au i t = 0; au i, t 1(, NUM:_SUITS; suit ,- + ) num in suit [suit] ~ 0;

while ((!ar'd8_re~a,d 'C: NOM CARD,S)' { bad card ~ false;

rank ch = g'etcha,r {) ; ,switch {r'Gnk=ch) {

10~5' O,rgalnizin,fJ 18 C Program 235

cass, l~k!l: case Iii a ~ :: d.efaul,t:

,exit (EXIT~SJJCCBSS) ; ral1k -- 0;' break; ran_k 1;' l)re,a r, ; xank - 2 _ break; rank - 3,;' break ; rank. ..... 4; hrea,k i rank - 5; break i ran'k - 6; br.eak;' r,ank - 7 i break;

ca~e 'I T ~: reM ...... 8 i b,re,ak.; case 1 IJ': rank ~ 9 ~ break;; ca,Sie I 'Q 1: rank - 1 Qt; bxeak;

ca ,s-Ie I K"", I '". """",1"" 11 b' ~eak

raJl'~ - .l.; "JL, !, I' ;

case I A I ~ rank - 12 ,~ bre·ak; bad oaz'd ~ true i

c,a,se I to I
ca,s,e I :2 I
caae I 3, I
case I 4 I ·
·
case I 5 I ~
"
a,ass I 6 Ii ~
·
oaae ~ 7 II i

Ca.,S'B ~I s: II •
iii
case ~ .9' ~ ·
i
case ~I t II ·
·
~I . ~
C,a,sE'! J ·
.,
case nl q~ •
· }

suit ch = getchar() ;

- .'

sWi-tch (erui'"t,_ch1 {

caS,E I C II ;a.! case ~ 'C A' '. suit, e .. break;'
'" . - ,:
oaae I d 'I' '" case I D A . suit 1 . br~a,k;
" ,_ - I
ca,B1B • h ! .. oaae • H ~ suit .2 ., brlaak ..
.. ~ . I ,
caae I s I riii case II S r suit J ~I break .'
'" - ,~ 111
def,a:ult ,. bad c-ax'd ..... true,;
.. }

while- (('cb = Igetcll,ar()) ~= II\nt)

if (ch J ~ I' I') ba,d cazd = true;

if (b,ad c,a.rd)

.pri,n tf ( ~'Bad card; igndr e,Q., \ n 'I!) i

e 1 ae if ( cazd ~Iexi,s ts [r,ankJ [suit:] ) printf (~~Dup'licate card; ignored" \n~I)1 ,;' els,e {

num in rank ['rank] ++ t

- -

Hum_i'n_suit [suit] ++;

card._exi~sts [rank] [·sui t] - true: i Icar'ds~read,+ + ;

}

I******·***********·***********·**·***·*·*~*·*****··***.***

*' analY'2aB hand i D~term,inles whether 'the ha'nd co'ntalins a 'ill

-

'* strs,igbt,f a f l.ush , fOI'u'r=of~a=kiDd~1 'If

.' and/lor thre'e-of~a·~ki.IJd; de-termine'IB t.he *

'*' numbe.r 10£ padr.s , stores the results i.nto •

* 'the extel"nal variahiles s:trai.ght:, flush, '*

,ok four ~ tl1ree; and pairs. ..

******~.*******.***-***.*.**** •• ** •• **.***~**~.**~***.·~*·I

void a'n,alyze_hand (void)'

,(

~nt·, 0

.L n'um, Icon.s:ec - ';

in:t rank, suit;,

str,aight ~ fals,e; flu,sh :, ,f,alse; f'i[),u.r :;; fals,e I thre2 :: fal'se; pairs ~ 0;

1* check for flu"sh fr I

for (Bui't = (J ,; ,sui t. < NUM SUITS; ,sui't++) if (num in suit lsudt.l == NtJM CARlJ'S)1

~ ~

flus.h ~ truer

/* check for straight -/ rank ~ 0;

while I(Dum_, in_, xank [ranJ~] == '0) r,ank++;

for (; rank "<:: NOM RANKS '&'& num in rank fr,ankj :> 0; rank++)

- - -

n,Urnl_con.slec'+ +- ;'

if ( 11 urn C;:;'O'JlS ec =__ N11M CARDS ,) { straight == true~'

return;

}

1*' check for 4--of -a=kdrid, 3 -,of-a~kin,d,j' and p,ai'rs * I

f'or 'rank :;;;;; 0; ·r,BDK, <: NOM~' RAmtS, i rank } {

if (num_in_rank[rank.] ;;;;,.~ 4) four = true;

if: (num in rank [rank] J) t,nree ;: tru,e~'

= ='"

i. f (num_i:l'l:_rank I[ rank] .,...'.... .2) pad.r s + + ;

}

1'* *-'** ** *' '* * 'in. '* ** ~ .. *..t. :1r'. W'.". -1 *' .. '.:If '*. *.".,.. .'ii '* , _ *"*' ,** '* * '*' '* *' * i'r' * .. * *' '* *' "* 'IIi'

ik pr'in,t,_res,ult: Prin,t:s 'the clas,sificaeti,on e,f th'e hand, '*

,!t basH~d oa the val ues of the ext:,'!~(rnal .,

'It variahl'Bs s,t.ra1.g'h't.j flu,sh, flaur,~ thre,e~ *

* and paiL'S ~ *

*.***.** •• *******~*****.~*****.***.**** •• **." •• ****** ••• ~,*/

void p,rint._,res'ult ('void)

{

if ("straight && flush) llrintf I( Ii Straight flush");, e:l:eHe: if (f,Q!'ur.) print:f (i~Four of a k:indU) ; e;lse i'r ('thr,ee &&

p,a,irs ~= 1, else if (,flus,h)

e Lee if (s tr',aigh,t) else if' (three)

else if (pairs 2) 'elsH:l~ if (prairs == 1, else

p,:t"in t f I( '" FUll hous e ~m) i printf ( IlmFlush") ; printf ( ~~S.traight ~~ ) i

print.-'f ('I'IThr,ee of a kindl! ,~I ; printf ('I'ITwo p,airsli " ; pri.ntf ( ~r Pai'r I~)I ;

p1ri'otf 1(' !'High card II) ;

}

Notice the use 'of the exf, t func ,:' on in read~cardlSi (in case ~ 0' ~ 0 the first awi t ch statemerm.exd t is convenient for his, program because of i:ts ability 'to terminate execution from anywhere in the pIDgrnm~,

Q: Whl,at impl8ct ,d,lo 10 '01 "ariabl - 'witl) s,ta' Ie _10' lag durati,o,n hal re 0.0, ,re ursf e fUD',,'tj,Oft,',?, (p'. 22,0]

A,: Wh' n a ~_Dction i called -- cursively fres h cc pte are mad, of it I automatic variables for ' ach call. This Joe n 't I" I cur 11 ,~, ,[mi,e "ali lie ,.,~ the ugh, In- l. ad, all c __ _c -, of the functi ,n I' bare the same st ItiC variables,

't" .

in- - ~ == 1.;

'Void f (vod d)

(

int j := i •
,t-
int " :2
~ - .
1 }

0.1 t'h:: I eede I i ~,aJ? If S~I" hat i I j-, II ntta val _,', or .:~'

A: Th .code is indeed legal. TIlle c '.0 'a.I al variable doesn 'r b gin until i .

ration", Therefore the declaration of j ref r "~O the xternal variable named, ill, The initial val ue of j will be 1.

S'e-"e' t" on '1'0" 4'

I,"'. __ r~ I, _ . r.'· _

. I L Tbe following pro, ram outline sho - onl" un Iion definitlon and ,ariabl declarations. int a ,

void f(int b)

{

int e ,

}

void g(void)

{

int Id,

{

int e;

}

}

ma.in(void)

int

{

}

int f;

F Ir each oftheUo ,ing copes U.,t, Uri', ible ane param tor names ·)1 The f function

b) The 9 lrm_l] n

I,~} The block in 'Ihi, h e i d (d The ma i.n function

2. Til' ;ono" ill1,~ program outli ne shows only fn nctlondeflnitions and -, ariable declarati []' . .iJ::lt b, C;

void f (void)

{

in"t b, di'

}

YO,; d Q (int a)

{

int It: I

- ~

{

int &, d;

}

}

Lnt; main (void)

{

int c , d;'

}

~-:I r I eh ' ,_ be U" ing scop , ,11'1, all . ariable and param 1 r names vi" ibk [f [her, 's tnl re Lhan on ariable . r P,&[' 1 IL:r will h Il, ame name. indi ,[I , i .ible,

a Tile f functi J (b) Th, 9 iLlDcti, 'n

h;) The bl kin, inch a and d are declared I dl Th' main fltn ti n

... " I" pp ~ _ -h~' -rogr',m ha~ on)1 'on fUD ti '0 (ma.i.n), How nlan), , 'i,ife~'D ~ II la Je .named i could this pro .am c ntain?

Prorammil 9 Pr, . jects

J. ' In 'ify the rae e J mple II' S ,-,cOon ] O~2 I"{J tha it I 'tore ,'I eharact 'T- lnstead 0 lou gel.

, t add, main fu cti - n th -' Ik th u~r t I, __ ter a. ries I .f P-I- emhe _ .... and/ r bn e

th f1 'i ndicat . whether 0,[ n10[ th ' ,"1 - r ~ prop rly nes ted:

Kniter pSJc,entheees, and/ror braces: () U {_') il:

Parentheses,/braces are nested prroperly'

,Hint; As he pro tTra m T' ad cO chara ners, haveu pull e sch lefl parenthe ,i -r I,_' brace. ten j read a right parernbe ~i~ or fa el, h _" it 'p: p the stack and heck tb I the jlt m ]lopp ,d 11: a rn,atch'ng parenthesi ,[ ra e. (If not, the paren'-h - s/braee aren [ nest ,d p~ perly, ben the prog am re ds th new ... line char, c er, h. ' .. il, h ck \~ h til, r th.· : IBCk t ", empty; if . o, th

parentheses/br II ,e ~ ~ mat hed .. If Lh t ck i II ~r e (or if stack_underflow i .

pe,

,Programmling Projects ,2:39

called the par __ UleK:-/bra, es ar 11" m itched. lf a,tack c' erflow i'k called hav tilt program piont the me' sag:e Stack ev,er=Elow and terminate tmm dbllte~:y.

2. M d Ly 'the poke r ;0 c program of Section I 0.51 by moving the num~, in _ r,ank and num~in_,s,ui t ar "ay imo main ,~ hi 'h will pat .. ' them a ~gumf1 s rtn read_Caltds and ,analyze_ha.nd.

I', 3., Remove tile' num in rank, Dum in_sluit, and caz'd exists array, from the

poke r ~,c program ' f Se tion I O~:5. H a e th c program sror the' card in _ 5 X ,1 : ray instead, Each row of the array wi U repre ent a card. for lex amp lie , if Ute array i - named hand, then hand I[ [)I ] [0 ] will store '[be rank of th first card and hand [0] [1] 'will. tore the ~ uit of the first card.

dif the po,ker . C pro - am of Secti n 10.5, by having it recognize an additional c- tego.ry I. royal flush' . ace, king, queen, jack ten of the sam suit). A royal flu· bran e hi her than a] 'I ther hand ,.

5r Modify the pokez , c prograrn of Section I O~S; by allo: lng ace-lei '~,trai', h - Be t-: Or three.Jour, "11 ve),

16. So-me calculators (notably those from Hewlett-Packard) us e a .. ystern of Writing mathemati-

iJ 1 xpressioes e -- own a', Rev r e P, Iish Noration 'RPI'-I E In lhi ~ notation. operators are placed after their operands inste I d of between their operands. Por example .. 1 'T ~ wouJd be written J 2 + in RP' nd Il + 2 ~,. 3 w uJd -c .~ .. ritten 1 2 ... : +. RP' lex pre' sloes can easily be evaluated using a stack, The algorithm involves readinn the operator and operand in am expression from left [0 ligbt performing the fallowing a tions:

When an operand is en ountered push it nto thestack.

When. an operator is encountered. pop its operands from th. stack. perform the op _ ration ',' n those operands, and then pu ,n the r, : U It onto the . tack,

Write a pr gram that e aluate ,RPN expressions. The op' rand - will be ,in~I--di.git integer . The operators an +.'~ :*,./~ arJld =., Th ;::' operator cau e the top stack he'm to be disp,hry'led'~ afterward . the stack i" cleared and the U' er i' prompted to , nter ',- other. ixpre ·.lon. The pmces cominu -;, until the u er enter a character that is, nut an operator or op, rand:

Enter an RP'Ni e.xpression:: 1 2 3 * + - Valule of exp'ression.: 7

Entler an R,PN expre'ssiion: 5, a '* 4 9 - / = Value of expressi:on,; -,8

Enter a.n RPN express;ioln:. g

If the tack overflows (he program will di· pllay the me sage Express ion is t.oo complex and terminate. If the stack unde rflow .. tbecau e of i" n e pr ssion - uch _, 1 2 + +'1 the program will display the message No't, enoug'h Q'per',a.nds in exp,ression and terminat. Hints: In _ orporare the tack co' _. [r0111 Sectn '11 10.2 ill to your program, se s oanf { mll%cU" ,&c.h) to read the operators and operands,

7. Write 3l program that prompt rhe user for anumber and then displays the number, D :ing ch acters to imulate the effect of se . en-segment di plH_ :

Entler a numbez : 4911-91014

,_~ I _I I~

hara ners ther than digit 'houhl be '1,211 red. _,. il:e the pr gram S,,· . hal the maximum number of digit i controlled bam [0 namec MAX EIIGJ:ITS- which has the value 10. If

the number contain - m· II - dum this numb "r . I i~'it Lh extr ~ d~itsl ~« -Ignor d .. Hint: ~ .. I, , two external 1!U1"J. y., ~ One j, UU~ segnlents, ':_'_) {'s ·--ere": 6 in Chapter '. ,I ' hich teres data, repre entin the correspondence between digin ande.gtl1enu,.· he aLb r,2lUI,Y., digit"6, will be an ,m,ay of ehara t rs Ub 4 rc ' '. ( inee e, eh ~egm_nled figit .,. four ch ,_ cLen high) and MAX~;oIGITS *- umns I ldj.· ~1: are three character. wide" but a ~ P' ., - is needed betwe ~a di_ its "T n adabili ,t . ,_ ri e : ur pro 1-' m _. four fun-bon: mad.n, ole,a,.r_,digits_arra'y. prcu::e,ss_d1git~ .-Ild print~digitB_array. Her ' are the protot~ pe~· fi r th _' l~-t _ r UUJ~'e funeti . ns:

void e,l,ea:r digi,ts arr-a'y (voi,d) i

~ _

void proc'ess_digit (Lnt; cl_i'git ~ int pos i.t.Lon) t voi d print_digits_ar'ray (void), i

cle:ax_dilgits_array will store blank eharacters into aU lements of the 'digi s arrn3~. pzoce e ,s_dig i t will ,$ '- re 'b, "eV'e'D- egment representution of dig 1. t i 11 to a

pecifled pesition in Lh - digits: ~ liT,ay (pi sltions ran,p frlm 0 b~1 .MAX_DI'G.ITS - ~ . print~,di9i ts=a'rr~y will dipJ,ay til Rl' ., . f be di'gi s rr -,~ ._ h 'cn ,8 Ingle line", proda in, 'IOU pet such r ,,~ lbal . hewn in lh u x.amp _ ~

You might also like