You are on page 1of 595

Contents

1. Getting Started What is C Getting Started with C The C Character Set Constants, Variables and Keywords Types o C Constants "#les or Constr#cting $nteger Constants "#les or Constr#cting "eal Constants "#les or Constr#cting Character Constants Types o C Variables "#les or Constr#cting Variable )a*es C Keywords The +irst C ,rogra* Co*pilation and ./ec#tion "eceiving $np#t C $nstr#ctions Type 0eclaration $nstr#ction 1rith*etic $nstr#ction $nteger and +loat Conversions Type Conversion in 1ssign*ents 2ierarchy o 3perations 1ssociativity o 3perators Control $nstr#ctions in C S#**ary ./ercise 2. The Decision Control Structure 0ecisions4 0ecisions4 The if State*ent The "eal Thing 5#ltiple State*ents within if The if-else State*ent 1 2 4 5 6 ! % & '( '' '' '2 ''& 2' 224 25 2& 2& -' -4 -! -! -%

49
5( 5' 55 56 5%

viii

)ested if-elses +or*s o if 6se o 7ogical 3perators The else if Cla#se The 4 3perator 2ierarchy o 3perators "evisited 1 Word o Ca#tion The Conditional 3perators S#**ary ./ercise 3. The Loop Control Structure 7oops The while 7oop Tips and Traps 5ore 3perators The for 7oop )esting o 7oops 5#ltiple $nitialisations in the for 7oop The 3dd 7oop The break State*ent The continue State*ent The do-while 7oop S#**ary ./ercise 4. The Case Control Structure 0ecisions 6sing switch The Tips and Traps switch Vers#s if-else 7adder The goto Keyword S#**ary ./ercise

6' 62 64 66 !2 !!!6 !! !%

97
&% && '(' '(5 '(! ''4 ''5 ''6 ''% '2( '2' '24 '24

135
'-6 '4( '44 '45 '4% '4&

i/

5. Functions

!ointers

157
'5% '65 '66 '!' '!2 '!'!4 '!5 '!% '!% '!& '%6 '%& '%& '&4 '&! 2(' 2('

What is a +#nction Why 6se +#nctions ,assing Val#es between +#nctions Scope "#le o +#nctions Calling Convention 3ne 0icey $ss#e 1dvanced +eat#res o +#nctions +#nction 0eclaration and ,rototypes Call by Val#e and Call by "e erence 1n $ntrod#ction to ,ointers ,ointer )otation 8ac9 to +#nction Calls Concl#sions "ec#rsion "ec#rsion and Stac9 1dding +#nctions to the 7ibrary S#**ary ./ercise ". Data T#pes $e%isited $ntegers, long and short $ntegers, signed and unsigned Chars, signed and unsigned +loats and 0o#bles 1 +ew 5ore $ss#es: Storage Classes in C 1#to*atic Storage Class "egister Storage Class Static Storage Class ./ternal Storage Class Which to 6se When S#**ary ./ercise /

213
2'4 2'6 2'! 2'& 22' 22224 226 22! 2-( 2-2-4 2-5

7. The C !reprocessor +eat#res o C ,reprocessor 5acro ./pansion 5acros with 1rg#*ents 5acros vers#s +#nctions +ile $ncl#sion Conditional Co*pilation #if and #elif 0irectives 5iscellaneo#s 0irectives #undef 0irective #pragma 0irective S#**ary ./ercise &. 'rra#s What are 1rrays 1 Si*ple ,rogra* 6sing 1rray 5ore on 1rrays 1rray $nitiali;ation 8o#nds Chec9ing ,assing 1rray .le*ents to a +#nction ,ointers and 1rrays ,assing an .ntire 1rray to a +#nction The "eal Thing Two 0i*ensional 1rrays $nitiali;ing a 2<0i*ensional 1rray 5e*ory 5ap o a 2<0i*ensional 1rray ,ointers and 2<0i*ensional 1rrays ,ointer to an 1rray ,assing 2<0 array to a +#nction 1rray o ,ointers Three 0i*ensional 1rray S#**ary /i

241
242 244 24% 252 25255 25% 26( 26( 26' 26264

2"9
2!( 2!2 2!5 2!5 2!6 2!! 2!& 2%6 2%! 2%& 2&( 2&' 2&2 2&5 2&! -(( -(2 -(4

./ercise 9. !uppetting (n Strings What are Strings 5ore abo#t Strings ,ointers and Strings Standard 7ibrary String +#nctions strlen( ) strcpy( ) strcat( ) strcmp( ) Two<0i*ensional 1rray o Characters 1rray o ,ointers to Strings 7i*itation o 1rray o ,ointers to Strings Sol#tion S#**ary ./ercise 1). Structures Why 6se Str#ct#res 0eclaring a Str#ct#re 1ccessing Str#ct#re .le*ents 2ow Str#ct#re .le*ents are Stored 1rray o Str#ct#res 1dditional +eat#res o Str#ct#res 6ses o Str#ct#res S#**ary ./ercise 11. Console *nput+(utput Types o $=3 Console $=3 +#nctions +or*atted Console $=3 +#nctions

-(4

327
-2% -2& --4 --5 --! --& -42 -4-44 -4! -5' -52 -5-54

3"3
-64 -6! -!( -!( -!' -!4 -%-%4 -%4

393
-&4 -&5 -&6

/ii

sprintf( ) and sscanf( ) +#nctions 6n or*atted Console $=3 +#nctions S#**ary ./ercise 12. File *nput+(utput 0ata 3rgani;ation +ile 3perations 3pening a +ile "eading ro* a +ile Tro#ble in 3pening a +ile Closing the +ile Co#nting Characters, Tabs, Spaces, : 1 +ile<copy ,rogra* Writing to a +ile +ile 3pening 5odes String >line? $=3 in +iles The 1w9ward )ewline "ecord $=3 in +iles Te/t +iles and 8inary +iles "ecord $=3 "evisited 0atabase 5anage*ent 7ow 7evel 0is9 $=3 1 7ow 7evel +ile<copy ,rogra* $=3 6nder Windows S#**ary ./ercise 13. ,ore *ssues *n *nput+(utput 6sing argc and argv 0etecting .rrors in "eading=Writing Standard $=3 0evices $=3 "edirection "edirecting the 3#tp#t /iii

4(4 4(5 4(& 4(&

415
4'6 4'! 4'% 42( 42' 422 422 424 425 426 42! 4-( 4-( 4-4 4-! 44' 44! 44% 4545454 4"5 466 4!( 4!2 4!4!4

"edirecting the $np#t 8oth Ways at 3nce S#**ary ./ercise 14. (perations (n -its 8itwise 3perators 3ne@s Co*ple*ent 3perator "ight Shi t 3perator 7e t Shi t 3perator 8itwise 1)0 3perator 8itwise 3" 3perator 8itwise A3" 3perator The showbits( ) +#nction S#**ary ./ercise 15. ,iscellaneous Features .n#*erated 0ata Type 6ses o .n#*erated 0ata Type "ena*ing 0ata Types with typedef Typecasting 8it +ields ,ointers to +#nctions +#nctions "et#rning ,ointers +#nctions with Variable )#*ber o 1rg#*ents 6nions 6nion o Str#ct#res S#**ary ./ercise

4!6 4!! 4!% 4!%

4&1
4%2 4%4 4%6 4%% 4&4&% 4&& 5(( 5(' 5(' 5)5 5(6 5(! 5'( 5'' 5'5'5 5'% 52( 524 5-( 5-' 5-'

/iv

1". C .nder /indo0s Which Windows: $ntegers The 6se o typedef ,ointers in the -2<bit World 5e*ory 5anage*ent 0evice 1ccess 03S ,rogra**ing 5odel Windows ,rogra**ing 5odel .vent 0riven 5odel Windows ,rogra**ing, a Closer 7oo9 The +irst Windows ,rogra* 2#ngarian )otation S#**ary ./ercise 17. /indo0s !rogra11ing The "ole o a 5essage 8o/ 2ere Co*es the window: 5ore Windows 1 "eal<World Window Creation and 0isplaying o Window $nteraction with Window "eacting to 5essages ,rogra* $nstances S#**ary ./ercise 1&. Graphics .nder /indo0s Graphics as o )ow 0evice $ndependent 0rawing

535 5-6 5-! 5-! 5-& 54( 545454! 55' 552 554 55% 55% 55&

5"1
562 56566 56! 56& 5!( 5!2 5!5 5!5 5!6 579 5%( 5%(

/v

2ello Windows 0rawing Shapes Types o ,ens Types o 8r#shes Code and "eso#rces +reehand 0rawing, the ,aintbr#sh Style Capt#ring the 5o#se 0evice Conte/t, a Closer 7oo9 0isplaying a 8it*ap 1ni*ation at Wor9 W5BC".1T. and OnCreate( ) W5BT$5." and OnTimer( ) 1 +ew 5ore ,oints: Windows, the .ndless World: S#**ary ./ercise 19. *nteraction /ith 2ard0are 2ardware $nteraction 2ardware $nteraction, 03S ,erspective 2ardware $nteraction, Windows ,erspective Co**#nication with Storage 0evices The Read ector( ) +#nction 1ccessing 3ther Storage 0evices Co**#nication with Keyboard 0yna*ic 7in9ing Windows 2oo9s Caps 7oc9ed, ,er*anently 0id Co# ,ress $t TTwwiiccee:: 5angling Keys Key7ogger Where is This 7eading S#**ary ./ercise

5%2 5%6 5&( 5&2 5&6 5&6 6(( 6(' 6(6(! 6'' 6'' 6'2 6'6'4 6'5

"17
6'% 6'& 62626 6-' 6-6-4 6-5 6-5 6-! 64644 645 646 64! 64!

/vi

2). C .nder Linu3 What is 7in#/ C ,rogra**ing 6nder 7in#/ The D2ello 7in#/@ ,rogra* ,rocesses ,arent and Child ,rocesses 5ore ,rocesses Eo*bies and 3rphans 3ne $nteresting +act S#**ary ./ercise 21. ,ore Linu3 !rogra11ing Co**#nication #sing Signals 2andling 5#ltiple Signals "egistering a Co**on 2andler 8loc9ing Signals .vent 0riven ,rogra**ing Where 0o Co# Go +ro* 2ere S#**ary ./ercise !ppendi" ! F #recedence Table !ppendi" $ F tandard %ibrary &unctions !ppendi" C F Chasing the $ugs !ppendi" ' F (e"adecimal )umbering !ppendi" * F ! C++ Chart !ppendi" & F (elper,h &ile !ppendi" - F $oot #arameters !ppendi" ( F %inu" +nstallation +nde"

"49 65( 65' 652 65655 65& 66( 66664 664 ""7 66% 6!' 6!6!5 6!% 6%4 6%4 6%5 6%! 6&' !(' !'!'& !25 !2& !-5 !-&

/vii

Getting Started
What is C Getting Started with C The C Character Set Constants, Variables and Keywords Types o C Constants "#les or Constr#cting $nteger Constants "#les or Constr#cting "eal Constants "#les or Constr#cting Character Constants Types o C Variables "#les or Constr#cting Variable )a*es C Keywords The +irst C ,rogra* Co*pilation and ./ec#tion "eceiving $np#t C $nstr#ctions Type 0eclaration $nstr#ction 1rith*etic $nstr#ction $nteger and +loat Conversions 2ierarchy o 3perations 1ssociativity 3 3perators Control $nstr#ction in C S#**ary ./ercise

%et .s C

e ore we can begin to write serio#s progra*s in C, it wo#ld be interesting to ind o#t what really is C, how it ca*e into e/istence and how does it co*pare with other co*p#ter lang#agesG $n this chapter we wo#ld brie ly o#tline these iss#esG +o#r i*portant aspects o any lang#age are the way it stores data, the way it operates #pon this data, how it acco*plishes inp#t and o#tp#t and how it lets yo# control the seH#ence o e/ec#tion o instr#ctions in a progra*G We wo#ld disc#ss the irst three o these b#ilding bloc9s in this chapterG

/hat is C
C is a progra**ing lang#age developed at 1T I T@s 8ell 7aboratories o 6S1 in '&!2G $t was designed and written by a *an na*ed 0ennis "itchieG $n the late seventies C began to replace the *ore a*iliar lang#ages o that ti*e li9e ,7=$, 17G37, etcG )o one p#shed CG $t wasn@t *ade the Do icial@ 8ell 7abs lang#ageG Th#s, witho#t any advertise*ent C@s rep#tation spread and its pool o #sers grewG "itchie see*s to have been rather s#rprised that so *any progra**ers pre erred C to older lang#ages li9e +3"T"1) or ,7=$, or the newer ones li9e ,ascal and 1,7G 8#t, thatJs what happenedG ,ossibly why C see*s so pop#lar is beca#se it is reliable, si*ple and easy to #seG 5oreover, in an ind#stry where newer lang#ages, tools and technologies e*erge and vanish day in and day o#t, a lang#age that has s#rvived or *ore than - decades has to be really goodG 1n opinion that is o ten heard today is F KC has been already s#perceded by lang#ages li9e CLL, CM and Nava, so why bother to

Chapter /0 -etting tarted

learn C todayOG $ serio#sly beg to di er with this opinionG There are several reasons or thisP >a? $ believe that nobody can learn CLL or Nava directlyG This is beca#se while learning these lang#ages yo# have things li9e classes, obQects, inheritance, poly*orphis*, te*plates, e/ception handling, re erences, etcG do deal with apart ro* 9nowing the act#al lang#age ele*entsG 7earning these co*plicated concepts when yo# are not even co* ortable with the basic lang#age ele*ents is li9e p#tting the cart be ore the horseG 2ence one sho#ld irst learn all the lang#age ele*ents very thoro#ghly #sing C lang#age be ore *igrating to CLL, CM or NavaG Tho#gh this two step learning process *ay ta9e *ore ti*e, b#t at the end o it yo# will de initely ind it worth the tro#bleG >b? CLL, CM or Nava *a9e #se o a principle called 3bQect 3riented ,rogra**ing >33,? to organi;e the progra*G This >c? organi;ing principle has lots o advantages to o erG 8#t even while #sing this organi;ing principle yo# wo#ld still need a >d? good hold over the lang#age ele*ents o C and the basic progra**ing s9illsG Tho#gh *any CLL and Nava based progra**ing tools and ra*ewor9s have evolved over the years the i*portance o C is still #nchallenged beca#se 9nowingly or #n9nowingly while #sing these ra*ewor9s and tools yo# wo#ld be still reH#ired to #se the core C lang#age ele*entsRanother good reason why one sho#ld learn C be ore CLL, CM or NavaG 5aQor parts o pop#lar operating syste*s li9e Windows, 6)$A, 7in#/ is still written in CG This is beca#se even today when it co*es to per or*ance >speed o e/ec#tion? nothing beats CG 5oreover, i one is to e/tend the operating syste* to wor9 with new devices one needs to write device driver progra*sG These progra*s are e/cl#sively written in CG

%et .s C

>e? 5obile devices li9e cell#lar phones and pal *tops are beco*ing increasingly pop#larG 1lso, co**on cons#*er devices li9e *icrowave oven, washing *achines and digital ca*eras are getting s*arter by the dayG This s*artness co*es ro* a *icroprocessor, an operating syste* and a progra* e*bedded in this devicesG These progra*s not only have to r#n ast b#t also have to wor9 in li*ited a*o#nt o *e*oryG )o wonder that s#ch progra*s are written in CG With these constraints on ti*e and space, C is the lang#age o choice while b#ilding s#ch operating syste*s and progra*sG > ? Co# *#st have seen several pro essional -0 co*p#ter ga*es where the #ser navigates so*e obQect, li9e say a spaceship and ires b#llets at the invadersG The essence o all s#ch ga*es is speedG )eedless to say, s#ch ga*es wonJt beco*e pop#lar i they ta9es a long ti*e to *ove the spaceship or to ire a b#lletG To *atch the e/pectations o the player the ga*e has to react ast to the #ser inp#tsG This is where C lang#age scores over other lang#agesG 5any pop#lar ga*ing ra*ewor9s have been b#ilt #sing C lang#ageG >g? 1t ti*es one is reH#ired to very closely interact with the hardware devicesG Since C provides several lang#age ele*ents that *a9e this interaction easible witho#t co*pro*ising the per or*ance it is the pre erred choice o the progra**erG $ hope that these are very convincing reasons why one sho#ld adopt C as the irst and the very i*portant step in yo#r H#est or learning progra**ing lang#agesG

Getting Started 0ith C


Co**#nicating with a co*p#ter involves spea9ing the lang#age the co*p#ter #nderstands, which i**ediately r#les o#t .nglish as the lang#age o co**#nication with co*p#terG 2owever, there is

Chapter /0 -etting tarted

a close analogy between learning .nglish lang#age and learning C lang#ageG The classical *ethod o learning .nglish is to irst learn the alphabets #sed in the lang#age, then learn to co*bine these alphabets to or* words, which in t#rn are co*bined to or* sentences and sentences are co*bined to or* paragraphsG 7earning C is si*ilar and easierG $nstead o straight<away learning how to write progra*s, we *#st irst 9now what alphabets, n#*bers and special sy*bols are #sed in C, then how #sing the* constants, variables and 9eywords are constr#cted, and inally how are these co*bined to or* an instr#ctionG 1 gro#p o instr#ctions wo#ld be co*bined later on to or* a progra*G This is ill#strated in the +ig#re 'G'G
Steps in learning .nglish lang#ageP 1lphabets Steps in learning CP 1lphabets 0igits Special sy< *bols Constants Variables Keywords Words Sentences ,aragraphs

$nstr#ctions

,rogra*

+ig#re 'G'

The C Character Set


1 character denotes any alphabet, digit or special sy*bol #sed to represent in or*ationG +ig#re 'G2 shows the valid alphabets, n#*bers and special sy*bols allowed in CG

"

%et .s C

1lphabets

1, 8, :GG, C, E a, b, ::, y, ;

0igits Special sy*bols

(, ', 2, -, 4, 5, 6, !, %, & SD4TM UVIW>?B<LXYZ[\ ]^P_ `Jab,Gc=

+ig#re 'G2

Constants4 5aria6les and 7e#0ords


The alphabets, n#*bers and special sy*bols when properly co*bined or* constants, variables and 9eywordsG 7et #s see what are Dconstants@ and Dvariables@ in CG 1 constant is an entity that doesn@t change whereas a variable is an entity that *ay changeG $n any progra* we typically do lots o calc#lationsG The res#lts o these calc#lations are stored in co*p#ters *e*oryG 7i9e h#*an *e*ory the co*p#ter *e*ory also consists o *illions o cellsG The calc#lated val#es are stored in these *e*ory cellsG To *a9e the retrieval and #sage o these val#es easy these *e*ory cells >also called *e*ory locations? are given na*esG Since the val#e stored in each location *ay change the na*es given to these locations are called variable na*esG Consider the ollowing e/a*pleG 2ere - is stored in a *e*ory location and a na*e 3 is given to itG Then we are assigning a new val#e 5 to the sa*e *e*ory location 3G This wo#ld overwrite the earlier val#e -, since a *e*ory location can hold only one val#e at a ti*eG This is shown in +ig#re 'G-G

Chapter /0 -etting tarted

/X-

5 /X5

+ig#re 'GSince the location whose na*e is 3 can hold di erent val#es at di erent ti*es 3 is 9nown as a variableG 1s against this, - or 5 do not change, hence are 9nown as constantsG

T#pes o8 C Constants
C constants can be divided into two *aQor categoriesP >a? ,ri*ary Constants >b? Secondary Constants These constants are #rther categori;ed as shown in +ig#re 'G4G

&

%et .s C

C Constants

,ri*ary Constants $nteger Constant "eal Constant Character Constant

Secondary Constants 1rray ,ointer Str#ct#re 6nion .n#*, etcG

+ig#re 'G4 1t this stage we wo#ld restrict o#r disc#ssion to only ,ri*ary Constants, na*ely, $nteger, "eal and Character constantsG 7et #s see the details o each o these constantsG +or constr#cting these di erent types o constants certain r#les have been laid downG These r#les are as #nderP

$ules 8or Constructing *nteger Constants


(a) (b) (c) (d)

1n integer constant *#st have at least one digitG $t *#st not have a deci*al pointG $t can be either positive or negativeG $ no sign precedes an integer constant it is ass#*ed to be positiveG (e) )o co**as or blan9s are allowed within an integer constantG (f) The allowable range or integer constants is <-2!6% to -2!6!G Tr#ly spea9ing the range o an $nteger constant depends #pon the co*pilerG +or a '6<bit co*piler li9e T#rbo C or T#rbo CLL the

Chapter /0 -etting tarted

range is F-2!6% to -2!6!G +or a -2<bit co*piler the range wo#ld be even greaterG d#estion li9e what e/actly do yo# *ean by a '6< bit or a -2<bit co*piler, what range o an $nteger constant has to do with the type o co*piler and s#ch H#estions are disc#ssed in detail in Chapter '6G Till that ti*e it wo#ld be ass#*ed that we are wor9ing with a '6<bit co*pilerG
Ex.: 426 +782 -8000 -7605

$ules 8or Constructing $eal Constants


"eal constants are o ten called +loating ,oint constantsG The real constants co#ld be written in two or*sR+ractional or* and ./ponential or*G +ollowing r#les *#st be observed while constr#cting real constants e/pressed in ractional or*P
(a) (b) (c) (d) (e)

1 real constant *#st have at least one digitG $t *#st have a deci*al pointG $t co#ld be either positive or negativeG 0e a#lt sign is positiveG )o co**as or blan9s are allowed within a real constantG
Ex.: +325.34 426.0 -32.76 -48.5792

The e/ponential or* o representation o real constants is #s#ally #sed i the val#e o the constant is either too s*all or too largeG $t however doesn@t restrict #s in any way ro* #sing e/ponential or* o representation or other real constantsG

1)

%et .s C

$n e/ponential or* o representation, the real constant is represented in two partsG The part appearing be ore De@ is called *antissa, whereas the part ollowing De@ is called e/ponentG +ollowing r#les *#st be observed while constr#cting real constants e/pressed in e/ponential or*P
(a) The *antissa part and the e/ponential part sho#ld be (b) The *antissa part *ay have a positive or negative signG (c) 0e a#lt sign o *antissa part is positiveG (d) The e/ponent *#st have at least one digit, which *#st be a (e) "ange o

separated by a letter eG

positive or negative integerG 0e a#lt sign is positiveG real constants e/pressed in e/ponential or* is <-G4e-% to -G4e-%G
Ex.: +3.2e-5 4.1e8 -0.2e+3 -3.2e-5

$ules 8or Constructing Character Constants


(a) 1 character constant is a single alphabet, a single digit or a

single special sy*bol enclosed within single inverted co**asG 8oth the inverted co**as sho#ld point to the le tG +or e/a*ple, @1@ is a valid character constant whereas D1@ is notG (b) The *a/i*#* length o a character constant can be ' characterG
Ex.: 'A' 'I' '5' '='

Chapter /0 -etting tarted

11

T#pes o8 C 5aria6les
1s we saw earlier, an entity that *ay vary d#ring progra* e/ec#tion is called a variableG Variable na*es are na*es given to locations in *e*oryG These locations can contain integer, real or character constantsG $n any lang#age, the types o variables that it can s#pport depend on the types o constants that it can handleG This is beca#se a partic#lar type o variable can hold only the sa*e type o constantG +or e/a*ple, an integer variable can hold only an integer constant, a real variable can hold only a real constant and a character variable can hold only a character constantG The r#les or constr#cting di erent types o constants are di erentG 2owever, or constr#cting variable na*es o all types the sa*e set o r#les applyG These r#les are given belowG

$ules 8or Constructing 5aria6le 9a1es


(a) 1 variable na*e is any co*bination o ' to -' alphabets,

digits or #nderscoresG So*e co*pilers allow variable na*es whose length co#ld be #p to 24! charactersG Still, it wo#ld be sa er to stic9 to the r#le o -' charactersG 0o not create #nnecessarily long variable na*es as it adds to yo#r typing e ortG (b) The irst character in the variable na*e *#st be an alphabet or #nderscoreG (c) )o co**as or blan9s are allowed within a variable na*eG (d) )o special sy*bol other than an #nderscore >as in gross:sal? can be #sed in a variable na*eG
Ex.: si_int m_hra ! _e_89

These r#les re*ain sa*e or all the types o pri*ary and secondary variablesG )at#rally, the H#estion ollowsGGG how is C able to di erentiate between these variablesc This is a rather si*ple

12

%et .s C

*atterG C co*piler is able to disting#ish between the variable na*es by *a9ing it co*p#lsory or yo# to declare the type o any variable na*e that yo# wish to #se in a progra*G This type declaration is done at the beginning o the progra*G +ollowing are the e/a*ples o type declaration state*entsP
Ex.: int si" m_hra # $%!at &assa% # 'har '!(e #

Since, the *a/i*#* allowable length o a variable na*e is -' characters, an enor*o#s n#*ber o variable na*es can be constr#cted #sing the above<*entioned r#lesG $t is a good practice to e/ploit this enor*o#s choice in na*ing variables by #sing *eaning #l variable na*esG Th#s, i we want to calc#late si*ple interest, it is always advisable to constr#ct *eaning #l variable na*es li9e prin, roi, no# to represent ,rinciple, "ate o interest and )#*ber o years rather than #sing the variables a, 6, cG

C 7e#0ords
Keywords are the words whose *eaning has already been e/plained to the C co*piler >or in a broad sense to the co*p#ter?G The 9eywords cannot be #sed as variable na*es beca#se i we do so we are trying to assign a new *eaning to the 9eyword, which is not allowed by the co*p#terG So*e C co*pilers allow yo# to constr#ct variable na*es that e/actly rese*ble the 9eywordsG 2owever, it wo#ld be sa er not to *i/ #p the variable na*es and the 9eywordsG The 9eywords are also called D"eserved words@G There are only -2 9eywords available in CG +ig#re 'G5 gives a list o these 9eywords or yo#r ready re erenceG 1 detailed disc#ssion o each o these 9eywords wo#ld be ta9en #p in later chapters wherever their #se is relevantG

Chapter /0 -etting tarted

13

auto break case char const continue default do

double else enum extern float for goto if

int long register return short signed sizeof static

struct switch typedef union unsigned void volatile while

+ig#re 'G5 )ote that co*piler vendors >li9e 5icroso t, 8orland, etcG? provide their own 9eywords apart ro* the ones *entioned aboveG These incl#de e/tended 9eywords li9e near, 8ar, as1, etcG Tho#gh it has been s#ggested by the 1)S$ co**ittee that every s#ch co*piler speci ic 9eyword sho#ld be preceded by two #nderscores >as in as1 ?, not every vendor ollows this r#leG

The First C !rogra1


1r*ed with the 9nowledge abo#t the types o variables, constants I 9eywords the ne/t logical step is to co*bine the* to or* instr#ctionsG 2owever, instead o this, we wo#ld write o#r irst C progra* nowG 3nce we have done that we wo#ld see in detail the instr#ctions that it *ade #se o G 8e ore we begin with o#r irst C progra* do re*e*ber the ollowing r#les that are applicable to all C progra*sP
(a)

.ach instr#ction in a C progra* is written as a separate state*entG There ore a co*plete C progra* wo#ld co*prise o a series o state*entsG

14

%et .s C

(b) The state*ents in a progra* *#st appear in the sa*e order in

which we wish the* to be e/ec#ted_ #nless o co#rse the logic o the proble* de*ands a deliberate DQ#*p@ or trans er o control to a state*ent, which is o#t o seH#enceG
(c) 8lan9 spaces *ay be inserted between two words to i*prove

the readability o the state*entG 2owever, no blan9 spaces are allowed within a variable, constant or 9eywordG
(d) 1ll state*ents are entered in s*all case lettersG (e)

C has no speci ic r#les or the position at which a state*ent is to be writtenG That@s why it is o ten called a ree< or* lang#ageG .very C state*ent *#st end with a ;G Th#s ; acts as a state*ent ter*inatorG

(f)

7et #s now write down o#r irst C progra*G $t wo#ld si*ply calc#late si*ple interest or a set o val#es representing principle, n#*ber o years and rate o interestG
)* +a%',%ati!n !$ sim %e interest *) )* A,th!r -e.a/ 0ate: 25)05)2004 *) main1 2 3 int " n # $%!at r" si # = 1000 # n=3# r = 8.5 # )* $!rm,%a $!r sim %e interest *) si = * n * r ) 100 # rint$ 1 45$4 " si 2 #

Chapter /0 -etting tarted


6

15

)ow a ew #se #l tips abo#t the progra*GGG Co**ent abo#t the progra* sho#ld be enclosed within =W W=G +or e/a*ple, the irst two state*ents in o#r progra* are co**entsG

Tho#gh co**ents are not necessary, it is a good practice to begin a progra* with a co**ent indicating the p#rpose o the progra*, its a#thor and the date on which the progra* was writtenG 1ny n#*ber o co**ents can be written at any place in the progra*G +or e/a*ple, a co**ent can be written be ore the state*ent, a ter the state*ent or within the state*ent as shown belowP
)* $!rm,%a *) si = * n * r ) 100 # si = * n * r ) 100 # )* $!rm,%a *) si = * n * r ) )* $!rm,%a *) 100 #

So*eti*es it is not so obvio#s as to what a partic#lar state*ent in a progra* acco*plishesG 1t s#ch ti*es it is worthwhile *entioning the p#rpose o the state*ent >or a set o state*ents? #sing a co**entG +or e/a*pleP
)* $!rm,%a $!r sim %e interest *) si = * n * r ) 100 #

3 ten progra**ers see* to ignore writing o co**entsG 8#t when a tea* is b#ilding big so tware well co**ented code is al*ost essential or other tea* *e*bers to #nderstand itG

1"

%et .s C

1ltho#gh a lot o co**ents are probably not necessary in this progra*, it is #s#ally the case that progra**ers tend to #se too ew co**ents rather than too *anyG 1n adeH#ate n#*ber o co**ents can save ho#rs o *isery and s# ering when yo# later try to ig#re o#t what the progra* doesG The nor*al lang#age r#les do not apply to te/t written within +< .. <+G Th#s we can type this te/t in s*all case, capital or a co*binationG This is beca#se the co**ents are solely given or the #nderstanding o the progra**er or the ellow progra**ers and are co*pletely ignored by the co*pilerG Co**ents cannot be nestedG +or e/a*ple,
)* +a% !$ 7I )* A,th!r sam (ate 01)01)2002 *) *)

is invalidG 1 co**ent can be split over *ore than one line, as in,
)* 8his is a 9a::/ '!mment *)

S#ch a co**ent is o ten called a *#lti<line co**entG 1ain= > is a collective na*e given to a set o state*entsG This na*e has to be 1ain= >, it cannot be anything elseG 1ll state*ents that belong to 1ain= > are enclosed within a pair o braces [ \ as shown belowG
main1 2 3 statement 1 # statement 2 #

Chapter /0 -etting tarted


statement 3 # 6

17

Technically spea9ing 1ain= > is a #nctionG .very #nction has a pair o parentheses = > associated with itG We wo#ld disc#ss #nctions and their wor9ing in great detail in Chapter 5G 1ny variable #sed in the progra* *#st be declared be ore #sing itG +or e/a*ple,
int " n # $%!at r" si #

1ny C state*ent always ends with a _ +or e/a*ple,


$%!at r" si # r = 8.5 #

$n the state*ent,
si = * n * r ) 100 #

< and + are the arith*etic operatorsG The arith*etic operators available in C are ?, @, < and +G C is very rich in operatorsG There are abo#t 45 operators available in CG S#rprisingly there is no operator or e/ponentiationGGG a slip, which can be orgiven considering the act that C has been developed by an individ#al, not by a co**itteeG 3nce the val#e o si is calc#lated it needs to be displayed on the screenG 6nli9e other lang#ages, C does not contain any instr#ction to display o#tp#t on the screenG 1ll o#tp#t to screen is achieved #sing ready*ade library #nctionsG 3ne s#ch

1&

%et .s C
#nction is print8= >G We have #sed it display on the screen the val#e contained in siG The general or* o print8= > #nction is,
rint$ 1 4;$!rmat strin-<4" ;%ist !$ =aria&%es< 2 # ;$!rmat strin-< 'an '!ntain" 5$ $!r rintin- rea% =a%,es 5( $!r rintin- inte-er =a%,es 5' $!r rintin- 'hara'ter =a%,es

$n addition to or*at speci iers li9e A8, Ad and Ac the or*at string *ay also contain any other charactersG These characters are printed as they are when the print8= > is e/ec#tedG +ollowing are so*e e/a*ples o #sage o print8= > #nctionP
rint$ 1 45$4" si 2 # rint$ 1 45( 5( 5$ 5$4" " n" r" si 2 # rint$ 1 47im %e interest = >s. 5$4" si 2 # rint$ 1 4?rin = 5( @n>ate = 5$4" " r 2 #

The o#tp#t o the last state*ent wo#ld loo9 li9e thisGGG


?rin = 1000 >ate = 8.5

What is DZn@ doing in this state*entc $t is called newline and it ta9es the c#rsor to the ne/t lineG There ore, yo# get the o#tp#t split over two linesG DZn@ is one o the several .scape SeH#ences available in CG These are disc#ssed in detail in Chapter ''G "ight now, all that we can say is DZn@ co*es in

Chapter /0 -etting tarted

19

handy when we want to or*at the o#tp#t properly on separate linesG print8= > can not only print val#es o variables, it can also print the res#lt o an e/pressionG 1n e/pression is nothing b#t a valid co*bination o constants, variables and operatorsG Th#s, -, - L 2, c and a L b W c F d all are valid e/pressionsG The res#lts o these e/pressions can be printed as shown belowP
rint$ 1 45( 5( 5( 5(4" 3" 3 + 2" '" a + & * ' A ( 2 #

)ote that 3 and c also represent valid e/pressionsG

Co1pilation and B3ecution


3nce yo# have written the progra* yo# need to type it and instr#ct the *achine to e/ec#te itG To type yo#r C progra* yo# need another progra* called .ditorG 3nce the progra* has been typed it needs to be converted to *achine lang#age >(s and 's? be ore the *achine can e/ec#te itG To carry o#t this conversion we need another progra* called Co*pilerG Co*piler vendors provide an $ntegrated 0evelop*ent .nviron*ent >$0.? which consists o an .ditor as well as the Co*pilerG There are several s#ch $0.s available in the *ar9et targeted towards di erent operating syste*sG +or e/a*ple, T#rbo C, T#rbo CLL and 5icroso t C are so*e o the pop#lar co*pilers that wor9 #nder 5S<03S_ Vis#al CLL and 8orland CLL are the co*pilers that wor9 #nder Windows, whereas gcc co*piler wor9s #nder 7in#/G )ote that T#rbo CLL, 5icroso t CLL and 8orland CLL so tware also contain a C co*piler b#ndled with the*G $ yo# are a beginner yo# wo#ld be better o #sing a si*ple co*piler li9e T#rbo C or T#rbo CLLG 3nce yo# have *astered the lang#age ele*ents yo# can then switch over to *ore sophisticated co*pilers li9e Vis#al CLL #nder Windows or gcc #nder 7in#/G 5ost o the

2)

%et .s C

progra*s in this boo9 wo#ld wor9 with all the co*pilersG Wherever there is a deviation $ wo#ld point it o#t that ti*eG 1ss#*ing that yo# are #sing a T#rbo C or T#rbo CLL co*piler here are the steps that yo# need to ollow to co*pile and e/ec#te yo#r irst C progra*: >a? Start the co*piler at CC pro*ptG The co*piler >TCG.A. is #s#ally present in CDETCE-*9 directory?G >b? Select 9e0 ro* the File *en#G >c? Type the progra*G >d? Save the progra* #sing F2 #nder a proper na*e >say ,rogra*'Gc?G >e? 6se Ctrl ? F9 to co*pile and e/ec#te the progra*G > ? 6se 'lt ? F5 to view the o#tp#tG )ote that on co*piling the progra* its *achine lang#age eH#ivalent is stored as an .A. ile >,rogra*'G.A.? on the dis9G This ile is called an e/ec#table ileG $ we copy this ile to another *achine we can e/ec#te it there witho#t being reH#ired to reco*pile itG $n act the other *achine need not even have a co*piler to be able to e/ec#te the ileG 1 word o ca#tion4 $ yo# r#n this progra* in T#rbo CLL co*piler, yo# *ay get an error R KThe #nction print sho#ld have a prototypeOG To get rid o this error, per or* the ollowing steps and then reco*pile the progra*G >a? Select D3ptions@ *en# and then select DCo*piler Y CLL 3ptions@G $n the dialog bo/ that pops #p, select DC,, always@ >b? in the D6se CLL Co*piler@ optionsG 1gain select D3ptions@ *en# and then select D.nviron*ent Y .ditor@G 5a9e s#re that the de a#lt e/tension is DC@ rather than DC,,@G

Chapter /0 -etting tarted

21

$ecei%ing *nput
$n the progra* disc#ssed above we ass#*ed the val#es o p, n and r to be '(((, - and %G5G .very ti*e we r#n the progra* we wo#ld get the sa*e val#e or si*ple interestG $ we want to calc#late si*ple interest or so*e other set o val#es then we are reH#ired to *a9e the relevant change in the progra*, and again co*pile and e/ec#te itG Th#s the progra* is not general eno#gh to calc#late si*ple interest or any set o val#es witho#t being reH#ired to *a9e a change in the progra*G 5oreover, i yo# distrib#te the .A. ile o this progra* to so*ebody he wo#ld not even be able to *a9e changes in the progra*G 2ence it is a good practice to create a progra* that is general eno#gh to wor9 or any set o val#esG To *a9e the progra* general the progra* itsel sho#ld as9 the #ser to s#pply the val#es o p, n and r thro#gh the 9eyboard d#ring e/ec#tionG This can be achieved #sing a #nction called scan8= >G This #nction is a co#nter<part o the print8= > #nctionG print8= > o#tp#ts the val#es to the screen whereas scan8= > receives the* ro* the 9eyboardG This is ill#strated in the progra* shown belowG
)* +a%',%ati!n !$ sim %e interest *) )* A,th!r -e.a/ 0ate 25)05)2004 *) main1 2 3 int " n # $%!at r" si # rint$ 1 4Enter =a%,es !$ " n" r4 2 # s'an$ 1 45( 5( 5$4" B " Bn" Br 2 # si = * n * r ) 100 # rint$ 1 45$4 " si 2 # 6

22

%et .s C

The irst print8= > o#tp#ts the *essage D.nter val#es o p, n, r@ on the screenG 2ere we have not #sed any e/pression in print8= > which *eans that #sing e/pressions in print8= > is optionalG )ote that the a*persand > ? be ore the variables in the scan8= > #nction is a *#stG is an D1ddress o @ operatorG $t gives the location n#*ber #sed by the variable in *e*oryG When we say a, we are telling scan8= > at which *e*ory location sho#ld it store the val#e s#pplied by the #ser ro* the 9eyboardG The detailed wor9ing o the operator wo#ld be ta9en #p in Chapter 5G )ote that a blan9, a tab or a new line *#st separate the val#es s#pplied to scan8= >G )ote that a blan9 is creating #sing a spacebar, tab #sing the Tab 9ey and new line #sing the .nter 9eyG This is shown belowP ./GP The three val#es separated by blan9
1000 5 15.5

./GP The three val#es separated by tabG


1000 5 1000 5 15.5 15.5

./GP The three val#es separated by newlineG

So *#ch or the tipsG 2ow abo#t another progra* to give yo# a eel o thingsGGG
)* C,st $!r $,n. A,th!r: D!:! *) main1 2 3 int n,m # rint$ 1 4Enter a n,m&er4 2 #

Chapter /0 -etting tarted


s'an$ 1 45(4" Bn,m 2 # rint$ 1 4E!F I am %ettin- /!, !n a se'ret...4 2 # rint$ 1 4G!, ha=e 9,st entere( the n,m&er 5(4" n,m 2 # 6

23

C *nstructions
)ow that we have written a ew progra*s let #s loo9 at the instr#ctions that we #sed in these progra*sG There are basically three types o instr#ctions in CP
(a) Type 0eclaration $nstr#ction (b) 1rith*etic $nstr#ction (c) Control $nstr#ction

The p#rpose o each o these instr#ctions is given belowP


(a) Type declaration instr#ction

To declare the type o variables #sed in a C progra*G To per or* arith*etic operations between con< stants and variablesG

(b) 1rith*etic instr#ction

(c)

Control instr#ction

To control the seH#ence o e/ec#tion o vario#s state< *ents in a C progra*G

Since, the ele*entary C progra*s wo#ld #s#ally contain only the type declaration and the arith*etic instr#ctions_ we wo#ld disc#ss only these two instr#ctions at this stageG The other types o instr#ctions wo#ld be disc#ssed in detail in the s#bseH#ent chaptersG

24
T#pe Declaration *nstruction

%et .s C

This instr#ction is #sed to declare the type o variables being #sed in the progra*G 1ny variable #sed in the progra* *#st be declared be ore #sing it in any state*entG The type declaration state*ent is written at the beginning o 1ain= > #nctionG
Ex.: int &as # $%!at rs" -r!sssa% # 'har name" '!(e #

There are several s#btle variations o instr#ctionG These are disc#ssed belowP shown belowG
int i = 10" 9 = 25 # $%!at a = 1.5" & = 1.99 + 2.4 * 1.44 #

the type declaration

(a) While declaring the type o variable we can also initiali;e it as

(b) The order in which we de ine the variables is so*eti*es

i*portant so*eti*es notG +or e/a*ple,


int i = 10" 9 = 25 #

is sa*e as
int 9 = 25" 9 = 10 #

2owever,
$%!at a = 1.5" & = a + 3.1 #

is alright, b#t
$%!at & = a + 3.1" a = 1.5 #

Chapter /0 -etting tarted

25

is notG This is beca#se here we are trying to #se a even be ore de ining itG
(c) The ollowing state*ents wo#ld wor9

int a" &" '" ( # a = & = ' = 10 #

2owever, the ollowing state*ent wo#ld not wor9


int a = & = ' = ( = 10 #

3nce again we are trying to #se 6 >to assign to a? be ore de ining itG

'rith1etic *nstruction
1 C arith*etic instr#ction consists o a variable na*e on the le t hand side o X and variable na*es I constants on the right hand side o XG The variables and constants appearing on the right hand side o X are connected by arith*etic operators li9e ?4 @4 <4 and +G
Ex.: int a( # $%!at .!t" (eta" a% ha" &eta" -amma # a( = 3200 # .!t = 0.0056 # (eta = a% ha * &eta ) -amma + 3.2 * 2 ) 5 #

2ere, <4 +4 @4 ? are the arith*etic operatorsG F is the assign*ent operatorG 2, 5 and -2(( are integer constantsG -G2 and (G((56 are real constantsG ad is an integer variableG Got4 deta4 alpha4 6eta4 ga11a are real variablesG

2"

%et .s C

The variables and constants together are called Doperands@ that are operated #pon by the Darith*etic operators@ and the res#lt is assigned, #sing the assign*ent operator, to the variable on le t< hand sideG 1 C arith*etic state*ent co#ld be o three typesG These are as ollowsP
(a) $nteger *ode arith*etic state*ent < This is an arith*etic (b) integer constantsG

state*ent in which all operands are either integer variables or

(c) Ex.: int i" .in-" issa'" n!teit #

i=i+1# .in- = issa' * 234 + n!teit - 7689 #

"eal *ode arith*etic state*ent < This is an arith*etic state*ent in which all operands are either real constants or real variablesG
Ex.: $%!at H&ee" antin." si" rin" an!/" r!i # H&ee = antin. + 23.123 ) 4.5 * 0.3442 # si = rin * an!/ * r!i ) 100.0 #

5i/ed *ode arith*etic state*ent < This is an arith*etic state*ent in which so*e o the operands are integers and so*e o the operands are realG
Ex.: $%!at si" rin" an!/" r!i" a=- # int a" &" '" n,m # si = rin * an!/ * r!i ) 100.0 # a=- = 1 a + & + ' + n,m 2 ) 4 #

$t is very i*portant to #nderstand how the e/ec#tion o an arith*etic state*ent ta9es placeG +irstly, the right hand side is eval#ated #sing constants and the n#*erical val#es stored in the variable na*esG This val#e is then assigned to the variable on the le t<hand sideG

Chapter /0 -etting tarted

27

Tho#gh 1rith*etic instr#ctions loo9 si*ple to #se one o ten co**its *ista9es in writing the*G 7et #s ta9e a closer loo9 at these state*entsG )ote the ollowing points care #llyG >a? C allows only one variable on le t<hand side o FG That is, H F G < l is legal, whereas G < l F H is illegalG >b? $n addition to the division operator C also provides a *od#lar division operatorG This operator ret#rns the re*ainder on dividing one integer with anotherG Th#s the e/pression '( = 2 yields 5, whereas, '( U 2 yields (G )ote that the *od#l#s operator >A? cannot be applied on a loatG 1lso note that on #sing U the sign o the re*ainder is always sa*e as the sign o the n#*eratorG Th#s F5 U 2 yields F', whereas, 5 U <2 yields 'G >c? 1n arith*etic instr#ction is o ten #sed or storing character constants in character variablesG
'har a" &" ( # a = 'I' # & = 'J' # ( = '+' #

When we do this the 1SC$$ val#es o the characters are stored in the variablesG 1SC$$ val#es are #sed to represent any character in *e*oryG The 1SC$$ val#es o D+@ and DG@ are !( >d? and !' >re er the 1SC$$ Table in 1ppendi/ .?G 1rith*etic operations can be per or*ed on ints, 8loats and charsG Th#s the state*ents,
'har x" / # int : # x = 'a' # / = '&' # :=x+/#

2&

%et .s C
are per ectly valid, since the addition is per or*ed on the 1SC$$ val#es o the characters and not on characters the*selvesG The 1SC$$ val#es o Da@ and Db@ are &! and &%, and hence can de initely be addedG

>e? )o operator is ass#*ed to be presentG $t *#st be written e/plicitlyG $n the ollowing e/a*ple, the *#ltiplication operator a ter b *#st be e/plicitly writtenG
a = '.(.&1x/2 &='*(*&*1x*/2 ,s,a% arithmeti' statement + statement

> ? 6nli9e other high level lang#ages, there is no operator or per or*ing e/ponentiation operationG Th#s ollowing state*ents are invalidG
a = 3 ** 2 # &=3K2#

$ we want to do the e/ponentiation we can get it done this wayP


Lin'%,(e ;math.h< main1 2 3 int a # a = !F 1 3" 2 2 # rint$ 1 M5(N" a 2 # 6

2ere po0= > #nction is a standard library #nctionG $t is being #sed to raise - to the power o 2G Iinclude J1ath.hC is a preprocessor directiveG $t is being #sed here to ens#re that the po0= > #nction wor9s correctlyG We wo#ld learn *ore abo#t standard library #nctions in Chapter 5 and abo#t preprocessor in Chapter !G

Chapter /0 -etting tarted

29

*nteger and Float Con%ersions


$n order to e ectively develop C progra*s, it will be necessary to #nderstand the r#les that are #sed or the i*plicit conversion o loating point and integer val#es in CG These are *entioned belowG )ote the* care #llyG
(a) 1n arith*etic operation between an integer and integer (b) (c)

always yields an integer res#ltG 1n operation between a real and real always yields a real res#ltG 1n operation between an integer and real always yields a real res#ltG $n this operation the integer is irst pro*oted to a real and then the operation is per or*edG 2ence the res#lt is realG

$ thin9 a ew practical e/a*ples shown in the ollowing ig#re wo#ld p#t the iss#e beyond do#btG

(peration 5=2 5G( = 2 5 = 2G( 5G( = 2G(

$esult 2 2G5 2G5 2G5

(peration 2=5 2G( = 5 2 = 5G( 2G( = 5G(

$esult ( (G4 (G4 (G4

+ig#re 'G6

T#pe Con%ersion in 'ssign1ents


$t *ay so happen that the type o the e/pression and the type o the variable on the le t<hand side o the assign*ent operator *ay not be sa*eG $n s#ch a case the val#e o the e/pression is pro*oted or

3)

%et .s C

de*oted depending on the type o the variable on le t<hand side o XG +or e/a*ple, consider the ollowing assign*ent state*entsG
int i # $%!at & # i = 3.5 # & = 30 #

2ere in the irst assign*ent state*ent tho#gh the e/pression@s val#e is a 8loat >-G5? it cannot be stored in i since it is an intG $n s#ch a case the 8loat is de*oted to an int and then its val#e is storedG 2ence what gets stored in i is -G ./actly opposite happens in the ne/t state*entG 2ere, -( is pro*oted to -(G(((((( and then stored in 6, since 6 being a 8loat variable cannot hold anything e/cept a 8loat val#eG $nstead o a si*ple e/pression #sed in the above e/a*ples i a co*ple/ e/pression occ#rs, still the sa*e r#les applyG +or e/a*ple, consider the ollowing progra* rag*entG
$%!at a" &" ' # int s # s = a * & * ' ) 100 + 32 ) 4 - 3 * 1.1 #

2ere, in the assign*ent state*ent so*e operands are ints whereas others are 8loatsG 1s we 9now, d#ring eval#ation o the e/pression the ints wo#ld be pro*oted to 8loats and the res#lt o the e/pression wo#ld be a 8loatG 8#t when this 8loat val#e is assigned to s it is again de*oted to an int and then stored in sG 3bserve the res#lts o the arith*etic state*ents shown in +ig#re 'G!G $t has been ass#*ed that G is an integer variable and a is a real variableG

Chapter /0 -etting tarted

31

'rith1etic *nstruction $esult 'rith1etic *nstruction $esult 9X2=& 9 X 2G( = & 9 X 2 = &G( 9 X 2G( = &G( 9X&=2 9 X &G( = 2 9 X & = 2G( 9 X &G( = 2G( ( ( ( ( 4 4 4 4 aX2=& a X 2G( = & a X 2 = &G( a X 2G( = &G( aX&=2 a X &G( = 2 a X & = 2G( a X &G( = 2G( (G( (G2222 (G2222 (G2222 4G( 4G5 4G5 4G5

+ig#re 'G! )ote that tho#gh the ollowing state*ents give the sa*e res#lt, (, the res#lts are obtained di erentlyG
.=2)9# . = 2.0 ) 9 #

$n the irst state*ent, since both 2 and & are integers, the res#lt is an integer, iGeG (G This ( is then assigned to GG $n the second state*ent & is pro*oted to &G( and then the division is per or*edG 0ivision yields (G222222G 2owever, this cannot be stored in G, G being an intG 2ence it gets de*oted to ( and then stored in GG

2ierarch# o8 (perations
While e/ec#ting an arith*etic state*ent, which has two or *ore operators, we *ay have so*e proble*s as to how e/actly does it get e/ec#tedG +or e/a*ple, does the e/pression 2 W / < - W y correspond to >2/?<>-y? or to 2>/<-y?c Si*ilarly, does 1 = 8 W C correspond to 1 = >8 W C? or to >1 = 8? W Cc To answer these H#estions satis actorily one has to #nderstand the Dhierarchy@ o operationsG The priority or precedence in which the operations in

32

%et .s C

an arith*etic state*ent are per or*ed is called the hierarchy o operationsG The hierarchy o co**only #sed operators is shown in +ig#re 'G%G

!riorit# ' 2 st nd rd

(perators W=U L< X

Description *#ltiplication, division, *od#lar division addition, s#btraction assign*ent

+ig#re 'G% )ow a ew tips abo#t #sage o operators in generalG


(a) Within parentheses the sa*e hierarchy as *entioned in +ig#re

'G'' is operativeG 1lso, i there are *ore than one set o parentheses, the operations within the inner*ost parentheses wo#ld be per or*ed irst, ollowed by the operations within the second inner*ost pair and so onG
(b) We *#st always re*e*ber to #se pairs o parenthesesG 1

careless i*balance o the right and le t parentheses is a co**on errorG 8est way to avoid this error is to type > ? and then type an e/pression inside itG 1 ew e/a*ples wo#ld clari y the iss#e #rtherG B3a1ple 1.1D 0eter*ine the hierarchy o operations and eval#ate the ollowing e/pressionP
i=2*3)4+4)4+8-2+5)8

Stepwise eval#ation o this e/pression is shown belowP


i=2*3)4+4)4+8-2+5)8

Chapter /0 -etting tarted


i=6)4+4)4+8-2+5)8 i=1+4)4+8-2+5)8 i = 1 + 1+ 8 - 2 + 5 ) 8 i=1+1+8-2+0 i=2+8-2+0 i = 10 - 2 + 0 i=8+0 i=8 ! ! ! ! ! ! ! ! erati!n: * erati!n: ) erati!n: ) erati!n: ) erati!n: + erati!n: + erati!n : erati!n: +

33

)ote that 6 = 4 gives ' and not 'G5G This so happens beca#se 6 and 4 both are integers and there ore wo#ld eval#ate to only an integer constantG Si*ilarly 5 = % eval#ates to ;ero, since 5 and % are integer constants and hence *#st ret#rn an integer val#eG B3a1ple 1.2D 0eter*ine the hierarchy o operations and eval#ate the ollowing e/pressionP
.. = 3 ) 2 * 4 + 3 ) 8 + 3

Stepwise eval#ation o this e/pression is shown belowP


.. = 3 ) 2 * 4 + 3 ) 8 + 3 .. = 1 * 4 + 3 ) 8 + 3 .. = 4 + 3 ) 8 + 3 .. = 4 + 0 + 3 .. = 4 + 3 .. = 7

! erati!n: ) ! erati!n: * ! erati!n: ) ! erati!n: + ! erati!n: +

)ote that - = % gives ;ero, again or the sa*e reason *entioned in the previo#s e/a*pleG 1ll operators in C are ran9ed according to their precedenceG 1nd *ind yo# there are as *any as 45 odd operators in C, and these can a ect the eval#ation o an e/pression in s#btle and #ne/pected ways i we arenJt care #lG 6n ort#nately, there are no si*ple r#les that one can ollow, s#ch as K83051SO that tells algebra st#dents in which order does an e/pression eval#ateG We have not

34

%et .s C

enco#ntered *any o#t o these 45 operators, so we won@t p#rs#e the s#bQect o precedence any #rther hereG 2owever, it can be reali;ed at this stage that it wo#ld be al*ost i*possible to re*e*ber the precedence o all these operatorsG So a #ll< ledged list o all operators and their precedence is given in 1ppendi/ 1G This *ay so#nd da#nting, b#t when its contents are absorbed in s*all bites, it beco*es *ore palatableG So ar we have seen how the co*p#ter eval#ates an arith*etic state*ent written in CG 8#t o#r 9nowledge wo#ld be inco*plete #nless we 9now how to convert a general arith*etic state*ent to a C state*entG C can handle any co*ple/ e/pression with easeG So*e o the e/a*ples o C e/pressions are shown in +ig#re 'G&G

'lge6ric B3pression

C B3pression

a/b1c/d (m 2 n) (a 2 b) 3"4 2 4" 2 5 a+b+c d+e

aWbFcWd >* L n? W >a L b? -W/W/L2W/L 5 >aLbLc?=>dLe?

2 W b W y = > d L ' ? F / = 2 $6 " d + ' -> 7 + y ? - W > ; L y ? +ig#re 'G&

'ssociati%it# o8 (perators
When an e/pression contains two operators o eH#al priority the tie between the* is settled #sing the associativity o the operatorsG 1ssociativity can be o two typesR7e t to "ight or "ight to 7e tG 7e t to "ight associativity *eans that the le t operand *#st be

Chapter /0 -etting tarted

35

#na*big#o#sG 6na*big#o#s in what sensec $t *#st not be involved in eval#ation o any other s#b<e/pressionG Si*ilarly, in case o "ight to 7e t associativity the right operand *#st be #na*big#o#sG 7et #s #nderstand this with an e/a*pleG Consider the e/pression aX-=2W5 _ 2ere there is a tie between operators o sa*e priority, that is between = and WG This tie is settled #sing the associativity o = and WG 8#t both enQoy 7e t to "ight associativityG +ig#re 'G'( shows or each operator which operand is #na*big#o#s and which is notG

3perator 7e t = W - = 2 or 2

"ight

"e*ar9

operand is 2 or 2 W 7e t 5 #na*big#o#s, "ight is not 5 "ight operand is #na*big#o#s, 7e t is not

+ig#re 'G'( Since both = and W have 7 to " associativity and only = has #na*big#o#s le t operand >necessary condition or 7 to " associativity? it is per or*ed earlierG Consider one *ore e/pression
a=&=3#

2ere both assign*ent operators have the sa*e priority and sa*e associativity >"ight to 7e t?G +ig#re 'G'' shows or each operator which operand is #na*big#o#s and which is notG

3"

%et .s C

3perator 7e t X a

"ight

"e*ar9 is is

b or b X 7e t operand #na*big#o#s, "ight not -

b or a X b

"ight operand is #na*big#o#s, 7e t is not

+ig#re 'G'' Since both X have " to 7 associativity and only the second X has #na*big#o#s right operand >necessary condition or " to 7 associativity? the second X is per or*ed earlierG Consider yet another e/pression
:=a*&+')(#

2ere < and + enQoys sa*e priority and sa*e associativity >7e t to "ight?G +ig#re 'G'2 shows or each operator which operand is #na*big#o#s and which is notG

3perator W = +ig#re 'G'2

7e t a c

"ight "e*ar9 b d 8oth operands are #na*big#o#s 8oth operands are #na*big#o#s

2ere since le t operands or both operators are #na*big#o#s Co*piler is ree to per or* < or + operation as per its convenience

Chapter /0 -etting tarted

37

since no *atter which is per or*ed earlier the res#lt wo#ld be sa*eG 1ppendi/ 1 gives the associativity o all the operators available in CG

Control *nstructions in C
1s the na*e s#ggests the DControl $nstr#ctions@ enable #s to speci y the order in which the vario#s instr#ctions in a progra* are to be e/ec#ted by the co*p#terG $n other words the control instr#ctions deter*ine the D low o control@ in a progra*G There are o#r types o control instr#ctions in CG They areP >a? >b? >c? >d? SeH#ence Control $nstr#ction Selection or 0ecision Control $nstr#ction "epetition or 7oop Control $nstr#ction Case Control $nstr#ction

The SeH#ence control instr#ction ens#res that the instr#ctions are e/ec#ted in the sa*e order in which they appear in the progra*G 0ecision and Case control instr#ctions allow the co*p#ter to ta9e a decision as to which instr#ction is to be e/ec#ted ne/tG The 7oop control instr#ction helps co*p#ter to e/ec#te a gro#p o state*ents repeatedlyG $n the ollowing chapters we are going to learn these instr#ctions in detailG Try yo#r hand at the ./ercise presented on the ollowing pages be ore proceeding to the ne/t chapter, which disc#sses the decision control instr#ctionG

Su11ar#
>a? The three pri*ary constants and variable types in C are integer, loat and characterG >b? 1 variable na*e can be o *a/i*#* -' charactersG >c? 0o not #se a 9eyword as a variable na*eG

3&

%et .s C

>d? 1n e/pression *ay contain any seH#ence o constants, variables and operatorsG >e? 3perators having eH#al precedence are eval#ated #sing associativityG > ? 7e t to right associativity *eans that the le t operand o a operator *#st be #na*big#o#s whereas right to le t associativity *eans that the right operand o a operator *#st be #na*big#o#sG >g? $np#t=o#tp#t in C can be achieved #sing scan8= > and print8= > #nctionsG

B3ercise
K'L Which o the ollowing are invalid variable na*es and whyc DA7I+7AOA>G LPEAE ! ,%ati!n in 2006 IOQA8 teamRs=i't!r/ _&asi' -r!, . !=er time hEOOQ ?%!t L 3 &asi'-hra 422 min(!=ermatter H,e,e. 2015_00a/

K-L ,oint o#t the errors, i any, in the ollowing C state*entsP

>a? int X -'4G562 W '5( _ >b? na*e X D1Qay@ _ >c? varchar X D-@ _ >d? -G'4 W r W r W h X volBo Bcyl _ >e? 9 X > a W b ? > c L > 2G5a L b ? > d L e ? _ > ? *Binst X rate o interest W a*o#nt in rs _

Chapter /0 -etting tarted


>g? si X principal W rateo interest W n#*bero years = '(( _ >h? area X -G'4 W r WW 2 _ >i? vol#*e X -G'4 W r V 2 W h _ >Q? 9 X > >a W b ? L c ? > 2G5 W a L b ? _ >9? a X b X - X 4 _ >l? co#nt X co#nt L ' _ >*? date X J2 5ar (4J _

39

KCL .val#ate the ollowing e/pressions and show their hierarchyG

>a? g X big = 2 L big W 4 = big < big L abc = - _ >abc X 2G5, big X 2, ass#*e g to be a loat? >b? on X in9 W act = 2 L - = 2 W act L 2 L tig _ >in9 X 4, act X ', tig X -G2, ass#*e on to be an int? >c? s X H#i W add = 4 < 6 = 2 L 2 = - W 6 = god _ >H#i X 4, add X 2, god X 2, ass#*e s to be an int? >d? s X ' = - W a = 4 < 6 = 2 L 2 = - W 6 = g _ >a X 4, g X -, ass#*e s to be an int?
KDL +ill the ollowing table or the e/pressions given below and then eval#ate the res#ltG 1 sa*ple entry has been illed in the table or e/pression >a?G

4)

%et .s C

3perator =

7e t '(

"ight

"e*ar9

5 or 5 = 2 7e t operand is =' #na*big#o#s, "ight is not GG GG

GG

GG

>a? g X '( = 5 =2 = ' _ >b? b X - = 2 L 5 W 4 = - _ >c? a X b X c X - L 4 _


KBL Convert the state*entsG

ollowing eH#ations into corresponding C

>a? >b? >c? >d?

E= A= "= 1X

%G% > a + b ? 2 = c < (G5 + 2 a = > H + r? >a+b?W>'=*? < b + > b W b ? + 2 4ac 2a 2v + 6G22 > c + d ? g+v !G!b > /y L a ? = c < (G% L 2b > / L a ? >' = y ?

KFL What wo#ld be the o#tp#t o the ollowing progra*sP 1a2 main1 2 3

Chapter /0 -etting tarted


int i = 2" 9 = 3" ." % # $%!at a" & # .=i)9*9# %=9)i*i# a=i)9*9# &=9)i*i# rint$1 45( 5( 5$ 5$4" ." %" a" & 2 # 6 1&2 main1 2 3 int a" & # a = -3 - - 3 # & = -3 - - 1 - 3 2 # rint$ 1 4a = 5( & = 5(4" a" & 2 # 6 1'2 main1 2 3 $%!at a = 5" & = 2 # int ' # '=a5&# rint$ 1 45(4" ' 2 # 6

41

1(2 main1 2 3 rint$ 1 4nn @n@n nn@n4 2 # rint$ 1 4nn )n)n nn)n4 2 # 6 1e2 main1 2 3 int a" & # rint$ 1 4Enter =a%,es !$ a an( &4 2 # s'an$ 1 4 5( 5( 4" Ba" B& 2 # rint$ 1 4a = 5( & = 5(4" a" & 2 # 6

42
1$2 main1 2 3 int " H # rint$ 1 4Enter =a%,es !$ an( H4 2 # s'an$ 1 4 5( 5( 4" " H 2 # rint$ 1 4 = 5( H =5(4" " H 2 # 6

%et .s C

KGL ,ic9 #p the correct alternative or each o the ollowing H#estionsP

>a? C lang#age has been developed by >'? Ken Tho*pson >2? 0ennis "itchie >-? ,eter )orton >4? 5artin "ichards >b? C can be #sed on >'? 3nly 5S<03S operating syste* >2? 3nly 7in#/ operating syste* >-? 3nly Windows operating syste* >4? 1ll the above >c? C progra*s are converted into *achine lang#age with the help o >'? 1n .ditor >2? 1 co*piler >-? 1n operating syste* >4? )one o the above >d? The real constant in C can be e/pressed in which o the ollowing or*s >'? +ractional or* only >2? ./ponential or* only >-? 1SC$$ or* only

Chapter /0 -etting tarted


>4? 8oth ractional and e/ponential or*s >e? 1 character variable can at a ti*e store >'? ' character >2? % characters >-? 254 characters >4? )one o the above > ? The state*ent char ch F MNO wo#ld store in ch >'? The character E >2? 1SC$$ val#e o E >-? E along with the single inverted co**as >4? 8oth >'? and >2? >g? Which o the ollowing is )3T a character constant >'? DThan9 Co#@ >2? D.nter val#es o ,, ), "@ >-? D2-G56.<(-@ >4? 1ll the above >h? The *a/i*#* val#e that an integer constant can have is >'? <-2!6! >2? -2!6! >-? 'G!('4eL-% >4? F'G!('4eL-% >i? 1 C variable cannot start with >'? 1n alphabet >2? 1 n#*ber >-? 1 special sy*bol other than #nderscore >4? 8oth >2? I >-? above >Q? Which o the ollowing state*ent is wrong >'? *es X '2-G56 _ >2? con X JTJ W J1J _ >-? this X JTJ W 2( _ >4? - L a X b _

43

44

%et .s C

>9? Which o the ollowing shows the correct hierarchy o arith*etic operators in C >'? WW, W or =, L or < >2? WW, W, =, L, < >-? WW, =, W, L, < >4? = or W, < or L >l? $n b X 6G6 = a L 2 W n _ which operation will be per or*ed irstc >'? 6G6 = a >2? a L 2 >-? 2 W n >4? 0epends #pon co*piler >*? Which o the ollowing is allowed in a C 1rith*etic instr#ction >'? ] ^ >2? [ \ >-? > ? >4? )one o the above >n? Which o the ollowing state*ents is alse >'? .ach new C instr#ction has to be written on a separate line >2? 6s#ally all C state*ents are entered in s*all case letters >-? 8lan9 spaces *ay be inserted between two words in a C state*ent >4? 8lan9 spaces cannot be inserted within a variable na*e >o? $ a is an integer variable, a X 5 = 2 _ will ret#rn a val#e >'? 2G5 >2? >-? 2 >4? ( >p? The e/pression, a X ! = 22 W > -G'4 L 2 ? W - = 5 _ eval#ates to

Chapter /0 -etting tarted


>'? >2? >-? >4? %G2% 6G2% -G'4 (

45

>H? The e/pression, a X -( W '((( L 2!6% _ eval#ates to >'? -2!6% >2? <-2!6% >-? ''-(4( >4? ( >r? The e/pression / X 4 L 2 U < % eval#ates to >'? <6 >2? 6 >-? 4 >4? )one o the above >s? 2ierarchy decides which operator >'? is *ost i*portant >2? is #sed irst >-? is astest >4? operates on largest n#*bers >t? 1n integer constant in C *#st haveP >'? 1t least one digit >2? 1tleast one deci*al point >-? 1 co**a along with digits >4? 0igits separated by co**as >#? 1 character variable can never store *ore than >'? -2 characters >2? % characters >-? 254 characters >4? ' character >v? $n C a variable cannot contain >'? 8lan9 spaces

4"
>2? 2yphen >-? 0eci*al point >4? 1ll the above >w? Which o the ollowing is +17S. in C >'? Keywords can be #sed as variable na*es >2? Variable na*es can contain a digit >-? Variable na*es do not contain a blan9 space >4? Capital letters can be #sed in variable na*es >/? $n C, 1rith*etic instr#ction cannot contain >'? variables >2? constants >-? variable na*es on right side o X >4? constants on le t side o X

%et .s C

>y? Which o the ollowing shows the correct hierarchy o arith*etic operations in C >'? = L W < >2? W < = L >-? L < = W >4? W = L < >;? What will be the val#e o d i d is a loat a ter the operation d F 2 + 7.)c >'? ( >2? (G2%5! >-? Cannot be deter*ined >4? )one o the above
K2L Write C progra*s or the ollowingP

>a? "a*esh@s basic salary is inp#t thro#gh the 9eyboardG 2is dearness allowance is 4(U o basic salary, and ho#se rent allowance is 2(U o basic salaryG Write a progra* to calc#late his gross salaryG

Chapter /0 -etting tarted

47

>b? The distance between two cities >in 9*G? is inp#t thro#gh the 9eyboardG Write a progra* to convert and print this distance in *eters, eet, inches and centi*etersG >c? $ the *ar9s obtained by a st#dent in ive di erent s#bQects are inp#t thro#gh the 9eyboard, ind o#t the aggregate *ar9s and percentage *ar9s obtained by the st#dentG 1ss#*e that the *a/i*#* *ar9s that can be obtained by a st#dent in each s#bQect is '((G >d? Te*perat#re o a city in +ahrenheit degrees is inp#t thro#gh the 9eyboardG Write a progra* to convert this te*perat#re into Centigrade degreesG >e? The length I breadth o a rectangle and radi#s o a circle are inp#t thro#gh the 9eyboardG Write a progra* to calc#late the area I peri*eter o the rectangle, and the area I circ#* erence o the circleG > ? Two n#*bers are inp#t thro#gh the 9eyboard into two locations C and 0G Write a progra* to interchange the contents o C and 0G >g? $ a ive<digit n#*ber is inp#t thro#gh the 9eyboard, write a progra* to calc#late the s#* o its digitsG >2intP 6se the *od#l#s operator DU@? >h? $ a ive<digit n#*ber is inp#t thro#gh the 9eyboard, write a progra* to reverse the n#*berG >i? $ a o#r<digit n#*ber is inp#t thro#gh the 9eyboard, write a progra* to obtain the s#* o the irst and last digit o this n#*berG >Q? $n a town, the percentage o *en is 52G The percentage o total literacy is 4%G $ total percentage o literate *en is -5 o the total pop#lation, write a progra* to ind the total n#*ber

4&

%et .s C
o illiterate *en and wo*en i the pop#lation o the town is %(,(((G

>9? 1 cashier has c#rrency notes o deno*inations '(, 5( and '((G $ the a*o#nt to be withdrawn is inp#t thro#gh the 9eyboard in h#ndreds, ind the total n#*ber o c#rrency notes o each deno*ination the cashier will have to give to the withdrawerG >l? $ the total selling price o '5 ite*s and the total pro it earned on the* is inp#t thro#gh the 9eyboard, write a progra* to ind the cost price o one ite*G >*? $ a ive<digit n#*ber is inp#t thro#gh the 9eyboard, write a progra* to print a new n#*ber by adding one to each o its digitsG +or e/a*ple i the n#*ber that is inp#t is '2-&' then the o#tp#t sho#ld be displayed as 2-4(2G

The Decision Control Structure


e 0ecisions4 0ecisions4 e The if State*ent The "eal Thing 5#ltiple State*ents within if e The if-else State*ent )ested if-elses +or*s o if e 6se o 7ogical 3perators The else if Cla#se The 4 3perator 2ierarchy o 3perators "evisited e 1 Word o Ca#tion e The Conditional 3perators e S#**ary e ./ercise

49

5)

%et .s C

e all need to alter o#r actions in the ace o changing circ#*stancesG $ the weather is ine, then $ will go or a strollG $ the highway is b#sy $ wo#ld ta9e a diversionG $ the pitch ta9es spin, we wo#ld win the *atchG $ she says no, $ wo#ld loo9 elsewhereG $ yo# li9e this boo9, $ wo#ld write the ne/t editionG Co# can notice that all these decisions depend on so*e condition being *etG C lang#age too *#st be able to per or* di erent sets o actions depending on the circ#*stancesG $n act this is what *a9es it worth its saltG C has three *aQor decision *a9ing instr#ctionsRthe i8 state*ent, the i8@else state*ent, and the s0itch state*entG 1 o#rth, so*ewhat less i*portant str#ct#re is the one that #ses conditional operatorsG $n this chapter we will e/plore all these ways >e/cept s0itch, which has a separate chapter devoted to it, later? in which a C progra* can react to changing circ#*stancesG

DecisionsP DecisionsP
$n the progra*s written in Chapter ' we have #sed seH#ence control str#ct#re in which the vario#s steps are e/ec#ted seH#entially, iGeG in the sa*e order in which they appear in the progra*G $n act to e/ec#te the instr#ctions seH#entially, we don@t have to do anything at allG 8y de a#lt the instr#ctions in a progra* are e/ec#ted seH#entiallyG 2owever, in serio#s progra**ing sit#ations, seldo* do we want the instr#ctions to be e/ec#ted seH#entiallyG 5any a ti*es, we want a set o instr#ctions to be e/ec#ted in one sit#ation, and an entirely di erent set o instr#ctions to be e/ec#ted in another sit#ationG This 9ind o sit#ation is dealt in C progra*s #sing a decision control instr#ctionG 1s *entioned earlier, a decision control instr#ction can be i*ple*ented in C #singP >a? The i8 state*ent >b? The i8@else state*ent >c? The conditional operators

Chapter 40 The 'ecision Control tructure


)ow let #s learn each o these and their variations in t#rnG

51

The if State1ent
7i9e *ost lang#ages, C #ses the 9eyword i8 to i*ple*ent the decision control instr#ctionG The general or* o i8 state*ent loo9s li9e thisP
i$ 1 this '!n(iti!n is tr,e 2 exe',te this statement #

The 9eyword i8 tells the co*piler that what ollows is a decision control instr#ctionG The condition ollowing the 9eyword i8 is always enclosed within a pair o parenthesesG $ the condition, whatever it is, is tr#e, then the state*ent is e/ec#tedG $ the condition is not tr#e then the state*ent is not e/ec#ted_ instead the progra* s9ips past itG 8#t how do we e/press the condition itsel in Cc 1nd how do we eval#ate its tr#th or alsityc 1s a general r#le, we e/press a condition #sing C@s Drelational@ operatorsG The relational operators allow #s to co*pare two val#es to see whether they are eH#al to each other, #neH#al, or whether one is greater than the otherG 2ere@s how they loo9 and how they are eval#ated in CG

this e3pression / XX y / 4X y /ay /by / aX y / bX y

is true i8 / is eH#al to y / is not eH#al to y / is less than y / is greater than y / is less than or eH#al to y / is greater than or eH#al to y

+ig#re 2G'

52

%et .s C

The relational operators sho#ld be a*iliar to yo# e/cept or the eH#ality operator FF and the ineH#ality operator PFG )ote that F is #sed or assign*ent, whereas, FF is #sed or co*parison o two H#antitiesG 2ere is a si*ple progra*, which de*onstrates the #se o i8 and the relational operatorsG
)* 0em!nstrati!n !$ i$ statement *) main1 2 3 int n,m # rint$ 1 4Enter a n,m&er %ess than 10 4 2 # s'an$ 1 45(4" Bn,m 2 # i$ 1 n,m ;= 10 2 rint$ 1 4Shat an !&e(ient ser=ant /!, are T4 2 # 6

3n e/ec#tion o this progra*, i yo# type a n#*ber less than or eH#al to '(, yo# get a *essage on the screen thro#gh print8= >G $ yo# type so*e other n#*ber the progra* doesn@t do anythingG The ollowing lowchart wo#ld help yo# #nderstand the low o control in the progra*G

Chapter 40 The 'ecision Control tructure


ST1"T ,"$)T enter a n#* less than '( $),6T n#* no is n#* b '( yes

53

,"$)T What an obedient servant yo# are 4

ST3,

+ig#re 2G2 To *a9e yo# co* ortable with the decision control instr#ction one *ore e/a*ple has been given belowG St#dy it care #lly be ore reading #rtherG To help yo# #nderstand it easily, the progra* is acco*panied by an appropriate lowchartG B3a1ple 2.1D While p#rchasing certain ite*s, a disco#nt o '(U is o ered i the H#antity p#rchased is *ore than '(((G $ H#antity and price per ite* are inp#t thro#gh the 9eyboard, write a progra* to calc#late the total e/pensesG

54
ST1"T dis X ( $),6T Hty, rate no is Hty b '((( yes

%et .s C

dis X '(

tot X Hty W rate F Hty W rate W dis = '(( ,"$)T tot ST3,

+ig#re 2G)* +a%',%ati!n !$ t!ta% ex enses *) main1 2 3 int Ht/" (is = 0 # $%!at rate" t!t # rint$ 1 4Enter H,antit/ an( rate 4 2 # s'an$ 1 45( 5$4" BHt/" Brate2 # i$ 1 Ht/ < 1000 2 (is = 10 #

Chapter 40 The 'ecision Control tructure


t!t = 1 Ht/ * rate 2 - 1 Ht/ * rate * (is ) 100 2 # rint$ 1 48!ta% ex enses = >s. 5$4" t!t 2 # 6

55

2ere is so*e sa*ple interaction with the progra*G


Enter H,antit/ an( rate 1200 15.50 8!ta% ex enses = >s. 16740.000000 Enter H,antit/ an( rate 200 15.50 8!ta% ex enses = >s. 3100.000000

$n the irst r#n o the progra*, the condition eval#ates to tr#e, as '2(( >val#e o Qt#? is greater than '(((G There ore, the variable dis, which was earlier set to (, now gets a new val#e '(G 6sing this new val#e total e/penses are calc#lated and printedG $n the second r#n the condition eval#ates to alse, as 2(( >the val#e o Qt#? isn@t greater than '(((G Th#s, dis, which is earlier set to (, re*ains (, and hence the e/pression a ter the *in#s sign eval#ates to ;ero, thereby o ering no disco#ntG $s the state*ent dis F ) necessaryc The answer is yes, since in C, a variable i not speci ically initiali;ed contains so*e #npredictable val#e >garbage val#e?G

The $eal Thing


We *entioned earlier that the general or* o the i state*ent is as ollows
i$ 1 '!n(iti!n 2 statement #

Tr#ly spea9ing the general or* is as ollowsP

5"
i$ 1 ex ressi!n 2 statement #

%et .s C

2ere the e/pression can be any valid e/pression incl#ding a relational e/pressionG We can even #se arith*etic e/pressions in the i8 state*entG +or e/a*ple all the ollowing i8 state*ents are valid
i$ 1 3 + 2 5 5 2 rint$ 1 48his F!r.s4 2 # i$ 1 a = 10 2 rint$ 1 4E=en this F!r.s4 2 # i$ 1 -5 2 rint$ 1 47,r risin-%/ e=en this F!r.s4 2 #

)ote that in C a non<;ero val#e is considered to be tr#e, whereas a ( is considered to be alseG $n the irst i8, the e/pression eval#ates to 5 and since 5 is non<;ero it is considered to be tr#eG 2ence the print8= > gets e/ec#tedG $n the second i8, '( gets assigned to a so the i8 is now red#ced to i8 = a > or i8 = 1) >G Since '( is non<;ero, it is tr#e hence again print8= > goes to wor9G $n the third i8, <5 is a non<;ero n#*ber, hence tr#eG So again print8= > goes to wor9G $n place o <5 even i a loat li9e -G'4 were #sed it wo#ld be considered to be tr#eG So the iss#e is not whether the n#*ber is integer or loat, or whether it is positive or negativeG $ss#e is whether it is ;ero or non<;eroG

,ultiple State1ents 0ithin if


$t *ay so happen that in a progra* we want *ore than one state*ent to be e/ec#ted i the e/pression ollowing i8 is satis iedG $ s#ch *#ltiple state*ents are to be e/ec#ted then they *#st be

Chapter 40 The 'ecision Control tructure

57

placed within a pair o braces as ill#strated in the ollowing e/a*pleG B3a1ple 2.2D The c#rrent year and the year in which the e*ployee Qoined the organi;ation are entered thro#gh the 9eyboardG $ the n#*ber o years or which the e*ployee has served the organi;ation is greater than - then a bon#s o "sG 25((=< is given to the e*ployeeG $ the years o service are not greater than -, then the progra* sho#ld do nothingG
)* +a%',%ati!n !$ &!n,s *) main1 2 3 int &!n,s" '/" /!9" /r_!$_ser # rint$ 1 4Enter ',rrent /ear an( /ear !$ 9!inin- 4 2 # s'an$ 1 45( 5(4" B'/" B/!9 2 # /r_!$_ser = '/ - /!9 # i$ 1 /r_!$_ser < 3 2 3 &!n,s = 2500 # rint$ 1 4D!n,s = >s. 5(4" &!n,s 2 # 6 6

3bserve that here the two state*ents to be e/ec#ted on satis action o the condition have been enclosed within a pair o bracesG $ a pair o braces is not #sed then the C co*piler ass#*es that the progra**er wants only the i**ediately ne/t state*ent a ter the i8 to be e/ec#ted on satis action o the conditionG $n other words we can say that the de a#lt scope o the i8 state*ent is the i**ediately ne/t state*ent a ter itG

5&
ST1"T $),6T yoQ

%et .s C

cy,

yrBo Bser X cy < yoQ

no

yrBo Bser b -

yes bon#s X 25(( ,"$)T bon#s

ST3,

+ig#re 2G4

The if-else State1ent


The i8 state*ent by itsel will e/ec#te a single state*ent, or a gro#p o state*ents, when the e/pression ollowing i8 eval#ates to tr#eG $t does nothing when the e/pression eval#ates to alseG Can we e/ec#te one gro#p o state*ents i the e/pression eval#ates to tr#e and another gro#p o state*ents i the e/pression eval#ates to alsec 3 co#rse4 This is what is the p#rpose o the else state*ent that is de*onstrated in the ollowing e/a*pleP B3a1ple 2.3D $n a co*pany an e*ployee is paid as #nderP

Chapter 40 The 'ecision Control tructure

59

$ his basic salary is less than "sG '5((, then 2"1 X '(U o basic salary and 01 X &(U o basic salaryG $ his salary is either eH#al to or above "sG '5((, then 2"1 X "sG 5(( and 01 X &%U o basic salaryG $ the e*ployeeJs salary is inp#t thro#gh the 9eyboard write a progra* to ind his gross salaryG
)* +a%',%ati!n !$ -r!ss sa%ar/ *) main1 2 3 $%!at &s" -s" (a" hra # rint$ 1 4Enter &asi' sa%ar/ 4 2 # s'an$ 1 45$4" B&s 2 # i$ 1 &s ; 1500 2 3 hra = &s * 10 ) 100 # (a = &s * 90 ) 100 # 6 e%se 3 hra = 500 # (a = &s * 98 ) 100 # 6 -s = &s + hra + (a # rint$ 1 4-r!ss sa%ar/ = >s. 5$4" -s 2 # 6

")

%et .s C

ST1"T $),6T bs is bs a '5(( hra X 5(( da X bs W &% = '(( hra X bs W '( = '(( da X bs W &( = '((

gs X bs L hra L da ,"$)T gs

+ig#re 2G5 +ig#re 2G5 1 ew points worth notingGGG

ST3,

(a) The gro#p o state*ents a ter the i8 #pto and not incl#ding the

else is called an Di bloc9@G Si*ilarly, the state*ents a ter the else or* the Delse bloc9@G (b) )otice that the else is written e/actly below the i8G The state*ents in the i bloc9 and those in the else bloc9 have been indented to the rightG This or*atting convention is

Chapter 40 The 'ecision Control tructure

"1

ollowed thro#gho#t the boo9 to enable yo# to #nderstand the wor9ing o the progra* betterG
(c) 2ad there been only one state*ent to be e/ec#ted in the i

bloc9 and only one state*ent in the else bloc9 we co#ld have dropped the pair o bracesG
(d) 1s with the i8 state*ent, the de a#lt scope o else is also the

state*ent i**ediately a ter the elseG To override this de a#lt scope a pair o braces as shown in the above e/a*ple *#st be #sedG

9ested if-elses
$t is per ectly all right i we write an entire i8@else constr#ct within either the body o the i8 state*ent or the body o an else state*entG This is called Dnesting@o i8sG This is shown in the ollowing progra*G
)* A H,i'. (em! !$ neste( i$-e%se *) main1 2 3 int i # rint$ 1 4Enter either 1 !r 2 4 2 # s'an$ 1 45(4" Bi 2 # i$ 1 i == 1 2 rint$ 1 4G!, F!,%( -! t! hea=en T4 2 # e%se 3 i$ 1 i == 2 2 rint$ 1 4Ue%% Fas 'reate( Fith /!, in min(4 2 # e%se rint$ 1 4U!F a&!,t m!ther earth T4 2 # 6

"2

%et .s C

)ote that the second i8@else constr#ct is nested in the irst else state*entG $ the condition in the irst i8 state*ent is alse, then the condition in the second i8 state*ent is chec9edG $ it is alse as well, then the inal else state*ent is e/ec#tedG Co# can see in the progra* how each ti*e a i8@else constr#ct is nested within another i8@else constr#ct, it is also indented to add clarity to the progra*G $nc#lcate this habit o indentation, otherwise yo# wo#ld end #p writing progra*s which nobody >yo# incl#ded? can #nderstand easily at a later dateG $n the above progra* an i8@else occ#rs within the else bloc9 o the irst i8 state*entG Si*ilarly, in so*e other progra* an i8@else *ay occ#r in the i8 bloc9 as wellG There is no li*it on how deeply the i8s and the elses can be nestedG

For1s o8 if
The i8 state*ent can ta9e any o the ollowing or*sP
1a2 i$ 1 '!n(iti!n 2 (! this # 1&2 i$ 1 '!n(iti!n 2 3 (! this # an( this # 6 1'2 i$ 1 '!n(iti!n 2 (! this # e%se (! this # 1(2 i$ 1 '!n(iti!n 2 3 (! this #

Chapter 40 The 'ecision Control tructure


an( this # 6 e%se 3 (! this # an( this # 6 1e2 i$ 1 '!n(iti!n 2 (! this # e%se 3 i$ 1 '!n(iti!n 2 (! this # e%se 3 (! this # an( this # 6 6 1$2 i$ 1 '!n(iti!n 2 3 i$ 1 '!n(iti!n 2 (! this # e%se 3 (! this # an( this # 6 6 e%se (! this #

"3

"4
.se o8 Logical (perators

%et .s C

C allows #sage o three logical operators, na*ely, II, YY and 4G These are to be read as D1)0@ D3"@ and D)3T@ respectivelyG There are several things to note abo#t these logical operatorsG 5ost obvio#sly, two o the* are co*posed o do#ble sy*bolsP RR and G 0on@t #se the single sy*bol R and G These single sy*bols also have a *eaningG They are bitwise operators, which we wo#ld e/a*ine in Chapter '4G The irst two operators, and RR, allow two or *ore conditions to be co*bined in an i8 state*entG 7et #s see how they are #sed in a progra*G Consider the ollowing e/a*pleG B3a1ple 2.4D The *ar9s obtained by a st#dent in 5 di erent s#bQects are inp#t thro#gh the 9eyboardG The st#dent gets a division as per the ollowing r#lesP ,ercentage above or eH#al to 6( < +irst division ,ercentage between 5( and 5& < Second division ,ercentage between 4( and 4& < Third division ,ercentage less than 4( < +ail Write a progra* to calc#late the division obtained by the st#dentG There are two ways in which we can write a progra* or this e/a*pleG These *ethods are given belowG
)* Peth!( A I *) main1 2 3 int m1" m2" m3" m4" m5" er # rint$ 1 4Enter mar.s in $i=e s,&9e'ts 4 2 # s'an$ 1 45( 5( 5( 5( 5(4" Bm1" Bm2" Bm3" Bm4" Bm5 2 # er = 1 m1 + m2 + m3 + m4 + m5 2 ) 5 #

Chapter 40 The 'ecision Control tructure


i$ 1 er <= 60 2 rint$ 1 4Iirst (i=isi!n 42 # e%se 3 i$ 1 er <= 50 2 rint$ 1 47e'!n( (i=isi!n4 2 # e%se 3 i$ 1 er <= 40 2 rint$ 1 48hir( (i=isi!n4 2 # e%se rint$ 1 4Iai%4 2 # 6 6 6

"5

This is a straight orward progra*G 3bserve that the progra* #ses nested i8@elsesG This leads to three disadvantagesP
(a) 1s the n#*ber o conditions go on increasing the level o

indentation also goes on increasingG 1s a res#lt the whole progra* creeps to the rightG (b) Care needs to be e/ercised to *atch the corresponding i8s and elsesG (c) Care needs to be e/ercised to *atch the corresponding pair o bracesG 1ll these three proble*s can be eli*inated by #sage o D7ogical operators@G The ollowing progra* ill#strates thisG
)* Peth!( A II *) main1 2 3 int m1" m2" m3" m4" m5" er # rint$ 1 4Enter mar.s in $i=e s,&9e'ts 4 2 # s'an$ 1 45( 5( 5( 5( 5(4" Bm1" Bm2" Bm3" Bm4" Bm5 2 # er = 1 m1 + m2 + m3 + m4 + m5 2 ) 5 #

""
i$ 1 er <= 60 2 rint$ 1 4Iirst (i=isi!n4 2 # i$ 1 1 er <= 50 2 BB 1 er ; 60 2 2 rint$ 1 47e'!n( (i=isi!n4 2 # i$ 1 1 er <= 40 2 BB 1 er ; 50 2 2 rint$ 1 48hir( (i=isi!n4 2 # i$ 1 er ; 40 2 rint$ 1 4Iai%4 2 # 6

%et .s C

1s can be seen ro* the second i8 state*ent, the operator is #sed to co*bine two conditionsG DSecond division@ gets printed i both the conditions eval#ate to tr#eG $ one o the conditions eval#ate to alse then the whole thing is treated as alseG Two distinct advantages can be cited in avo#r o this progra*P
(a) The *atching >or do $ say *is*atching? o the i8s with their (b) this progra*G

corresponding elses gets avoided, since there are no elses in $n spite o #sing several conditions, the progra* doesnJt creep to the rightG $n the previo#s progra* the state*ents went on creeping to the rightG This e ect beco*es *ore prono#nced as the n#*ber o conditions go on increasingG This wo#ld *a9e the tas9 o *atching the i8s with their corresponding elses and *atching o opening and closing braces that *#ch *ore di ic#ltG

The else if Clause


There is one *ore way in which we can write progra* or ./a*ple 2G4G This involves #sage o else i8 bloc9s as shown belowP

Chapter 40 The 'ecision Control tructure


)* e%se i$ %a((er (em! *) main1 2 3 int m1" m2" m3" m4" m5" er # er = 1 m1+ m2 + m3 + m4+ m5 2 ) er # i$ 1 er <= 60 2 rint$ 1 4Iirst (i=isi!n4 2 # e%se i$ 1 er <= 50 2 rint$ 1 47e'!n( (i=isi!n4 2 # e%se i$ 1 er <= 40 2 rint$ 1 48hir( (i=isi!n4 2 # e%se rint$ 1 4$ai%4 2 #

"7

Co# can note that this progra* red#ces the indentation o the state*entsG $n this case every else is associated with its previo#s i8G The last else goes to wor9 only i all the conditions ailG .ven in else i8 ladder the last else is optionalG )ote that the else i8 cla#se is nothing di erentG $t is Q#st a way o rearranging the else with the i8 that ollows itG This wo#ld be evident i yo# loo9 at the ollowing codeP
i$ 1 i == 2 2 rint$ 1 4Sith /!,V4 2 # e%se 3 i$ 1 9 == 2 2 rint$ 1 4VA%% the time4 2 # 6 i$ 1 i == 2 2 rint$ 1 4Sith /!,V4 2 # e%se i$ 1 9 == 2 2 rint$ 1 4VA%% the time 4 2 #

1nother place where logical operators are #se #l is when we want to write progra*s or co*plicated logics that #lti*ately boil down

"&
to only two answersG +or e/a*ple, consider the e/a*pleP

%et .s C
ollowing

B3a1ple 2.5D 1 co*pany ins#res its drivers in the ollowing casesP f $ the driver is *arriedG f $ the driver is #n*arried, *ale I above -( years o ageG f $ the driver is #n*arried, e*ale I above 25 years o ageG $n all other cases the driver is not ins#redG $ the *arital stat#s, se/ and age o the driver are the inp#ts, write a progra* to deter*ine whether the driver is to be ins#red or notG 2ere a ter chec9ing a co*plicated set o instr#ctions the inal o#tp#t o the progra* wo#ld be one o the twoR.ither the driver sho#ld be ens#red or the driver sho#ld not be ens#redG 1s *entioned above, since these are the only two o#tco*es this proble* can be solved #sing logical operatorsG 8#t be ore we do that let #s write a progra* that does not *a9e #se o logical operatorsG
)* Ins,ran'e !$ (ri=er - Fith!,t ,sin- %!-i'a% ! erat!rs *) main1 2 3 'har sex" ms # int a-e # rint$ 1 4Enter a-e" sex" marita% stat,s 4 2 # s'an$ 1 45( 5' 5'4" Ba-e" Bsex" Bms 2 # i$ 1 ms == 'P' 2 rint$ 1 40ri=er is ins,re(4 2 # e%se 3 i$ 1 sex == 'P' 2 3

Chapter 40 The 'ecision Control tructure


i$ 1 a-e < 30 2 rint$ 1 40ri=er is ins,re(4 2 # e%se rint$ 1 40ri=er is n!t ins,re(4 2 # 6 e%se 3 i$ 1 a-e < 25 2 rint$ 1 40ri=er is ins,re(4 2 # e%se rint$ 1 40ri=er is n!t ins,re(4 2 #

"9

6 6

+ro* the progra* it is evident that we are reH#ired to *atch several i8s and elses and several pairs o bracesG $n a *ore real<li e sit#ation there wo#ld be *ore conditions to chec9 leading to the progra* creeping to the rightG 7et #s now see how to avoid these proble*s by #sing logical operatorsG 1s *entioned above, in this e/a*ple we e/pect the answer to be either D0river is ins#red@ or D0river is not ins#red@G $ we list down all those cases in which the driver is ins#red, then they wo#ld beP
(a) 0river is *arriedG (b) 0river is an #n*arried *ale above -( years o ageG (c) 0river is an #n*arried e*ale above 25 years o ageG

Since all these cases lead to the driver being ins#red, they can be co*bined together #sing and RR as shown in the progra* belowP
)* Ins,ran'e !$ (ri=er - ,sin- %!-i'a% ! erat!rs *) main1 2 3 'har sex" ms #

7)
int a-e # rint$ 1 4Enter a-e" sex" marita% stat,s 4 2 # s'an$ 1 45( 5' 5'4 Ba-e" Bsex" Bms 2 # i$ 1 1 ms == 'P'2 WW 1 ms == 'X' BB sex == 'P' BB a-e < 30 2 WW 1 ms == 'X' BB sex == 'I' BB a-e < 25 2 2 rint$ 1 40ri=er is ins,re(4 2 # e%se rint$ 1 40ri=er is n!t ins,re(4 2 #

%et .s C

$n this progra* it is i*portant to note thatP f The driver will be ins#red only i one o the conditions enclosed in parentheses eval#ates to tr#eG f +or the second pair o parentheses to eval#ate to tr#e, each condition in the parentheses separated by *#st eval#ate to tr#eG f .ven i one o the conditions in the second parentheses eval#ates to alse, then the whole o the second parentheses eval#ates to alseG f The last two o the above arg#*ents apply to third pair o parentheses as wellG Th#s we can concl#de that the ollowing progra**ing sit#ationsP and RR are #se #l in the

(a) When it is to be tested whether a val#e

alls within a partic#lar range or notG (b) When a ter testing several conditions the o#tco*e is only one o the two answers >This proble* is o ten called yes=no proble*?G

Chapter 40 The 'ecision Control tructure

71

There can be one *ore sit#ation other than chec9ing ranges or yes=no proble* where yo# *ight ind logical operators #se #lG The ollowing progra* de*onstrates itG B3a1ple 2."D Write a progra* to calc#late the salary as per the ollowing tableP

Gender 5ale

Sears o8 Ser%ice bX '( bX '( a '( a '(

Tuali8ications ,ost<Grad#ate Grad#ate ,ost<Grad#ate Grad#ate ,ost<Grad#ate Grad#ate ,ost<Grad#ate Grad#ate

Salar# '5((( '(((( '(((( !((( '2((( &((( '(((( 6(((

+e*ale

bX '( bX '( a '( a '(

+ig#re 2G6
main1 2 3 'har - # int /!s" H,a%" sa% # rint$ 1 4Enter Jen(er" Gears !$ 7er=i'e an( Y,a%i$i'ati!ns 1 0 = J" 1 = ?J 2:4 2 # s'an$ 1 45'5(5(4" B-" B/!s" BH,a% 2 # i$ 1 - == 'm' BB /!s <= 10 BB H,a% == 1 2 sa% = 15000 # e%se i$ 1 1 - == 'm' BB /!s <= 10 BB H,a% == 0 2 WW 1 - == 'm' BB /!s ; 10 BB H,a% == 1 2 2 sa% = 10000 #

72
e%se i$ 1 - == 'm' BB /!s ; 10 BB H,a% == 0 2 sa% = 7000 # e%se i$ 1 - == '$' BB /!s <= 10 BB H,a% == 1 2 sa% = 12000 # e%se i$ 1 - == '$' BB /!s <= 10 BB H,a% == 0 2 sa% = 9000 # e%se i$ 1 - == '$' BB /!s ; 10 BB H,a% == 1 2 sa% = 10000 # e%se i$ 1 - == '$' BB /!s ; 10 BB H,a% == 0 2 sa% = 6000 # rint$ 1 4@n7a%ar/ !$ Em %!/ee = 5(4" sa% 2 # 6

%et .s C

The P (perator
So ar we have #sed only the logical operators and RRG The third logical operator is the )3T operator, written as PG This operator reverses the res#lt o the e/pression it operates onG +or e/a*ple, i the e/pression eval#ates to a non<;ero val#e, then applying P operator to it res#lts into a (G Vice versa, i the e/pression eval#ates to ;ero then on applying P operator to it *a9es it ', a non<;ero val#eG The inal res#lt >a ter applying P? ( or ' is considered to be alse or tr#e respectivelyG 2ere is an e/a*ple o the )3T operator applied to a relational e/pressionG
T 1 / ; 10 2

This *eans Knot # less than '(OG $n other words, i # is less than '(, the e/pression will be alse, since = # J 1) > is tr#eG We can e/press the sa*e condition as = # CF 1) >G The )3T operator is o ten #sed to reverse the logical val#e o a single variable, as in the e/pression
i$ 1 T $%a- 2

Chapter 40 The 'ecision Control tructure


This is another way o saying
i$ 1 $%a- == 0 2

73

0oes the )3T operator so#nd con #singc 1void it i yo# want, as the sa*e thing can be achieved witho#t #sing the )3T operatorG

2ierarch# o8 (perators $e%isited


Since we have now added the logical operators to the list o operators we 9now, it is ti*e to review these operators and their prioritiesG +ig#re 2G! s#**ari;es the operators we have seen so arG The higher the position o an operator is in the table, higher is its priorityG >1 #ll< ledged precedence table o operators is given in 1ppendi/ 1G?
(perators 4 W = U L < a b aX bX XX 4X II YY X T#pe 7ogical )3T 1rith*etic and *od#l#s 1rith*etic "elational "elational 7ogical 1)0 7ogical 3" 1ssign*ent

+ig#re 2G!

' /ord o8 Caution


What will be the o#tp#t o the ollowing progra*P

74
main1 2 3 int i # rint$ 1 4Enter =a%,e !$ i 4 2 # s'an$ 1 45(4" Bi 2 # i$ 1 i = 5 2 rint$ 1 4G!, entere( 54 2 # e%se rint$ 1 4G!, entere( s!methin- !ther than 54 2 #

%et .s C

1nd here is the o#tp#t o two r#ns o this progra*GGG


Enter =a%,e !$ i 200 G!, entere( 5 Enter =a%,e !$ i 9999 G!, entere( 5

S#rprisingc Co# have entered 2(( and &&&&, and still yo# ind in either case the o#tp#t is DCo# entered 5@G This is beca#se we have written the condition wronglyG We have #sed the assign*ent operator F instead o the relational operator FFG 1s a res#lt, the condition gets red#ced to i8 = 5 >, irrespective o what yo# s#pply as the val#e o iG 1nd re*e*ber that in C Dtr#th@ is always non< ;ero, whereas D alsity@ is always ;eroG There ore, i8 = 5 > always eval#ates to tr#e and hence the res#ltG 1nother co**on *ista9e while #sing the i8 state*ent is to write a se*icolon >;? a ter the condition, as shown belowP
main1 2 3 int i # rint$ 1 4Enter =a%,e !$ i 4 2 # s'an$ 1 45(4" Bi 2 #

Chapter 40 The 'ecision Control tructure


i$ 1 i == 5 2 # rint$ 1 4G!, entere( 54 2 # 6

75

The _ *a9es the co*piler to interpret the state*ent as i yo# have written it in ollowing *annerP
i$ 1 i == 5 2 # rint$ 1 4G!, entere( 54 2 #

2ere, i the condition eval#ates to tr#e the _ >n#ll state*ent, which does nothing on e/ec#tion? gets e/ec#ted, ollowing which the print8= > gets e/ec#tedG $ the condition ails then straightaway the print8= > gets e/ec#tedG Th#s, irrespective o whether the condition eval#ates to tr#e or alse the print8= > is bo#nd to get e/ec#tedG "e*e*ber that the co*piler wo#ld not point o#t this as an error, since as ar as the synta/ is concerned nothing has gone wrong, b#t the logic has certainly gone awryG 5oral is, beware o s#ch pit allsG The ollowing ig#re s#**ari;es the wor9ing o all the three logical operatorsG

(perands 3 ( ( non<;ero non<;ero # ( non<;ero ( non<;ero P3 ' ' ( ( P# ' ( ' (

$esults 3 ( ( ( ' # 3 RR # ( ( ' '

+ig#re 2G%

7"
The Conditional (perators

%et .s C

The conditional operators U and D are so*eti*es called ternary operators since they ta9e three arg#*entsG $n act, they or* a 9ind o oreshortened i <then<elseG Their general or* is,
ex ressi!n 1 Z ex ressi!n 2 : ex ressi!n 3

What this e/pression says isP Ki e3pression 1 is tr#e >that is, i its val#e is non<;ero?, then the val#e ret#rned will be e3pression 2, otherwise the val#e ret#rned will be e3pression 3OG 7et #s #nderstand this with the help o a ew e/a*plesP
1a2 int x" / # s'an$ 1 45(4" Bx 2 # /=1x<5Z3:42#

This state*ent will store - in # i 3 is greater than 5, otherwise it will store 4 in yG The eH#ivalent i8 state*ent will be,
i$ 1 x < 5 2 /=3# e%se /=4# 1&2 'har a # int / # s'an$ 1 45'4" Ba 2 # / = 1 a <= 65 BB a ;= 90 Z 1 : 0 2 #

2ere ' wo#ld be assigned to # i a CF"5 tr#e, otherwise ( wo#ld be assignedG

a JF9) eval#ates to

The ollowing points *ay be noted abo#t the conditional operatorsP

Chapter 40 The 'ecision Control tructure

77

(a) $t@s not necessary that the conditional operators sho#ld be

#sed only in arith*etic state*entsG This is ill#strated in the ollowing e/a*plesP


Ex.: int i # s'an$ 1 45(4" Bi 2 # 1 i == 1 Z rint$ 1 4Amit4 2 : rint$ 1 4A%% an( s,n(r/4 2 2 # 'har a = ':' # rint$ 1 45'4 " 1 a <= 'a' Z a : 'T' 2 2 #

Ex.:

(b) The conditional operators can be nested as shown belowG

int &i-" a" &" ' # &i- = 1 a < & Z 1 a < ' Z 3: 4 2 : 1 & < ' Z 6: 8 2 2 #
(c) Chec9 o#t the ollowing conditional e/pressionP

a<&Z-=a:-=&#

This will give yo# an error D7val#e "eH#ired@G The error can be overco*e by enclosing the state*ent in the D part within a pair o parenthesisG This is shown belowP
a<&Z-=a:1-=&2#

$n absence o parentheses the co*piler believes that 6 is being assigned to the res#lt o the e/pression to the le t o second FG 2ence it reports an errorG The li*itation o the conditional operators is that a ter the U or a ter the D only one C state*ent can occ#rG $n practice rarely is this the reH#ire*entG There ore, in serio#s C progra**ing conditional operators aren@t as reH#ently #sed as the i8@elseG

Su11ar#
>a? There are three ways or ta9ing decisions in a progra*G +irst way is to #se the i8<else state*ent, second way is to #se the

7&

%et .s C
conditional operators and third way is to #se the s0itch state*entG The de a#lt scope o the i8 state*ent is only the ne/t state*entG So, to e/ec#te *ore than one state*ent they *#st be written in a pair o bracesG 1n i8 bloc9 need not always be associated with an else bloc9G 2owever, an else bloc9 is always associated with an i8 state*entG $ the o#tco*e o an i8@else ladder is only one o two answers then the ladder sho#ld be replaced either with an else@i8 cla#se or by logical operatorsG and RR are binary operators, whereas, P is a #nary operatorG $n C every test e/pression is eval#ated in ter*s o ;ero and non<;ero val#esG 1 ;ero val#e is considered to be alse and a non<;ero val#e is considered to be tr#eG 1ssign*ent state*ents #sed with conditional operators *#st be enclosed within a pair o parenthesisG

>b? >c? >d? >e? >? >g?

B3ercise
if, if-else, 9ested if-elses
K'L What wo#ld be the o#tp#t o the ollowing progra*sP 1a2 main1 2 3 int a = 300" &" ' # i$ 1 a <= 400 2 & = 300 # ' = 200 # rint$ 1 4@n5( 5(4" &" ' 2 # 6 1&2 main1 2 3 int a = 500" &" ' # i$ 1 a <= 400 2

Chapter 40 The 'ecision Control tructure


& = 300 # ' = 200 # rint$ 1 4@n5( 5(4" &" ' 2 #

79

6 1'2

main1 2 3 int x = 10" / = 20 # i$ 1 x == / 2 # rint$ 1 4@n5( 5(4" x" / 2 # 6

1(2 main1 2 3 int x = 3" / = 5 # i$ 1 x == 3 2 rint$ 1 4@n5(4" x 2 # e%se # rint$ 1 4@n5(4" / 2 # 6 1e2 main1 2 3 int x = 3 # $%!at / = 3.0 # i$ 1 x == / 2 rint$ 1 4@nx an( / are eH,a%4 2 # e%se rint$ 1 4@nx an( / are n!t eH,a%4 2 #

1$2

6 main1 2 3 int x = 3" /" : # / = x = 10 # : = x ; 10 # rint$ 1 4@nx = 5( / = 5( : = 5(4" x" /" : 2 # 6

&)
1-2 main1 2 3 int . = 35 # rint$ 1 4@n5( 5( 5(4" . == 35" . = 50" . < 40 2 # 6 1h2 main1 2 3 int i = 65 # 'har 9 = [AR # i$ 1 i == 9 2 rint$ 1 M+ is SQSN 2 # e%se rint$1 4+ is a hea(a'he4 2 # 6 1i2 main1 2 3 int a = 5" &" ' # & = a = 15 # ' = a ; 15 # rint$ 1 4@na = 5( & = 5( ' = 5(4" a" &" ' 2 # 6 main1 2 3 int x = 15 # rint$ 1 4@n5( 5( 5(4" x T= 15" x = 20" x ; 30 2 # 6

%et .s C

192

K-L ,oint o#t the errors, i any, in the ollowing progra*sP 1a2 main1 2 3 $%!at a = 12.25" & = 12.52 # i$ 1 a = & 2 rint$ 1 4@na an( & are eH,a%4 2 #

Chapter 40 The 'ecision Control tructure


6 1&2 main1 2 3 int 9 = 10" . = 12 # i$ 1 . <= 9 2 3 3 .=9# 9=.# 6 6 6 1'2 main1 2 3 i$ 1 '\' ; 'x' 2 rint$ 1 4@nas'ii =a%,e !$ \ is sma%%er than that !$ x4 2 # 6

&1

1(2 main1 2 3 int x = 10 # i$ 1 x <= 2 2 then rint$ 1 4@n5(4" x 2 # 6 1e2 main1 2 3 int x = 10 # i$ x <= 2 rint$ 1 4@n5(4" x 2 # 6 1$2 main1 2 3 int x = 10" / = 15 # i$ 1 x 5 2 = / 5 3 2

&2
6 rint$ 1 4@n+ar athians4 2 #

%et .s C

1-2 main1 2 3 int x = 30 " / = 40 # i$ 1 x == / 2 rint$1 4x is eH,a% t! /4 2 # e%sei$ 1 x < / 2 rint$1 4x is -reater than /4 2 # e%sei$ 1 x ; / 2 rint$1 4x is %ess than /4 2 # 6 1h2 main1 2 3 int x = 10 # i$ 1 x <= 2 2 then rint$ 1 4@n5(4" x 2 # 6 1i2 main1 2 3 int a" & # s'an$ 1 45( 5(4"a" & 2 # i$ 1 a < & 2 # rint$ 1 48his is a -ame4 2 # e%se rint$ 1 4G!, ha=e t! %a/ it4 2 # 6

KCL 1tte*pt the ollowingP


(a)

$ cost price and selling price o an ite* is inp#t thro#gh the 9eyboard, write a progra* to deter*ine whether the seller has *ade pro it or inc#rred lossG 1lso deter*ine how *#ch pro it he *ade or loss he inc#rredG

Chapter 40 The 'ecision Control tructure

&3

(b) 1ny integer is inp#t thro#gh the 9eyboardG Write a progra* to (c)

ind o#t whether it is an odd n#*ber or even n#*berG 1ny year is inp#t thro#gh the 9eyboardG Write a progra* to deter*ine whether the year is a leap year or notG

(d) >2intP 6se the U >*od#l#s? operator?

1ccording to the Gregorian calendar, it was 5onday on the date ('=('='&((G $ any year is inp#t thro#gh the 9eyboard write a progra* to ind o#t what is the day on 'st Nan#ary o (e) this yearG
(f)

1 ive<digit n#*ber is entered thro#gh the 9eyboardG Write a (g) progra* to obtain the reversed n#*ber and to deter*ine whether the original and reversed n#*bers are eH#al or notG
(h) $ the ages o "a*, Shya* and 1Qay are inp#t thro#gh the

9eyboard, write a progra* to deter*ine the yo#ngest o the threeG


(i)

Write a progra* to chec9 whether a triangle is valid or not, when the three angles o the triangle are entered thro#gh the 9eyboardG 1 triangle is valid i the s#* o all the three angles is eH#al to '%( degreesG +ind the absol#te val#e o a n#*ber entered thro#gh the 9eyboardG
Given the length and breadth o a rectangle, write a progra* to ind whether the area o the rectangle is greater than its peri*eterG +or e/a*ple, the area o the rectangle with length X 5 and breadth X 4 is greater than its peri*eterG Given three points =314 #1>, =324 #2> and =334 #3>, write a progra* to chec9 i all the three points all on one straight lineG

(j)

&4

%et .s C

(k) Given the coordinates =34 #> o a center o a circle and it@s radi#s,

write a progra* which will deter*ine whether a point lies inside the circle, on the circle or o#tside the circleG

>2intP 6se sQrt= > and po0= > #nctions?


(l)

Given a point =34 #>, write a progra* to ind o#t i it lies on the /<a/is, y<a/is or at the origin, vi;G >(, (?G

Logical (perators
$ a X '(, b X '2, c X (, ind the val#es o the e/pressions in the ollowing tableP
B3pression a 4X 6 II b b 5 a XX & YY b a 4 > a a '( ? 4 > a b 5 II c ? 5 II c 4X % YY 4c 5alue '

KDL What wo#ld be the o#tp#t o the ollowing progra*sP 1a2 main1 2 3 int i = 4" : = 12 # i$ 1 i = 5 WW : < 50 2 rint$ 1 4@n0ean !$ st,(ents a$$airs4 2 # e%se rint$ 1 4@n0!sa4 2 # 6 1&2 main1 2 3 int i = 4" : = 12 #

Chapter 40 The 'ecision Control tructure


i$ 1 i = 5 BB : < 5 2 rint$ 1 4@nOet ,s +4 2 # e%se rint$ 1 4@nSish + Fas $ree T4 2 #

&5

6 1'2

main1 2 3 int i = 4" 9 = -1" . = 0" F" x" /" : # F = i WW 9 WW . # x = i BB 9 BB . # / = i WW 9 BB . # : = i BB 9 WW . # rint$ 1 4@nF = 5( x = 5( / = 5( : = 5(4" F" x" /" : 2 # 6

1(2 main1 2 3 int i = 4" 9 = -1" . = 0" /" : # / = i + 5 BB 9 + 1 WW . + 2 # : = i + 5 WW 9 + 1 BB . + 2 # rint$ 1 4@n/ = 5( : = 5(4" /" : 2 # 6 1e2 main1 2 3 int i = -3" 9 = 3 # i$ 1 Ti + T9 * 1 2 rint$ 1 4@nPassar!4 2 # e%se rint$ 1 4@nDennari=!4 2 # 6 1$2 main1 2 3 int a = 40 # i$ 1 a < 40 BB a ; 45 2 rint$ 1 4a is -reater than 40 an( %ess than 454 2 #

&"
e%se 6 rint$ 1 45(4" a 2 #

%et .s C

1-2 main1 2 3 int = 8" H = 20 # i$ 1 == 5 BB H < 5 2 rint$ 1 4@nSh/ n!t +4 2 # e%se rint$ 1 4@n0e$inite%/ + T4 2 # 6 1h2 main1 2 3 int i = -1" 9 = 1" . "% # . = i BB 9 # % = i WW 9 # rint$ 1 45( 5(4" I" 9 2 # 6 1i2 main1 2 3 int x = 20 " / = 40 " : = 45 # i$ 1 x < / BB x < : 2 rint$1 4x is &i-4 2 # e%se i$ 1 / < x BB / < : 2 rint$1 4/ is &i-4 2 # e%se i$ 1 : < x BB : < / 2 rint$1 4: is &i-4 2 # 6 main1 2 3 int i = -1" 9 = 1" . "% # . = Ti BB 9 # % = Ti WW 9 # rint$ 1 45( 5(4" i" 9 2 #

192

Chapter 40 The 'ecision Control tructure


6 1.2 main1 2 3 int 9 = 4" . # . = T5 BB 9 # rint$ 1 4@n. = 5(4" . 2 # 6

&7

KBL ,oint o#t the errors, i any, in the ollowing progra*sP 1a2 )* 8his r!-ram )* is an exam %e !$ )* ,sin- O!-i'a% ! erat!rs *) main1 2 3 int i = 2" 9 = 5 # i$ 1 i == 2 BB 9 == 5 2 rint$ 1 4@n7atis$ie( at %ast4 2 # 6 1&2 main1 2 3 int '!(e" $%a- # i$ 1 '!(e == 1 B $%a- == 0 2 rint$ 1 4@n8he ea-%e has %an(e(4 2 # 6 1'2 main1 2 3 'har s / = 'a'" assF!r( = ':' # i$ 1 s / == 'a' !r assF!r( == ':' 2 rint$ 1 4@nA%% the &ir(s are sa$e in the nest4 2 # 6

1(2 main1 2 3

&&
int i = 10" 9 = 20 # i$ 1 i = 5 2 BB i$ 1 9 = 10 2 rint$ 1 4@nUa=e a ni'e (a/4 2 # 6 1a2 main1 2 3 int x = 10 " / = 20# i$ 1 x <= 2 an( / ;=50 2 rint$ 1 4@n5(4" x 2 # 6 1&2 main1 2 3 int a" & # i$ 1 a == 1 B & == 0 2 rint$ 1 4@nJ!( is Jreat4 2 # 6 1'2 main1 2 3 int x = 2# i$ 1 x == 2 BB x T= 0 2 # 3 rint$ 1 4@nUi4 2 # rint$1 4@nUe%%!4 2 # 6 e%se rint$1 4D/e4 2 # 6

%et .s C

1(2 main1 2 3 int i = 10" 9 = 10 # i$ 1 i BB 9 == 102 rint$ 1 4@nUa=e a ni'e (a/4 2 # 6

Chapter 40 The 'ecision Control tructure

&9

KFL 1tte*pt the ollowingP


(a) 1ny year is entered thro#gh the 9eyboard, write a progra* to

deter*ine whether the year is leap or notG 6se the logical operators and RRG
(b) 1ny character is entered thro#gh the 9eyboard, write a

progra* to deter*ine whether the character entered is a capital letter, a s*all case letter, a digit or a special sy*bolG The ollowing table shows the range o 1SC$$ val#es or vario#s charactersG
Characters 1FE aF; (F& special sy*bols 'SC** 5alues 65 F &( &! F '22 4% F 5! ( < 4!, 5% < 64, &' < &6, '2- < '2!

(c) 1n $ns#rance co*pany ollows ollowing r#les to calc#late

pre*i#*G >'? $ a person@s health is e/cellent and the person is between 25 and -5 years o age and lives in a city and is a *ale then the pre*i#* is "sG 4 per tho#sand and his policy a*o#nt cannot e/ceed "sG 2 la9hsG >2? $ a person satis ies all the above conditions e/cept that the se/ is e*ale then the pre*i#* is "sG - per tho#sand and her policy a*o#nt cannot e/ceed "sG ' la9hG >-? $ a person@s health is poor and the person is between 25 and -5 years o age and lives in a village and is a *ale

9)

%et .s C
then the pre*i#* is "sG 6 per tho#sand and his policy cannot e/ceed "sG '(,(((G >4? $n all other cases the person is not ins#redG Write a progra* to o#tp#t whether the person sho#ld be ins#red or not, his=her pre*i#* rate and *a/i*#* a*o#nt or which he=she can be ins#redG

(d) 1 certain grade o steel is graded according to the ollowing

conditionsP >i? 2ardness *#st be greater than 5( >ii? Carbon content *#st be less than (G! >iii? Tensile strength *#st be greater than 56(( The grades are as ollowsP Grade is '( i all three conditions are *et Grade is & i conditions >i? and >ii? are *et Grade is % i conditions >ii? and >iii? are *et Grade is ! i conditions >i? and >iii? are *et Grade is 6 i only one condition is *et Grade is 5 i none o the conditions are *et Write a progra*, which will reH#ire the #ser to give val#es o hardness, carbon content and tensile strength o the steel #nder consideration and o#tp#t the grade o the steelG
(e) 1 library charges a ine or every boo9 ret#rned lateG +or irst

5 days the ine is 5( paise, or 6<'( days ine is one r#pee and above '( days ine is 5 r#peesG $ yo# ret#rn the boo9 a ter -( days yo#r *e*bership will be cancelledG Write a progra* to accept the n#*ber o days the *e*ber is late to ret#rn the boo9 and display the ine or the appropriate *essageG

Chapter 40 The 'ecision Control tructure


(f)

91

$ the three sides o a triangle are entered thro#gh the 9eyboard, write a progra* to chec9 whether the triangle is valid or notG The triangle is valid i the s#* o two sides is greater than the largest o the three sidesG the three sides o a triangle are entered thro#gh the 9eyboard, write a progra* to chec9 whether the triangle is isosceles, eH#ilateral, scalene or right angled triangleG the ti*e reH#ired or a wor9er to co*plete a partic#lar QobG $ the ti*e ta9en by the wor9er is between 2 F - ho#rs, then the wor9er is said to be highly e icientG $ the ti*e reH#ired by the wor9er is between - F 4 ho#rs, then the wor9er is ordered to i*prove speedG $ the ti*e ta9en is between 4 F 5 ho#rs, the wor9er is given training to i*prove his speed, and i the ti*e ta9en by the wor9er is *ore than 5 ho#rs, then the wor9er has to leave the co*panyG $ the ti*e ta9en by the wor9er is inp#t thro#gh the 9eyboard, ind the e iciency o the wor9erG

(g) $

(h) $n a co*pany, wor9er e iciency is deter*ined on the basis o

(i)

1 #niversity has the ollowing r#les or a st#dent to H#ali y or a degree with 1 as the *ain s#bQect and 8 as the s#bsidiary s#bQectP >a? 2e sho#ld get 55 percent or *ore in 1 and 45 percent or *ore in 8G >b? $ he gets than 55 percent in 1 he sho#ld get 55 percent or *ore in 8G 2owever, he sho#ld get at least 45 percent in 1G >c? $ he gets less than 45 percent in 8 and 65 percent or *ore in 1 he is allowed to reappear in an e/a*ination in 8 to H#ali yG >d? $n all other cases he is declared to have ailedG Write a progra* to receive *ar9s in 1 and 8 and 3#tp#t whether the st#dent has passed, ailed or is allowed to reappear in 8G

92
(j)

%et .s C
The policy ollowed by a co*pany to process c#sto*er orders is given by the ollowing r#lesP >a? $ a c#sto*er order is less than or eH#al to that in stoc9 and has credit is 3K, s#pply has reH#ire*entG >b? $ has credit is not 3K do not s#pplyG Send hi* inti*ationG >c? $ has credit is 39 b#t the ite* in stoc9 is less than has order, s#pply what is in stoc9G $nti*ate to hi* data the balance will be shippedG Write a C progra* to i*ple*ent the co*pany policyG

Conditional operators
KGL What wo#ld be the o#tp#t o the ollowing progra*sP 1a2 main1 2 3 int i = -4" 9" n,m # 9 = 1 n,m ; 0 Z 0 : n,m * n,m 2 # rint$ 1 4@n5(4" 9 2 # 6 1&2 main1 2 3 int ." n,m = 30 # . = 1 n,m < 5 Z 1 n,m ;= 10 Z 100 : 200 2 : 500 2 # rint$ 1 4@n5(4" n,m 2 # 6 1'2 main1 2 3 int 9 = 4 # 1 T9 T= 1 Z rint$ 1 4@nSe%'!me42 : rint$ 1 4@nJ!!( D/e42 2 #

Chapter 40 The 'ecision Control tructure


6 K2L ,oint o#t the errors, i any, in the ollowing progra*sP 1a2 main1 2 3 int ta- = 0" '!(e = 1 # i$ 1 ta- == 0 2 1 '!(e < 1 Z rint$ 1 4@nUe%%!4 2 Z rint$ 1 4@nUi4 2 2 # e%se rint$ 1 4@nUe%%! Ui TT4 2 # 6 1&2 main1 2 3 int 9i = 65 # rint$ 1 4@n9i <= 65 Z 5( : 5'4" 9i 2 # 6 1'2 main1 2 3 int i = 10" 9 # i <= 5 Z 1 9 = 10 2 : 1 9 = 15 2 # rint$ 1 4@n5( 5(4" i" 9 2 # 6

93

1(2 main1 2 3 int a = 5 " & = 6 # 1 a == & Z rint$1 45(4"a2 2 # 6 1e2 main1 2 3 int n = 9 # 1 n == 9 Z rint$1 4G!, are '!rre't4 2 # : rint$1 4G!, are Fr!n-4 2 #2 # 6

94
1$2

%et .s C
main1 2 3 int .. = 65 "%% # %% = 1 .. == 65 : rint$ 1 4@n .. is eH,a% t! 654 2 : rint$ 1 4@n .. is n!t eH,a% t! 654 2 2 # rint$1 45(4" %% 2 # 6

1-2 main1 2 3 int x = 10" / = 20 # x == 20 BB / T= 10 Z rint$1 48r,e4 2 : rint$1 4Ia%se4 2 # 6 K*L "ewrite the ollowing progra*s #sing conditional operatorsG 1a2 main1 2 3 int x" min" max # s'an$ 1 4@n5( 5(4" Bmax" Bx 2 # i$ 1 x < max 2 max = x # e%se min = x # 6 1&2 main1 2 3 int '!(e # s'an$ 1 45(4" B'!(e 2 # i$ 1 '!(e < 1 2 rint$ 1 4@nCer,sa%em4 2 # e%se i$ 1 '!(e ; 1 2 rint$ 1 4@nE((ie4 2 # e%se rint$ 1 4@n+ Drain4 2 # 6

Chapter 40 The 'ecision Control tructure


1'2 main1 2 3 $%!at sa% # rint$ 14Enter the sa%ar/4 2 # s'an$ 1 45$4" Bsa% 2 # i$ 1 sa% ; 40000 BB sa% < 25000 2 rint$ 1 4Pana-er4 2 # e%se i$ 1 sa% ; 25000 BB sa% < 15000 2 rint$ 1 4A''!,ntant4 2 # e%se rint$ 1 4+%er.4 2 # 6

95

KVL 1tte*pt the ollowingP


(a) 6sing conditional operators deter*ineP

>'? Whether the character entered thro#gh the 9eyboard is a lower case alphabet or notG >2? Whether a character entered thro#gh the 9eyboard is a special sy*bol or notG
(b) Write a progra* #sing conditional operators to deter*ine

whether a year entered thro#gh the 9eyboard is a leap year or notG


(c) Write a progra* to ind the greatest o the three n#*bers

entered thro#gh the 9eyboard #sing conditional operatorsG

9"

%et .s C

7oops The while 7oop Tips and Traps 5ore 3perators The for 7oop )esting o 7oops 5#ltiple $nitialisations in the for 7oop The 3dd 7oop The break State*ent The continue State*ent The do-while 7oop S#**ary ./ercise

he progra*s that we have developed so ar #sed either a seH#ential or a decision control instr#ctionG $n the irst one, the calc#lations were carried o#t in a i/ed order, while in the second, an appropriate set o instr#ctions were e/ec#ted depending #pon the o#tco*e o the condition being tested >or a logical decision being ta9en?G

97

9&

%et .s C

These progra*s were o li*ited nat#re, beca#se when e/ec#ted, they always per or*ed the sa*e series o actions, in the sa*e way, e/actly onceG 1l*ost always, i so*ething is worth doing, it@s worth doing *ore than onceG Co# can probably thin9 o several e/a*ples o this ro* real li e, s#ch as eating a good dinner or going or a *ovieG ,rogra**ing is the sa*e_ we reH#ently need to per or* an action over and over, o ten with variations in the details each ti*eG The *echanis*, which *eets this need, is the Dloop@, and loops are the s#bQect o this chapterG

Loops
The versatility o the co*p#ter lies in its ability to per or* a set o instr#ctions repeatedlyG This involves repeating so*e portion o the progra* either a speci ied n#*ber o ti*es or #ntil a partic#lar condition is being satis iedG This repetitive operation is done thro#gh a loop control instr#ctionG There are three *ethods by way o which we can repeat a part o a progra*G They areP >a? 6sing a 8or state*ent >b? 6sing a 0hile state*ent >c? 6sing a do@0hile state*ent .ach o these *ethods is disc#ssed in the ollowing pagesG

The while Loop


$t is o ten the case in progra**ing that yo# want to do so*ething a i/ed n#*ber o ti*esG ,erhaps yo# want to calc#late gross salaries o ten di erent persons, or yo# want to convert te*perat#res ro* centigrade to ahrenheit or '5 di erent citiesG

Chapter 30 The %oop Control tructure

99

The 0hile loop is ideally s#ited or s#ch casesG 7et #s loo9 at a si*ple e/a*ple, which #ses a 0hile loopG The lowchart shown below wo#ld help yo# to #nderstand the operation o the 0hile loopG
ST1"T

co#nt X '

is co#nt aX Ces $),6T p, n, r si X p W n W r = '(( ,"$)T si co#nt X co#nt L '

)o

ST3,

+ig#re -G'
)* +a%',%ati!n !$ sim %e interest $!r 3 sets !$ " n an( r *) main1 2 3 int " n" '!,nt # $%!at r" si # '!,nt = 1 #

1))
Fhi%e 1 '!,nt ;= 3 2 3 rint$ 1 4@nEnter =a%,es !$ " n an( r 4 2 # s'an$ 1 45( 5( 5$4" B " Bn" Br 2 # si = * n * r ) 100 # rint$ 1 47im %e interest = >s. 5$4" si 2 # 6 6 '!,nt = '!,nt + 1 #

%et .s C

1nd here are a ew sa*ple r#nsGGG


Enter =a%,es !$ " n an( r 1000 5 13.5 7im %e interest = >s. 675.000000 Enter =a%,es !$ " n an( r 2000 5 13.5 7im %e interest = >s. 1350.000000 Enter =a%,es !$ " n an( r 3500 5 3.5 7im %e interest = >s. 612.500000

The progra* e/ec#tes all state*ents a ter the 0hile - ti*esG The logic or calc#lating the si*ple interest is written within a pair o braces i**ediately a ter the 0hile 9eywordG These state*ents or* what is called the Dbody@ o the 0hile loopG The parentheses a ter the 0hile contain a conditionG So long as this condition re*ains tr#e all state*ents within the body o the 0hile loop 9eep getting e/ec#ted repeatedlyG To begin with the variable count is initiali;ed to ' and every ti*e the si*ple interest logic is e/ec#ted the val#e o count is incre*ented by oneG The variable count is *any a ti*es called either a Dloop co#nter@ or an Dinde/ variable@G The operation o the 0hile loop is ill#strated in the ollowing ig#reG

Chapter 30 The %oop Control tructure

1)1

ST1"T initialise

test Tr#e body o loop

+alse

ST3,

incre*ent

+ig#re -G2

Tips and Traps


The general or* o 0hile is as shown belowP
initia%ise %!! '!,nter # Fhi%e 1 test %!! '!,nter ,sin- a '!n(iti!n 2 3 (! this # an( this # in'rement %!! '!,nter # 6

)ote the ollowing points abo#t 0hile... The state*ents within the 0hile loop wo#ld 9eep on getting e/ec#ted till the condition being tested re*ains tr#eG When the

1)2

%et .s C

condition beco*es alse, the control passes to the irst state*ent that ollows the body o the 0hile loopG $n place o the condition there can be any other valid e/pressionG So long as the e/pression eval#ates to a non<;ero val#e the state*ents within the loop wo#ld get e/ec#tedG The condition being tested *ay #se relational or logical operators as shown in the ollowing e/a*plesP
Fhi%e 1 i ;= 10 2 Fhi%e 1 i <= 10 BB 9 ;= 15 2 Fhi%e 1 9 < 10 BB 1 & ; 15 WW ' ; 20 2 2

The state*ents within the loop *ay be a single line or a bloc9 o state*entsG $n the irst case the parentheses are optionalG +or e/a*ple,
Fhi%e 1 i ;= 10 2 i=i+1#

is sa*e as
Fhi%e 1 i ;= 10 2 3 i=i+1# 6

1s a r#le the while *#st test a condition that will event#ally beco*e alse, otherwise the loop wo#ld be e/ec#ted orever, inde initelyG
main1 2 3 int i = 1 # Fhi%e 1 i ;= 10 2 rint$ 1 45(@n4" i 2 # 6

Chapter 30 The %oop Control tructure

1)3

This is an inde inite loop, since i re*ains eH#al to ' oreverG The correct or* wo#ld be as #nderP
main1 2 3 int i = 1 # Fhi%e 1 i ;= 10 2 3 rint$ 1 45(@n4" i 2 # i=i+1# 6 6

$nstead o incre*enting a loop co#nter, we can even decre*ent it and still *anage to get the body o the loop e/ec#ted repeatedlyG This is shown belowP
main1 2 3 int i = 5 # Fhi%e 1 i <= 1 2 3 rint$ 1 4@nPa.e the '!m ,ter %iterateT4 2 # i=i-1# 6 6

$t is not necessary that a loop co#nter *#st only be an intG $t can even be a loatG
main1 2 3 $%!at a = 10.0 # Fhi%e 1 a ;= 10.5 2 3 rint$ 1 4@n>ain(r! s !n r!ses...4 2 # rint$ 1 4...an( Fhis.ers !n .ittens4 2 # a = a + 0.1 #

1)4
6 6

%et .s C

.ven loating point loop co#nters can be decre*entedG 3nce again the incre*ent and decre*ent co#ld be by any val#e, not necessarily 'G What do yo# thin9 wo#ld be the o#tp#t o the ollowing progra*c
main1 2 3 int i = 1 # Fhi%e 1 i ;= 32767 2 3 rint$ 1 45(@n4" i 2 # i=i+1# 6 6

)o, it doesn@t print n#*bers ro* ' to -2!6!G $t@s an inde inite loopG To begin with, it prints o#t n#*bers ro* ' to -2!6!G 1 ter that val#e o i is incre*ented by ', there ore it tries to beco*e -2!6%, which alls o#tside the valid integer range, so it goes to other side and beco*es <-2!6% which wo#ld certainly satis y the condition in the 0hileG This process goes on inde initelyG What will be the o#tp#t o the ollowing progra*c
main1 2 3 int i = 1 # Fhi%e 1 i ;= 10 2 # 3 rint$ 1 45(@n4" i 2 # i=i+1# 6 6

Chapter 30 The %oop Control tructure

1)5

This is another inde inite loop, and it doesn@t give any o#tp#t at allG The reason is, we have carelessly given a ; a ter the 0hileG This wo#ld *a9e the loop wor9 li9e thisGGG
Fhi%e 1 i ;= 10 2 # 3 rint$ 1 45(@n4" i 2 # i=i+1# 6

Since the val#e o i is not getting incre*ented the control wo#ld 9eep rotating within the loop, eternallyG )ote that enclosing print8= > and i F i ?1 within a pair o braces is not an errorG $n act we can p#t a pair o braces aro#nd any individ#al state*ent or set o state*ents witho#t a ecting the e/ec#tion o the progra*G

,ore (perators
There are variety o operators which are reH#ently #sed with 0hileG To ill#strate their #sage let #s consider a proble* wherein n#*bers ro* ' to '( are to be printed on the screenG The progra* or per or*ing this tas9 can be written #sing 0hile in the ollowing di erent waysP
1a2 main1 2 3 int i = 1 # Fhi%e 1 i ;= 10 2 3 rint$ 1 45(@n4" i 2 # i=i+1# 6 6

1)"
1&2 main1 2 3 int i = 1 # Fhi%e 1 i ;= 10 2 3 rint$ 1 45(@n4" i 2 # i++ # 6 6

%et .s C

)ote that the incre*ent operator ?? incre*ents the val#e o i by ', every ti*e the state*ent i?? gets e/ec#tedG Si*ilarly, to red#ce the val#e o a variable by ' a decre*ent operator @@ is also availableG 2owever, never #se n??? to incre*ent the val#e o n by 2, since C doesn@t recogni;e the operator ???G
1'2 main1 2 3 int i = 1 # Fhi%e 1 i ;= 10 2 3 rint$ 1 45(@n4" i 2 # i += 1 # 6 6

)ote that ?F is a co*po#nd assign*ent operatorG $t incre*ents the val#e o i by 'G Si*ilarly, W F W ? 1) can also be written as W ?F 1)G 3ther co*po#nd assign*ent operators are @F4 <F4 + F and AFG
1(2 main1 2 3 int i = 0 # Fhi%e 1 i++ ; 10 2

Chapter 30 The %oop Control tructure


rint$ 1 45(@n4" i 2 # 6

1)7

$n the state*ent 0hile = i?? J 1) >, irstly the co*parison o val#e o i with '( is per or*ed, and then the incre*entation o i ta9es placeG Since the incre*entation o i happens a ter its #sage, here the ?? operator is called a post<incre*entation operatorG When the control reaches print8= >, i has already been incre*ented, hence i *#st be initiali;ed to (G
1e2 main1 2 3 int i = 0 # Fhi%e 1 ++i ;= 10 2 rint$ 1 45(@n4" i 2 # 6

$n the state*ent 0hile = ??i JF 1) >, irstly incre*entation o i ta9es place, then the co*parison o val#e o i with '( is per or*edG Since the incre*entation o i happens be ore its #sage, here the ?? operator is called a pre<incre*entation operatorG

The for Loop


,erhaps one reason why ew progra**ers #se 0hile is that they are too b#sy #sing the 8or, which is probably the *ost pop#lar looping instr#ctionG The 8or allows #s to speci y three things abo#t a loop in a single lineP >a? Setting a loop co#nter to an initial val#eG >b? Testing the loop co#nter to deter*ine whether its val#e has reached the n#*ber o repetitions desiredG >c? $ncreasing the val#e o loop co#nter each ti*e the progra* seg*ent within the loop has been e/ec#tedG

1)&
The general or* o 8or state*ent is as #nderP
$!r 1 initia%ise '!,nter # test '!,nter # in'rement '!,nter 2 3 (! this # an( this # an( this # 6

%et .s C

7et #s write down the si*ple interest progra* #sing 8orG Co*pare this progra* with the one, which we wrote #sing 0hileG The lowchart is also given below or a better #nderstandingG

Chapter 30 The %oop Control tructure


ST1"T

1)9

co#nt INP X'

bs

co#nt X co#nt L '

is co#nt aX Ces $),6T p, n, r

)o

ST3,

si X p W n W r = '((

,"$)T si

+ig#re -G)* +a%',%ati!n !$ sim %e interest $!r 3 sets !$ " n an( r *) main 1 2 3 int " n" '!,nt # $%!at r" si # $!r 1 '!,nt = 1 # '!,nt ;= 3 # '!,nt = '!,nt + 1 2 3 rint$ 1 4Enter =a%,es !$ " n" an( r 4 2 # s'an$ 1 45( 5( 5$4" B " Bn" Br 2 # si = * n * r ) 100 # rint$ 1 47im %e Interest = >s.5$@n4" si 2 #

6 6

11)

%et .s C

$ this progra* is co*pared with the one written #sing 0hile, it can be seen that the three stepsRinitiali;ation, testing and incre*entationRreH#ired or the loop constr#ct have now been incorporated in the 8or state*entG 7et #s now e/a*ine how the 8or state*ent gets e/ec#tedP When the 8or state*ent is e/ec#ted or the irst ti*e, the val#e o count is set to an initial val#e 'G )ow the condition count JF 3 is testedG Since count is ' the condition is satis ied and the body o the loop is e/ec#ted or the irst ti*eG 6pon reaching the closing brace o 8or, control is sent bac9 to the 8or state*ent, where the val#e o count gets incre*ented by 'G o 1gain the test is per or*ed to chec9 whether the new val#e count e/ceeds -G

$ the val#e o count is still within the range ' to -, the state*ents within the braces o 8or are e/ec#ted againG The body o the 8or loop contin#es to get e/ec#ted till count doesn@t e/ceed the inal val#e -G When count reaches the val#e 4 the control e/its ro* the loop and is trans erred to the state*ent >i any? i**ediately a ter the body o 8orG The ollowing ig#re wo#ld help in #rther clari ying the concept o e/ec#tion o the 8or loopG

Chapter 30 The %oop Control tructure

111

ST1"T initialise

test Tr#e body o loop incre*ent

+alse

ST3,

+ig#re -G4 $t is i*portant to note that the initiali;ation, testing and incre*entation part o a 8or loop can be replaced by any valid e/pressionG Th#s the ollowing 8or loops are per ectly o9G
$!r 1 i = 10 # i # i -- 2 rint$ 1 45(4" i 2 # $!r 1 i ; 4 # 9 = 5 # 9 = 0 2 rint$ 1 45(4" i 2 # $!r 1 i = 1# i ;=10 # rint$ 1 45(4"i++ 2 # $!r 1 s'an$ 1 45(4" Bi 2 # i ;= 10 # i++ 2 rint$ 1 45(4" i 2 #

7et #s now write down the progra* to print n#*bers ro* ' to '( in di erent waysG This ti*e we wo#ld #se a 8or loop instead o a 0hile loopG

112
1a2 main1 2 3 int i # $!r 1 i = 1 # i ;= 10 # i = i + 1 2 rint$ 1 45(@n4" i 2 # 6

%et .s C

)ote that the initialisation, testing and incre*entation o loop co#nter is done in the 8or state*ent itsel G $nstead o i F i ? 1, the state*ents i?? or i ?F 1 can also be #sedG Since there is only one state*ent in the body o the 8or loop, the pair o braces have been droppedG 1s with the 0hile, the de a#lt scope o 8or is the i**ediately ne/t state*ent a ter 8orG
1&2 main1 2 3 int i # $!r 1 i = 1 # i ;= 10 # 2 3 rint$ 1 45(@n4" i 2 # i=i+1# 6 6

2ere, the incre*entation is done within the body o the 8or loop and not in the 8or state*entG )ote that inspite o this the se*icolon a ter the condition is necessaryG
1'2 main1 2 3 int i = 1 # $!r 1 # i ;= 10 # i = i + 1 2 rint$ 1 45(@n4" i 2 # 6

Chapter 30 The %oop Control tructure

113

2ere the initialisation is done in the declaration state*ent itsel , b#t still the se*icolon be ore the condition is necessaryG
1(2 main1 2 3 int i = 1 # $!r 1 # i ;= 10 # 2 3 rint$ 1 45(@n4" i 2 # i=i+1# 6 6

2ere, neither the initialisation, nor the incre*entation is done in the 8or state*ent, b#t still the two se*icolons are necessaryG
1e2 main1 2 3 int i # $!r 1 i = 0 # i++ ; 10 # 2 rint$ 1 45(@n4" i 2 # 6

2ere, the co*parison as well as the incre*entation is done thro#gh the sa*e state*ent, i?? J 1)G Since the ?? operator co*es a ter i irstly co*parison is done, ollowed by incre*entationG )ote that it is necessary to initiali;e i to (G
1$2 main1 2 3 int i # $!r 1 i = 0 # ++i ;= 10 # 2 rint$ 1 45(@n4" i 2 # 6

114

%et .s C

2ere, both, the co*parison and the incre*entation is done thro#gh the sa*e state*ent, ??i JF 1)G Since ?? precedes i irstly incre*entation is done, ollowed by co*parisonG )ote that it is necessary to initiali;e i to (G

9esting o8 Loops
The way i8 state*ents can be nested, si*ilarly 0hiles and 8ors can also be nestedG To #nderstand how nested loops wor9, loo9 at the progra* given belowP
)* 0em!nstrati!n !$ neste( %!! s *) main1 2 3 int r" '" s,m # $!r 1 r = 1 # r ;= 3 # r++ 2 )* !,ter %!! *) 3 $!r 1 ' = 1 # ' ;= 2 # '++ 2 )* inner %!! *) 3 s,m = r + ' # rint$ 1 4r = 5( ' = 5( s,m = 5(@n4" r" '" s,m 2 # 6 6 6

When yo# r#n this progra* yo# will get the ollowing o#tp#tP
r = 1 ' = 1 s,m = 2 r = 1 ' = 2 s,m = 3 r = 2 ' = 1 s,m = 3 r = 2 ' = 2 s,m = 4 r = 3 ' = 1 s,m = 4 r = 3 ' = 2 s,m = 5

2ere, or each val#e o r the inner loop is cycled thro#gh twice, with the variable c ta9ing val#es ro* ' to 2G The inner loop

Chapter 30 The %oop Control tructure

115

ter*inates when the val#e o c e/ceeds 2, and the o#ter loop ter*inates when the val#e o r e/ceeds -G 1s yo# can see, the body o the o#ter 8or loop is indented, and the body o the inner 8or loop is #rther indentedG These *#ltiple indentations *a9e the progra* easier to #nderstandG $nstead o #sing two state*ents, one to calc#late su1 and another to print it o#t, we can co*pact this into one single state*ent by sayingP
rint$ 1 4r = 5( ' = 5( s,m = 5(@n4" r" '" r + ' 2 #

The way 8or loops have been nested here, si*ilarly, two 0hile loops can also be nestedG )ot only this, a 8or loop can occ#r within a 0hile loop, or a 0hile within a 8orG

,ultiple *nitialisations in the for Loop


The initialisation e/pression o the 8or loop can contain *ore than one state*ent separated by a co**aG +or e/a*ple,
$!r 1 i = 1" 9 = 2 # 9 ;= 10 # 9++ 2

5#ltiple state*ents can also be #sed in the incre*entation e/pression o 8or loop_ iGeG, yo# can incre*ent >or decre*ent? two or *ore variables at the sa*e ti*eG 2owever, only one e/pression is allowed in the test e/pressionG This e/pression *ay contain several conditions lin9ed together #sing logical operatorsG 6se o *#ltiple state*ents in the initialisation e/pression also de*onstrates why se*icolons are #sed to separate the three e/pressions in the 8or loopG $ co**as had been #sed, they co#ld not also have been #sed to separate *#ltiple state*ents in the initialisation e/pression, witho#t con #sing the co*pilerG

11"
The (dd Loop

%et .s C

The loops that we have #sed so ar e/ec#ted the state*ents within the* a inite n#*ber o ti*esG 2owever, in real li e progra**ing one co*es across a sit#ation when it is not 9nown be orehand how *any ti*es the state*ents in the loop are to be e/ec#tedG This sit#ation can be progra**ed as shown belowP
)* Exe',ti!n !$ a %!! an ,n.n!Fn n,m&er !$ times *) main1 2 3 'har an!ther # int n,m # (! 3 rint$ 1 4Enter a n,m&er 4 2 # s'an$ 1 45(4" Bn,m 2 # rint$ 1 4sH,are !$ 5( is 5(4" n,m" n,m * n,m 2 # rint$ 1 4@nSant t! enter an!ther n,m&er /)n 4 2 # s'an$ 1 4 5'4" Ban!ther 2 # 6 Fhi%e 1 an!ther == '/' 2 # 6

1nd here is the sa*ple o#tp#tGGG


Enter a n,m&er 5 sH,are !$ 5 is 25 Sant t! enter an!ther n,m&er /)n / Enter a n,m&er 7 sH,are !$ 7 is 49 Sant t! enter an!ther n,m&er /)n n

$n this progra* the do@0hile loop wo#ld 9eep getting e/ec#ted till the #ser contin#es to answer yG The *o*ent he answers n, the loop ter*inates, since the condition > another FF X#X ? ailsG )ote that this loop ens#res that state*ents within it are e/ec#ted at least once even i n is s#pplied irst ti*e itsel G

Chapter 30 The %oop Control tructure

117

Tho#gh it is si*pler to progra* s#ch a reH#ire*ent #sing a do@ 0hile loop, the sa*e #nctionality i reH#ired, can also be acco*plished #sing 8or and 0hile loops as shown belowP
)* !(( %!! ,sin- a $!r %!! *) main1 2 3 'har an!ther = '/' # int n,m # $!r 1 # an!ther == '/' # 2 3 rint$ 1 4Enter a n,m&er 4 2 # s'an$ 1 45(4" Bn,m 2 # rint$ 1 4sH,are !$ 5( is 5(4" n,m" n,m * n,m 2 # rint$ 1 4@nSant t! enter an!ther n,m&er /)n 4 2 # s'an$ 1 4 5'4" Ban!ther 2 # 6 6 )* !(( %!! ,sin- a Fhi%e %!! *) main1 2 3 'har an!ther = '/' # int n,m # Fhi%e 1 an!ther == '/' 2 3 rint$ 1 4Enter a n,m&er 4 2 # s'an$ 1 45(4" Bn,m 2 # rint$ 1 4sH,are !$ 5( is 5(4" n,m" n,m * n,m 2 # rint$ 1 4@nSant t! enter an!ther n,m&er /)n 4 2 # s'an$ 1 4 5'4" Ban!ther 2 # 6 6

11&
The break State1ent

%et .s C

We o ten co*e across sit#ations where we want to Q#*p o#t o a loop instantly, witho#t waiting to get bac9 to the conditional testG The 9eyword 6reaG allows #s to do thisG When 6reaG is enco#ntered inside any loop, control a#to*atically passes to the irst state*ent a ter the loopG 1 6reaG is #s#ally associated with an i8G 1s an e/a*ple, let@s consider the ollowing e/a*pleG B3a1pleD Write a progra* to deter*ine whether a n#*ber is pri*e or notG 1 pri*e n#*ber is one, which is divisible only by ' or itsel G 1ll we have to do to test whether a n#*ber is pri*e or not, is to divide it s#ccessively by all n#*bers ro* 2 to one less than itsel G $ re*ainder o any o these divisions is ;ero, the n#*ber is not a pri*eG $ no division yields a ;ero then the n#*ber is a pri*e n#*berG +ollowing progra* i*ple*ents this logicG
main1 2 3 int n,m" i # rint$ 1 4Enter a n,m&er 4 2 # s'an$ 1 45(4" Bn,m 2 # i=2# Fhi%e 1 i ;= n,m - 1 2 3 i$ 1 n,m 5 i == 0 2 3 rint$ 1 4E!t a rime n,m&er4 2 # &rea. # 6 i++ # 6

Chapter 30 The %oop Control tructure


i$ 1 i == n,m 2 rint$ 1 4?rime n,m&er4 2 # 6

119

$n this progra* the *o*ent nu1 A i t#rns o#t to be ;ero, >iGeG nu1 is e/actly divisible by i? the *essage K)ot a pri*e n#*berO is printed and the control brea9s o#t o the 0hile loopG Why does the progra* reH#ire the i8 state*ent a ter the 0hile loop at allc Well, there are two ways the control co#ld have reached o#tside the 0hile loopP >a? $t Q#*ped o#t beca#se the n#*ber proved to be not a pri*eG >b? The loop ca*e to an end beca#se the val#e o i beca*e eH#al to nu1G When the loop ter*inates in the second case, it *eans that there was no n#*ber between 2 to nu1 @ 1 that co#ld e/actly divide nu1G That is, nu1 is indeed a pri*eG $ this is tr#e, the progra* sho#ld print o#t the *essage K,ri*e n#*berOG The 9eyword 6reaG, brea9s the control only ro* the 0hile in which it is placedG Consider the ollowing progra*, which ill#strates this actG
main1 2 3 int i = 1 " 9 = 1 # Fhi%e 1 i++ ;= 100 2 3 Fhi%e 1 9++ ;= 200 2 3 i$ 1 9 == 150 2 &rea. # e%se rint$ 1 45( 5(@n4" i" 9 2 # 6

12)
6 6

%et .s C

$n this progra* when W eH#als '5(, 6reaG ta9es the control o#tside the inner 0hile only, since it is placed inside the inner 0hileG

The continue State1ent


$n so*e progra**ing sit#ations we want to ta9e the control to the beginning o the loop, bypassing the state*ents inside the loop, which have not yet been e/ec#tedG The 9eyword continue allows #s to do thisG When continue is enco#ntered inside any loop, control a#to*atically passes to the beginning o the loopG 1 continue is #s#ally associated with an i8G 1s an e/a*ple, letJs consider the ollowing progra*G
main1 2 3 int i" 9 # $!r 1 i = 1 # i ;= 2 # i++ 2 3 $!r 1 9 = 1 # 9 ;= 2 # 9++ 2 3 i$ 1 i == 9 2 '!ntin,e # rint$ 1 4@n5( 5(@n4" i" 9 2 # 6 6 6

The o#tp#t o the above progra* wo#ld beGGG


12 21

Chapter 30 The %oop Control tructure

121

)ote that when the val#e o i eH#als that o W, the continue state*ent ta9es the control to the 8or loop >inner? bypassing rest o the state*ents pending e/ec#tion in the 8or loop >inner?G

The do@while Loop


The do@0hile loop loo9s li9e thisP
(! 3 this # an( this # an( this # an( this # 6 Fhi%e 1 this '!n(iti!n is tr,e 2 #

There is a *inor di erence between the wor9ing o 0hile and do@ 0hile loopsG This di erence is the place where the condition is testedG The 0hile tests the condition be ore e/ec#ting any o the state*ents within the 0hile loopG 1s against this, the do@0hile tests the condition a ter having e/ec#ted the state*ents within the loopG +ig#re -G5 wo#ld clari y the e/ec#tion o do@0hile loop still #rtherG

122

%et .s C

ST1"T initialise

body o loop

incre*ent

Tr#e

test +alse ST3,

+ig#re -G5 This *eans that do@0hile wo#ld e/ec#te its state*ents at least once, even i the condition ails or the irst ti*eG The 0hile, on the other hand will not e/ec#te its state*ents i the condition ails or the irst ti*eG This di erence is bro#ght abo#t *ore clearly by the ollowing progra*G
main1 2 3 Fhi%e 1 4 ; 1 2 rint$ 1 4Ue%%! there @n42 # 6

Chapter 30 The %oop Control tructure

123

2ere, since the condition ails the irst ti*e itsel , the print8= > will not get e/ec#ted at allG 7etJs now write the sa*e progra* #sing a do@0hile loopG
main1 2 3 (! 3 rint$ 1 4Ue%%! there @n42 # 6 Fhi%e 1 4 ; 1 2 # 6

$n this progra* the print8= > wo#ld be e/ec#ted once, since irst the body o the loop is e/ec#ted and then the condition is testedG There are so*e occasions when we want to e/ec#te a loop at least once no *atter whatG This is ill#strated in the ollowing e/a*pleP 6reaG and continue are #sed with do@0hile Q#st as they wo#ld be in a 0hile or a 8or loopG 1 6reaG ta9es yo# o#t o the do@0hile bypassing the conditional testG 1 continue sends yo# straight to the test at the end o the loopG

124
Su11ar#

%et .s C

>a? The three type o loops available in C are 8or, 0hile, and do@ 0hileG >b? 1 6reaG state*ent ta9es the e/ec#tion control o#t o the loopG >c? 1 continue state*ent s9ips the e/ec#tion o the state*ents a ter it and ta9es the control to the beginning o the loopG >d? 1 do@0hile loop is #sed to ens#re that the state*ents within the loop are e/ec#ted at least onceG >e? The ?? operator incre*ents the operand by ', whereas, the << operator decre*ents it by 'G > ? The operators LX, <X, WX, =X, UX are co*po#nd assign*ent operatorsG They *odi y the val#e o the operand to the le t o the*G

B3ercise
while Loop
K'L What wo#ld be the o#tp#t o the ollowing progra*sP 1a2 main1 2 3 int 9 # Fhi%e 1 9 ;= 10 2 3 rint$ 1 4@n5(4" 9 2 # 9=9+1# 6 6 1&2 main1 2 3 int i = 1 # Fhi%e 1 i ;= 10 2 # 3 rint$ 1 4@n5(4" i 2 #

Chapter 30 The %oop Control tructure


6 6 i++ #

125

1'2

main1 2 3 int 9 # Fhi%e 1 9 ;= 10 2 3 rint$ 1 4@n5(4" 9 2 # 9=9+1# 6 6

1(2 main1 2 3 int x = 1 # Fhi%e 1 x == 1 2 3 x=x-1# rint$ 1 4@n5(4" x 2 # 6 6 1e2 main1 2 3 int x = 1 # Fhi%e 1 x == 1 2 x=x-1# rint$ 1 4@n5(4" x 2 # 6 1$2 main1 2 3 'har x #

12"
Fhi%e 1 x = 0 # x ;= 255 # x++ 2 rint$ 1 4@nAs'ii =a%,e 5( +hara'ter 5'4" x" x 2 # 6 1-2 main1 2 3 int x = 4" /" : # / = --x # : = x-- # rint$ 1 4@n5( 5( 5(4" x" /" : 2 # 6 1h2 main1 2 3 int x = 4" / = 3" : # : = x-- -/ # rint$ 1 4@n5( 5( 5(4" x" /" : 2 # 6 1i2 main1 2 3 Fhi%e 1 'a' ; '&' 2 rint$ 1 4@nma%/a%am is a a%in(r!me4 2 # 6 main1 2 3 int i = 10 # Fhi%e 1 i = 20 2 rint$ 1 4@nA '!m ,ter &,$$T4 2 # 6 main1 2 3 int i # Fhi%e 1 i = 10 2 3

%et .s C

192

1.2

Chapter 30 The %oop Control tructure


rint$ 1 4@n5(4" i 2 # i=i+1# 6 6

127

1%2

main1 2 3 $%!at x = 1.1 # Fhi%e 1 x == 1.1 2 3 rint$ 1 4@n5$4" x 2 # x = x A 0.1 # 6 6

1m2 main1 2 3 Fhi%e 1 '1' ; '2' 2 rint$ 1 4@nIn Fhi%e %!! 4 2 # 6 1n2 main1 2 3 'har x # $!r 1 x = 0 # x ;= 255 # x++ 2 rint$ 1 4@nAs'ii =a%,e 5( +hara'ter 5'4" x" x 2 # 6 1!2 main1 2 3 int x = 4" / = 0" : # Fhi%e 1 x <= 0 2 3 x-- # /++ # i$ 1 x == / 2

12&
e%se 6 6 1 2 main1 2 3 int x = 4" / = 0" : # Fhi%e 1 x <= 0 2 3 i$ 1 x == / 2 &rea. # e%se rint$ 1 M@n5( 5(N" x" / 2 # x-- # /++ # 6 6 K-L 1tte*pt the ollowingP '!ntin,e # rint$ 1 M@n5( 5(N" x" / 2 #

%et .s C

>a? Write a progra* to calc#late overti*e pay o '( e*ployeesG 3verti*e is paid at the rate o "sG '2G(( per ho#r or every ho#r wor9ed above 4( ho#rsG 1ss#*e that e*ployees do not wor9 or ractional part o an ho#rG >b? Write a progra* to ind the actorial val#e o any n#*ber entered thro#gh the 9eyboardG >c? Two n#*bers are entered thro#gh the 9eyboardG Write a progra* to ind the val#e o one n#*ber raised to the power >d? o anotherG Write a progra* to print all the 1SC$$ val#es and their eH#ivalent characters #sing a 0hile loopG The 1SC$$ val#es vary ro* ( to 255G

Chapter 30 The %oop Control tructure

129

>e? Write a progra* to print o#t all 1r*strong n#*bers between ' and 5((G $ s#* o c#bes o each digit o the n#*ber is eH#al to the n#*ber itsel , then the n#*ber is called an 1r*strong n#*berG +or e/a*ple, '5- X > ' W ' W ' ? L > 5 W 5 W5?L>-W-W-? > ? Write a progra* or a *atchstic9 ga*e being played between the co*p#ter and a #serG Co#r progra* sho#ld ens#re that the co*p#ter always winsG "#les or the ga*e are as ollowsP There are 2' *atchstic9sG The co*p#ter as9s the player to pic9 ', 2, -, or 4 *atchstic9sG 1 ter the person pic9s, the co*p#ter does its pic9ingG Whoever is orced to pic9 #p the last *atchstic9 loses the ga*eG >g? Write a progra* to enter the n#*bers till the #ser wants and at the end it sho#ld display the co#nt o positive, negative and ;eros enteredG >h? Write a progra* to ind the octal eH#ivalent o the entered n#*berG >i? Write a progra* to ind the range o a set o n#*bersG "ange is the di erence between the s*allest and biggest n#*ber in the listG

for, break, continue, do-while


KCL What wo#ld be the o#tp#t o the ollowing progra*sP 1a2 main1 2 3 int i = 0 # $!r 1 # i # 2

13)
6 rint$ 1 4@nUere is s!me mai% $!r /!,4 2 #

%et .s C

1&2 main1 2 3 int i # $!r 1 i = 1 # i ;= 5 # rint$ 1 4@n5(4" i 2 2 # i++ # 6 1'2 main1 2 3 int i = 1" 9 = 1 # $!r 1 # # 2 3 i$ 1 i < 5 2 &rea. # e%se 9 += i # rint$ 1 4@n5(4" 9 2 # i += 9 # 6 6

1(2 main1 2 3 int i # $!r 1 i = 1 # i ;= 5 # rint$ 1 4@n5'4" 65 2 2 # i++ # 6 KDL 1nswer the ollowingP
(a) The three parts o the loop e/pression in the 8or loop areP

the i the t the i

e/pression e/pression e/pression

Chapter 30 The %oop Control tructure

131

(b) 1n e/pression contains relational operators, assign*ent

operators, and arith*etic operatorsG $n the absence o parentheses, they will be eval#ated in which o the ollowing orderP 'G 2G -G 4G assign*ent, relational, arith*etic arith*etic, relational, assign*ent relational, arith*etic, assign*ent assign*ent, arith*etic, relational

(c) The 6reaG state*ent is #sed to e/it ro*P

'G 2G -G 4G
(d)

an i8 state*ent a 8or loop a progra* the 1ain= > #nction

1 do@0hile loop is #se #l when we want that the state*ents within the loop *#st be e/ec#tedP 'G 2G -G 4G 3nly once 1t least once 5ore than once )one o the above

(e)

$n what seH#ence the initiali;ation, testing and e/ec#tion o body is done in a do<while loop 'G 2G -G 4G $nitiali;ation, e/ec#tion o body, testing ./ec#tion o body, initiali;ation, testing $nitiali;ation, testing, e/ec#tion o body )one o the above

(f)

Which o the ollowing is not an in inite loopG


1. int i = 1 # Fhi%e 1 1 2 3 i++ # 6

2G $!r 1 # # 2 #

132

%et .s C

-G int 8r,e = 0" $a%se # Fhi%e 1 8r,e 2 3 Ia%se = 1 # 6

4G int /" x = 0 # (! 3 /=x# 6 Fhi%e 1 x == 0 2 #

(g) Which o the ollowing state*ent is #sed to ta9e the control to

the beginning o the loopc 'G 2G -G 4G e/it brea9 contin#e )one o the above

KBL 1tte*pt the ollowingP


(a) Write a progra* to print all pri*e n#*bers ro* ' to -((G

>2intP 6se nested loops, 6reaG and continue?


(b) Write a progra* to ill the entire screen with a s*iling aceG

The s*iling ace has an 1SC$$ val#e 'G


(c) Write a progra* to add irst seven ter*s o the ollowing

series #sing a 8or loopP


' '4 2 24 -4 ::

(d) Write a progra* to generate all co*binations o ', 2 and -

#sing 8or loopG


(e) 1ccording to a st#dy, the appro/i*ate level o intelligence o

a person can be calc#lated #sing the ollowing or*#laP


i = 2 + 1 / + 0.5 x 2

Chapter 30 The %oop Control tructure

133

Write a progra*, which will prod#ce a table o val#es o i, # and 3, where # varies ro* ' to 6, and, or each val#e o #, 3 varies ro* 5G5 to '2G5 in steps o (G5G
(f)

Write a progra* to prod#ce the ollowing o#tp#tP 1 1 1 1 1 1 1 8 8 8 8 8 8 C C C C C 0 . + G + . 0 0 . + + . 0 0 . . 0 0 0 C C C C C 8 8 8 8 8 8 1 1 1 1 1 1 1

(g) Write a progra* to ill the entire screen with dia*ond and

heart alternativelyG The 1SC$$ val#e or heart is - and that o dia*ond is 4G


(h)

Write a progra* to print the *#ltiplication table o the n#*ber entered by the #serG The table sho#ld get displayed in the ollowing or*G 2& W ' X 2& 2& W 2 X 5% : Write a progra* to prod#ce the ollowing o#tp#tP ' 2 4 ! % 5 & 6 '(

(i)

134
(j)

%et .s C

Write a progra* to prod#ce the ollowing o#tp#tP ' ' ' ' ' 4 6 2 4 ' ' ' '

(k) 1 *achine is p#rchased which will prod#ce earning o "sG

'((( per year while it lastsG The *achine costs "sG 6((( and will have a salvage o "sG 2((( when it is conde*nedG $ '2 percent per ann#* can be earned on alternate invest*ents what wo#ld be the *ini*#* li e o the *achine to *a9e it a *ore attractive invest*ent co*pared to alternative invest*entc
(l)

When interest co*po#nds Q ti*es per year at an ann#al rate o r U or n years, the principle p co*po#nds to an a*o#nt a as per the ollowing or*#la a = 1 1 + r ) H 2 nH

Write a progra* to read '( sets o p4 r4 n I Q and calc#late the corresponding asG
(m) The nat#ral logarith* can be appro/i*ated by the ollowing

seriesG
4 " ' + ' " ' + ' ' "' "' + + GGGG " 2 " " 2 " 2 2 -

$ 3 is inp#t thro#gh the 9eyboard, write a progra* to calc#late the s#* o irst seven ter*s o this seriesG

The Case Control Structure


e 0ecisions 6sing switch The Tips and Traps e switch Vers#s if-else 7adder e The goto Keyword e S#**ary e ./ercise

135

13"

%et .s C

n real li e we are o ten aced with sit#ations where we are reH#ired to *a9e a choice between a n#*ber o alternatives rather than only one or twoG +or e/a*ple, which school to Qoin or which hotel to visit or still harder which girl to *arry >yo# al*ost always end #p *a9ing a wrong decision is a di erent *atter altogether4?G Serio#s C progra**ing is sa*e_ the choice we are as9ed to *a9e is *ore co*plicated than *erely selecting between two alternativesG C provides a special control state*ent that allows #s to handle s#ch cases e ectively_ rather than #sing a series o i8 state*entsG This control instr#ction is in act the topic o this chapterG Towards the end o the chapter we wo#ld also st#dy a 9eyword called goto, and #nderstand why we sho#ld avoid its #sage in C progra**ingG

Decisions .sing switch


The control state*ent that allows #s to *a9e a decision ro* the n#*ber o choices is called a s0itch, or *ore correctly a s0itch@ case@de8ault, since these three 9eywords go together to *a9e #p the control state*entG They *ost o ten appear as ollowsP
sFit'h 1 inte-er ex ressi!n 2 3 'ase '!nstant 1 : (! this # 'ase '!nstant 2 : (! this # 'ase '!nstant 3 : (! this # (e$a,%t : (! this # 6

The integer e/pression ollowing the 9eyword s0itch is any C e/pression that will yield an integer val#eG $t co#ld be an integer constant li9e ', 2 or -, or an e/pression that eval#ates to an

Chapter 80 The Case Control tructure

137

integerG The 9eyword case is ollowed by an integer or a character constantG .ach constant in each case *#st be di erent ro* all the othersG The Kdo thisO lines in the above or* o s0itch represent any valid C state*entG What happens when we r#n a progra* containing a s0itchc +irst, the integer e/pression ollowing the 9eyword s0itch is eval#atedG The val#e it gives is then *atched, one by one, against the constant val#es that ollow the case state*entsG When a *atch is o#nd, the progra* e/ec#tes the state*ents ollowing that case, and all s#bseH#ent case and de8ault state*ents as wellG $ no *atch is o#nd with any o the case state*ents, only the state*ents ollowing the de8ault are e/ec#tedG 1 ew e/a*ples will show how this control str#ct#re wor9sG Consider the ollowing progra*P
main1 2 3 int i = 2 # sFit'h 1 i 2 3 'ase 1 : rint$ 1 4I am in 'ase 1 @n4 2 # 'ase 2 : rint$ 1 4I am in 'ase 2 @n4 2 # 'ase 3 : rint$ 1 4I am in 'ase 3 @n4 2 # (e$a,%t : rint$ 1 4I am in (e$a,%t @n4 2 # 6 6

The o#tp#t o this progra* wo#ld beP


I am in 'ase 2

13&
I am in 'ase 3 I am in (e$a,%t

%et .s C

The o#tp#t is de initely not what we e/pected4 We didn@t e/pect the second and third line in the above o#tp#tG The progra* prints case 2 and - and the de a#lt caseG Well, yesG We said the s0itch e/ec#tes the case where a *atch is o#nd and all the s#bseH#ent cases and the de8ault as wellG $ yo# want that only case 2 sho#ld get e/ec#ted, it is #pto yo# to get o#t o the s0itch then and there by #sing a 6reaG state*entG The ollowing e/a*ple shows how this is doneG )ote that there is no need or a 6reaG state*ent a ter the de8ault, since the control co*es o#t o the s0itch anywayG
main1 2 3 int i = 2 # sFit'h 1 i 2 3 'ase 1 : rint$ 1 4I am in 'ase 1 @n4 2 # &rea. # 'ase 2 : rint$ 1 4I am in 'ase 2 @n4 2 # &rea. # 'ase 3 : rint$ 1 4I am in 'ase 3 @n4 2 # &rea. # (e$a,%t : rint$ 1 4I am in (e$a,%t @n4 2 # 6 6

The o#tp#t o this progra* wo#ld beP


I am in 'ase 2

Chapter 80 The Case Control tructure

139

The operation o s0itch is shown below in the or* o a lowchart or a better #nderstandingG
ST1"T case ' )o case 2 )o case )o case 4 )o Ces Ces Ces Ces state*ent ' state*ent 2 state*ent state*ent 4

ST3, switch ( choice ) " case # $ statement # % break % case & $ statement & % break % case ' $ statement ' % break % case ( $ statement ( % )

+ig#re 4G'

14)
The Tips and Traps

%et .s C

1 ew #se #l tips abo#t the #sage o s0itch and a ew pit alls to be avoidedP >a? The earlier progra* that #sed s0itch *ay give yo# the wrong i*pression that yo# can #se only cases arranged in ascending order, ', 2, - and de a#ltG Co# can in act p#t the cases in any order yo# pleaseG 2ere is an e/a*ple o scra*bled case orderP
main1 2 3 int i = 22 # sFit'h 1 i 2 3 'ase 121 : rint$ 1 4I am in 'ase 121 @n4 2 # &rea. # 'ase 7 : rint$ 1 4I am in 'ase 7 @n4 2 # &rea. # 'ase 22 : rint$ 1 4I am in 'ase 22 @n4 2 # &rea. # (e$a,%t : rint$ 1 4I am in (e$a,%t @n4 2 # 6 6

The o#tp#t o this progra* wo#ld beP


I am in 'ase 22

>b? Co# are also allowed to #se char val#es in case and s0itch as shown in the ollowing progra*P
main1 2

Chapter 80 The Case Control tructure


3 'har ' = 'x' # sFit'h 1 ' 2 3 'ase '=' : rint$ 1 4I am in 'ase = @n4 2 # &rea. # 'ase 'a' : rint$ 1 4I am in 'ase a @n4 2 # &rea. # 'ase 'x' : rint$ 1 4I am in 'ase x @n4 2 # &rea. # (e$a,%t : rint$ 1 4I am in (e$a,%t @n4 2 # 6 6

141

The o#tp#t o this progra* wo#ld beP


I am in 'ase x

$n act here when we #se Dv@, Da@, D/@ they are act#ally replaced by the 1SC$$ val#es >''%, &!, '2(? o these character constantsG >c? 1t ti*es we *ay want to e/ec#te a co**on set o state*ents or *#ltiple casesG 2ow this can be done is shown in the ollowing e/a*pleG
main1 2 3 'har 'h # rint$ 1 4Enter an/ !$ the a% ha&et a" &" !r ' 4 2 # s'an$ 1 45'4" B'h 2 #

142
sFit'h 1 'h 2 3 'ase 'a' : 'ase 'A' : rint$ 1 4a as in ashar4 2 # &rea. # 'ase '&' : 'ase 'D' : rint$ 1 4& as in &rain4 2 # &rea. # 'ase ''' : 'ase '+' : rint$ 1 4' as in '!!.ie4 2 # &rea. # (e$a,%t : rint$ 1 4Fish /!, .neF Fhat are a% ha&ets4 2 # 6 6

%et .s C

2ere, we are *a9ing #se o the act that once a case is satis ied the control si*ply alls thro#gh the case till it doesn@t enco#nter a 6reaG state*entG That is why i an alphabet a is entered the case MaO is satis ied and since there are no state*ents to be e/ec#ted in this case the control a#to*atically reaches the ne/t case iGeG case M'O and e/ec#tes all the state*ents in this caseG >d? .ven i there are *#ltiple state*ents to be e/ec#ted in each case there is no need to enclose the* within a pair o braces >e? >#nli9e i8, and else?G .very state*ent in a s0itch *#st belong to so*e case or the otherG $ a state*ent doesn@t belong to any case the co*piler won@t report an errorG 2owever, the state*ent wo#ld never get e/ec#tedG +or e/a*ple, in the ollowing progra* the print8= > never goes to wor9G

Chapter 80 The Case Control tructure


main1 2 3 int i" 9 # rint$ 1 4Enter =a%,e !$ i4 2 # s'an$ 1 45(N" Bi 2 # sFit'h 1 i 2 3 rint$ 1 4Ue%%!4 2 # 'ase 1 : 9 = 10 # &rea. # 'ase 2 : 9 = 20 # &rea. # 6 6

143

> ? $ we have no de8ault case, then the progra* si*ply alls thro#gh the entire s0itch and contin#es with the ne/t >g? instr#ction >i any,? that ollows the closing brace o s0itchG $s s0itch a replace*ent or i8c Ces and noG Ces, beca#se it o ers a better way o writing progra*s as co*pared to i8, and no beca#se in certain sit#ations we are le t with no choice b#t to #se i8G The disadvantage o s0itch is that one cannot have a case in a s0itch which loo9s li9eP
'ase i ;= 20 :

1ll that we can have a ter the case is an int constant or a char constant or an e/pression that eval#ates to one o these constantsG .ven a 8loat is not allowedG The advantage o s0itch over i8 is that it leads to a *ore str#ct#red progra* and the level o indentation is *anageable,

144

%et .s C

*ore so i there are *#ltiple state*ents within each case o a s0itchG >h? We can chec9 the val#e o any e/pression in a s0itchG Th#s the ollowing s0itch state*ents are legalG
sFit'h 1 i + 9 * . 2 sFit'h 1 23 + 45 5 4 * . 2 sFit'h 1 a ; 4 BB & < 7 2

./pressions can also be #sed in cases provided they are constant e/pressionsG Th#s case 3 ? 7 is correct, however, case a ? 6 is incorrectG >i? The 6reaG state*ent when #sed in a s0itch ta9es the control o#tside the s0itchG 2owever, #se o continue will not ta9e the control to the beginning o s0itch as one is li9ely to believeG >Q? $n principle, a s0itch *ay occ#r within another, b#t in practice it is rarely doneG S#ch state*ents wo#ld be called nested s0itch state*entsG >9? The s0itch state*ent is very #se #l while writing *en# driven progra*sG This aspect o s0itch is disc#ssed in the e/ercise at the end o this chapterG

switch 5ersus if-else Ladder


There are so*e things that yo# si*ply cannot do with a s0itchG These areP >a? 1 loat e/pression cannot be tested #sing a s0itch >b? Cases can never have variable e/pressions > or e/a*ple it is wrong to say case a ?3 D ? >c? 5#ltiple cases cannot #se sa*e e/pressionsG Th#s the ollowing s0itch is illegalP

Chapter 80 The Case Control tructure


sFit'h 1 a 2 3 'ase 3 : ... 'ase 1 + 2 : ... 6

145

>a?, >b? and >c? above *ay lead yo# to believe that these are obvio#s disadvantages with a s0itch, especially since there weren@t any s#ch li*itations with i8@elseG Then why #se a s0itch at allc +or speedRs0itch wor9s aster than an eH#ivalent i8@else ladderG 2ow co*ec This is beca#se the co*piler generates a Q#*p table or a s0itch d#ring co*pilationG 1s a res#lt, d#ring e/ec#tion it si*ply re ers the Q#*p table to decide which case sho#ld be e/ec#ted, rather than act#ally chec9ing which case is satis iedG 1s against this, i8@elses are slower beca#se they are eval#ated at e/ec#tion ti*eG 1 s0itch with '( cases wo#ld wor9 aster than an eH#ivalent i8@else ladderG 1lso, a s0itch with 2 cases wo#ld wor9 slower than i8@else ladderG Whyc $ the '(th case is satis ied then Q#*p table wo#ld be re erred and state*ents or the '(th case wo#ld be e/ec#tedG 1s against this, in an i8@else ladder '( conditions wo#ld be eval#ated at e/ec#tion ti*e, which *a9es it slowG )ote that a loo9#p in the Q#*p table is aster than eval#ation o a condition, especially i the condition is co*ple/G $ on the other hand the conditions in the i8@else were si*ple and less in n#*ber then i8@else wo#ld wor9 o#t aster than the loo9#p *echanis* o a s0itchG 2ence a s0itch with two cases wo#ld wor9 slower than an eH#ivalent i8@elseG Th#s, yo# as a progra**er sho#ld ta9e a decision which o the two sho#ld be #sed whenG

The goto 7e#0ord


1void goto 9eyword4 They *a9e a C progra**er@s li e *iserableG There is seldo* a legiti*ate reason or #sing goto, and its #se is

14"

%et .s C

one o the reasons that progra*s beco*e #nreliable, #nreadable, and hard to deb#gG 1nd yet *any progra**ers ind goto sed#ctiveG $n a di ic#lt progra**ing sit#ation it see*s so easy to #se a goto to ta9e the control where yo# wantG 2owever, al*ost always, there is a *ore elegant way o writing the sa*e progra* #sing i8, 8or, 0hile and s0itchG These constr#cts are ar *ore logical and easy to #nderstandG The big proble* with gotos is that when we do #se the* we can never be s#re how we got to a certain point in o#r codeG They obsc#re the low o controlG So as ar as possible s9ip the*G Co# can always get the Qob done witho#t the*G Tr#st *e, with good progra**ing s9ills goto can always be avoidedG This is the irst and last ti*e that we are going to #se goto in this boo9G 2owever, or sa9e o co*pleteness o the boo9, the ollowing progra* shows how to #se gotoG
main1 2 3 int -!a%s # rint$ 1 4Enter the n,m&er !$ -!a%s s'!re( a-ainst In(ia4 2 # s'an$ 1 45(4" B-!a%s 2 # i$ 1 -!a%s ;= 5 2 -!t! s!s # e%se 3 rint$ 1 4A&!,t time s!''er %a/ers %earnt +@n4 2 # rint$ 1 4an( sai( -!!(&/eT a(ie,T t! s!''er4 2 # exit1 2 # )* terminates r!-ram exe',ti!n *) 6 s!s : rint$ 1 48! err is h,manT4 2 #

Chapter 80 The Case Control tructure


6

147

1nd here are two sa*ple r#ns o the progra*GGG


Enter the n,m&er !$ -!a%s s'!re( a-ainst In(ia 3 8! err is h,manT Enter the n,m&er !$ -!a%s s'!re( a-ainst In(ia 7 A&!,t time s!''er %a/ers %earnt + an( sai( -!!(&/eT a(ie,T t! s!''er

1 ew re*ar9s abo#t the progra* wo#ld *a9e the things clearerG f $ the condition is satis ied the goto state*ent trans ers control to the label Dsos@, ca#sing print8= > ollowing sos to be e/ec#tedG The label can be on a separate line or on the sa*e line as the state*ent ollowing it, as in,
s!s : rint$ 1 48! err is h,manT4 2 #

f 1ny n#*ber o gotos can ta9e the control to the sa*e labelG f The e3it= > #nction is a standard library #nction which ter*inates the e/ec#tion o the progra*G $t is necessary to #se this #nction since we donJt want the state*ent
rint$ 1 48! err is h,manT4 2

to get e/ec#ted a ter e/ec#tion o the else bloc9G f The only progra**ing sit#ation in avo#r o #sing goto is when we want to ta9e the control o#t o the loop that is contained in several other loopsG The ollowing progra* ill#strates thisG

14&
main1 2 3 int i" 9" . # $!r 1 i = 1 # i ;= 3 # i++ 2 3 $!r 1 9 = 1 # 9 ;= 3 # 9++ 2 3 $!r 1 . = 1 # . ;= 3 # .++ 2 3 i$ 1 i == 3 BB 9 == 3 BB . == 3 2 -!t! !,t # e%se rint$ 1 45( 5( 5(@n4" i" 9" . 2 # 6 6 6 !,t : rint$ 1 4Q,t !$ the %!! at %astT4 2 # 6

%et .s C

Go thro#gh the progra* care #lly and ind o#t how it wor9sG 1lso write down the sa*e progra* witho#t #sing gotoG

Su11ar#
>a? When we need to choose one a*ong n#*ber o alternatives, a s0itch state*ent is #sedG >b? The s0itch 9eyword is ollowed by an integer or an e/pression that eval#ates to an integerG >c? The case 9eyword is ollowed by an integer or a character constantG >d? The control alls thro#gh all the cases #nless the 6reaG state*ent is givenG >e? The #sage o the goto 9eyword sho#ld be avoided as it #s#ally violets the nor*al low o e/ec#tionG

Chapter 80 The Case Control tructure

149

B3ercise
K'L What wo#ld be the o#tp#t o the ollowing progra*sP 1a2 main1 2 3 'har s,ite = 3 # sFit'h 1 s,ite 2 3 'ase 1 : rint$ 1 4@n0iam!n(4 2 # 'ase 2 : rint$ 1 4@n7 a(e4 2 # (e$a,%t : rint$ 1 4@nUeart42 # 6 rint$ 1 4@nI th!,-ht !ne Fears a s,ite4 2 # 6 1&2 main1 2 3 int ' = 3 # sFit'h 1 ' 2 3 'ase '=' : rint$ 1 4I am in 'ase = @n4 2 # &rea. # 'ase 3 : rint$ 1 4I am in 'ase 3 @n4 2 # &rea. # 'ase 12 : rint$ 1 4I am in 'ase 12 @n4 2 # &rea. # (e$a,%t : rint$ 1 4I am in (e$a,%t @n4 2 # 6

15)
6 1'2 main1 2 3 int ." 9 = 2 # sFit'h 1 . = 9 + 1 2 3 'ase 0 : rint$ 1 4@n8ai%!r42 # 'ase 1 : rint$ 1 4@n8,t!r42 # 'ase 2 : rint$ 1 4@n8ram 42 # (e$a,%t : rint$ 1 4@n?,re 7im %e E--hea(T4 2 # 6 6

%et .s C

1(2 main1 2 3 int i = 0 # sFit'h 1 i 2 3 'ase 0 : rint$ 1 4@n+,st!mers are (i'e/4 2 # 'ase 1 : rint$ 1 4@nPar.ets are ri'e/4 2 # 'ase 2 : rint$ 1 4@nIn=est!rs are m!!(/4 2 # 'ase 3 : rint$ 1 4@nAt %east em %!/ees are -!!(4 2 # 6 6 1e2 main1 2 3 int . # $%!at 9 = 2.0 #

Chapter 80 The Case Control tructure


sFit'h 1 . = 9 + 1 2 3 'ase 3 : rint$ 1 4@n8ra e(4 2 # &rea. # (e$a,%t : rint$ 1 4@n+a,-htT4 2 # 6 6 1$2 main1 2 3 int 'h = 'a' + '&' # sFit'h 1 'h 2 3 'ase 'a' : 'ase '&' : rint$ 1 4@nG!, entere( &4 2 # 'ase 'A' : rint$ 1 4@na as in ashar4 2 # 'ase '&' + 'a' : rint$ 1 4@nG!, entere( a an( &4 2 # 6 6

151

1-2 main1 2 3 int i = 1 # sFit'h 1 i - 2 2 3 'ase -1 : rint$ 1 4@nIee(in- $ish4 2 # 'ase 0 : rint$ 1 4@nSee(in- -rass4 2 # 'ase 1 : rint$ 1 4@nmen(in- r!!$4 2 # (e$a,%t : rint$ 1 4@nC,st t! s,r=i=e4 2 #

152
6 6

%et .s C

K-L ,oint o#t the errors, i any, in the ollowing progra*sP 1a2 main1 2 3 int s,ite = 1 # sFit'h 1 s,ite 2 # 3 'ase 0 # rint$ 1 4@n+%,&4 2 # 'ase 1 # rint$ 1 4@n0iam!n(4 2 # 6 6 1&2 main1 2 3 int tem # s'an$ 1 45(4" Btem 2 # sFit'h 1 tem 2 3 'ase 1 tem ;= 20 2 : rint$ 1 4@nQ!!!!!!hhhhT 0amn '!!%T4 2 # 'ase 1 tem < 20 BB tem ;= 30 2 : rint$ 1 4@n>ain rain here a-ainT4 2 # 'ase 1 tem < 30 BB tem ;= 40 2 : rint$ 1 4@nSish I am !n E=erest4 2 # (e$a,%t : rint$ 1 4@nJ!!( !%( na- ,r Feather4 2 # 6 6 1'2 main1 2 3 $%!at a = 3.5 # sFit'h 1 a 2

Chapter 80 The Case Control tructure


3 'ase 0.5 : rint$ 1 4@n8he art !$ +4 2 # &rea. # 'ase 1.5 : rint$ 1 4@n8he s irit !$ +4 2 # &rea. # 'ase 2.5 : rint$ 1 4@n7ee thr!,-h +4 2 # &rea. # 'ase 3.5 : rint$ 1 4@n7im %/ '4 2 #

153

6 6 1(2 main1 2 3 int a = 3" & = 4" ' # '=&Aa# sFit'h 1 ' 2 3 'ase 1 WW 2 : rint$ 1 4J!( -i=e me an ! !rt,nit/ t! 'han-e thin-s4 2 # &rea. # 'ase a WW & : rint$ 1 4J!( -i=e me an ! !rt,nit/ t! r,n m/ sh!F4 2 # &rea. # 6 6 KCL Write a *en# driven progra* which has ollowing optionsP

'G 2G -G 4G

+actorial o a n#*berG ,ri*e or not 3dd or even ./it

154
5a9e #se o switch state*entG The o#tline o this progra* is given belowP
)* A men, (ri=en r!-ram *) main1 2 3 int 'h!i'e # Fhi%e 1 1 2 3 rint$ 1 4@n1. Ia't!ria%4 2 # rint$ 1 4@n2. ?rime4 2 # rint$ 1 4@n3. Q(()E=en4 2 # rint$ 1 4@n4. Exit4 2 # rint$ 1 4@nG!,r 'h!i'eZ 4 2 # s'an$ 1 45(4" B'h!i'e 2 # sFit'h 1 'h!i'e 2 3 'ase 1 : )* %!-i' $!r $a't!ria% !$ a n,m&er *) &rea. # 'ase 2 : )* %!-i' $!r (e'i(in- rime n,m&er *) &rea. # 'ase 3 : )* %!-i' $!r !(()e=en *) &rea. # 'ase 4 : exit1 2 # 6 6 6

%et .s C

)oteP

Chapter 80 The Case Control tructure

155

The state*ent 0hile = 1 > p#ts the entire logic in an in inite loopG This is necessary since the *en# *#st 9eep reappearing on the screen once an ite* is selected and an appropriate action ta9enG
KDL Write a progra* which to ind the grace *ar9s or a st#dent #sing s0itchG The #ser sho#ld enter the class obtained by the st#dent and the n#*ber o s#bQects he has ailed inG

f $ the st#dent gets irst class and the n#*ber o s#bQects he ailed in is greater than -, then he does not get any graceG $ the n#*ber o s#bQects he ailed in is less than or eH#al to - then the grace is o 5 *ar9s per s#bQectG f $ the st#dent gets second class and the n#*ber o s#bQects he ailed in is greater than 2, then he does not get any graceG $ the n#*ber o s#bQects he ailed in is less than or eH#al to 2 then the grace is o 4 *ar9s per s#bQectG f $ the st#dent gets third class and the n#*ber o s#bQects he ailed in is greater than ', then he does not get any graceG $ the n#*ber o s#bQects he ailed in is eH#al to ' then the grace is o 5 *ar9s per s#bQect

15"

%et .s C

Functions & Pointers


e What is a +#nction Why 6se +#nctions e ,assing Val#es between +#nctions e Scope "#le o +#nctions e Calling Convention e 3ne 0icey $ss#e e 1dvanced +eat#res o +#nctions +#nction 0eclaration and ,rototypes Call by Val#e and Call by "e erence 1n $ntrod#ction to ,ointers ,ointer )otation 8ac9 to +#nction Calls Concl#sions "ec#rsion e 1dding +#nctions to the 7ibrary e S#**ary e ./ercise

157

15&

%et .s C

nowingly or #n9nowingly we rely on so *any persons or so *any thingsG 5an is an intelligent species, b#t still cannot per or* all o li e@s tas9s all aloneG 2e has to rely on othersG Co# *ay call a *echanic to i/ #p yo#r bi9e, hire a gardener to *ow yo#r lawn, or rely on a store to s#pply yo# groceries every *onthG 1 co*p#ter progra* >e/cept or the si*plest one? inds itsel in a si*ilar sit#ationG $t cannot handle all the tas9s by itsel G $nstead, it reH#ests other progra* li9e entitiesRcalled D #nctions@ in CRto get its tas9s doneG $n this chapter we will st#dy these #nctionsG We will loo9 at a variety o eat#res o these #nctions, starting with the si*plest one and then wor9ing towards those that de*onstrate the power o C #nctionsG

/hat is a Function
1 #nction is a sel <contained bloc9 o state*ents that per or* a coherent tas9 o so*e 9indG .very C progra* can be tho#ght o as a collection o these #nctionsG 1s we noted earlier, #sing a #nction is so*ething li9e hiring a person to do a speci ic Qob or yo#G So*eti*es the interaction with this person is very si*ple_ so*eti*es it@s co*ple/G S#ppose yo# have a tas9 that is always per or*ed e/actly in the sa*e wayRsay a bi*onthly servicing o yo#r *otorbi9eG When yo# want it to be done, yo# go to the service station and say, K$t@s ti*e, do it nowOG Co# don@t need to give instr#ctions, beca#se the *echanic 9nows his QobG Co# don@t need to be told when the Qob is doneG Co# ass#*e the bi9e wo#ld be serviced in the #s#al way, the *echanic does it and that@s thatG 7et #s now loo9 at a si*ple C #nction that operates in *#ch the sa*e way as the *echanicG 1ct#ally, we will be loo9ing at two thingsRa #nction that calls or activates the #nction and the #nction itsel G

Chapter 50 &unctions 9 #ointers


main1 2 3 messa-e1 2 # rint$ 1 4@n+r/" an( /!, st! the m!n!t!n/T4 2 # 6 messa-e1 2 3 rint$ 1 4@n7mi%e" an( the F!r%( smi%es Fith /!,...4 2 # 6

159

1nd here@s the o#tp#tGGG


7mi%e" an( the F!r%( smi%es Fith /!,... +r/" an( /!, st! the m!n!t!n/T

2ere, 1ain= > itsel is a #nction and thro#gh it we are calling the #nction 1essage= >G What do we *ean when we say that 1ain= > Dcalls@ the #nction 1essage= >c We *ean that the control passes to the #nction 1essage= >G The activity o 1ain= > is te*porarily s#spended_ it alls asleep while the 1essage= > #nction wa9es #p and goes to wor9G When the 1essage= > #nction r#ns o#t o state*ents to e/ec#te, the control ret#rns to 1ain= >, which co*es to li e again and begins e/ec#ting its code at the e/act point where it le t o G Th#s, 1ain= > beco*es the Dcalling@ #nction, whereas 1essage= > beco*es the Dcalled@ #nctionG $ yo# have grasped the concept o Dcalling@ a #nction yo# are prepared or a call to *ore than one #nctionG Consider the ollowing e/a*pleP
main1 2 3 rint$ 1 4@nI am in main4 2 # ita%/1 2 # &ra:i%1 2 # ar-entina1 2 # 6

1")
ita%/1 2 3 rint$ 1 4@nI am in ita%/4 2 # 6 &ra:i%1 2 3 rint$ 1 4@nI am in &ra:i%4 2 # 6 ar-entina1 2 3 rint$ 1 4@nI am in ar-entina4 2 # 6

%et .s C

The o#tp#t o the above progra* when e/ec#ted wo#ld be as #nderP


I am in main I am in ita%/ I am in &ra:i% I am in ar-entina

+ro* this progra* a n#*ber o concl#sions can be drawnP f 1ny C progra* contains at least one #nctionG f $ a progra* contains only one #nction, it *#st be 1ain= >G f $ a C progra* contains *ore than one #nction, then one >and only one? o these #nctions *#st be 1ain= >, beca#se progra* e/ec#tion always begins with 1ain= >G f There is no li*it on the n#*ber o present in a C progra*G #nctions that *ight be

f .ach #nction in a progra* is called in the seH#ence speci ied by the #nction calls in 1ain= >G

Chapter 50 &unctions 9 #ointers


f

1"1

1 ter each #nction has done its thing, control ret#rns to 1ain= >GWhen 1ain= > r#ns o#t o #nction calls, the progra* endsG

1s we have noted earlier the progra* e/ec#tion always begins with 1ain= >. ./cept or this act all C #nctions enQoy a state o per ect eH#alityG )o precedence, no priorities, nobody is nobody@s bossG 3ne #nction can call another #nction it has already called b#t has in the *eanti*e le t te*porarily in order to call a third #nction which will so*eti*e later call the #nction that has called it, i yo# #nderstand what $ *eanG )oc Well, let@s ill#strate with an e/a*pleG
main1 2 3 rint$ 1 4@nI am in main4 2 # ita%/1 2 # rint$ 1 4@nI am $ina%%/ &a'. in main4 2 # 6 ita%/1 2 3 rint$ 1 4@nI am in ita%/4 2 # &ra:i%1 2 # rint$ 1 4@nI am &a'. in ita%/4 2 # 6 &ra:i%1 2 3 rint$ 1 4@nI am in &ra:i%4 2 # ar-entina1 2 # 6 ar-entina1 2 3 rint$ 1 4@nI am in ar-entina4 2 # 6

1nd the o#tp#t wo#ld loo9 li9eGGG

1"2
I am in main I am in ita%/ I am in &ra:i% I am in ar-entina I am &a'. in ita%/ I am $ina%%/ &a'. in main

%et .s C

2ere, 1ain= > calls other #nctions, which in t#rn call still other #nctionsG Trace care #lly the way control passes ro* one #nction to anotherG Since the co*piler always begins the progra* e/ec#tion with 1ain= >, every #nction in a progra* *#st be called directly or indirectly by 1ain= >G $n other words, the 1ain= > #nction drives other #nctionsG 7et #s now s#**ari;e what we have learnt so arG >a? C progra* is a collection o one or *ore #nctionsG >b? 1 #nction gets called when the #nction na*e is ollowed by a se*icolonG +or e/a*ple,
main1 2 3 ar-entina1 2 # 6

>c? 1 #nction is de ined when #nction na*e is ollowed by a pair o braces in which one or *ore state*ents *ay be presentG +or e/a*ple,
ar-entina1 2 3 statement 1 # statement 2 # statement 3 # 6

Chapter 50 &unctions 9 #ointers

1"3

>d? 1ny #nction can be called ro* any other #nctionG .ven 1ain= > can be called ro* other #nctionsG +or e/a*ple,
main1 2 3 messa-e1 2 # 6 messa-e1 2 3 rint$ 1 4@n+an't ima-ine %i$e Fith!,t +4 2 # main1 2 # 6

>e? 1 #nction can be called any n#*ber o ti*esG +or e/a*ple,


main1 2 3 messa-e1 2 # messa-e1 2 # 6 messa-e1 2 3 rint$ 1 4@nCeFe% 8hie$TT4 2 # 6

> ? The order in which the #nctions are de ined in a progra* and the order in which they get called need not necessarily be sa*eG +or e/a*ple,
main1 2 3 messa-e11 2 # messa-e21 2 # 6 messa-e21 2 3 rint$ 1 4@nD,t the &,tter Fas &itter4 2 #

1"4
6 messa-e11 2 3 rint$ 1 4@nPar/ &!,-ht s!me &,tter4 2 # 6

%et .s C

2ere, even tho#gh 1essage1= > is getting called be ore 1essage2= >, still, 1essage1= > has been de ined a ter 1essage2= >G 2owever, it is advisable to de ine the #nctions in the sa*e order in which they are calledG This *a9es the progra* easier to #nderstandG >g? 1 #nction can call itsel G S#ch a process is called Drec#rsion@G We wo#ld disc#ss this aspect o C #nctions later in this >h? chapterG 1 #nction can be called ro* other #nction, b#t a #nction cannot be de ined in another #nctionG Th#s, the ollowing progra* code wo#ld be wrong, since argentina= > is being de ined inside another #nction, 1ain= >G
main1 2 3 rint$ 1 4@nI am in main4 2 # ar-entina1 2 3 rint$ 1 4@nI am in ar-entina4 2 # 6 6

>i? There are basically two types o #nctionsP 7ibrary #nctions ./G print8= >, scan8= > etcG 6ser<de ined #nctions ./G argentina= >, 6raHil= > etcG 1s the na*e s#ggests, library #nctions are nothing b#t co**only reH#ired #nctions gro#ped together and stored in

Chapter 50 &unctions 9 #ointers

1"5

what is called a 7ibraryG This library o #nctions is present on the dis9 and is written or #s by people who write co*pilers or #sG 1l*ost always a co*piler co*es with a library o standard #nctionsG The proced#re o calling both types o #nctions is e/actly sa*eG

/h# .se Functions


Why write separate #nctions at allc Why not sH#ee;e the entire logic into one #nction, 1ain= >c Two reasonsP
(a)

Writing #nctions avoids rewriting the sa*e code over and overG S#ppose yo# have a section o code in yo#r progra* that calc#lates area o a triangleG $ later in the progra* yo# want to calc#late the area o a di erent triangle, yo# won@t li9e it i yo# are reH#ired to write the sa*e instr#ctions all over againG $nstead, yo# wo#ld pre er to Q#*p to a Dsection o code@ that calc#lates area and then Q#*p bac9 to the place ro* where yo# le t o G This section o code is nothing b#t a #nctionG 6sing #nctions it beco*es easier to write progra*s and 9eep trac9 o what they are doingG $ the operation o a progra* can be divided into separate activities, and each activity placed in a di erent #nction, then each co#ld be written and chec9ed *ore or less independentlyG Separating the code into *od#lar #nctions also *a9es the progra* easier to design and #nderstandG

(b)

What is the *oral o the storyc 0on@t try to cra* the entire logic in one #nctionG $t is a very bad style o progra**ingG $nstead, brea9 a progra* into s*all #nits and write #nctions or each o these isolated s#bdivisionsG 0on@t hesitate to write #nctions that are called only onceG What is i*portant is that these #nctions per or* so*e logically isolated tas9G

1""
!assing 5alues 6et0een Functions

%et .s C

The #nctions that we have #sed so ar haven@t been very le/ibleG We call the* and they do what they are designed to doG 7i9e o#r *echanic who always services the *otorbi9e in e/actly the sa*e way, we haven@t been able to in l#ence the #nctions in the way they carry o#t their tas9sG $t wo#ld be nice to have a little *ore control over what #nctions do, in the sa*e way it wo#ld be nice to be able to tell the *echanic, K1lso change the engine oil, $ a* going or an o#tingOG $n short, now we want to co**#nicate between the Dcalling@ and the Dcalled@ #nctionsG The *echanis* #sed to convey in or*ation to the #nction is the Darg#*ent@G Co# have #n9nowingly #sed the arg#*ents in the print8= > and scan8= > #nctions_ the or*at string and the list o variables #sed inside the parentheses in these #nctions are arg#*entsG The arg#*ents are so*eti*es also called Dpara*eters@G Consider the ollowing progra*G $n this progra*, in 1ain= > we receive the val#es o a, 6 and c thro#gh the 9eyboard and then o#tp#t the s#* o a, 6 and cG 2owever, the calc#lation o s#* is done in a di erent #nction called calsu1= >G $ s#* is to be calc#lated in calsu1= > and val#es o a, 6 and c are received in 1ain= >, then we *#st pass on these val#es to calsu1= >, and once calsu1= > calc#lates the s#* we *#st ret#rn it ro* calsu1= > bac9 to 1ain= >G
)* 7en(in- an( re'ei=in- =a%,es &etFeen $,n'ti!ns *) main1 2 3 int a" &" '" s,m # rint$ 1 4@nEnter an/ three n,m&ers 4 2 # s'an$ 1 45( 5( 5(4" Ba" B&" B' 2 # s,m = 'a%s,m 1 a" &" ' 2 #

Chapter 50 &unctions 9 #ointers


rint$ 1 4@n7,m = 5(4" s,m 2 # 6 'a%s,m 1 x" /" : 2 int x" /" : # 3 int ( # (=x+/+:# ret,rn 1 ( 2 # 6

1"7

1nd here is the o#tp#tGGG


Enter an/ three n,m&ers 10 20 30 7,m = 60

There are a n#*ber o things to note abo#t this progra*P >a? $n this progra*, ro* the #nction 1ain= > the val#es o a, 6 and c are passed on to the #nction calsu1= >, by *a9ing a call to the #nction calsu1= > and *entioning a, 6 and c in the parenthesesP
s,m = 'a%s,m 1 a" &" ' 2 #

$n the calsu1= > #nction these val#es get collected in three variables 3, # and HP
'a%s,m 1 x" /" : 2 int x" /" : #

>b? The variables a, 6 and c are called Dact#al arg#*ents@, whereas the variables 3, # and H are called D or*al arg#*ents@G 1ny n#*ber o arg#*ents can be passed to a #nction being calledG 2owever, the type, order and n#*ber o the act#al and or*al arg#*ents *#st always be sa*eG

1"&

%et .s C

$nstead o #sing di erent variable na*es 3, # and H, we co#ld have #sed the sa*e variable na*es a, 6 and cG 8#t the co*piler wo#ld still treat the* as di erent variables since they are in di erent #nctionsG >c? There are two *ethods o declaring the or*al arg#*entsG The one that we have #sed in o#r progra* is 9nown as Kernighan and "itchie >or Q#st K I "? *ethodG
'a%s,m 1 x" /" : 2 int x" /" : #

1nother *ethod is,


'a%s,m 1 int x" int /" int : 2

This *ethod is called 1)S$ *ethod and is *ore co**only #sed these daysG >d? $n the earlier progra*s the *o*ent closing brace > Y ? o the called #nction was enco#ntered the control ret#rned to the calling #nctionG )o separate return state*ent was necessary to send bac9 the controlG This approach is ine i the called #nction is not going to ret#rn any *eaning #l val#e to the calling #nctionG $n the above progra*, however, we want to ret#rn the s#* o 3, # and HG There ore, it is necessary to #se the return state*entG The return state*ent serves two p#rposesP >'? 3n e/ec#ting the return state*ent it i**ediately trans ers the control bac9 to the calling progra*G >2? $t ret#rns the val#e present in the parentheses a ter return, to th-e calling progra*G $n the above progra* the val#e o s#* o three n#*bers is being ret#rnedG

Chapter 50 &unctions 9 #ointers

1"9

>e? There is no restriction on the n#*ber o return state*ents that *ay be present in a #nctionG 1lso, the return state*ent need not always be present at the end o the called #nctionG The ollowing progra* ill#strates these actsG
$,n1 2 3 'har 'h # rint$ 1 4@nEnter an/ a% ha&et 4 2 # s'an$ 1 45'4" B'h 2 # i$ 1 'h <= 65 BB 'h ;= 90 2 ret,rn 1 'h 2 # e%se ret,rn 1 'h + 32 2 #

$n this #nction di erent return state*ents will be e/ec#ted depending on whether ch is capital or notG > ? Whenever the control ret#rns ro* a #nction so*e val#e is de initely ret#rnedG $ a *eaning #l val#e is ret#rned then it sho#ld be accepted in the calling progra* by eH#ating the called #nction to so*e variableG +or e/a*ple,
s,m = 'a%s,m 1 a" &" ' 2 #

>g? 1ll the ollowing are valid return state*entsG


ret,rn 1 a 2 # ret,rn 1 23 2 # ret,rn 1 12.34 2 # ret,rn #

17)

%et .s C

$n the last state*ent a garbage val#e is ret#rned to the calling #nction since we are not ret#rning any speci ic val#eG )ote that in this case the parentheses a ter return are droppedG >h? $ we want that a called #nction sho#ld not ret#rn any val#e, in that case, we *#st *ention so by #sing the 9eyword %oid as shown belowG
=!i( (is %a/1 2 3 rint$ 1 4@nUea(s I Fin...4 2 # rint$ 1 4@n8ai%s /!, %!se4 2 # 6

>i? 1 #nction can ret#rn only one val#e at a ti*eG Th#s, the ollowing state*ents are invalidG
ret,rn 1 a" & 2 # ret,rn 1 x" 12 2 #

There is a way to get aro#nd this li*itation, which wo#ld be disc#ssed later in this chapter when we learn pointersG >Q? $ the val#e o a or*al arg#*ent is changed in the called #nction, the corresponding change does not ta9e place in the calling #nctionG +or e/a*ple,
main1 2 3 int a = 30 # $,n 1 a 2 # rint$ 1 4@n5(4" a 2 # 6 $,n 1 int & 2 3 & = 60 #

Chapter 50 &unctions 9 #ointers


rint$ 1 4@n5(4" & 2 # 6

171

The o#tp#t o the above progra* wo#ld beP


60 30

Th#s, even tho#gh the val#e o 6 is changed in 8un= >4 the val#e o a in 1ain= > re*ains #nchangedG This *eans that when val#es are passed to a called #nction the val#es present in act#al arg#*ents are not physically *oved to the or*al arg#*ents_ Q#st a photocopy o val#es in act#al arg#*ent is *ade into or*al arg#*entsG

Scope $ule o8 Functions


7oo9 at the ollowing progra*
main1 2 3 int i = 20 # (is %a/ 1 i 2 # 6 (is %a/ 1 int 9 2 3 int . = 35 # rint$ 1 4@n5(4" 9 2 # rint$ 1 4@n5(4" . 2 # 6

$n this progra* is it necessary to pass the val#e o the variable i to the #nction displa#= >c Will it not beco*e a#to*atically available to the #nction displa#= >c )oG 8eca#se by de a#lt the scope o a variable is local to the #nction in which it is de inedG The presence

172

%et .s C

o i is 9nown only to the #nction 1ain= > and not to any other #nctionG Si*ilarly, the variable G is local to the #nction displa#= > and hence it is not available to 1ain= >G That is why to *a9e the val#e o i available to displa#= > we have to e/plicitly pass it to displa#= >G 7i9ewise, i we want G to be available to 1ain= > we will have to ret#rn it to 1ain= > #sing the return state*entG $n general we can say that the scope o a variable is local to the #nction in which it is de inedG

Calling Con%ention
Calling convention indicates the order in which arg#*ents are passed to a #nction when a #nction call is enco#nteredG There are two possibilities hereP >a? 1rg#*ents *ight be passed ro* le t to rightG >b? 1rg#*ents *ight be passed ro* right to le tG C lang#age ollows the second orderG Consider the ollowing #nction callP
$,n 1a" &" '" ( 2 #

$n this call it doesn@t *atter whether the arg#*ents are passed ro* le t to right or ro* right to le tG 2owever, in so*e #nction call the order o passing arg#*ents beco*es an i*portant considerationG +or e/a*pleP
int a = 1 # rint$ 1 45( 5( 5(4" a" ++a" a++ 2 #

$t appears that this print8= > wo#ld o#tp#t ' 2 -G This however is not the caseG S#rprisingly, it o#tp#ts - - 'G This is beca#se C@s calling convention is ro* right to le tG That is, irstly

Chapter 50 &unctions 9 #ointers

173

' is passed thro#gh the e/pression a?? and then a is incre*ented to 2G Then res#lt o ??a is passedG That is, a is incre*ented to and then passedG +inally, latest val#e o a, iGeG -, is passedG Th#s in right to le t order ', -, - get passedG 3nce print8= > collects the* it prints the* in the order in which we have as9ed it to get the* printed >and not the order in which they were passed?G Th#s - - ' gets printedG

(ne Dice# *ssue


Consider the ollowing #nction callsP
Lin'%,(e ;'!ni!.h< '%rs'r 1 2 # -!t!x/ 1 10" 20 2 # 'h = -et'h 1 a 2 #

2ere we are calling three standard library #nctionsG Whenever we call the library #nctions we *#st write their prototype be ore *a9ing the callG This helps the co*piler in chec9ing whether the val#es being passed and ret#rned are as per the prototype declarationG 8#t since we don@t de ine the library #nctions >we *erely call the*? we *ay not 9now the prototypes o library #nctionsG 2ence when the library o #nctions is provided a set o DGh@ iles is also providedG These iles contain the prototypes o library #nctionsG 8#t why *#ltiple ilesc 8eca#se the library #nctions are divided into di erent gro#ps and one ile is provided or each gro#pG +or e/a*ple, prototypes o all inp#t=o#tp#t #nctions are provided in the ile DstdioGh@, prototypes o all *athe*atical #nctions are provided in the ile D*athGh@, etcG 3n co*pilation o the above code the co*piler reports all errors d#e to the *is*atch between para*eters in #nction call and their corresponding prototypes declared in the ile DconioGh@G Co# can even open this ile and loo9 at the prototypesG They wo#ld appear as shown belowP

174
=!i( '%rs'r1 2 # =!i( -!t!x/ 1 int" int 2 # int -et'h1 2 #

%et .s C

)ow consider the ollowing #nction callsP


Lin'%,(e ;st(i!.h< int i = 10" 9 = 20 # rint$ 1 45( 5( 5( 4" i" 9 2 # rint$ 1 45(4" i" 9 2 #

The above #nctions get s#ccess #lly co*piled even tho#gh there is a *is*atch in the or*at speci iers and the variables in the listG This is beca#se print8= > accepts variable n#*ber o arg#*ents >so*eti*es 2 arg#*ents, so*eti*es - arg#*ents, etcG?, and even with the *is*atch above the call still *atches with the prototype o print8= > present in DstdioGh@G 1t r#n<ti*e when the irst print8= > is e/ec#ted, since there is no variable *atching with the last speci ier Ad, a garbage integer gets printedG Si*ilarly, in the second print8= > since the or*at speci ier or W has not been *entioned its val#e does not get printedG

'd%anced Features o8 Functions


With a so#nd basis o the preli*inaries o C #nctions, let #s now get into their intricaciesG +ollowing advanced topics wo#ld be considered hereG
(a) +#nction 0eclaration and ,rototypes (b) Calling #nctions by val#e or by re erence (c) "ec#rsion

7et #s #nderstand these eat#res one by oneG

Chapter 50 &unctions 9 #ointers

175

Function Declaration and !rotot#pes


1ny C #nction by de a#lt ret#rns an int val#eG 5ore speci ically, whenever a call is *ade to a #nction, the co*piler ass#*es that this #nction wo#ld ret#rn a val#e o the type intG $ we desire that a #nction sho#ld ret#rn a val#e other than an int, then it is necessary to e/plicitly *ention so in the calling #nction as well as in the called #nctionG S#ppose we want to ind o#t sH#are o a n#*ber #sing a #nctionG This is how this si*ple progra* wo#ld loo9 li9eP
main1 2 3 $%!at a" & # rint$ 1 4@nEnter an/ n,m&er 4 2 # s'an$ 1 45$4" Ba 2 # & = sH,are 1 a 2 # rint$ 1 4@n7H,are !$ 5$ is 5$4" a" & 2 # 6 sH,are 1 $%!at x 2 3 $%!at / # /=x*x# ret,rn 1 / 2 # 6

1nd here are three sa*ple r#ns o this progra*GGG


Enter an/ n,m&er 3 7H,are !$ 3 is 9.000000 Enter an/ n,m&er 1.5 7H,are !$ 1.5 is 2.000000 Enter an/ n,m&er 2.5 7H,are !$ 2.5 is 6.000000

17"

%et .s C

The irst o these answers is correctG 8#t sH#are o 'G5 is de initely not 2G )either is 6 a sH#are o 2G5G This happened beca#se any C #nction, by de a#lt, always ret#rns an integer val#eG There ore, even tho#gh the #nction sQuare= > calc#lates the sH#are o 'G5 as 2G25, the proble* crops #p when this 2G25 is to be ret#rned to 1ain= >G sQuare= > is not capable o ret#rning a 8loat val#eG 2ow do we overco*e thisc The ollowing progra* seg*ent ill#strates how to *a9e sQuare= > capable o ret#rning a 8loat val#eG
main1 2 3 $%!at sH,are 1 $%!at 2 # $%!at a" & # rint$ 1 4@nEnter an/ n,m&er 4 2 # s'an$ 1 45$4" Ba 2 # & = sH,are 1 a 2 # rint$ 1 4@n7H,are !$ 5$ is 5$4" a" & 2 # 6 $%!at sH,are 1 $%!at x 2 3 $%!at / # /=x*x# ret,rn 1 / 2 # 6

1nd here is the o#tp#tGGG


Enter an/ n,m&er 1.5 7H,are !$ 1.5 is 2.250000 Enter an/ n,m&er 2.5 7H,are !$ 2.5 is 6.250000

Chapter 50 &unctions 9 #ointers

177

)ow the e/pected answers iGeG 2G25 and 6G25 are obtainedG )ote that the #nction sQuare= > *#st be declared in 1ain= > as
$%!at sH,are 1 $%!at 2 #

This state*ent is o ten called the prototype declaration o the sQuare= > #nctionG What it *eans is sQuare= > is a #nction that receives a 8loat and ret#rns a 8loatG We have done the prototype declaration in 1ain= > beca#se we have called it ro* 1ain= >G There is a possibility that we *ay call sQuare= > ro* several other #nctions other than 1ain= >G 0oes this *ean that we wo#ld need prototype declaration o sQuare= > in all these #nctionsG )o, in s#ch a case we wo#ld *a9e only one declaration o#tside all the #nctions at the beginning o the progra*G $n practice yo# *ay seldo* be reH#ired to ret#rn a val#e other than an int, b#t Q#st in case yo# are reH#ired to, e*ploy the above *ethodG $n so*e progra**ing sit#ations we want that a called #nction sho#ld not ret#rn any val#eG This is *ade possible by #sing the 9eyword %oidG This is ill#strated in the ollowing progra*G
main1 2 3 =!i( -!s e%1 2 # -!s e%1 2 # 6 =!i( -!s e%1 2 3 rint$ 1 4@n]ir,ses are e%e'tr!ni' &an(its...4 2 # rint$ 1 4@nFh! eat n,--ets !$ in$!rmati!n...4 2 # rint$ 1 4@nan( 'h,n.s !$ &/tes...4 2 # rint$ 1 4@nFhen /!, %east ex e't...4 2 # 6

17&

%et .s C

2ere, the gospel= > #nction has been de ined to ret#rn %oid_ *eans it wo#ld ret#rn nothingG There ore, it wo#ld Q#st lash the o#r *essages abo#t vir#ses and ret#rn the control bac9 to the 1ain= > #nctionG

Call 6# 5alue and Call 6# $e8erence


8y now we are well a*iliar with how to call #nctionsG 8#t, i yo# observe care #lly, whenever we called a #nction and passed so*ething to it we have always passed the Dval#es@ o variables to the called #nctionG S#ch #nction calls are called Dcalls by val#e@G 8y this what we *ean is, on calling a #nction we are passing val#es o variables to itG The e/a*ples o call by val#e are shown belowP
s,m = 'a%s,m 1 a" &" ' 2 # $ = $a'tr 1 a 2 #

We have also learnt that variables are stored so*ewhere in *e*oryG So instead o passing the val#e o a variable, can we not pass the location n#*ber >also called address? o the variable to a #nctionc $ we were able to do so it wo#ld beco*e a Dcall by re erence@G What p#rpose a Dcall by re erence@ serves we wo#ld ind o#t a little laterG +irst we *#st eH#ip o#rselves with 9nowledge o how to *a9e a Dcall by re erence@G This eat#re o C #nctions needs at least an ele*entary 9nowledge o a concept called Dpointers@G So let #s irst acH#ire the basics o pointers a ter which we wo#ld ta9e #p this topic once againG

'n *ntroduction to !ointers


Which eat#re o C do beginners ind *ost di ic#lt to #nderstandc The answer is easyP pointersG 3ther lang#ages have pointers b#t ew #se the* so reH#ently as C doesG 1nd why notc $t is C@s clever #se o pointers that *a9es it the e/cellent lang#age it isG

Chapter 50 &unctions 9 #ointers

179

The di ic#lty beginners have with pointers has *#ch to do with C@s pointer ter*inology than the act#al conceptG +or instance, when a C progra**er says that a certain variable is a KpointerO, what does that *eanc $t is hard to see how a variable can point to so*ething, or in a certain directionG $t is hard to get a grip on pointers Q#st by listening to progra**er@s QargonG $n o#r disc#ssion o C pointers, there ore, we will try to avoid this di ic#lty by e/plaining pointers in ter*s o progra**ing concepts we already #nderstandG The irst thing we want to do is e/plain the rationale o C@s pointer notationG

!ointer 9otation
Consider the declaration,
int i = 3 #

This declaration tells the C co*piler toP


(a) "eserve space in *e*ory to hold the integer val#eG (b) 1ssociate the na*e i with this *e*ory locationG (c) Store the val#e - at this locationG

We *ay represent i@s location in *e*ory by the ollowing *e*ory *apG

i 65524

location na*e val#e at location location n#*ber

+ig#re 5G'

1&)

%et .s C

We see that the co*p#ter has selected *e*ory location 65524 as the place to store the val#e -G The location n#*ber 65524 is not a n#*ber to be relied #pon, beca#se so*e other ti*e the co*p#ter *ay choose a di erent location or storing the val#e -G The i*portant point is, i@s address in *e*ory is a n#*berG We can print this address n#*ber thro#gh the ollowing progra*P
main1 2 3 int i = 3 # rint$ 1 4@nA((ress !$ i = 5,4" Bi 2 # rint$ 1 4@n]a%,e !$ i = 5(4" i 2 # 6

The o#tp#t o the above progra* wo#ld beP


A((ress !$ i = 65524 ]a%,e !$ i = 3

7oo9 at the irst print8= > state*ent care #llyG DI@ #sed in this state*ent is C@s Daddress o @ operatorG The e/pression i ret#rns the address o the variable i, which in this case happens to be 65524G Since 65524 represents an address, there is no H#estion o a sign being associated with itG 2ence it is printed o#t #sing Au, which is a or*at speci ier or printing an #nsigned integerG We have been #sing the DI@ operator all the ti*e in the scan8= > state*entG The other pointer operator available in C is D<O, called Dval#e at address@ operatorG $t gives the val#e stored at a partic#lar addressG The Dval#e at address@ operator is also called Dindirection@ operatorG 3bserve care #lly the o#tp#t o the ollowing progra*P

Chapter 50 &unctions 9 #ointers


main1 2 3 int i = 3 # rint$ 1 4@nA((ress !$ i = 5,4" Bi 2 # rint$ 1 4@n]a%,e !$ i = 5(4" i 2 # rint$ 1 4@n]a%,e !$ i = 5(4" *1 Bi 2 2 # 6

1&1

The o#tp#t o the above progra* wo#ld beP


A((ress !$ i = 65524 ]a%,e !$ i = 3 ]a%,e !$ i = 3

)ote that printing the val#e o <= o iG

i > is sa*e as printing the val#e

The e/pression i gives the address o the variable iG This address can be collected in a variable, by saying,
9 = Bi #

8#t re*e*ber that W is not an ordinary variable li9e any other integer variableG $t is a variable that contains the address o other variable >i in this case?G Since W is a variable the co*piler *#st provide it space in the *e*oryG 3nce again, the ollowing *e*ory *ap wo#ld ill#strate the contents o i and WG

i 65524

Q 65524 65522

+ig#re 5G2

1&2

%et .s C

1s yo# can see, i@s val#e is - and W@s val#e is i@s addressG 8#t wait, we can@t #se W in a progra* witho#t declaring itG 1nd since W is a variable that contains the address o i, it is declared as,
int *9 #

This declaration tells the co*piler that W will be #sed to store the address o an integer val#eG $n other words W points to an integerG 2ow do we Q#sti y the #sage o < in the declaration,
int *9 #

7et #s go by the *eaning o <G $t stands or Dval#e at address@G Th#s, int <W wo#ld *ean, the val#e at the address contained in W is an intG 2ere is a progra* that de*onstrates the relationships we have been disc#ssingG
main1 2 3 int i = 3 # int *9 # 9 = Bi # rint$ 1 4@nA((ress !$ i = 5,4" Bi 2 # rint$ 1 4@nA((ress !$ i = 5,4" 9 2 # rint$ 1 4@nA((ress !$ 9 = 5,4" B9 2 # rint$ 1 4@n]a%,e !$ 9 = 5,4" 9 2 # rint$ 1 4@n]a%,e !$ i = 5(4" i 2 # rint$ 1 4@n]a%,e !$ i = 5(4" *1 Bi 2 2 # rint$ 1 4@n]a%,e !$ i = 5(4" *9 2 # 6

The o#tp#t o the above progra* wo#ld beP

Chapter 50 &unctions 9 #ointers


A((ress !$ i = 65524 A((ress !$ i = 65524 A((ress !$ 9 = 65522 ]a%,e !$ 9 = 65524 ]a%,e !$ i = 3 ]a%,e !$ i = 3 ]a%,e !$ i = 3

1&3

Wor9 thro#gh the above progra* care #lly, ta9ing help o the *e*ory locations o i and W shown earlierG This progra* s#**ari;es everything that we have disc#ssed so arG $ yo# don@t #nderstand the progra*@s o#tp#t, or the *eanings o i, W, <W and <= i >, re<read the last ew pagesG .verything we say abo#t C pointers ro* here onwards will depend on yo#r #nderstanding these e/pressions thoro#ghlyG 7oo9 at the ollowing declarations,
int *a% ha # 'har *'h # $%!at *s #

2ere, alpha4 ch and s are declared as pointer variables, iGeG variables capable o holding addressesG "e*e*ber that, addresses >location nosG? are always going to be whole n#*bers, there ore pointers always contain whole n#*bersG )ow we can p#t these two acts together and sayRpointers are variables that contain addresses, and since addresses are always whole n#*bers, pointers wo#ld always contain whole n#*bersG The declaration 8loat <s does not *ean that s is going to contain a loating<point val#eG What it *eans is, s is going to contain the address o a loating<point val#eG Si*ilarly, char <ch *eans that ch is going to contain the address o a char val#eG 3r in other words, the val#e at address stored in ch is going to be a charG

1&4

%et .s C

The concept o pointers can be #rther e/tendedG ,ointer, we 9now is a variable that contains address o another variableG )ow this variable itsel *ight be another pointerG Th#s, we now have a pointer that contains another pointer@s addressG The ollowing e/a*ple sho#ld *a9e this point clearG
main1 2 3 int i = 3" *9" **. # 9 = Bi # . = B9 # rint$ 1 4@nA((ress !$ i = 5,4" Bi 2 # rint$ 1 4@nA((ress !$ i = 5,4" 9 2 # rint$ 1 4@nA((ress !$ i = 5,4" *. 2 # rint$ 1 4@nA((ress !$ 9 = 5,4" B9 2 # rint$ 1 4@nA((ress !$ 9 = 5,4" . 2 # rint$ 1 4@nA((ress !$ . = 5,4" B. 2 # rint$ 1 4@n]a%,e !$ 9 = 5,4" 9 2 # rint$ 1 4@n]a%,e !$ . = 5,4" . 2 # rint$ 1 4@n]a%,e !$ i = 5(4" i 2 # rint$ 1 4@n]a%,e !$ i = 5(4" * 1 Bi 2 2 # rint$ 1 4@n]a%,e !$ i = 5(4" *9 2 # rint$ 1 4@n]a%,e !$ i = 5(4" **. 2 # 6

The o#tp#t o the above progra* wo#ld beP


A((ress !$ i = 65524 A((ress !$ i = 65524 A((ress !$ i = 65524 A((ress !$ 9 = 65522 A((ress !$ 9 = 65522 A((ress !$ . = 65520 ]a%,e !$ 9 = 65524 ]a%,e !$ . = 65522

Chapter 50 &unctions 9 #ointers


]a%,e !$ i ]a%,e !$ i ]a%,e !$ i ]a%,e !$ i =3 =3 =3 =3

1&5

+ig#re 5G- wo#ld help yo# in tracing o#t how the progra* prints the above o#tp#tG "e*e*ber that when yo# r#n this progra* the addresses that get printed *ight t#rn o#t to be so*ething di erent than the ones shown in the ig#reG 2owever, with these addresses too the relationship between i, W and G can be easily establishedG
i 65524 Q 65524 65522 9 65522 6552(

+ig#re 5G3bserve how the variables W and G have been declared,


int i" *9" **. #

2ere, i is an ordinary int, W is a pointer to an int >o ten called an integer pointer?, whereas G is a pointer to an integer pointerG We can e/tend the above progra* still #rther by creating a pointer to a pointer to an integer pointerG $n principle, yo# wo#ld agree that li9ewise there co#ld e/ist a pointer to a pointer to a pointer to a pointer to a pointerG There is no li*it on how ar can we go on e/tending this de initionG ,ossibly, till the point we can co*prehend itG 1nd that point o co*prehension is #s#ally a pointer to a pointerG 8eyond this one rarely reH#ires to e/tend the de inition o a pointerG 8#t Q#st in caseGGG

1&"
-acG to Function Calls

%et .s C

2aving had the irst tryst with pointers let #s now get bac9 to what we had originally set o#t to learnRthe two types o #nction calls Rcall by val#e and call by re erenceG 1rg#*ents can generally be passed to #nctions in one o the two waysP
(a) sending the val#es o the arg#*ents (b) sending the addresses o the arg#*ents

$n the irst *ethod the Dval#e@ o each o the act#al arg#*ents in the calling #nction is copied into corresponding or*al arg#*ents o the called #nctionG With this *ethod the changes *ade to the or*al arg#*ents in the called #nction have no e ect on the val#es o act#al arg#*ents in the calling #nctionG The ollowing progra* ill#strates the DCall by Val#e@G
main1 2 3 int a = 10" & = 20 # sFa = 1 a" & 2 # rint$ 1 4@na = 5( & = 5(4" a" & 2 # 6 sFa = 1 int x" int / 2 3 int t # t=x# x=/# /=t# rint$ 1 4@nx = 5( / = 5(4" x" / 2 # 6

The o#tp#t o the above progra* wo#ld beP

Chapter 50 &unctions 9 #ointers


x = 20 / = 10 a = 10 & = 20

1&7

)ote that val#es o a and 6 re*ain #nchanged even a ter e/changing the val#es o 3 and #G $n the second *ethod >call by re erence? the addresses o act#al arg#*ents in the calling #nction are copied into or*al arg#*ents o the called #nctionG This *eans that #sing these addresses we wo#ld have an access to the act#al arg#*ents and hence we wo#ld be able to *anip#late the*G The ollowing progra* ill#strates this actG
main1 2 3 int a = 10" & = 20 # sFa r 1 Ba" B& 2 # rint$ 1 4@na = 5( & = 5(4" a" & 2 # 6 sFa r1 int *x" int */ 2 3 int t # t = *x # *x = */ # */ = t # 6

The o#tp#t o the above progra* wo#ld beP


a = 20 & = 10

)ote that this progra* *anages to e/change the val#es o a and 6 #sing their addresses stored in 3 and #G

1&&

%et .s C

6s#ally in C progra**ing we *a9e a call by val#eG This *eans that in general yo# cannot alter the act#al arg#*entsG 8#t i desired, it can always be achieved thro#gh a call by re erenceG 6sing a call by re erence intelligently we can *a9e a #nction ret#rn *ore than one val#e at a ti*e, which is not possible ordinarilyG This is shown in the progra* given belowG
main1 2 3 int ra(i,s # $%!at area" erimeter # rint$ 1 4@nEnter ra(i,s !$ a 'ir'%e 4 2 # s'an$ 1 45(4" Bra(i,s 2 # area eri 1 ra(i,s" Barea" B erimeter 2 # rint$ 1 4Area = 5$4" area 2 # rint$ 1 4@n?erimeter = 5$4" erimeter 2 # 6 area eri 1 int r" $%!at *a" $%!at * 2 3 *a = 3.14 * r * r # * = 2 * 3.14 * r # 6

1nd here is the o#tp#tGGG


Enter ra(i,s !$ a 'ir'%e 5 Area = 78.500000 ?erimeter = 31.400000

2ere, we are *a9ing a *i/ed call, in the sense, we are passing the val#e o radius b#t, addresses o area and peri1eterG 1nd since we are passing the addresses, any change that we *a9e in val#es stored at addresses contained in the variables a and p, wo#ld *a9e

Chapter 50 &unctions 9 #ointers

1&9

the change e ective in 1ain= >G That is why when the control ret#rns ro* the #nction areaperi= > we are able to o#tp#t the val#es o area and peri1eterG Th#s, we have been able to indirectly ret#rn two val#es ro* a called #nction, and hence, have overco*e the li*itation o the return state*ent, which can ret#rn only one val#e ro* a #nction at a ti*eG

Conclusions
+ro* the progra*s that we disc#ssed here we can draw the ollowing concl#sionsP >a? $ we want that the val#e o an act#al arg#*ent sho#ld not get changed in the #nction being called, pass the act#al arg#*ent >b? by val#eG >c? $ we want that the val#e o an act#al arg#*ent sho#ld get changed in the #nction being called, pass the act#al arg#*ent by re erenceG $ a #nction is to be *ade to ret#rn *ore than one val#e at a ti*e then ret#rn these val#es indirectly by #sing a call by re erenceG

$ecursion
$n C, it is possible or the #nctions to call the*selvesG 1 #nction is called Drec#rsive@ i a state*ent within the body o a #nction calls the sa*e #nctionG So*eti*es called Dcirc#lar de inition@, rec#rsion is th#s the process o de ining so*ething in ter*s o itsel G 7et #s now see a si*ple e/a*ple o rec#rsionG S#ppose we want to calc#late the actorial val#e o an integerG 1s we 9now, the

19)

%et .s C

actorial o a n#*ber is the prod#ct o all the integers between ' and that n#*berG +or e/a*ple, 4 actorial is 4 W - W 2 W 'G This can also be e/pressed as 44 X 4 W -4 where D4@ stands or actorialG Th#s actorial o a n#*ber can be e/pressed in the or* o itsel G 2ence this can be progra**ed #sing rec#rsionG 2owever, be ore we try to write a rec#rsive #nction or calc#lating actorial let #s ta9e a loo9 at the non<rec#rsive #nction or calc#lating the actorial val#e o an integerG
main1 2 3 int a" $a't # rint$ 1 4@nEnter an/ n,m&er 4 2 # s'an$ 1 45(4" Ba 2 # $a't = $a't!ria% 1 a 2 # rint$ 1 4Ia't!ria% =a%,e = 5(4" $a't 2 # 6 $a't!ria% 1 int x 2 3 int $ = 1" i # $!r 1 i = x # i <= 1 # i-- 2 $=$*i# ret,rn 1 $ 2 # 6

1nd here is the o#tp#tGGG


Enter an/ n,m&er 3 Ia't!ria% =a%,e = 6

Chapter 50 &unctions 9 #ointers

191

Wor9 thro#gh the above progra* care #lly, till yo# #nderstand the logic o the progra* properlyG "ec#rsive actorial #nction can be #nderstood only i yo# are thoro#gh with the above logicG +ollowing is the rec#rsive version o the #nction to calc#late the actorial val#eG
main1 2 3 int a" $a't # rint$ 1 4@nEnter an/ n,m&er 4 2 # s'an$ 1 45(4" Ba 2 # $a't = re' 1 a 2 # rint$ 1 4Ia't!ria% =a%,e = 5(4" $a't 2 # 6 re' 1 int x 2 3 int $ # i$ 1 x == 1 2 ret,rn 1 1 2 # e%se $ = x * re' 1 x - 1 2 # ret,rn 1 $ 2 # 6

1nd here is the o#tp#t or o#r r#ns o the progra*


Enter an/ n,m&er 1 Ia't!ria% =a%,e = 1 Enter an/ n,m&er 2 Ia't!ria% =a%,e = 2 Enter an/ n,m&er 3

192
Ia't!ria% =a%,e = 6 Enter an/ n,m&er 5 Ia't!ria% =a%,e = 120

%et .s C

7et #s #nderstand this rec#rsive actorial #nction thoro#ghlyG $n the irst r#n when the n#*ber entered thro#gh scan8= > is ', let #s see what action does rec= > ta9eG The val#e o a >iGeG '? is copied into 3G Since 3 t#rns o#t to be ' the condition i8 = 3 FF 1 > is satis ied and hence ' >which indeed is the val#e o ' actorial? is ret#rned thro#gh the return state*entG When the n#*ber entered thro#gh scan8= > is 2, the = 3 FF 1 > test ails, so we reach the state*ent,
$ = x * re' 1 x - 1 2 #

1nd here is where we *eet rec#rsionG 2ow do we handle the e/pression 3 < rec = 3 @ 1 >c We *#ltiply 3 by rec = 3 @ 1 >G Since the c#rrent val#e o 3 is 2, it is sa*e as saying that we *#st calc#late the val#e >2 W rec > ' ??G We 9now that the val#e ret#rned by rec = 1 > is ', so the e/pression red#ces to >2 W '?, or si*ply 2G Th#s the state*ent,
x * re' 1 x - 1 2 #

eval#ates to 2, which is stored in the variable 8, and is ret#rned to 1ain= >, where it is d#ly printed as
Ia't!ria% =a%,e = 2

)ow perhaps yo# can see what wo#ld happen i the val#e o a is -, 4, 5 and so onG $n case the val#e o a is 5, 1ain= > wo#ld call rec= > with 5 as its act#al arg#*ent, and rec= > will send bac9 the co*p#ted val#eG 8#t be ore sending the co*p#ted val#e, rec= > calls rec= > and waits or a val#e to be ret#rnedG $t is possible or the rec= > that has Q#st been

Chapter 50 &unctions 9 #ointers

193

called to call yet another rec= >, the arg#*ent 3 being decreased in val#e by ' or each o these rec#rsive callsG We spea9 o this series o calls to rec= > as being di erent invocations o rec= >G These s#ccessive invocations o the sa*e #nction are possible beca#se the C co*piler 9eeps trac9 o which invocation calls whichG These rec#rsive invocations end inally when the last invocation gets an arg#*ent val#e o ', which the preceding invocation o rec= > now #ses to calc#late its own 8 val#e and so on #p the ladderG So we *ight say what happens is,
re' 1 5 2 ret,rns 1 5 times re' 1 4 2" Fhi'h ret,rns 1 4 times re' 1 3 2" Fhi'h ret,rns 1 3 times re' 1 2 2" Fhi'h ret,rns 1 2 times re' 1 1 2" Fhi'h ret,rns 1 1 2 2 2 2 2

+o/edc Well, that is rec#rsion or yo# in its si*plest garbsG $ hope yo# agree that it@s di ic#lt to vis#ali;e how the control lows ro* one #nction call to anotherG ,ossibly +ig#re 5G4 wo#ld *a9e things a bit clearerG 1ss#*e that the n#*ber entered thro#gh scan8= > is -G 6sing +ig#re 5G4 let@s vis#ali;e what e/actly happens when the rec#rsive #nction rec= > gets calledG Go thro#gh the ig#re care #llyG The irst ti*e when rec= > is called ro* 1ain= >, 3 collects -G +ro* here, since 3 is not eH#al to ', the i8 bloc9 is s9ipped and rec= > is called again with the arg#*ent = 3 Z 1 >, iGeG 2G This is a rec#rsive callG Since 3 is still not eH#al to ', rec= > is called yet another ti*e, with arg#*ent >2 < '?G This ti*e as 3 is ', control goes bac9 to previo#s rec= > with the val#e ', and 8 is eval#ated as 2G Si*ilarly, each rec= > eval#ates its 8 ro* the ret#rned val#e, and inally 6 is ret#rned to 1ain= >G The seH#ence wo#ld be grasped better by ollowing the arrows shown in +ig#re 5G4G 7et it be clear that while e/ec#ting the progra* there do not e/ist so *any copies o the #nction rec= >G These have been shown in the ig#re Q#st to

194

%et .s C

help yo# 9eep trac9 o how the control lows d#ring s#ccessive rec#rsive callsG
ro* *ain> ? rec > int / ? [ int _ rec > int / ? [ int _ rec > int / ? [ int _ i >/ XX '? ret#rn > ' ? _ else X / W rec > / F ' ? _ ret#rn > ? _ \

i >/ XX '? i >/ XX '? ret#rn > ' ? _ ret#rn > ' ? _ else else X / W rec > / F ' ? _ X / W rec > / F ' ? _ ret#rn > ? _ \ to *ain> ? \ ret#rn > ? _

+ig#re 5G4 "ec#rsion *ay see* strange and co*plicated at irst glance, b#t it is o ten the *ost direct way to code an algorith*, and once yo# are a*iliar with rec#rsion, the clearest way o doing soG

$ecursion and StacG


There are di erent ways in which data can be organi;edG +or e/a*ple, i yo# are to store ive n#*bers then we can store the* in ive di erent variables, an array, a lin9ed list, a binary tree, etcG 1ll these di erent ways o organi;ing the data are 9nown as data str#ct#resG The co*piler #ses one s#ch data str#ct#re called stac9 or i*ple*enting nor*al as well as rec#rsive #nction callsG

Chapter 50 &unctions 9 #ointers

195

1 stac9 is a 7ast $n +irst 3#t >7$+3? data str#ct#reG This *eans that the last ite* to get stored on the stac9 >o ten called ,#sh operation? is the irst one to get o#t o it >o ten called as ,op operation?G Co# can co*pare this to the stac9 o plates in a ca eteriaRthe last plate that goes on the stac9 is the irst one to get o#t o itG )ow let #s see how the stac9 wor9s in case o the ollowing progra*G
main1 2 3 int a = 5" & = 2" ' # ' = a(( 1 a" & 2 # rint$ 1 4s,m = 5(4" ' 2 # 6 a(( 1 int i" int 9 2 3 int s,m # s,m = i + 9 # ret,rn s,m # 6

$n this progra* be ore trans erring the e/ec#tion control to the #nction 8un= > the val#es o para*eters a and 6 are p#shed onto the stac9G +ollowing this the address o the state*ent print8= > is p#shed on the stac9 and the control is trans erred to 8un= >G $t is necessary to p#sh this address on the stac9G $n 8un= > the val#es o a and 6 that were p#shed on the stac9 are re erred as i and WG $n 8un= > the local variable su1 gets p#shed on the stac9G When val#e o su1 is ret#rned su1 is popped #p ro* the stac9G )e/t the address o the state*ent where the control sho#ld be ret#rned is popped #p ro* the stac9G 6sing this address the control ret#rns to the print8= > state*ent in 1ain= >G 8e ore e/ec#tion o print8= > begins the two integers that were earlier p#shed on the stac9 are now popped o G 2ow the val#es are being p#shed and popped even tho#gh we didn@t write any code to do soc Si*pleRthe co*piler on

19"

%et .s C

enco#ntering the #nction call wo#ld generate code to p#sh para*eters and the addressG Si*ilarly, it wo#ld generate code to clear the stac9 when the control ret#rns bac9 ro* 8un= >G +ig#re 5G5 shows the contents o the stac9 at di erent stages o e/ec#tionG

Copy o a Copy o b .*pty stac9

5 2 When call to 8un= > is *et

1ddress o print8= > Copy o a Copy o b

//// 5 2 8e ore trans ering control to 8un= >

s#* 1ddress i Q

! //// 5 2 1 ter control reaches 8un= > //// 5 2 3n ret#rning control While ret#rning ro* 8un= > control ro* 8un= >

+ig#re 5G5 )ote that in this progra* popping o su1 and address is done by 8un= >, whereas popping o the two integers is done by 1ain= >G When it is done this way it is 9nown as DC0ecl Calling Convention@G There are other calling conventions as well where instead o 1ain= >, 8un= > itsel clears the two integersG The calling convention also decides whether the para*eters being passed to the #nction are p#shed on the stac9 in le t<to<right or right<to<le t orderG The standard calling convention always #ses the right<to<le t

Chapter 50 &unctions 9 #ointers

197

orderG Th#s d#ring the call to 8un= > irstly val#e o 6 is p#shed to the stac9, ollowed by the val#e o aG The rec#rsive calls are no di erentG Whenever we *a9e a rec#rsive call the para*eters and the ret#rn address gets p#shed on the stac9G The stac9 gets #nwo#nd when the control ret#rns ro* the called #nctionG Th#s d#ring every rec#rsive #nction call we are wor9ing with a resh set o para*etersG 1lso, note that while writing rec#rsive #nctions yo# *#st have an i8 state*ent so*ewhere in the rec#rsive #nction to orce the #nction to ret#rn witho#t rec#rsive call being e/ec#tedG $ yo# don@t do this and yo# call the #nction, yo# will all in an inde inite loop, and the stac9 will 9eep on getting illed with para*eters and the ret#rn address each ti*e there is a callG Soon the stac9 wo#ld beco*e #ll and yo# wo#ld get a r#n<ti*e error indicating that the stac9 has beco*e #llG This is a very co**on error while writing rec#rsive #nctionsG 5y advice is to #se print8= > state*ent liberally d#ring the develop*ent o rec#rsive #nction, so that yo# can watch what is going on and can abort e/ec#tion i yo# see that yo# have *ade a *ista9eG

'dding Functions to the Li6rar#


5ost o the ti*es we either #se the #nctions present in the standard library or we de ine o#r own #nctions and #se the*G Can we not add o#r #nctions to the standard libraryc 1nd wo#ld it *a9e any sense in doing soc We can add #ser<de ined #nctions to the libraryG $t *a9es sense in doing so as the #nctions that are to be added to the library are irst co*piled and then addedG When we #se these #nctions >by calling the*? we save on their co*pilation ti*e as they are available in the library in the co*piled or*G 7et #s now see how to add #ser<de ined #nctions to the libraryG 0i erent co*pilers provide di erent #tilities to add=delete=*odi y #nctions in the standard libraryG +or e/a*ple, T#rbo C=CLL

19&

%et .s C

co*pilers provide a #tility called DtlibGe/e@ >T#rbo 7ibrarian?G 7et #s #se this #tility to add a #nction 8actorial= > to the libraryG Given below are the steps to do soP >a? Write the #nction de inition o 8actorial= > in so*e ile, say D actGc@G
int $a't!ria% 1 int n,m 2 3 int i" $ = 1 # $!r 1 i = 1 # i ;= n,m # i++ 2 $=$*i# ret,rn 1 $ 2 # 6

>b? Co*pile the D actGc@ ile #sing 1lt +&G 1 new ile called D actGobQ@ wo#ld get created containing the co*piled code in >c? *achine lang#ageG 1dd the #nction to the library by iss#ing the co**and
+:@<t%i& math.%i& + ':@$a't.!&9

2ere, D*athGlib@ is a library ilena*e, L is a switch, which >d? *eans we want to add new #nction to library and DcPZ actGobQ@ is the path o the DGobQ@ ileG >e? 0eclare the prototype o the 8actorial= > #nction in the header ile, say D actGh@G This ile sho#ld be incl#ded while calling the #nctionG To #se the #nction present inside the library, create a progra* as shown belowP
Lin'%,(e 4':@@$a't.h4 main1 2

Chapter 50 &unctions 9 #ointers


3 int $ # $ = $a't!ria% 1 5 2 # rint$ 1 45(4" $ 2 #

199

> ? Co*pile and e/ec#te the progra* #sing Ctrl +&G $ we wish we can delete the e/isting #nctions present in the library #sing the *in#s > < ? switchG $nstead o *odi ying the e/isting libraries we can create o#r own libraryG 7et@s see how to do thisG 7et #s ass#*e that we wish to create a library containing the #nctions 8actorial= >, pri1e= > and 8i6onacci= >G 1s their na*es s#ggest, 8actorial= > calc#lates and ret#rns the actorial val#e o the integer passed to it, pri1e= > reports whether the n#*ber passed to it is a pri*e n#*ber or not and 8i6onacci= > prints the irst n ter*s o the +ibonacci series, where n is the n#*ber passed to itG 2ere are the steps that need to be carried o#t to create this libraryG )ote that these steps are speci ic to T#rbo C=CLL co*piler and wo#ld vary or other co*pilersG >a? 0e ine the #nctions 8actorial= >, pri1e= > and 8i6onacci= > in a ile, say D*y #ncsGc@G 0o not de ine 1ain= > in this ileG >b? Create a ile D*y #ncsGh@ and declare the prototypes o 8actorial= >, pri1e= > and 8i6onacci= > in it as shown belowP
int $a't!ria% 1 int 2 # int rime 1 int 2 # >c? =!i( $i&!na''i 1 int 2 #

+ro* the 3ptions *en# select the *en#<ite* D1pplication@G +ro* the dialog that pops #s select the option D7ibrary@G Select 3KG

2))

%et .s C

>d? Co*pile the progra* #sing 1lt +&G This wo#ld create the library ile called D*y #ncsGlib@G That@s itG The library now stands createdG )ow we have to #se the #nctions de ined in this libraryG 2ere is how it can be doneG >a? Create a ile, say Dsa*pleGc@ and type the ollowing code in itG
Lin'%,(e 4m/$,n's.h4 main1 2 3 int $" res,%t # $ = $a't!ria% 1 5 2 # res,%t = rime 1 13 2 # $i&!na''i 1 6 2 # rint$ 1 4@n5( 5(4" $" res,%t 2 # 6

)ote that the ile D*y #ncsGh@ sho#ld be in the sa*e directory as the ile Dsa*pleGc@G $ not, then while incl#ding D*y #ncsGh@ *ention the appropriate pathG >b? Go to the D,roQect@ *en# and select D3pen ,roQect:@ optionG 3n doing so a dialog wo#ld pop #pG Give the na*e o the >c? proQect, say Dsa*pleGprQ@ and select 3KG +ro* the D,roQect@ *en# select D1dd $te*@G 3n doing so a ile >d? dialog wo#ld appearG Select the ile Dsa*pleGc@ and then select D1dd@G 1lso add the ile D*y #ncsGlib@ in the sa*e *annerG +inally select D0one@G Co*pile and e/ec#te the proQect #sing Ctrl +&G

Chapter 50 &unctions 9 #ointers

2)1

Su11ar#
>a? To avoid repetition o code and b#l9y progra*s #nctionally related state*ents are isolated into a #nctionG >b? +#nction declaration speci ies what is the ret#rn type o the #nction and the types o para*eters it acceptsG >c? +#nction de inition de ines the body o the #nctionG >d? Variables declared in a #nction are not available to other #nctions in a progra*G So, there won@t be any clash even i we give sa*e na*e to the variables declared in di erent #nctionsG >e? ,ointers are variables which hold addresses o other variablesG > ? 1 #nction can be called either by val#e or by re erenceG >g? ,ointers can be #sed to *a9e a #nction ret#rn *ore than one val#e si*#ltaneo#slyG >h? "ec#rsion is di ic#lt to #nderstand, b#t in so*e cases o er a better sol#tion than loopsG >i? 1dding too *any #nctions and calling the* reH#ently *ay slow down the progra* e/ec#tionG

B3ercise
Si1ple 8unctions4 !assing %alues 6et0een 8unctions
K'L What wo#ld be the o#tp#t o the ollowing progra*sP 1a2 main1 2 3 rint$ 1 4@nQn%/ st, i(s ,se +Z4 2 # (is %a/1 2 # 6 (is %a/1 2 3 rint$ 1 4@nI!!%s t!! ,se +T4 2 # main1 2 # 6

2)2
1&2 main1 2 3 rint$ 1 4@n+ t! it that + s,r=i=es4 2 # main1 2 # 6 1'2 main1 2 3 int i = 45" ' # ' = 'he'. 1 i 2 # rint$ 1 4@n5(4" ' 2 # 6 'he'. 1 int 'h 2 3 i$ 1 'h <= 45 2 ret,rn 1 100 2 # e%se ret,rn 1 10 * 10 2 # 6

%et .s C

1(2 main1 2 3 int i = 45" ' # ' = m,%ti %/ 1 i * 1000 2 # rint$ 1 4@n5(4" ' 2 # 6 'he'. 1 int 'h 2 3 i$ 1 'h <= 40000 2 ret,rn 1 'h ) 10 2 # e%se ret,rn 1 10 2 # 6 K-L ,oint o#t the errors, i any, in the ollowing progra*sP 1a2 main1 2 3

Chapter 50 &unctions 9 #ointers


int i = 3" 9 = 4" ." % # . = a((m,%t 1 i" 9 2 # % = a((m,%t 1 i" 9 2 # rint$ 1 4@n5( 5(4" ." % 2 # 6 a((m,%t 1 int ii" int 99 2 3 int .." %% # .. = ii + 99 # %% = ii * 99 # ret,rn 1 .." %% 2 # 6 1&2 main1 2 3 int a # a = messa-e1 2 # 6 messa-e1 2 3 rint$ 1 4@n]ir,ses are Fritten in +4 2 # ret,rn # 6 1'2 main1 2 3 $%!at a = 15.5 # 'har 'h = '+' # rintit 1 a" 'h 2 # 6 rintit 1 a" 'h 2 3 rint$ 1 4@n5$ 5'4" a" 'h 2 # 6

2)3

1(2 main1 2 3 messa-e1 2 #

2)4
messa-e1 2 # 6 messa-e1 2 # 3 rint$ 1 4@n?raise F!rth/ an( + F!rth/ are s/n!n/ms4 2 # 6 1e2 main1 2 3 %et_,s_'1 2 3 rint$ 1 4@n+ is a +im %e min(e( %an-,a-e T4 2 # rint$ 1 4@nQthers are !$ '!,rse n! mat'h T4 2 # 6 6 1$2 main1 2 3 messa-e1 messa-e 1 2 2 # 6 =!i( messa-e1 2 3 rint$ 1 4@n?raise F!rth/ an( + F!rth/ are s/n!n/ms4 2 # 6

%et .s C

KCL 1nswer the ollowingP

>a? $s this a correctly written #nctionP


sHr 1 a 2 # int a # 3 ret,rn 1 a * a 2 # 6

>b? State whether the ollowing state*ents are Tr#e or +alseP

Chapter 50 &unctions 9 #ointers

2)5

'G The variables co**only #sed in C #nctions are available to all the #nctions in a progra*G 2G To ret#rn the control bac9 to the calling #nction we *#st #se the 9eyword returnG -G The sa*e variable na*es can be #sed in di erent #nctions witho#t any con lictG 4G .very called #nction *#st contain a return state*entG 5G 1 #nction *ay contain *ore than one return state*entsG 6G .ach return state*ent in a #nction *ay ret#rn a di erent val#eG !G 1 #nction can still be #se #l even i yo# don@t pass any arg#*ents to it and the #nction doesn@t ret#rn any val#e bac9G %G Sa*e na*es can be #sed or di erent #nctions witho#t any con lictG &G 1 #nction *ay be called *ore than once ro* any other #nctionG '(G $t is necessary or a #nction to ret#rn so*e val#eG
KDL 1nswer the ollowingP

>a? Write a #nction to calc#late the actorial val#e o any integer entered thro#gh the 9eyboardG >b? Write a #nction po0er = a4 6 >, to calc#late the val#e o a raised to 6G

2)"

%et .s C

>c? Write a general<p#rpose #nction to convert any given year into its ro*an eH#ivalentG The ollowing table shows the ro*an eH#ivalents o deci*al n#*bersP
Deci1al ' 5 '( 5( $o1an i v / l Deci1al '(( 5(( '((( $o1an c d *

./a*pleP "o*an eH#ivalent o '&%% is *dccccl///viii "o*an eH#ivalent o '525 is *d//v >d? 1ny year is entered thro#gh the 9eyboardG Write a #nction to deter*ine whether the year is a leap year or notG >e? 1 positive integer is entered thro#gh the 9eyboardG Write a #nction to obtain the pri*e actors o this n#*berG +or e/a*ple, pri*e actors o 24 are 2, 2, 2 and -, whereas pri*e actors o -5 are 5 and !G

Function !rotot#pes4 Call 6# 5alue+$e8erence4 !ointers


KBL What wo#ld be the o#tp#t o the ollowing progra*sP 1a2 main1 2 3 $%!at area # int ra(i,s = 1 # area = 'ir'%e 1 ra(i,s 2 # rint$ 1 4@n5$4" area 2 # 6 'ir'%e 1 int r 2

Chapter 50 &unctions 9 #ointers


3 $%!at a # a = 3.14 * r * r # ret,rn 1 a 2 #

2)7

6 1&2 main1 2 3 =!i( s%!-an1 2 # int ' = 5 # ' = s%!-an1 2 # rint$ 1 4@n5(4" ' 2 # 6 =!i( s%!-an1 2 3 rint$ 1 4@nQn%/ Ue men ,se +T4 2 # 6 KFL 1nswer the ollowingP

>a? Write a #nction which receives a 8loat and an int ro* 1ain= >, inds the prod#ct o these two and ret#rns the prod#ct which is printed thro#gh 1ain= >G >b? Write a #nction that receives 5 integers and ret#rns the s#*, average and standard deviation o these n#*bersG Call this #nction ro* 1ain= > and print the res#lts in 1ain= >G >c? Write a #nction that receives *ar9s received by a st#dent in s#bQects and ret#rns the average and percentage o these *ar9sG Call this #nction ro* 1ain= > and print the res#lts in 1ain= >G
KGL What wo#ld be the o#tp#t o the ollowing progra*sP 1a2 main1 2 3 int i = 5" 9 = 2 #

2)&
9,n. 1 i" 9 2 # rint$ 1 4@n5( 5(4" i" 9 2 # 6 9,n. 1 int i" int 9 2 3 i=i*i# 9=9*9# 6 1&2 main1 2 3 int i = 5" 9 = 2 # 9,n. 1 Bi" B9 2 # rint$ 1 4@n5( 5(4" i" 9 2 # 6 9,n. 1 int *i" int *9 2 3 *i = *i * *i # *9 = *9 * *9 # 6 1'2 main1 2 3 int i = 4" 9 = 2 # 9,n. 1 Bi" 9 2 # rint$ 1 4@n5( 5(4" i" 9 2 # 6 9,n. 1 int *i" int 9 2 3 *i = *i * *i # 9=9*9# 6

%et .s C

1(2 main1 2 3 $%!at a = 13.5 # $%!at *&" *' # & = Ba # )* s, !se a((ress !$ a is 1006 *)

Chapter 50 &unctions 9 #ointers


'=&# rint$ 1 4@n5, 5, 5,4" Ba" &" ' 2 # rint$ 1 4@n5$ 5$ 5$ 5$ 5$4" a" *1Ba2" *Ba" *&" *' 2 # 6 K2L ,oint o#t the errors, i any, in the ollowing progra*sP 1a2 main1 2 3 int i = 135" a = 135" . # . = ass 1 i" a 2 # rint$ 1 4@n5(4" . 2 # 6 ass 1 int 9" int & 2 int ' # 3 '=9+&# ret,rn 1 ' 2 # 6 1&2 main1 2 3 int = 23" $ = 24 # 9iaa/9! 1 B " B$ 2 # rint$ 1 4@n5( 5(4" " $ 2 # 6 9iaa/9! 1 int H" int - 2 3 H=H+H# -=-+-# 6 1'2 main1 2 3 int . = 35" : # : = 'he'. 1 . 2 # rint$ 1 4@n5(4" : 2 # 6

2)9

21)
'he'. 1 m 2 3 int m # i$ 1 m < 40 2 ret,rn 1 1 2 # e%se ret,rn 1 0 2 # 6 1(2 main1 2 3 int i = 35" *: # : = $,n'ti!n 1 Bi 2 # rint$ 1 4@n5(4" : 2 # 6 $,n'ti!n 1 int *m 2 3 ret,rn 1 m + 2 2 # 6

%et .s C

K*L What wo#ld be the o#tp#t o the ollowing progra*sP 1a2 main1 2 3 int i = 0 # i++ # i$ 1 i ;= 5 2 3 rint$ 1 4@n+ a((s Fin-s t! /!,r th!,-hts4 2 # exit1 2 # main1 2 # 6 6 1&2 main1 2 3 stati' int i = 0 # i++ #

Chapter 50 &unctions 9 #ointers


i$ 1 i ;= 5 2 3 rint$ 1 4@n5(4" i 2 # main1 2 # 6 e%se exit1 2 # 6 KVL 1tte*pt the ollowingP

211

>a? 1 5<digit positive integer is entered thro#gh the 9eyboard, write a #nction to calc#late s#* o digits o the 5<digit n#*berP >'? Witho#t #sing rec#rsion >2? 6sing rec#rsion >b? 1 positive integer is entered thro#gh the 9eyboard, write a progra* to obtain the pri*e actors o the n#*berG 5odi y the #nction s#itably to obtain the pri*e actors rec#rsivelyG >c? Write a rec#rsive #nction to obtain the irst 25 n#*bers o a +ibonacci seH#enceG $n a +ibonacci seH#ence the s#* o two s#ccessive ter*s gives the third ter*G +ollowing are the irst ew ter*s o the +ibonacci seH#enceP ' ' 2 - 5 % '- 2' -4 55 %&GGG >d? 1 positive integer is entered thro#gh the 9eyboard, write a #nction to ind the binary eH#ivalent o this n#*ber #sing rec#rsionG >e? Write a rec#rsive #nction to obtain the r#nning s#* o 25 nat#ral n#*bersG > ? Write a C #nction to eval#ate the series irst

sin> "? X " f > " = -4? L > " = 54? f > " = !4? L 7

212
to ive signi icant digitsG

%et .s C

>g? Given three variables 3, #, H write a #nction to circ#larly shi t their val#es to rightG $n other words i / X 5, y X %, ; X '( a ter circ#lar shi t y X 5, ; X %, / X'( a ter circ#lar shi t y X 5, ; X % and / X '(G Call the #nction with variables a, 6, c to circ#larly shi t val#esG >h? Write a #nction to ind the binary eH#ivalent o a given deci*al integer and display itG >i? $ the lengths o the sides o a triangle are denoted by a, 6, and c, then area o triangle is given by

area X

> f a ?> f b?> f c ?

where, S X > a L b L c ? = 2 >Q? Write a #nction to co*p#te the distance between two points and #se it to develop another #nction that will co*p#te the area o the triangle whose vertices are '=314 #1>, -=324 #2>, and C=334 #3>G 6se these #nctions to develop a #nction which ret#rns a val#e ' i the point =34 #> lines inside the triangle 18C, otherwise a val#e (G >9? Write a #nction to co*p#te the greatest co**on divisor given by .#clid@s algorith*, e/e*pli ied or N X '&%(, K X '6'! as ollowsP '&%( F ' W '6'! X -6'&%( = '6'! X ' '6'! = -6- X 4 '6'! F 4 W -6- X '65 -6- = '65 X 2 -6- F 2 W '65 X -5 = -- X 5 '65 F 5 W -- X ( Th#s, the greatest co**on divisor is --G

Data Types Re isited


e e e e e e $ntegers, long and short $ntegers, signed and unsigned Chars, signed and unsigned +loats and 0o#bles 1 +ew 5ore $ss#es: Storage Classes in C 1#to*atic Storage Class "egister Storage Class Static Storage Class ./ternal Storage Class Which to 6se When e S#**ary e ./ercise

213

214

%et .s C

s seen in the irst chapter the pri*ary data types co#ld be o three varietiesRchar, int, and 8loatG $t *ay see* odd to *any, how C progra**ers *anage with s#ch a tiny set o data typesG +act is, the C progra**ers aren@t really deprivedG They can derive *any data types ro* these three typesG $n act, the n#*ber o data types that can be derived in C, is in principle, #nli*itedG 1 C progra**er can always invent whatever data type he needsG )ot only this, the pri*ary data types the*selves co#ld be o several typesG +or e/a*ple, a char co#ld be an unsigned char or a signed charG 3r an int co#ld be a short int or a long intG S# iciently con #singc Well, let #s ta9e a closer loo9 at these variations o pri*ary data types in this chapterG To #lly de ine a variable one needs to *ention not only its type b#t also its storage classG $n this chapter we wo#ld be e/ploring the di erent storage classes and their relevance in C progra**ingG

'

*ntegers4 long and short


We had seen earlier that the range o an $nteger constant depends #pon the co*pilerG +or a '6<bit co*piler li9e T#rbo C or T#rbo CL L the range is F-2!6% to -2!6!G +or a -2<bit co*piler the range wo#ld be F2'4!4%-64% to L2'4!4%-64!G 2ere a '6<bit co*piler *eans that when it co*piles a C progra* it generates *achine lang#age code that is targeted towards wor9ing on a '6<bit *icroprocessor li9e $ntel %(%6=%(%%G 1s against this, a -2<bit co*piler li9e VCLL generates *achine lang#age code that is targeted towards a -2<bit *icroprocessor li9e $ntel ,enti#*G )ote that this does not *ean that a progra* co*piled #sing T#rbo C wo#ld not wor9 on -2<bit processorG $t wo#ld r#n s#ccess #lly b#t at that ti*e the -2<bit processor wo#ld wor9 as i it were a '6<bit processorG This happens beca#se a -2<bit processor provides s#pport or progra*s co*piled #sing '6<bit co*pilersG $ this bac9ward co*patibility s#pport is not provided the '6<bit progra*

Chapter :0 'ata Types Revisited

215

wo#ld not r#n on itG This is precisely what happens on the new $ntel $tani#* processors, which have withdrawn s#pport or '6<bit codeG "e*e*ber that o#t o the two= o#r bytes #sed to store an integer, the highest bit >'6th=-2nd bit? is #sed to store the sign o the integerG This bit is ' i the n#*ber is negative, and ( i the n#*ber is positiveG C o ers a variation o the integer data type that provides what are called short and long integer val#esG The intention o providing these variations is to provide integers with di erent ranges wherever possibleG Tho#gh not a r#le, short and long integers wo#ld #s#ally occ#py two and o#r bytes respectivelyG .ach co*piler can decide appropriate si;es depending on the operating syste* and hardware or which it is being written, s#bQect to the ollowing r#lesP >a? >b? >c? >d? shorts are at least 2 bytes big longs are at least 4 bytes big shorts are never bigger than ints ints are never bigger than longs

+ig#re 6G' shows the si;es o di erent integers based #pon the 3S #sedG

Co1piler '6<bit >T#rbo C=CLL? -2<bit >Vis#al CLL?

short 2 2

int 2 4

long 4 4

+ig#re 6G' long variables which hold long integers are declared #sing the 9eyword long, as in,

21"
%!n- int i # %!n- int a&' #

%et .s C

long integers ca#se the progra* to r#n a bit slower, b#t the range o val#es that we can #se is e/panded tre*endo#slyG The val#e o a long integer typically can vary ro* <2'4!4%-64% to L2'4!4%-64!G 5ore than this yo# sho#ld not need #nless yo# are ta9ing a world cens#sG $ there are s#ch things as longs, sy**etry reH#ires shorts as well Rintegers that need less space in *e*ory and th#s help speed #p progra* e/ec#tionG short integer variables are declared as,
sh!rt int 9 # sh!rt int hei-ht #

C allows the abbreviation o short int to short and o long int to longG So the declarations *ade above can be written as,
%!n- i # %!n- a&' # sh!rt 9 # sh!rt hei-ht #

)at#rally, *ost C progra**ers pre er this short<c#tG So*eti*es we co*e across sit#ations where the constant is s*all eno#gh to be an int, b#t still we want to give it as *#ch storage as a longG $n s#ch cases we add the s# i/ D7@ or Dl@ at the end o the n#*ber, as in 2-7G

*ntegers4 signed and unsigned


So*eti*es, we 9now in advance that the val#e stored in a given integer variable will always be positiveRwhen it is being #sed to

Chapter :0 'ata Types Revisited

217

only co#nt things, or e/a*pleG $n s#ch a case we can declare the variable to be unsigned, as in,
,nsi-ne( int n,m_st,(ents #

With s#ch a declaration, the range o per*issible integer val#es > or a '6<bit 3S? will shi t ro* the range <-2!6% to L-2!6! to the range ( to 655-5G Th#s, declaring an integer as unsigned al*ost do#bles the si;e o the largest possible val#e that it can otherwise ta9eG This so happens beca#se on declaring the integer as unsigned, the le t<*ost bit is now ree and is not #sed to store the sign o the n#*berG )ote that an unsigned integer still occ#pies two bytesG This is how an unsigned integer can be declaredP
,nsi-ne( int i # ,nsi-ne( i #

7i9e an unsigned int, there also e/ists a short unsigned int and a long unsigned intG 8y de a#lt a short int is a signed short int and a long int is a signed long intG

Chars4 signed and unsigned


,arallel to signed and unsigned ints >either short or long?, si*ilarly there also e/ist signed and unsigned chars, both occ#pying one byte each, b#t having di erent rangesG To begin with it *ight appear strange as to how a char can have a signG Consider the state*ent
'har 'h = 'A' #

2ere what gets stored in ch is the binary eH#ivalent o the 1SC$$ val#e o D1@ >iGeG binary o 65?G 1nd i 65@s binary can be stored, then <54@s binary can also be stored >in a signed char?G

21&

%et .s C

1 signed char is sa*e as an ordinary char and has a range ro* <'2% to L'2!_ whereas, an unsigned char has a range ro* ( to 255G 7et #s now see a progra* that ill#strates this rangeP
main1 2 3 'har 'h = 291 # rint$ 1 4@n5( 5'4" 'h" 'h 2 # 6

What o#tp#t do yo# e/pect ro* this progra*c ,ossibly, 2&' and the character corresponding to itG Well, not reallyG S#rprisedc The reason is that ch has been de ined as a char, and a char cannot ta9e a val#e bigger than L'2!G 2ence when val#e o ch e/ceeds L'2!, an appropriate val#e ro* the other side o the range is pic9ed #p and stored in chG This val#e in o#r case happens to be -5, hence -5 and its corresponding character M, gets printed o#tG 2ere is another progra* that wo#ld *a9e the concept clearerG
main1 2 3 'har 'h # $!r 1 'h = 0 # 'h ;= 255 # 'h++ 2 rint$ 1 4@n5( 5'4" 'h" 'h 2 # 6

This progra* sho#ld o#tp#t 1SC$$ val#es and their corresponding charactersG Well, )o4 This is an inde inite loopG The reason is that ch has been de ined as a char, and a char cannot ta9e val#es bigger than L'2!G 2ence when val#e o ch is L'2! and we per or* ch?? it beco*es <'2% instead o L'2%G <'2% is less than 255 hence the condition is still satis iedG 2ere onwards ch wo#ld ta9e val#es li9e <'2!, <'26, <'25, GGGG <2, <', (, L', L2, GGG L'2!, <'2%, <'2!, etcG Th#s the val#e o ch wo#ld 9eep oscillating between <'2% to L'2!, thereby ens#ring that the loop never gets ter*inatedG 2ow do yo#

Chapter :0 'ata Types Revisited

219

overco*e this di ic#ltyc Wo#ld declaring ch as an unsigned char solve the proble*c .ven this wo#ld not serve the p#rpose since when ch reaches a val#e 255, ch?? wo#ld try to *a9e it 256 which cannot be stored in an unsigned charG Th#s the only alternative is to declare ch as an intG 2owever, i we are bent #pon writing the progra* #sing unsigned char, it can be done as shown belowG The progra* is de initely less elegant, b#t wor9able all the sa*eG
main1 2 3 ,nsi-ne( 'har 'h # $!r 1 'h = 0 # 'h ;= 254 # 'h++ 2 rint$ 1 4@n5( 5'4" 'h" 'h 2 # rint$ 1 4@n5( 5'4" 'h" 'h 2 # 6

Floats and Dou6les


1 8loat occ#pies o#r bytes in *e*ory and can range ro* <-G4e-% to L-G4e-%G $ this is ins# icient then C o ers a dou6le data type that occ#pies % bytes in *e*ory and has a range ro* <'G!e-(% to L'G!e-(%G 1 variable o type dou6le can be declared as,
(!,&%e a" ! ,%ati!n #

$ the sit#ation de*ands #sage o real n#*bers that lie even beyond the range o ered by dou6le data type, then there e/ists a long dou6le that can range ro* <'G!e4&-2 to L'G!e4&-2G 1 long dou6le occ#pies '( bytes in *e*oryG Co# wo#ld see that *ost o the ti*es in C progra**ing one is reH#ired to #se either chars or ints and cases where 8loats, dou6les or long dou6les wo#ld be #sed are indeed rareG

22)

%et .s C

7et #s now write a progra* that p#ts to #se all the data types that we have learnt in this chapterG Go thro#gh the ollowing progra* care #lly, which shows how to #se these di erent data typesG )ote the or*at speci iers #sed to inp#t and o#tp#t these data typesG
main1 2 3 'har ' # ,nsi-ne( 'har ( # int i # ,nsi-ne( int 9 # sh!rt int . # ,nsi-ne( sh!rt int % # %!n- int m # ,nsi-ne( %!n- int n # $%!at x # (!,&%e / # %!n- (!,&%e : # )* 'har *) s'an$ 1 45' 5'4" B'" B( 2 # rint$ 1 45' 5'4" '" ( 2 # )* int *) s'an$ 1 45( 5,4" Bi" B9 2 # rint$ 1 45( 5,4" i" 9 2 # )* sh!rt int *) s'an$ 1 45( 5,4" B." B% 2 # rint$ 1 45( 5,4" ." % 2 # )* %!n- int *) s'an$ 1 45%( 5%,4" Bm" Bn 2 # rint$ 1 45%( 5%,4" m" n 2 # )* $%!at" (!,&%e" %!n- (!,&%e *) s'an$ 1 45$ 5%$ 5O$4" Bx" B/" B: 2 # rint$ 1 45$ 5%$ 5O$4" x" /" : 2 #

Chapter :0 'ata Types Revisited


6

221

The essence o all the data types that we have learnt so ar has been capt#red in +ig#re 6G2G

Data T#pe signed char #nsigned char short signed int short #nsigned int signed int #nsigned int long signed int long #nsigned int loat do#ble long do#ble

$ange <'2% to L '2! ( to 255 <-2!6% to L-2!6! ( to 655-5 <-2!6% to L-2!6! ( to 655-5
<2'4!4%-64% to L2'4!4%-64!

-#tes ' ' 2 2 2 2 4 4 4 % '(

For1at Uc Uc Ud U# Ud U# Uld Ul# U Ul U7

( to 42&4&6!2&5 <-G4e-% to L-G4e-% <'G!e-(% to L'G!e-(% <'G!e4&-2 to L'G!e4&-2

)oteP The si;es and ranges o int, short and long are co*piler dependentG Si;es in this ig#re are or '6<bit co*pilerG

+ig#re 6G2

' Fe0 ,ore *ssues[


2aving seen all the variations o the pri*ary types let #s ta9e a loo9 at so*e *ore related iss#esG >a? We saw earlier that si;e o an integer is co*piler dependentG This is even tr#e in case o chars and 8loatsG 1lso, depending #pon the *icroprocessor or which the co*piler targets its code the acc#racy o loating point calc#lations *ay changeG +or e/a*ple, the res#lt o 22G(=!G( wo#ld be reported *ore

222

%et .s C

acc#rately by VCLL co*piler as co*pared to TC=TCLL co*pilersG This is beca#se TC=TCLL targets its co*piled code to %(%%=%(%6 >'6<bit? *icroprocessorsG Since these *icroprocessors do not o er loating point s#pport, TC=TCLL per or*s all loat operations #sing a so tware piece called +loating ,oint .*#latorG This e*#lator has li*itations and hence prod#ces less acc#rate res#ltsG 1lso, this e*#lator beco*es part o the .A. ile, thereby increasing its si;eG $n addition to this increased si;e there is a per or*ance penalty since this bigger code wo#ld ta9e *ore ti*e to e/ec#teG >b? $ yo# loo9 at ranges o chars and ints there see*s to be one e/tra n#*ber on the negative sideG This is beca#se a negative n#*ber is always stored as 2@s co*pli*ent o its binaryG +or e/a*ple, let #s see how <'2% is storedG +irstly, binary o '2% is calc#lated >'(((((((?, then its '@s co*pli*ent is obtained >('''''''?G 1 '@s co*pli*ent is obtained by changing all (s to 's and 's to (sG +inally, 2@s co*pli*ent o this n#*ber, iGeG '(((((((, gets storedG 1 2@s co*pli*ent is obtained by adding ' to the '@s co*pli*entG Th#s, or <'2%, '((((((( gets storedG This is an %<bit n#*ber and it can be easily acco**odated in a charG 1s against this, L'2% cannot be stored in a char beca#se its binary ('((((((( >le t<*ost ( is or positive sign? is a &<bit n#*berG 2owever L'2! can be stored as its binary (''''''' t#rns o#t to be a %<bit n#*berG >c? What happens when we atte*pt to store L'2% in a charc The irst n#*ber on the negative side, iGeG <'2% gets storedG This is beca#se ro* the &<bit binary o L'2%, ('(((((((, only the right<*ost % bits get storedG 8#t when '((((((( is stored the le t<*ost bit is ' and it is treated as a sign bitG Th#s the val#e o the n#*ber beco*es <'2% since it is indeed the binary o <'2%, as can be #nderstood ro* >b? aboveG Si*ilarly, yo# can veri y that an atte*pt to store L'2& in a char res#lts in storing <'2! in itG $n general, i we e/ceed the range ro* positive side we end #p on the negative sideG Vice versa is

Chapter :0 'ata Types Revisited

223

also tr#eG $ we e/ceed the range ro* negative side we end #p on positive sideG

Storage Classes in C
We have already said all that needs to be said abo#t constants, b#t we are not inished with variablesG To #lly de ine a variable one needs to *ention not only its Dtype@ b#t also its Dstorage class@G $n other words, not only do all variables have a data type, they also have a Dstorage class@G We have not *entioned storage classes yet, tho#gh we have written several progra*s in CG We were able to get away with this beca#se storage classes have de a#ltsG $ we don@t speci y the storage class o a variable in its declaration, the co*piler will ass#*e a storage class depending on the conte/t in which the variable is #sedG Th#s, variables have certain de a#lt storage classesG +ro* C co*piler@s point o view, a variable na*e identi ies so*e physical location within the co*p#ter where the string o bits representing the variable@s val#e is storedG There are basically two 9inds o locations in a co*p#ter where s#ch a val#e *ay be 9eptR 5e*ory and C,6 registersG $t is the variable@s storage class that deter*ines in which o these two locations the val#e is storedG 5oreover, a variable@s storage class tells #sP >a? Where the variable wo#ld be storedG >b? What will be the initial val#e o the variable, i initial val#e is not speci ically assignedG>iGeG the de a#lt initial val#e?G >c? What is the scope o the variable_ iGeG in which #nctions the val#e o the variable wo#ld be availableG >d? What is the li e o the variable_ iGeG how long wo#ld the variable e/istG

224
There are o#r storage classes in CP >a? >b? >c? >d? 1#to*atic storage class "egister storage class Static storage class ./ternal storage class

%et .s C

7et #s e/a*ine these storage classes one by oneG

'uto1atic Storage Class


The eat#res o a variable de ined to have an a#to*atic storage class are as #nderP Storage 0e a#lt initial val#e Scope 7i e f f 5e*oryG 1n #npredictable val#e, which is o ten called a garbage val#eG f 7ocal to the bloc9 in which the variable is de inedG f Till the control re*ains within the bloc9 in which the variable is de inedG

+ollowing progra* shows how an a#to*atic storage class variable is declared, and the act that i the variable is not initiali;ed it contains a garbage val#eG
main1 2 3 a,t! int i" 9 # rint$ 1 4@n5( 5(4" i" 9 2 # 6

The o#tp#t o the above progra* co#ld beGGG


1211 221

where, '2'' and 22' are garbage val#es o i and WG When yo# r#n this progra* yo# *ay get di erent val#es, since garbage val#es

Chapter :0 'ata Types Revisited

225

are #npredictableG So always *a9e it a point that yo# initiali;e the a#to*atic variables properly, otherwise yo# are li9ely to get #ne/pected res#ltsG )ote that the 9eyword or this storage class is auto, and not a#to*aticG Scope and li e o an a#to*atic variable is ill#strated in the ollowing progra*G
main1 2 3 a,t! int i = 1 # 3 3 3 rint$ 1 4@n5( 4" i 2 # 6 rint$ 1 45( 4" i 2 # 6 6 6 rint$ 1 45(4" i 2 #

The o#tp#t o the above progra* isP


111

This is beca#se, all print8= > state*ents occ#r within the o#ter*ost bloc9 >a bloc9 is all state*ents enclosed within a pair o braces? in which i has been de inedG $t *eans the scope o i is local to the bloc9 in which it is de inedG The *o*ent the control co*es o#t o the bloc9 in which the variable is de ined, the variable and its val#e is irretrievably lostG To catch *y point, go thro#gh the ollowing progra*G
main1 2 3 a,t! int i = 1 # 3

22"
a,t! int i = 2 # 3 a,t! int i = 3 # rint$ 1 4@n5( 4" i 2 # 6 rint$ 1 45( 4" i 2 # 6 rint$ 1 45(4" i 2 # 6

%et .s C

The o#tp#t o the above progra* wo#ld beP


321

)ote that the Co*piler treats the three i@s as totally di erent variables, since they are de ined in di erent bloc9sG 3nce the control co*es o#t o the inner*ost bloc9 the variable i with val#e - is lost, and hence the i in the second print8= > re ers to i with val#e 2G Si*ilarly, when the control co*es o#t o the ne/t inner*ost bloc9, the third print8= > re ers to the i with val#e 'G 6nderstand the concept o li e and scope o an a#to*atic storage class variable thoro#ghly be ore proceeding with the ne/t storage classG

$egister Storage Class


The eat#res o a variable de ined to be o register storage class are as #nderP Storage 0e a#lt initial val#e Scope 7i e
-

C,6 registersG Garbage val#eG 7ocal to the bloc9 in which the variable is de inedG Till the control re*ains within the bloc9 in which the variable is de inedG

Chapter :0 'ata Types Revisited

227

1 val#e stored in a C,6 register can always be accessed aster than the one that is stored in *e*oryG There ore, i a variable is #sed at *any places in a progra* it is better to declare its storage class as registerG 1 good e/a*ple o reH#ently #sed variables is loop co#ntersG We can na*e their storage class as registerG
main1 2 3 re-ister int i # $!r 1 i = 1 # i ;= 10 # i++ 2 rint$ 1 4@n5(4" i 2 # 6

2ere, even tho#gh we have declared the storage class o i as register, we cannot say or s#re that the val#e o i wo#ld be stored in a C,6 registerG Whyc 8eca#se the n#*ber o C,6 registers are li*ited, and they *ay be b#sy doing so*e other tas9G What happens in s#ch an eventGGG the variable wor9s as i its storage class is autoG )ot every type o variable can be stored in a C,6 registerG +or e/a*ple, i the *icroprocessor has '6<bit registers then they cannot hold a 8loat val#e or a dou6le val#e, which reH#ire 4 and % bytes respectivelyG 2owever, i yo# #se the register storage class or a 8loat or a dou6le variable yo# won@t get any error *essagesG 1ll that wo#ld happen is the co*piler wo#ld treat the variables to be o auto storage classG

Static Storage Class


The eat#res o a variable de ined to have a static storage class are as #nderP Storage 0e a#lt initial val#e f 5e*oryG f EeroG

22&
Scope 7i e

%et .s C
f 7ocal to the bloc9 in which the variable is de inedG f Val#e o the variable persists between di erent #nction callsG

Co*pare the two progra*s and their o#tp#t given in +ig#re 6G- to #nderstand the di erence between the auto1atic and static storage classesG
main1 2 3 in'rement1 2 # in'rement1 2 # in'rement1 2 # 6 main1 2 3 in'rement1 2 # in'rement1 2 # in'rement1 2 # 6

in'rement1 2 in'rement1 2 3 3 a,t! int i = 1 # stati' int i = 1 # rint$ 1 45(@n4" i 2 # rint$ 1 45(@n4" i 2 # i=i+1# i=i+1# 6 6 8he !,t ,t !$ the a&!=e r!-rams F!,%( &e: 1 1 1 1 2 3

+ig#re 6GThe progra*s above consist o two #nctions 1ain= > and incre1ent= >G The #nction incre1ent= > gets called ro* 1ain= > thriceG .ach ti*e it incre*ents the val#e o i and prints itG The only di erence in the two progra*s is that one #ses an auto storage class or variable i, whereas the other #ses static storage classG

Chapter :0 'ata Types Revisited

229

7i9e auto variables, static variables are also local to the bloc9 in which they are declaredG The di erence between the* is that static variables don@t disappear when the #nction is no longer activeG Their val#es persistG $ the control co*es bac9 to the sa*e #nction again the static variables have the sa*e val#es they had last ti*e aro#ndG $n the above e/a*ple, when variable i is auto, each ti*e incre1ent= > is called it is re<initiali;ed to oneG When the #nction ter*inates, i vanishes and its new val#e o 2 is lostG The res#ltP no *atter how *any ti*es we call incre1ent= >4 i is initiali;ed to ' every ti*eG 3n the other hand, i i is static, it is initiali;ed to ' only onceG $t is never initiali;ed againG 0#ring the irst call to incre1ent= >, i is incre*ented to 2G 8eca#se i is static, this val#e persistsG The ne/t ti*e incre1ent= > is called, i is not re<initiali;ed to '_ on the contrary its old val#e 2 is still availableG This c#rrent val#e o i >iGeG 2? gets printed and then i F i ? 1 adds ' to i to get a val#e o -G When incre1ent= > is called the third ti*e, the c#rrent val#e o i >iGeG -? gets printed and once again i is incre*entedG $n short, i the storage class is static then the state*ent static int i F 1 is e/ec#ted only once, irrespective o how *any ti*es the sa*e #nction is calledG Consider one *ore progra*G
main1 2 3 int *9 # int * $,n1 2 # 9 = $,n1 2 # rint$ 1 4@n5(4" *9 2 # 6 int *$,n1 2 3

23)
int . = 35 # ret,rn 1 B. 2 # 6

%et .s C

2ere we are ret#rning an address o G ro* 8un= > and collecting it in WG Th#s W beco*es pointer to GG Then #sing this pointer we are printing the val#e o GG This correctly prints o#t -5G )ow try calling any #nction >even print8= > ? i**ediately a ter the call to 8un= >G This ti*e print8= > prints a garbage val#eG Why does this happenc $n the irst case, when the control ret#rned ro* 8un= > tho#gh G went dead it was still le t on the stac9G We then accessed this val#e #sing its address that was collected in WG 8#t when we precede the call to print8= > by a call to any other #nction, the stac9 is now changed, hence we get the garbage val#eG $ we want to get the correct val#e each ti*e then we *#st declare G as staticG 8y doing this when the control ret#rns ro* 8un= >, G wo#ld not dieG 1ll this having been said, a word o adviceRavoid #sing static variables #nless yo# really need the*G 8eca#se their val#es are 9ept in *e*ory when the variables are not active, which *eans they ta9e #p space in *e*ory that co#ld otherwise be #sed by other variablesG

B3ternal Storage Class


The eat#res o a variable whose storage class has been de ined as e/ternal are as ollowsP Storage 0e a#lt initial val#e Scope 7i e f f f f 5e*oryG EeroG GlobalG 1s long as the progra*@s e/ec#tion doesn@t co*e to an endG

Chapter :0 'ata Types Revisited

231

./ternal variables di er ro* those we have already disc#ssed in that their scope is global, not localG ./ternal variables are declared o#tside all #nctions, yet are available to all #nctions that care to #se the*G 2ere is an e/a*ple to ill#strate this actG
int i # main1 2 3 rint$ 1 4@ni = 5(4" i 2 # in'rement1 2 # in'rement1 2 # (e'rement1 2 # (e'rement1 2 # 6 in'rement1 2 3 i=i+1# rint$ 1 4@n!n in'rementin- i = 5(4" i 2 # 6 (e'rement1 2 3 i=i-1# rint$ 1 4@n!n (e'rementin- i = 5(4" i 2 # 6

The o#tp#t wo#ld beP


i=0 !n in'rementin- i = 1 !n in'rementin- i = 2 !n (e'rementin- i = 1 !n (e'rementin- i = 0

232

%et .s C

1s is obvio#s ro* the above o#tp#t, the val#e o i is available to the #nctions incre1ent= > and decre1ent= > since i has been declared o#tside all #nctionsG 7oo9 at the ollowing progra*G
int x = 21 # main1 2 3 extern int / # rint$ 1 4@n5( 5(4" x" / 2 # 6 int / = 31 #

2ere, 3 and # both are global variablesG Since both o the* have been de ined o#tside all the #nctions both enQoy e/ternal storage classG )ote the di erence between the ollowingP
extern int / # int / = 31 #

2ere the irst state*ent is a declaration, whereas the second is the de initionG When we declare a variable no space is reserved or it, whereas, when we de ine it space gets reserved or it in *e*oryG We had to declare # since it is being #sed in print8= > be ore it@s de inition is enco#nteredG There was no need to declare 3 since its de inition is done be ore its #sageG 1lso re*e*ber that a variable can be declared several ti*es b#t can be de ined only onceG 1nother s*all iss#eRwhat will be the o#tp#t o the ollowing progra*c
int x = 10 # main1 2 3 int x = 20 # rint$ 1 4@n5(4" x 2 #

Chapter :0 'ata Types Revisited


(is %a/1 2 # 6 (is %a/1 2 3 rint$ 1 4@n5(4" x 2 # 6

233

2ere 3 is de ined at two places, once o#tside 1ain= > and once inside itG When the control reaches the print8= > in 1ain= > which 3 gets printedc Whenever s#ch a con lict arises, it@s the local variable that gets pre erence over the global variableG 2ence the print8= > o#tp#ts 2(G When displa#= > is called and control reaches the print8= > there is no s#ch con lictG 2ence this ti*e the val#e o the global 3, iGeG '( gets printedG 3ne last thingRa static variable can also be declared o#tside all the #nctionsG +or all practical p#rposes it will be treated as an e3tern variableG 2owever, the scope o this variable is li*ited to the sa*e ile in which it is declaredG This *eans that the variable wo#ld not be available to any #nction that is de ined in a ile other than the ile in which the variable is de inedG

/hich to .se /hen


0ennis "itchie has *ade available to the C progra**er a n#*ber o storage classes with varying eat#res, believing that the progra**er is in a best position to decide which one o these storage classes is to be #sed whenG We can *a9e a ew gro#nd r#les or #sage o di erent storage classes in di erent progra**ing sit#ations with a view toP >a? econo*ise the *e*ory space cons#*ed by the variables >b? i*prove the speed o e/ec#tion o the progra* The r#les are as #nderP

234

%et .s C

f 6se static storage class only i yo# want the val#e o a variable to persist between di erent #nction callsG f 6se register storage class or only those variables that are being #sed very o ten in a progra*G "eason is, there are very ew C,6 registers at o#r disposal and *any o the* *ight be b#sy doing so*ething elseG 5a9e care #l #tili;ation o the scarce reso#rcesG 1 typical application o register storage class is loop co#nters, which get #sed a n#*ber o ti*es in a progra*G f 6se e3tern storage class or only those variables that are being #sed by al*ost all the #nctions in the progra*G This wo#ld avoid #nnecessary passing o these variables as arg#*ents when *a9ing a #nction callG 0eclaring all the variables as e3tern wo#ld a*o#nt to a lot o wastage o *e*ory space beca#se these variables wo#ld re*ain active thro#gho#t the li e o the progra*G f $ yo# don@t have any o the e/press needs *entioned above, then #se the auto storage classG $n act *ost o the ti*es we end #p #sing the auto variables, beca#se o ten it so happens that once we have #sed the variables in a #nction we don@t *ind loosing the*G

Su11ar#
>a? We can #se di erent variations o the pri*ary data types, na*ely signed and unsigned char, long and short int, 8loat, dou6le and long dou6leG There are di erent or*at speci ications or all these data types when they are #sed in scan8= > and print8= > #nctionsG >b? The *a/i*#* val#e a variable can hold depends #pon the n#*ber o bytes it occ#pies in *e*oryG >c? 8y de a#lt all the variables are signedG We can declare a variable as unsigned to acco**odate greater val#e witho#t increasing the bytes occ#piedG

Chapter :0 'ata Types Revisited

235

>d? We can *a9e #se o proper storage classes li9e auto, register, static and e3tern to control o#r properties o the variableRstorage, de a#lt initial val#e, scope and li eG

B3ercise
K'L What wo#ld be the o#tp#t o the ollowing progra*sP 1a2 main1 2 3 int i # $!r 1 i = 0 # i ;= 50000 # i++ 2 rint$ 1 4@n5(4" i 2 # 6 1&2 main1 2 3 $%!at a = 13.5 # (!,&%e & = 13.5 # rint$ 1 4@n5$ 5%$4" a" & 2 # 6 1'2 int i = 0 # main1 2 3 rint$ 1 4@nmain's i = 5(4" i 2 # i++ # =a%1 2 # rint$ 1 4@nmain's i = 5(4" i 2 # =a%1 2 # 6 =a%1 2 3 i = 100 # rint$ 1 4@n=a%'s i = 5(4" i 2 # i++ # 6

23"
1(2 main1 2 3 int x" /" s = 2 # s *= 3 # /=$1s2# x=-1s2# rint$ 1 4@n5( 5( 5(4" s" /" x 2 # 6 int t = 8 # $ 1 int a 2 3 a += -5 # t -= 4 # ret,rn 1 a + t 2 # 6 - 1 int a 2 3 a=1# t += a # ret,rn 1 a + t 2 # 6 1e2 main1 2 3 stati' int '!,nt = 5 # rint$ 1 4@n'!,nt = 5(4" '!,nt-- 2 # i$ 1 '!,nt T= 0 2 main1 2 # 6 1$2 main1 2 3 int i" 9 # $!r 1 i = 1 # i ; 5 # i++ 2 3 9=-1i2# rint$ 1 4@n5(4" 9 2 # 6

%et .s C

Chapter :0 'ata Types Revisited


6 - 1 int x 2 3 stati' int = = 1 # int & = 3 # = += x # ret,rn 1 = + x + & 2 # 6 1-2 $%!at x = 4.5 # main1 2 3 $%!at /" $%!at $ 1 $%!at 2 # x *= 2.0 # /=$1x2# rint$ 1 4@n5$ 5$4" x" / 2 # 6 $%!at $ 1 $%!at a 2 3 a += 1.3 # x -= 4.5 # ret,rn 1 a + x 2 # 6 1h2 main1 2 3 $,n'1 2 # $,n'1 2 # 6 $,n'1 2 3 a,t! int i = 0 # re-ister int 9 = 0 # stati' int . = 0 # i++ # 9++ # .++ # rint$ 1 4@n 5( 5 ( 5(4" i" 9" . 2 # 6

237

23&
1i2 int x = 10 # main1 2 3 int x = 20 # 3 int x = 30 # rint$ 1 4@n5(4" x 2 # 6 rint$ 14@n5(4" x 2 # 6

%et .s C

K-L ,oint o#t the errors, i any, in the ollowing progra*sP 1a2 main1 2 3 %!n- n,m # n,m = 2 # rint$ 1 4@n5%(4" n,m 2 # 6 1&2 main1 2 3 'har 'h = 200 # rint$ 1 4@n5(4" 'h 2 # 6 1'2 main1 2 3 ,nsi-ne( a = 25 # %!n- ,nsi-ne( & = 25% # rint$ 1 4@n5%, 5,4" a" & 2 # 6

1(2 main1 2 3 %!n- $%!at a = 25.345e454 # ,nsi-ne( (!,&%e & = 25 # rint$ 1 4@n5%$ 5(4" a" & 2 #

Chapter :0 'ata Types Revisited


6 1e2 main1 2 3 $%!at a = 25.345 # $%!at *& # & = Ba # rint$ 1 4@n5$ 5,4" a" & 2 # 6 1$2 stati' int / # main1 2 3 stati' int : # rint$ 145( 5(4" /" : 2 # 6

239

KCL State whether the ollowing state*ents are Tr#e or +alseP

>a? Storage or a register storage class variable is allocated each ti*e the control reaches the bloc9 in which it is presentG >b? 1n e/tern storage class variable is not available to the #nctions that precede its de inition, #nless the variable is e/plicitly declared in these #nctionsG >c? The val#e o an a#to*atic storage class variable persists between vario#s #nction invocationsG >d? $ the C,6 registers are not available, the register storage class variables are treated as static storage class variablesG >e? The register storage class variables cannot hold loat val#esG > ? $ we try to #se register storage class or a 8loat variable the co*piler will lash an error *essageG

24)

%et .s C

>g? $ the variable 3 is de ined as e3tern and a variable 3 is also de ined as a local variable o so*e #nction, then the global variable gets pre erence over the local variableG >h? The de a#lt val#e or a#to*atic variable is ;eroG >i? The li e o static variable is till the control re*ains within the bloc9 in which it is de inedG >Q? $ a global variable is to be de ined, then the e3tern 9eyword is necessary in its declarationG >9? The address o register variable is not accessibleG
KDL +ollowing progra* calc#lates the s#* o digits o the n#*ber '2-45G Go thro#gh it and ind o#t why is it necessary to declare the storage class o the variable su1 as staticG main1 2 3 int a # a = s,m(i- 1 12345 2 # rint$ 1 4@n5(4" a 2 # 6 s,m(i- 1 int n,m 2 3 stati' int s,m # int a" & # a = n,m 5 10 # & = 1 n,m - a 2 ) 10 # s,m = s,m + a # i$ 1 & T= 0 2 s,m(i- 1 & 2 # e%se ret,rn 1 s,m 2 # 6

The C Preproces" sor


e +eat#res o C ,reprocessor e 5acro ./pansion 5acros with 1rg#*ents 5acros vers#s +#nctions e +ile $ncl#sion e Conditional Co*pilation e #if and #elif 0irectives e 5iscellaneo#s 0irectives #undef 0irective #pragma 0irective e S#**ary e ./ercise

241

242

%et .s C

he C preprocessor is e/actly what its na*e i*pliesG $t is a progra* that processes o#r so#rce progra* be ore it is passed to the co*pilerG ,reprocessor co**ands >o ten 9nown as directives? or* what can al*ost be considered a lang#age within C lang#ageG We can certainly write C progra*s witho#t 9nowing anything abo#t the preprocessor or its acilitiesG 8#t preprocessor is s#ch a great convenience that virt#ally all C progra**ers rely on itG This chapter e/plores the preprocessor directives and disc#sses the pros and cons o #sing the* in progra*sG

Features o8 C !reprocessor
There are several steps involved ro* the stage o writing a C progra* to the stage o getting it e/ec#tedG +ig#re !G' shows these di erent steps along with the iles created d#ring each stageG Co# can observe ro* the ig#re that o#r progra* passes thro#gh several processors be ore it is ready to be e/ec#tedG The inp#t and o#tp#t to each o these processors is shown in +ig#re !G2G )ote that i the so#rce code is stored in a ile ,"'GC then the e/panded so#rce code gets stored in a ile ,"'G$G When this e/panded so#rce code is co*piled the obQect code gets stored in ,"'G38NG When this obQect code is lin9ed with the obQect code o library #nctions the res#ltant e/ec#table code gets stored in ,"'G.A.G The preprocessor o ers several eat#res called preprocessor directivesG .ach o these preprocessor directives begin with a M sy*bolG The directives can be placed anywhere in a progra* b#t are *ost o ten placed at the beginning o a progra*, be ore the irst #nction de initionG We wo#ld learn the oll owing preprocessor directives hereP >a? 5acro e/pansion >b? +ile incl#sion

Chapter ;0 The C #reprocessor

243

2and written progra* Te/t editor C So#rce code >,"'GC? ,reprocessor ./panded so#rce code >,"'G$? Co*piler 3bQect code >,"'G38N? 7in9er ./ec#table code >,"'G.A.?

+ig#re !G'
!rocessor .ditor *nput ,rogra* typed ro* 9eyboard C so#rce code ile (utput C so#rce code containing progra* and preprocessor co**ands So#rce code ile with the preprocessing co**ands properly sorted o#t "elocatable obQect code

,repro< cessor Co*piler

So#rce code ile with preprocessing co**ands sorted o#t "elocatable obQect code and the standard C library #nctions

7in9er

./ec#table code in *achine lang#age

+ig#re !G2

244
>c? Conditional Co*pilation >d? 5iscellaneo#s directives

%et .s C

7et #s #nderstand these eat#res o preprocessor one by oneG

,acro B3pansion
2ave a loo9 at the ollowing progra*G
L(e$ine X??E> 25 main1 2 3 int i # $!r 1 i = 1 # i ;= X??E> # i++ 2 rint$ 1 4@n5(4" i 2 # 6

$n this progra* instead o writing 25 in the 8or loop we are writing it in the or* o 6,,.", which has already been de ined be ore 1ain= > thro#gh the state*ent,
L(e$ine X??E> 25

This state*ent is called D*acro de inition@ or *ore co**only, Q#st a D*acro@G What p#rpose does it servec 0#ring preprocessing, the preprocessor replaces every occ#rrence o 6,,." in the progra* with 25G 2ere is another e/a*ple o *acro de initionG
L(e$ine ?I 3.1415 main1 2 3 $%!at r = 6.25 # $%!at area # area = ?I * r * r # rint$ 1 4@nArea !$ 'ir'%e = 5$4" area 2 #

Chapter ;0 The C #reprocessor

245

6,,." and ,$ in the above progra*s are o ten called D*acro te*plates@, whereas, 25 and -G'4'5 are called their corresponding D*acro e/pansions@G When we co*pile the progra*, be ore the so#rce code passes to the co*piler it is e/a*ined by the C preprocessor or any *acro de initionsG When it sees the Ide8ine directive, it goes thro#gh the entire progra* in search o the *acro te*plates_ wherever it inds one, it replaces the *acro te*plate with the appropriate *acro e/pansionG 3nly a ter this proced#re has been co*pleted is the progra* handed over to the co*pilerG $n C progra**ing it is c#sto*ary to #se capital letters or *acro te*plateG This *a9es it easy or progra**ers to pic9 o#t all the *acro te*plates when reading thro#gh the progra*G )ote that a *acro te*plate and its *acro e/pansion are separated by blan9s or tabsG 1 space between I and de8ine is optionalG "e*e*ber that a *acro de inition is never to be ter*inated by a se*icolonG 1nd now a *illion dollar H#estionGGG why #se Ide8ine in the above progra*sc What have we gained by s#bstit#ting ,$ or -G'4'5 in o#r progra*c ,robably, we have *ade the progra* easier to readG .ven tho#gh -G'4'5 is s#ch a co**on constant that it is easily recogni;able, there are *any instances where a constant doesn@t reveal its p#rpose so readilyG +or e/a*ple, i the phrase KZ/'8]2NO ca#ses the screen to clearG 8#t which wo#ld yo# ind easier to #nderstand in the *iddle o yo#r progra* KZ/'8]2NO or KC7.1"SC"..)Oc Th#s, we wo#ld #se the *acro de inition
L(e$ine +OEA>7+>EEE 4@x1D^2C4

Then wherever C7.1"SC"..) appears in the progra* it wo#ld a#to*atically be replaced by KZ/'8]2NO be ore co*pilation beginsG

24"

%et .s C

There is perhaps a *ore i*portant reason or #sing *acro de inition than *ere readabilityG S#ppose a constant li9e -G'4'5 appears *any ti*es in yo#r progra*G This val#e *ay have to be changed so*e day to -G'4'5&2G 3rdinarily, yo# wo#ld need to go thro#gh the progra* and *an#ally change each occ#rrence o the constantG 2owever, i yo# have de ined ,$ in a Ide8ine directive, yo# only need to *a9e one change, in the Ide8ine directive itsel P
L(e$ine ?I 3.141592

8eyond this the change will be *ade a#to*atically to all occ#rrences o ,$ be ore the beginning o co*pilationG $n short, it is nice to 9now that yo# wo#ld be able to change val#es o a constant at all the places in the progra* by Q#st *a9ing a change in the Ide8ine directiveG This convenience *ay not *atter or s*all progra*s shown above, b#t with large progra*s *acro de initions are al*ost indispensableG 8#t the sa*e p#rpose co#ld have been served had we #sed a variable pi instead o a *acro te*plate !*G 1 variable co#ld also have provided a *eaning #l na*e or a constant and per*itted one change to e ect *any occ#rrences o the constantG $t@s tr#e that a variable can be #sed in this wayG Then, why not #se itc +or three reasons it@s a bad ideaG +irstly, it is ine icient, since the co*piler can generate aster and *ore co*pact code or constants than it can or vari ablesG Secondly, #sing a variable or what is really a constant enco#rages sloppy thin9ing and *a9es the progra* *ore di ic#lt to #nderstandP i so*ething never changes, it is hard to i*agine it as a variableG 1nd thirdly, there is always a danger that the variable *ay inadvertently get altered so*ewhere in the progra*G So it@s no longer a constant that yo# thin9 it isG

Chapter ;0 The C #reprocessor

247

Th#s, #sing Ide8ine can prod#ce *ore e icient and *ore easily #nderstandable progra*sG This directive is #sed e/tensively by C progra**ers, as yo# will see in *any progra*s in this boo9G +ollowing three e/a*ples show places where a Ide8ine directive is pop#larly #sed by C progra**ersG 1 Ide8ine directive is *any a ti*es #sed to de ine operators as shown belowG
L(e$ine AE0 BB L(e$ine Q> WW main1 2 3 int $ = 1" x = 4" / = 90 # i$ 1 1 $ ; 5 2 AE0 1 x ;= 20 Q> / ;= 45 2 2 rint$ 1 4@nG!,r ?+ Fi%% a%Fa/s F!r. $ine...4 2 # e%se rint$ 1 4@nIn $r!nt !$ the maintenan'e man4 2 #

1 Ide8ine directive co#ld be #sed even to replace a condition, as shown belowG


L(e$ine AE0 BB L(e$ine A>AEJE 1 a < 25 AE0 a ; 50 2 main1 2 3 int a = 30 # i$ 1 A>AEJE 2 rint$ 1 4Fithin ran-e4 2 # e%se rint$ 1 4!,t !$ ran-e4 2 #

24&

%et .s C

1 Ide8ine directive co#ld be #sed to replace even an entire C state*entG This is shown belowG
L(e$ine IQXE0 rint$ 1 48he Gan.ee 0!!(%e ]ir,s4 2 # main1 2 3 'har si-nat,re # i$ 1 si-nat,re == 'G' 2 IQXE0 e%se rint$ 1 47a$e... as /et T4 2 # 6

,acros 0ith 'rgu1ents


The *acros that we have #sed so ar are called si*ple *acrosG 5acros can have arg#*ents, Q#st as #nctions canG 2ere is an e/a*ple that ill#strates this actG
L(e$ine A>EA1x2 1 3.14 * x * x 2 main1 2 3 $%!at r1 = 6.25" r2 = 2.5" a # a = A>EA 1 r1 2 # rint$ 1 4@nArea !$ 'ir'%e = 5$4" a 2 # a = A>EA 1 r2 2 # rint$ 1 4@nArea !$ 'ir'%e = 5$4" a 2 # 6

2ere@s the o#tp#t o the progra*GGG


Area !$ 'ir'%e = 122.656250 Area !$ 'ir'%e = 19.625000

Chapter ;0 The C #reprocessor

249

$n this progra* wherever the preprocessor inds the phrase '$B'=3> it e/pands it into the state*ent = 3.14 < 3 < 3 >G 2owever, that@s not all that it doesG The 3 in the *acro te*plate '$B'=3> is an arg#*ent that *atches the 3 in the *acro e/pansion = 3.14 < 3 < 3 >G The state*ent '$B'=r1> in the progra* ca#ses the variable r1 to be s#bstit#ted or 3G Th#s the state*ent '$B'=r1> is eH#ivalent toP
1 3.14 * r1 * r1 2

1 ter the above so#rce code has passed thro#gh the preprocessor, what the co*piler gets to wor9 on will be thisP
main1 2 3 $%!at r1 = 6.25" r2 = 2.5" a # a = 3.14 * r1 *r1 # rint$ 1 4Area !$ 'ir'%e = 5$@n4" a 2 # a = 3.14 *r2 * r2 # rint$ 1 4Area !$ 'ir'%e = 5$4" a 2 # 6

2ere is another e/a*ple o *acros with arg#*entsP


L(e$ine I70IJI81/2 1 / <= 48 BB / ;= 57 2 main1 2 3 'har 'h # rint$ 1 4Enter an/ (i-it 4 2 # s'an$ 1 45'4" B'h 2 # i$ 1 I70IJI8 1 'h 2 2 rint$ 1 4@nG!, entere( a (i-it4 2 # e%se rint$ 1 4@nI%%e-a% in ,t4 2 #

25)
6

%et .s C

2ere are so*e i*portant points to re*e*ber while writing *acros with arg#*entsP >a? 8e care #l not to leave a blan9 between the *acro te*plate and its arg#*ent while de ining the *acroG +or e/a*ple, there sho#ld be no blan9 between '$B' and =3> in the de inition, Mde ine 1".1>/? > -G'4 W / W / ? $ we were to write '$B' =3> instead o '$B'=3>, the =3> wo#ld beco*e a part o *acro e/pansion, which we certainly don@t wantG What wo#ld happen is, the te*plate wo#ld be e/panded to
1 r1 2 1 3.14 * r1 * r1 2

which won@t r#nG )ot at all what we wantedG >b? The entire *acro e/pansion sho#ld be enclosed within parenthesesG 2ere is an e/a*ple o what wo#ld happen i we ail to enclose the *acro e/pansion within parenthesesG
L(e$ine 7YXA>E1n2 n * n main1 2 3 int 9 # 9 = 64 ) 7YXA>E 1 4 2 # rint$ 1 49 = 5(4" 9 2 # 6

The o#tp#t o the above progra* wo#ld beP


9 = 64

whereas, what we e/pected was Q X 4G

Chapter ;0 The C #reprocessor


What went wrongc The *acro was e/panded into
9 = 64 ) 4 * 4 #

251

which yielded 64G >c? 5acros can be split into *#ltiple lines, with a DZ@ >bac9 slash? present at the end o each lineG +ollowing progra* shows how we can de ine and #se *#ltiple line *acrosG
L(e$ine UOIEE $!r 1 i = 0 # i ; 79 # i++ 2 @ rint$ 1 45'4" 196 2 # L(e$ine ]OIEE1 \" G 2 3@ 6 main1 2 3 int i" / # '%rs'r1 2 # -!t!x/ 1 1" 12 2 # UOIEE $!r 1 / = 1 # / ; 25 # /++ 2 ]OIEE 1 39" / 2 # 6 -!t!x/ 1 \" G 2 # @ rint$ 1 45'4" 179 2 # @

This progra* draws a vertical and a hori;ontal line in the center o the screenG >d? $ or any reason yo# are #nable to deb#g a *acro then yo# sho#ld view the e/panded code o the progra* to see how the *acros are getting e/pandedG $ yo#r so#rce code is present in the ile ,"'GC then the e/panded so#rce code wo#ld be stored

252

%et .s C

in ,"'G$G Co# need to generate this ile at the co**and pro*pt by sayingP
' r1.'

2ere C,, stands or C ,re,rocessorG $t generates the e/panded so#rce code and stores it in a ile called ,"'G$G Co# can now open this ile and see the e/panded so#rce codeG )ote that the ile ,"'G$ gets generated in CPZTCZ8$) directoryG The proced#re or generating e/panded so#rce code or co*pilers other than T#rbo C=CLL *ight be a little di erentG

,acros %ersus Functions


$n the above e/a*ple a *acro was #sed to calc#late the area o the circleG 1s we 9now, even a #nction can be written to calc#late the area o the circleG Tho#gh *acro calls are Dli9e@ #nction calls, they are not really the sa*e thingsG Then what is the di erence between the twoc $n a *acro call the preprocessor replaces the *acro te*plate with its *acro e/pansion, in a st#pid, #nthin9ing, literal wayG 1s against this, in a #nction call the control is passed to a #nction along with certain arg#*ents, so*e calc#lations are per or*ed in the #nction and a #se #l val#e is ret#rned bac9 ro* the #nctionG This brings #s to a H#estionP when is it best to #se *acros with arg#*ents and when is it better to #se a #nctionc 6s#ally *acros *a9e the progra* r#n aster b#t increase the progra* si;e, whereas #nctions *a9e the progra* s*aller and co*pactG $ we #se a *acro h#ndred ti*es in a progra*, the *acro e/pansion goes into o#r so#rce code at h#ndred di erent places, th#s increasing the progra* si;eG 3n the other hand, i a #nction is #sed, then even i it is called ro* h#ndred di erent places in

Chapter ;0 The C #reprocessor

253

the progra*, it wo#ld ta9e the sa*e a*o#nt o space in the progra*G 8#t passing arg#*ents to a #nction and getting bac9 the ret#rned val#e does ta9e ti*e and wo#ld there ore slow down the progra*G This gets avoided with *acros since they have already been e/panded and placed in the so#rce code be ore co*pilationG 5oral o the story isRi the *acro is si*ple and sweet li9e in o#r e/a*ples, it *a9es nice shorthand and avoids the overheads associated with #nction callsG 3n the other hand, i we have a airly large *acro and it is #sed airly o ten, perhaps we o#ght to replace it with a #nctionG

File *nclusion
The second preprocessor directive we@ll e/plore in this chapter is ile incl#sionG This directive ca#ses one ile to be incl#ded in anotherG The preprocessor co**and or ile incl#sion loo9s li9e thisP
Lin'%,(e 4$i%ename4

and it si*ply ca#ses the entire contents o 8ilena1e to be inserted into the so#rce code at that point in the progra*G 3 co#rse this pres#*es that the ile being incl#ded is e/istingG When and why this eat#re is #sedc $t can be #sed in two casesP >a? $ we have a very large progra*, the code is best divided into several di erent iles, each containing a set o related #nctionsG $t is a good progra**ing practice to 9eep di erent sections o a large progra* separateG These iles are Iincluded at the beginning o *ain progra* ileG >b? There are so*e #nctions and so*e *acro de initions that we need al*ost in all progra*s that we writeG These co**only

254

%et .s C

needed #nctions and *acro de initions can be stored in a ile, and that ile can be incl#ded in every progra* we write, which wo#ld add all the state*ents in this ile to o#r progra* as i we have typed the* inG $t is co**on or the iles that are to be incl#ded to have a Gh e/tensionG This e/tension stands or Dheader ile@, possibly beca#se it contains state*ents which when incl#ded go to the head o yo#r progra*G The prototypes o all the library #nctions are gro#ped into di erent categories and then stored in di erent header ilesG +or e/a*ple prototypes o all *athe*atics related #nctions are stored in the header ile D*athGh@, prototypes o console inp#t=o#tp#t #nctions are stored in the header ile DconioGh@, and so onG 1ct#ally there e/ist two ways to write Iinclude state*entG These areP
Lin'%,(e 4$i%ename4 Lin'%,(e ;$i%ename<

The *eaning o each o these or*s is given belowP


Lin'%,(e 4-!t!.'4

This co**and wo#ld loo9 or the ile goto.c in the c#rrent directory as well as the speci ied list o directories as *entioned in the incl#de search path that *ight have been set #pG This co**and wo#ld loo9 or the ile goto.c in the speci ied list o directories onlyG

Lin'%,(e ;-!t!.'<

The incl#de search path is nothing b#t a list o directories that wo#ld be searched or the ile being incl#dedG 0i erent C co*pilers let yo# set the search path in di erent *annersG $ yo# are #sing T#rbo C=CLL co*piler then the search path can be set #p by selecting D0irectories@ ro* the D3ptions@ *en#G 3n doing this

Chapter ;0 The C #reprocessor

255

a dialog bo/ appearsG $n this dialog bo/ against D$ncl#de 0irectories@ we can speci y the search pathG We can also speci y *#ltiple incl#de paths separated by D_@ >se*icolon? as shown belowP
':@t'@%i& # ':@m/%i& # (:@%i&$i%es

The path can contain *a/i*#* o '2! charactersG 8oth relative and absol#te paths are validG +or e/a*ple DGGZdirZinc iles@ is a valid pathG

Conditional Co1pilation
We can, i we want, have the co*piler s9ip over part o a so#rce code by inserting the preprocessing co**ands Ii8de8 and Iendi8, which have the general or*P
Li$(e$ ma'r!name statement 1 # statement 2 # statement 3 # Len(i$

$ 1acrona1e has been Ide8ined, the bloc9 o code will be processed as #s#al_ otherwise notG Where wo#ld Ii8de8 be #se #lc When wo#ld yo# li9e to co*pile only a part o yo#r progra*c $n three casesP >a? To Kco**ent o#tO obsolete lines o codeG $t o ten happens that a progra* is changed at the last *in#te to satis y a clientG This involves rewriting so*e part o so#rce code to the client@s satis action and deleting the old codeG 8#t veteran progra**ers are a*iliar with the clients who change their *ind and want the old code bac9 again Q#st the way it wasG

25"

%et .s C

)ow yo# wo#ld de initely not li9e to retype the deleted code againG 3ne sol#tion in s#ch a sit#ation is to p#t the old code within a pair o =W W= co*binationG 8#t we *ight have already written a co**ent in the code that we are abo#t to Kco**ent o#tOG This wo#ld *ean we end #p with nested co**entsG 3bvio#sly, this sol#tion won@t wor9 since we can@t nest co**ents in CG There ore the sol#tion is to #se conditional co*pilation as shown belowG
main1 2 3 Li$(e$ Q_AG statement 1 # statement 2 # )* (ete'ts =ir,s *) statement 3 # statement 4 # )* s e'i$i' t! st!ne =ir,s *) Len(i$ statement 5 # statement 6 # statement 7 # 6

2ere, state*ents ', 2, - and 4 wo#ld get co*piled only i the *acro 3K1C has been de ined, and we have p#rpose #lly o*itted the de inition o the *acro 3K1CG 1t a later date, i we want that these state*ents sho#ld also get co*piled all that we are reH#ired to do is to delete the Ii8de8 and Iendi8 state*entsG >b? 1 *ore sophisticated #se o Ii8de8 has to do with *a9ing the progra*s portable, iGeG to *a9e the* wor9 on two totally di erent co*p#tersG S#ppose an organi;ation has two

Chapter ;0 The C #reprocessor

257

di erent types o co*p#ters and yo# are e/pected to write a progra* that wor9s on both the *achinesG Co# can do so by isolating the lines o code that *#st be di erent or each *achine by *ar9ing the* o with Ii8de8G +or e/a*pleP
main1 2 3 Li$(e$ IE8EO '!(e s,ita&%e $!r a Inte% ?+ Le%se '!(e s,ita&%e $!r a P!t!r!%a ?+ Len(i$ '!(e '!mm!n t! &!th the '!m ,ters 6

When yo# co*pile this progra* it wo#ld co*pile only the code s#itable or a $ntel ,C and the co**on codeG This is beca#se the *acro $)T.7 has not been de inedG )ote that the wor9ing o Ii8de8 @ Ielse @ Iendi8 is si*ilar to the ordinary i8 @ else control instr#ction o CG $ yo# want to r#n yo#r progra* on a 5otorola ,C, Q#st add a state*ent at the top saying,
L(e$ine IE8EO

So*eti*es, instead o Ii8de8 the Ii8nde8 directive is #sedG The Ii8nde8 >which *eans Di not de ined@? wor9s e/actly opposite to Ii8de8G The above e/a*ple i written #sing Ii8nde8, wo#ld loo9 li9e thisP
main1 2 3 Li$n(e$ IE8EO '!(e s,ita&%e $!r a Inte% ?+ Le%se '!(e s,ita&%e $!r a P!t!r!%a ?+

25&
Len(i$ '!(e '!mm!n t! &!th the '!m ,ters 6

%et .s C

>c? S#ppose a #nction 1#8unc= > is de ined in a ile D*y ileGh@ which is Iincluded in a ile D*y ile'Gh@G )ow in yo#r progra* ile i yo# Iinclude both D*y ileGh@ and D*y ile'Gh@ the co*piler lashes an error D5#ltiple declaration or 1#8uncOG This is beca#se the sa*e ile D*y ileGh@ gets incl#ded twiceG To avoid this we can write ollowing code in the header ileG
)* m/$i%e.h *) Li$n(e$ m/$i%e_h L(e$ine m/$i%e_h m/$,n'1 2 3 )* s!me '!(e *) 6 Len(i$

+irst ti*e the ile D*y ileGh@ gets incl#ded the preprocessor chec9s whether a *acro called 1#8ile:h has been de ined or notG $ it has not been then it gets de ined and the rest o the code gets incl#dedG )e/t ti*e we atte*pt to incl#de the sa*e ile, the incl#sion is prevented since 1#8ile:h already stands de inedG )ote that there is nothing special abo#t 1#8ile:hG $n its place we can #se any other *acro as wellG

#if and #elif Directi%es


The Ii8 directive can be #sed to test whether an e/pression eval#ates to a non;ero val#e or notG $ the res#lt o the e/pression is non;ero, then s#bseH#ent lines #pto a Ielse, Ieli8 or Iendi8 are co*piled, otherwise they are s9ippedG

Chapter ;0 The C #reprocessor


1 si*ple e/a*ple o Ii8 directive is shown belowP
main1 2 3 Li$ 8E78 ;= 5 statement 1 # statement 2 # statement 3 # Le%se statement 4 # statement 5 # statement 6 # Len(i$ 6

259

$ the e/pression, TBST JF 5 eval#ates to tr#e then state*ents ', 2 and - are co*piled otherwise state*ents 4, 5 and 6 are co*piledG $n place o the e/pression TBST JF 5 other e/pressions li9e = LB5BL FF 2*G2 RR LB5BL FF L(/ > or 'D'!TB$ FF CG' can also be #sedG $ we so desire we can have nested conditional co*pilation directivesG 1n e/a*ple that #ses s#ch directives is shown belowG
Li$ A0A?8E> == ]JA '!(e $!r =i(e! -ra hi's arra/ Le%se Li$ A0A?8E> == 7]JA '!(e $!r s, er =i(e! -ra hi's arra/ Le%se '!(e $!r exten(e( -ra hi's a(a ter Len(i$ Len(i$

The above progra* seg*ent can be *ade *ore co*pact by #sing another conditional co*pilation directive called Ieli8G The sa*e progra* #sing this directive can be rewritten as shown belowG

2")

%et .s C

3bserve that by #sing the Ieli8 directives the n#*ber o Mendi8s #sed in the progra* get red#cedG
Li$ A0A?8E> == ]JA '!(e $!r =i(e! -ra hi's arra/ Le%i$ A0A?8E> == 7]JA '!(e $!r s, er =i(e! -ra hi's arra/ Le%se '!(e $!r exten(e( -ra hi's a(a ter Len(i$

,iscellaneous Directi%es
There are two *ore preprocessor directives available, tho#gh they are not very co**only #sedG They areP >a? M#nde >b? Mprag*a

#undef Directi%e
3n so*e occasions it *ay be desirable to ca#se a de ined na*e to beco*e D#nde ined@G This can be acco*plished by *eans o the Iunde8 directiveG $n order to #nde ine a *acro that has been earlier Ide8ined, the directive,
L,n(e$ ma'r! tem %ate

can be #sedG Th#s the state*ent,


L,n(e$ ?EE8IXP

wo#ld ca#se the de inition o ,.)T$65 to be re*oved ro* the syste*G 1ll s#bseH#ent Ii8de8 !B9T*., state*ents wo#ld eval#ate to alseG $n practice seldo* are yo# reH#ired to #nde ine a *acro, b#t or so*e reason i yo# are reH#ired to, then yo# 9now that there is so*ething to all bac9 #ponG

Chapter ;0 The C #reprocessor

2"1

#pragma Directi%e
This directive is another special<p#rpose directive that yo# can #se to t#rn on or o certain eat#resG ,rag*as vary ro* one co*piler to anotherG There are certain prag*as available with 5icroso t C co*piler that deal with or*atting so#rce listings and placing co**ents in the obQect ile generated by the co*pilerG T#rbo C=CL L co*piler has got a prag*a that allows yo# to s#ppress warnings generated by the co*pilerG So*e o these prag*as are disc#ssed belowG >a? Iprag1a startup and Iprag1a e3itD These directives allow #s to speci y #nctions that are called #pon progra* start#p >be ore 1ain= >? or progra* e/it >Q#st be ore the progra* ter*inates?G Their #sage is as ollowsP
=!i( $,n11 2 # =!i( $,n21 2 # L ra-ma start, $,n1 L ra-ma exit $,n2 main1 2 3 rint$ 1 4@nInsi(e maim4 2 # 6 =!i( $,n11 2 3 rint$ 1 4@nInsi(e $,n14 2 # 6 =!i( $,n21 2 3 rint$ 1 4@nInsi(e $,n24 2 # 6

2"2
1nd here is the o#tp#t o the progra*G
Insi(e $,n1 Insi(e main Insi(e $,n2

%et .s C

)ote that the #nctions 8un1= > and 8un2= > sho#ld neither receive nor ret#rn any val#eG $ we want two #nctions to get e/ec#ted at start#p then their prag*as sho#ld be de ined in the reverse order in which yo# want to get the* calledG >b? Iprag1a 0arnD This directive tells the co*piler whether or not we want to s#ppress a speci ic warningG 6sage o this prag*a is shown belowG
L ra-ma Farn Ar=% )* ret,rn =a%,e *) L ra-ma Farn A ar )* arameter n!t ,se( *) L ra-ma Farn Ar'h )* ,nrea'ha&%e '!(e *) int $11 2 3 int a = 5 # 6 =!i( $2 1 int x 2 3 rint$ 1 4@nInsi(e $24 2 # 6 int $31 2 3 int x = 6 # ret,rn x # x++ # 6 =!i( main1 2

Chapter ;0 The C #reprocessor


3 $11 2 # $2 1 7 2 # $31 2 #

2"3

$ yo# go thro#gh the progra* yo# can notice three proble*s i**ediatelyG These areP >a? Tho#gh pro*ised, 81= > doesn@t ret#rn a val#eG >b? The para*eter 3 that is passed to 82= > is not being #sed anywhere in 82= >G >c? The control can never reach 3?? in 83= >G $ we co*pile the progra* we sho#ld e/pect warnings indicating the above proble*sG 2owever, this does not happen since we have s#ppressed the warnings #sing the Iprag1a directivesG $ we replace the DF@ sign with a DL@ then these warnings wo#ld be lashed on co*pilationG Tho#gh it is a bad practice to s#ppress warnings, at ti*es it beco*es #se #l to s#ppress the*G +or e/a*ple, i yo# have written a h#ge progra* and are trying to co*pile it, then to begin with yo# are *ore interested in locating the errors, rather than the warningsG 1t s#ch ti*es yo# *ay s#ppress the warningsG 3nce yo# have located all errors, then yo# *ay t#rn on the warnings and sort the* o#tG

Su11ar#
>a? The preprocessor directives enable the progra**er to write progra*s that are easy to develop, read, *odi y and transport to a di erent co*p#ter syste*G

2"4

%et .s C

>b? We can *a9e #se o vario#s preprocessor directives s#ch as Ide8ine, Iinclude, Ii8de8 < Ielse < Iendi8, Ii8 and Ieli8 in o#r progra*G >c? The directives li9e Iunde8 and Iprag1a are also #se #l altho#gh they are seldo* #sedG

B3ercise
K'L 1nswer the ollowingP

>a? What is a preprocessor directive 'G 2G -G 4G a *essage a *essage a *essage a *essage ro* co*piler to the progra**er ro* co*piler to the lin9er ro* progra**er to the preprocessor ro* progra**er to the *icroprocessor ollowing are correctly or*ed Ide8ine

>b? Which o the state*entsP


L(e$ine L(e$ine L(e$ine L(e$ine

IE+U ?E> IEE8 12 7Y> 1\2 1 \ * \ 2 7Y>1\2 \ * \ 7Y>1\2 1 \ * \ 2

>c? State Tr#e or +alseP 'G 1 *acro *#st always be written in capital lettersG 2G 1 *acro sho#ld always be acco*odated in a single lineG -G 1 ter preprocessing when the progra* is sent or co*pilation the *acros are re*oved ro* the e/panded so#rce codeG 4G 5acros with arg#*ents are not allowedG 5G )ested *acros are allowedG 6G $n a *acro call the control is passed to the *acroG

Chapter ;0 The C #reprocessor

2"5

>d? 2ow *any Iinclude directives can be there in a given progra* ilec >e? What is the di erence between the ollowing two Iinclude directivesP
Lin'%,(e 4'!ni!.h4 Lin'%,(e ;'!ni!.h<

> ? 1 header ile isP 'G 2G -G 4G 1 1 1 1 ile that contains standard library #nctions ile that contains de initions and *acros ile that contains #ser < de ined #nctions ile that is present in c#rrent wor9ing directory

>g? Which o the ollowing is not a preprocessor directive 'G 2G -G 4G 'G 2G -G 4G Mi Melsei M#nde Mprag*a 8e ore co*pilation o the progra* 1 ter co*pilation 0#ring e/ec#tion )one o the above

>h? 1ll *acro s#bstit#tions in a progra* are done

>i? $n a progra* the state*entP


Lin'%,(e 4$i%ename4

is replaced by the contents o the ile K ilena*eO 'G 2G -G 4G 8e ore co*pilation 1 ter Co*pilation 0#ring e/ec#tion )one o the above

2""
1a2 main1 2 3 int i = 2 # Li$(e$ 0EI i *= i # Le%se rint$ 1 4@n5(4" i 2 # Len(i$ 6 1&2 L(e$ine ?>Q0X+81x2 1 x * x 2 main1 2 3 int i = 3" 9 # 9 = ?>Q0X+81 i + 1 2 # rint$ 1 4@n5(4" 9 2 # 6 1'2 L(e$ine ?>Q0X+81x2 1 x * x 2 main1 2 3 int i = 3" 9" . # 9 = ?>Q0X+81 i++ 2 # . = ?>Q0X+8 1 ++i 2 # rint$ 1 4@n5( 5(4" 9" . 2 # 6 1(2 L (e$ine 7EPI # main12 3 int = 3 7EPI # rint$ 1 45(4" 2 7EPI 6

%et .s C

K-L What wo#ld be the o#tp#t o the ollowing progra*P

Chapter ;0 The C #reprocessor


KCL 1tte*pt the ollowingP

2"7

>a? Write down *acro de initions or the ollowingP 'G To test whether a character entered is a s*all case letter or notG 2G To test whether a character entered is a #pper case letter or notG -G To test whether a character is an alphabet or notG 5a9e #se o the *acros yo# de ined in >'? and >2? aboveG 4G To obtain the bigger o two n#*bersG >b? Write *acro de initions with arg#*ents or calc#lation o area and peri*eter o a triangle, a sH#are and a circleG Store these *acro de initions in a ile called KareaperiGhOG $ncl#de this ile in yo#r progra*, and call the *acro de initions or calc#lating area and peri*eter or di erent sH#ares, triangles and circlesG >c? Write down *acro de initions or the ollowingP 'G 2G -G 4G To ind arith*etic *ean o two n#*bersG To ind absol#te val#e o a n#*berG To convert a #ppercase alphabet to lowercaseG To obtain the bigger o two n#*bersG

>d? Write *acro de initions with arg#*ents or calc#lation o Si*ple $nterest and 1*o#ntG Store these *acro de initions in a ile called KinterestGhOG $ncl#de this ile in yo#r progra*, and #se the *acro de initions or calc#lating si*ple interest and a*o#ntG

2"&

%et .s C

$rrays
e What are 1rrays 1 Si*ple ,rogra* 6sing 1rray e 5ore on 1rrays 1rray $nitialisation 8o#nds Chec9ing ,assing 1rray .le*ents to a +#nction e ,ointers and 1rrays ,assing an .ntire 1rray to a +#nction The "eal Thing e Two 0i*ensional 1rrays $nitialising a 2<0i*ensional 1rray 5e*ory 5ap o a 2<0i*ensional 1rray ,ointers and 2<0i*ensional 1rrays ,ointer to an 1rray ,assing 2<0 1rray to a +#nction e 1rray o ,ointers e Three<0i*ensional 1rray e S#**ary e ./ercise

2"9

27)

%et .s C
he C lang#age provides a capability that enables the #ser to design a set o si*ilar data types, called arrayG This chapter describes how arrays can be created and *anip#lated in CG

We sho#ld note that, in *any C boo9s and co#rses arrays and pointers are ta#ght separatelyG $ eel it is worthwhile to deal with these topics togetherG This is beca#se pointers and arrays are so closely related that disc#ssing arrays witho#t disc#ssing pointers wo#ld *a9e the disc#ssion inco*plete and wantingG $n act all arrays *a9e #se o pointers internallyG 2ence it is all too relevant to st#dy the* together rather than as isolated topicsG

/hat are 'rra#s


+or #nderstanding the arrays properly, let #s consider the ollowing progra*P
main1 2 3 int x # x=5# x = 10 # rint$ 1 4@nx = 5(4" x 2 # 6

)o do#bt, this progra* will print the val#e o 3 as '(G Why soc 8eca#se when a val#e '( is assigned to 3, the earlier val#e o 3, iGeG 5, is lostG Th#s, ordinary variables >the ones which we have #sed so ar? are capable o holding only one val#e at a ti*e >as in the above e/a*ple?G 2owever, there are sit#ations in which we wo#ld want to store *ore than one val#e at a ti*e in a single variableG +or e/a*ple, s#ppose we wish to arrange the percentage *ar9s obtained by '(( st#dents in ascending orderG $n s#ch a case we have two options to store these *ar9s in *e*oryP

Chapter <0 !rrays

271

>a? Constr#ct '(( variables to store percentage *ar9s obtained by '(( di erent st#dents, iGeG each variable containing one st#dent@s *ar9sG >b? Constr#ct one variable >called array or s#bscripted variable? capable o storing or holding all the h#ndred val#esG 3bvio#sly, the second alternative is betterG 1 si*ple reason or this is, it wo#ld be *#ch easier to handle one variable than handling '(( di erent variablesG 5oreover, there are certain logics that cannot be dealt with, witho#t the #se o an arrayG )ow a or*al de inition o an arrayR1n array is a collective na*e given to a gro#p o Dsi*ilar H#antities@G These si*ilar H#antities co#ld be percentage *ar9s o '(( st#dents, or salaries o -(( e*ployees, or ages o 5( e*ployeesG What is i*portant is that the H#antities *#st be Dsi*ilar@G .ach *e*ber in the gro#p is re erred to by its position in the gro#pG +or e/a*ple, ass#*e the ollowing gro#p o n#*bers, which represent percentage *ar9s obtained by ive st#dentsG
er = 3 48" 88" 34" 23" 96 6

$ we want to re er to the second n#*ber o the gro#p, the #s#al notation #sed is per2G Si*ilarly, the o#rth n#*ber o the gro#p is re erred as per4G 2owever, in C, the o#rth n#*ber is re erred as perK3L. This is beca#se in C the co#nting o ele*ents begins with ( and not with 'G Th#s, in this e/a*ple perK3L re ers to 2- and perK4L re ers to &6G $n general, the notation wo#ld be perKiL, where, i can ta9e a val#e (, ', 2, -, or 4, depending on the position o the ele*ent being re erredG 2ere per is the s#bscripted variable >array?, whereas i is its s#bscriptG Th#s, an array is a collection o si*ilar ele*entsG These si*ilar ele*ents co#ld be all ints, or all 8loats, or all chars, etcG 6s#ally, the array o characters is called a Dstring@, whereas an array o ints or 8loats is called si*ply an arrayG "e*e*ber that all ele*ents o

272

%et .s C

any given array *#st be o the sa*e typeG iGeG we cannot have an array o '( n#*bers, o which 5 are ints and 5 are 8loatsG

' Si1ple !rogra1 .sing 'rra#


7et #s try to write a progra* to ind average *ar9s obtained by a class o -( st#dents in a testG
main1 2 3 int a=-" s,m = 0 # int i # int mar.s^30` # )* arra/ (e'%arati!n *) $!r 1 i = 0 # i ;= 29 # i++ 2 3 rint$ 1 4@nEnter mar.s 4 2 # s'an$ 1 45(4" Bmar.s^i` 2 # )* st!re (ata in arra/ *) 6 $!r 1 i = 0 # i ;= 29 # i++ 2 s,m = s,m + mar.s^i` # )* rea( (ata $r!m an arra/*) a=- = s,m ) 30 # rint$ 1 4@nA=era-e mar.s = 5(4" a=- 2 # 6

There is a lot o new *aterial in this progra*, so let #s ta9e it apart slowlyG 'rra# Declaration To begin with, li9e other variables an array needs to be declared so that the co*piler will 9now what 9ind o an array and how large an array we wantG $n o#r progra* we have done this with the state*entP

Chapter <0 !rrays


int mar.s^30` #

273

2ere, int speci ies the type o the variable, Q#st as it does with ordinary variables and the word 1arGs speci ies the na*e o the variableG The K3)L however is newG The n#*ber -( tells how *any ele*ents o the type int will be in o#r arrayG This n#*ber is o ten called the Ddi*ension@ o the arrayG The brac9et > ] ^ ? tells the co*piler that we are dealing with an arrayG 'ccessing Ble1ents o8 an 'rra# 3nce an array is declared, let #s see how individ#al ele*ents in the array can be re erredG This is done with s#bscript, the n#*ber in the brac9ets ollowing the array na*eG This n#*ber speci ies the ele*ent@s position in the arrayG 1ll the array ele*ents are n#*bered, starting with (G Th#s, 1arGsK2L is not the second ele*ent o the array, b#t the thirdG $n o#r progra* we are #sing the variable i as a s#bscript to re er to vario#s ele*ents o the arrayG This variable can ta9e di erent val#es and hence can re er to the di erent ele*ents in the array in t#rnG This ability to #se variables as s#bscripts is what *a9es arrays so #se #lG Bntering Data into an 'rra# 2ere is the section o code that places data into an arrayP
$!r 1 i = 0 # i ;= 29 # i++ 2 3 rint$ 1 4@nEnter mar.s 4 2 # s'an$ 1 45(4" Bmar.s^i` 2 # 6

The 8or loop ca#ses the process o as9ing or and receiving a st#dent@s *ar9s ro* the #ser to be repeated -( ti*esG The irst ti*e thro#gh the loop, i has a val#e (, so the scan8= > #nction will ca#se the val#e typed to be stored in the array ele*ent 1arGsK)L4 the irst ele*ent o the arrayG This process will be repeated #ntil i

274

%et .s C

beco*es 2&G This is last ti*e thro#gh the loop, which is a good thing, beca#se there is no array ele*ent li9e 1arGsK3)LG $n scan8= > #nction, we have #sed the Kaddress o O operator >I? on the ele*ent 1arGsKiL o the array, Q#st as we have #sed it earlier on other variables = rate, or e/a*ple?G $n so doing, we are passing the address o this partic#lar array ele*ent to the scan8= > #nction, rather than its val#e_ which is what scan8= > reH#iresG $eading Data 8ro1 an 'rra# The balance o the progra* reads the data bac9 o#t o the array and #ses it to calc#late the averageG The 8or loop is *#ch the sa*e, b#t now the body o the loop ca#ses each st#dent@s *ar9s to be added to a r#nning total stored in a variable called su1G When all the *ar9s have been added #p, the res#lt is divided by -(, the n#*ber o st#dents, to get the averageG
$!r 1 i = 0 # i ;= 29 # i++ 2 s,m = s,m + mar.s^i` # a=- = s,m ) 30 # rint$ 1 4@nA=era-e mar.s = 5(4" a=- 2 #

To i/ o#r ideas, let #s revise whatever we have learnt abo#t arraysP >a? 1n array is a collection o si*ilar ele*entsG >b? The irst ele*ent in the array is n#*bered (, so the last ele*ent is ' less than the si;e o the arrayG >c? 1n array is also 9nown as a s#bscripted variableG >d? 8e ore #sing an array its type and di*ension *#st be declaredG >e? 2owever big an array its ele*ents are always stored in contig#o#s *e*ory locationsG This is a very i*portant point which we wo#ld disc#ss in *ore detail later onG

Chapter <0 !rrays

275

,ore on 'rra#s
1rray is a very pop#lar data type with C progra**ersG This is beca#se o the convenience with which arrays lend the*selves to progra**ingG The eat#res which *a9e arrays so convenient to progra* wo#ld be disc#ssed below, along with the possible pit alls in #sing the*G

'rra# *nitialisation
So ar we have #sed arrays that did not have any val#es in the* to begin withG We *anaged to store val#es in the* d#ring progra* e/ec#tionG 7et #s now see how to initiali;e an array while declaring itG +ollowing are a ew e/a*ples that de*onstrate thisG
int n,m^6` = 3 2" 4" 12" 5" 45" 5 6 # int n^ ` = 3 2" 4" 12" 5" 45" 5 6 # $%!at ress^ ` = 3 12.3" 34.2 -23.4" -11.3 6 #

)ote the ollowing points care #llyP >a? Till the array ele*ents are not given any speci ic val#es, they are s#pposed to contain garbage val#esG >b? $ the array is initialised where it is declared, *entioning the di*ension o the array is optional as in the 2nd e/a*ple aboveG 'rra# Ble1ents in ,e1or# Consider the ollowing array declarationP
int arr^8` #

What happens in *e*ory when we *a9e this declarationc '6 bytes get i**ediately reserved in *e*ory, 2 bytes each or the % integers >#nder Windows=7in#/ the array wo#ld occ#py -2 bytes

27"

%et .s C

as each integer wo#ld occ#py 4 bytes?G 1nd since the array is not being initiali;ed, all eight val#es present in it wo#ld be garbage val#esG This so happens beca#se the storage class o this array is ass#*ed to be autoG $ the storage class is declared to be static then all the array ele*ents wo#ld have a de a#lt initial val#e as ;eroG Whatever be the initial val#es, all the array ele*ents wo#ld always be present in contig#o#s *e*ory locationsG This arrange*ent o array ele*ents in *e*ory is shown in +ig#re %G'G

'2

-4

66

<45

2-

-46

!!

&(

655(% 655'( 655'2 655'4 655'6

655'% 6552( 65522

+ig#re %G'

-ounds ChecGing
$n C there is no chec9 to see i the s#bscript #sed or an array e/ceeds the si;e o the arrayG 0ata entered with a s#bscript e/ceeding the array si;e will si*ply be placed in *e*ory o#tside the array_ probably on top o other data, or on the progra* itsel G This will lead to #npredictable res#lts, to say the least, and there will be no error *essage to warn yo# that yo# are going beyond the array si;eG $n so*e cases the co*p#ter *ay Q#st hangG Th#s, the ollowing progra* *ay t#rn o#t to be s#icidalG
main1 2 3 int n,m^40`" i # $!r 1 i = 0 # i ;= 100 # i++ 2 n,m^i` = i # 6

Chapter <0 !rrays

277

Th#s, to see to it that we do not reach beyond the array si;e is entirely the progra**er@s botheration and not the co*piler@sG

!assing 'rra# Ble1ents to a Function


1rray ele*ents can be passed to a #nction by calling the #nction by val#e, or by re erenceG $n the call by val#e we pass val#es o array ele*ents to the #nction, whereas in the call by re erence we pass addresses o array ele*ents to the #nctionG These two calls are ill#strated belowP
)* 0em!nstrati!n !$ 'a%% &/ =a%,e *) main1 2 3 int i # int mar.s^ ` = 3 55" 65" 75" 56" 78" 78" 90 6 # $!r 1 i = 0 # i ;= 6 # i++ 2 (is %a/ 1 mar.s^i` 2 # 6 (is %a/ 1 int m 2 3 rint$ 1 45( 4" m 2 # 6

1nd here@s the o#tp#tGGG


55 65 75 56 78 78 90

2ere, we are passing an individ#al array ele*ent at a ti*e to the #nction displa#= > and getting it printed in the #nction displa#= >. )ote that since at a ti*e only one ele*ent is being passed, this ele*ent is collected in an ordinary integer variable 1, in the #nction displa#= >G 1nd now the call by re erenceG

27&
)* 0em!nstrati!n !$ 'a%% &/ re$eren'e *) main1 2 3 int i # int mar.s^ ` = 3 55" 65" 75" 56" 78" 78" 90 6 # $!r 1 i = 0 # i ;= 6 # i++ 2 (is 1 Bmar.s^i` 2 # 6 (is 1 int *n 2 3 rint$ 1 45( 4" *n 2 # 6

%et .s C

1nd here@s the o#tp#tGGG


55 65 75 56 78 78 90

2ere, we are passing addresses o individ#al array ele*ents to the #nction displa#= >G 2ence, the variable in which this address is collected >n? is declared as a pointer variableG 1nd since n contains the address o array ele*ent, to print o#t the array ele*ent we are #sing the Dval#e at address@ operator =<>G "ead the ollowing progra* care #llyG The p#rpose o the #nction disp= > is Q#st to display the array ele*ents on the screenG The progra* is only partly co*pleteG Co# are reH#ired to write the #nction sho0= > on yo#r ownG Try yo#r hand at itG
main1 2 3 int i # int mar.s^ ` = 3 55" 65" 75" 56" 78" 78" 90 6 # $!r 1 i = 0 # i ;= 6 # i++ 2 (is 1 Bmar.s^i` 2 #

Chapter <0 !rrays


6 (is 1 int *n 2 3 sh!F 1 Bn 2 # 6

279

!ointers and 'rra#s


To be able to see what pointers have got to do with arrays, let #s irst learn so*e pointer arith*eticG Consider the ollowing e/a*pleP
main1 2 3 int i = 3" *x # $%!at 9 = 1.5" */ # 'har . = '''" *: # rint$ 1 4@n]a%,e !$ i = 5(4" i 2 # rint$ 1 4@n]a%,e !$ 9 = 5$4" 9 2 # rint$ 1 4@n]a%,e !$ . = 5'4" . 2 # x = Bi # / = B9 # : = B. # rint$ 1 4@nQri-ina% a((ress in x = 5,4" x 2 # rint$ 1 4@nQri-ina% a((ress in / = 5,4" / 2 # rint$ 1 4@nQri-ina% a((ress in : = 5,4" : 2 # x++ # /++ # :++ # rint$ 1 4@nEeF a((ress in x = 5,4" x 2 # rint$ 1 4@nEeF a((ress in / = 5,4" / 2 # rint$ 1 4@nEeF a((ress in : = 5,4" : 2 # 6

2ere is the o#tp#t o the progra*G

2&)
]a%,e !$ i = 3 ]a%,e !$ 9 = 1.500000 ]a%,e !$ . = ' Qri-ina% a((ress in x = 65524 Qri-ina% a((ress in / = 65520 Qri-ina% a((ress in : = 65519 EeF a((ress in x = 65526 EeF a((ress in / = 65524 EeF a((ress in : = 65520

%et .s C

3bserve the last three lines o the o#tp#tG 65526 is original val#e in 3 pl#s 2, 65524 is original val#e in # pl#s 4, and 6552( is original val#e in H pl#s 'G This so happens beca#se every ti*e a pointer is incre*ented it points to the i**ediately ne/t location o its typeG That is why, when the integer pointer 3 is incre*ented, it points to an address two locations a ter the c#rrent location, since an int is always 2 bytes long >#nder Windows=7in#/ since int is 4 bytes long, new val#e o 3 wo#ld be 6552%?G Si*ilarly, # points to an address 4 locations a ter the c#rrent location and H points ' location a ter the c#rrent locationG This is a very i*portant res#lt and can be e ectively #sed while passing the entire array to a #nctionG The way a pointer can be incre*ented, it can be decre*ented as well, to point to earlier locationsG Th#s, the ollowing operations can be per or*ed on a pointerP >a? 1ddition o a n#*ber to a pointerG +or e/a*ple,
int i = 4" *9" *. # 9 = Bi # 9=9+1# 9=9+9# .=9+3#

>b? S#btraction o a n#*ber ro* a pointerG +or e/a*ple,

Chapter <0 !rrays


int i = 4" *9" *. # 9 = Bi # 9=9-2#9 =9-5#. =9-6#

2&1

>c? S#btraction o one pointer ro* anotherG 3ne pointer variable can be s#btracted ro* another provided both variables point to ele*ents o the sa*e arrayG The res#lting val#e indicates the n#*ber o bytes separating the corresponding array ele*entsG This is ill#strated in the ollowing progra*G
main1 2 3 int arr^ ` = 3 10" 20" 30" 45" 67" 56" 74 6 # int *i" *9 # i = Barr^1` # 9 = Barr^5` # rint$ 1 45( 5(4" 9 - i" *9 - *i 2 # 6

2ere i and W have been declared as integer pointers holding addresses o irst and i th ele*ent o the array respectivelyG S#ppose the array begins at location 655(2, then the ele*ents arrK1L and arrK5L wo#ld be present at locations 655(4 and 655'2 respectively, since each integer in the array occ#pies two bytes in *e*oryG The e/pression W @ i wo#ld print a val#e 4 and not %G This is beca#se W and i are pointing to locations that are 4 integers apartG What wo#ld be the res#lt o the e/pression <W @ <ic -6, since <W and <i ret#rn the val#es present at addresses contained in the pointers W and iG >d? Co*parison o two pointer variables

2&2

%et .s C

,ointer variables can be co*pared provided both variables point to obQects o the sa*e data typeG S#ch co*parisons can be #se #l when both pointer variables point to ele*ents o the sa*e arrayG The co*parison can test or either eH#ality or ineH#alityG 5oreover, a pointer variable can be co*pared with ;ero >#s#ally e/pressed as )677?G The ollowing progra* ill#strates how the co*parison is carried o#tG
main1 2 3 int arr^ ` = 3 10" 20" 36" 72" 45" 36 6 # int *9" *. # 9 = Barr ^ 4 ` # . = 1 arr + 4 2 # i$ 1 9 == . 2 rint$ 1 48he tF! !inters !int t! the same %!'ati!n4 2 # e%se rint$ 1 48he tF! !inters (! n!t !int t! the same %!'ati!n4 2 #

1 word o ca#tion4 0o not atte*pt the ollowing operations on pointersGGG they wo#ld never wor9 o#tG >a? 1ddition o two pointers >b? 5#ltiplication o a pointer with a constant >c? 0ivision o a pointer with a constant )ow we will try to correlate the ollowing two acts, which we have learnt aboveP >a? 1rray ele*ents are always stored in contig#o#s *e*ory locationsG >b? 1 pointer when incre*ented always points to an i**ediately ne/t location o its typeG

Chapter <0 !rrays

2&3

S#ppose we have an array nu1K L X [ 24, -4, '2, 44, 56, '! \G The ollowing ig#re shows how this array is located in *e*oryG

24 655'2

-4 655'4

'2

44

56 6552(

'!

655'6

655'%

65522

+ig#re %G2 2ere is a progra* that prints o#t the *e*ory locations in which the ele*ents o this array are storedG
main1 2 3 int n,m^ ` = 3 24" 34" 12" 44" 56" 17 6 # int i # $!r 1 i = 0 # i ;= 5 # i++ 2 3 rint$ 1 4@ne%ement n!. 5( 4" i 2 # rint$ 1 4a((ress = 5,4" Bn,m^i` 2 # 6 6

The o#tp#t o this progra* wo#ld loo9 li9e thisP


e%ement n!. 0 a((ress = 65512 e%ement n!. 1 a((ress = 65514 e%ement n!. 2 a((ress = 65516 e%ement n!. 3 a((ress = 65518 e%ement n!. 4 a((ress = 65520 e%ement n!. 5 a((ress = 65522

)ote that the array ele*ents are stored in contig#o#s *e*ory locations, each ele*ent occ#pying two bytes, since it is an integer

2&4

%et .s C

arrayG When yo# r#n this progra*, yo# *ay get di erent addresses, b#t what is certain is that each s#bseH#ent address wo#ld be 2 bytes >4 bytes #nder Windows=7in#/? greater than its i**ediate predecessorG 3#r ne/t two progra*s show ways in which we can access the ele*ents o this arrayG
main1 2 3 int n,m^ ` = 3 24" 34" 12" 44" 56" 17 6 # int i # $!r 1 i = 0 # i ;= 5 # i++ 2 3 rint$ 1 4@na((ress = 5, 4" Bn,m^i` 2 # rint$ 1 4e%ement = 5(4" n,m^i` 2 # 6 6

The o#tp#t o this progra* wo#ld beP


a((ress = 65512 e%ement = 24 a((ress = 65514 e%ement = 34 a((ress = 65516 e%ement = 12 a((ress = 65518 e%ement = 44 a((ress = 65520 e%ement = 56 a((ress = 65522 e%ement = 17

This *ethod o accessing array ele*ents by #sing s#bscripted variables is already 9nown to #sG This *ethod has in act been given here or easy co*parison with the ne/t *ethod, which accesses the array ele*ents #sing pointersG
main1 2 3 int n,m^ ` = 3 24" 34" 12" 44" 56" 17 6 #

Chapter <0 !rrays


int i" *9 # 9 = Bn,m^0` # )* assi-n a((ress !$ :er!th e%ement *) $!r 1 i = 0 # i ;= 5 # i++ 2 3 rint$ 1 4@na((ress = 5, 4" 9 2 # rint$ 1 4e%ement = 5(4" *9 2 # 9++ # )* in'rement !inter t! !int t! next %!'ati!n *) 6 6

2&5

The o#tp#t o this progra* wo#ld beP


a((ress = 65512 e%ement = 24 a((ress = 65514 e%ement = 34 a((ress = 65516 e%ement = 12 a((ress = 65518 e%ement = 44 a((ress = 65520 e%ement = 56 a((ress = 65522 e%ement = 17

$n this progra*, to begin with we have collected the base address o the array >address o the (th ele*ent? in the variable W #sing the state*ent,
9 = Bn,m^0` # )* assi-ns a((ress 65512 t! 9 *)

When we are inside the loop or the irst ti*e, W contains the address 655'2, and the val#e at this address is 24G These are printed #sing the state*ents,
rint$ 1 4@na((ress = 5, 4" 9 2 # rint$ 1 4e%ement = 5(4" *9 2 #

3n incre*enting W it points to the ne/t *e*ory location o its type >that is location noG 655'4?G 8#t location noG 655'4 contains the second ele*ent o the array, there ore when the print8= >

2&"

%et .s C

state*ents are e/ec#ted or the second ti*e they print o#t the second ele*ent o the array and its address >iGeG -4 and 655'4?GGG and so on till the last ele*ent o the array has been printedG 3bvio#sly, a H#estion arises as to which o the above two *ethods sho#ld be #sed whenc 1ccessing array ele*ents by pointers is al0a#s aster than accessing the* by s#bscriptsG 2owever, ro* the point o view o convenience in progra**ing we sho#ld observe the ollowingP 1rray ele*ents sho#ld be accessed #sing pointers i the ele*ents are to be accessed in a i/ed order, say ro* beginning to end, or ro* end to beginning, or every alternate ele*ent or any s#ch de inite logicG $nstead, it wo#ld be easier to access the ele*ents #sing a s#bscript i there is no i/ed logic in accessing the ele*entsG 2owever, in this case also, accessing the ele*ents by pointers wo#ld wor9 aster than s#bscriptsG

!assing an Bntire 'rra# to a Function


$n the previo#s section we saw two progra*sRone in which we passed individ#al ele*ents o an array to a #nction, and another in which we passed addresses o individ#al ele*ents to a #nctionG 7et #s now see how to pass an entire array to a #nction rather than its individ#al ele*entsG Consider the ollowing e/a*pleP
)* 0em!nstrati!n !$ assin- an entire arra/ t! a $,n'ti!n *) main1 2 3 int n,m^ ` = 3 24" 34" 12" 44" 56" 17 6 # (is% a/ 1 Bn,m^0`" 6 2 # 6 (is %a/ 1 int *9" int n 2 3

Chapter <0 !rrays


int i # $!r 1 i = 0 # i ;= n - 1 # i++ 2 3 rint$ 1 4@ne%ement = 5(4" *9 2 # 9++ # )* in'rement !inter t! !int t! next e%ement *) 6 6

2&7

2ere, the displa#= > #nction is #sed to print o#t the array ele*entsG )ote that the address o the ;eroth ele*ent is being passed to the displa#= > #nctionG The 8or loop is sa*e as the one #sed in the earlier progra* to access the array ele*ents #sing pointersG Th#s, Q#st passing the address o the ;eroth ele*ent o the array to a #nction is as good as passing the entire array to the #nctionG $t is also necessary to pass the total n#*ber o ele*ents in the array, otherwise the displa#= > #nction wo#ld not 9now when to ter*inate the 8or loopG )ote that the address o the ;eroth ele*ent >*any a ti*es called the base address? can also be passed by Q#st passing the na*e o the arrayG Th#s, the ollowing two #nction calls are sa*eP
(is %a/ 1 Bn,m^0`" 6 2 # (is %a/ 1 n,m" 6 2 #

The $eal Thing


$ yo# have grasped the concept o storage o array ele*ents in *e*ory and the arith*etic o pointers, here is so*e real ood or tho#ghtG 3nce again consider the ollowing arrayG

24 655'2

-4 655'4

'2 655'6

44 655'%

56 6552(

'! 65522

+ig#re %G-

2&&
This is how we wo#ld declare the above array in C,
int n,m^ ` = 3 24" 34" 12" 44" 56" 17 6 #

%et .s C

We also 9now that on *entioning the na*e o the array we get its base addressG Th#s, by saying <nu1 we wo#ld be able to re er to the ;eroth ele*ent o the array, that is, 24G 3ne can easily see that <nu1 and <= nu1 ? ) > both re er to 24G Si*ilarly, by saying <= nu1 ? 1 > we can re er the irst ele*ent o the array, that is, -4G $n act, this is what the C co*piler does internallyG When we say, nu1KiL, the C co*piler internally converts it to <= nu1 ? i >G This *eans that all the ollowing notations are sa*eP
n,m^i` *1 n,m + i 2 *1 i + n,m 2 i^n,m`

1nd here is a progra* to prove *y pointG


)* A''essin- arra/ e%ements in (i$$erent Fa/s *) main1 2 3 int n,m^ ` = 3 24" 34" 12" 44" 56" 17 6 # int i # $!r 1 i = 0 # i ;= 5 # i++ 2 3 rint$ 1 4@na((ress = 5, 4" Bn,m^i` 2 # rint$ 1 4e%ement = 5( 5( 4" n,m^i`" *1 n,m + i 2 2 # rint$ 1 45( 5(4" *1 i + n,m 2" i^n,m` 2 # 6 6

The o#tp#t o this progra* wo#ld beP

Chapter <0 !rrays


a((ress = 65512 e%ement = 24 24 24 24 a((ress = 65514 e%ement = 34 34 34 34 a((ress = 65516 e%ement = 12 12 12 12 a((ress = 65518 e%ement = 44 44 44 44 a((ress = 65520 e%ement = 56 56 56 56 a((ress = 65522 e%ement = 17 17 17 17

2&9

T0o Di1ensional 'rra#s


So ar we have e/plored arrays with only one di*ensionG $t is also possible or arrays to have two or *ore di*ensionsG The two< di*ensional array is also called a *atri/G 2ere is a sa*ple progra* that stores roll n#*ber and *ar9s obtained by a st#dent side by side in a *atri/G
main1 2 3 int st,(^4`^2` # int i" 9 # $!r 1 i = 0 # i ;= 3 # i++ 2 3 rint$ 1 4@n Enter r!%% n!. an( mar.s4 2 # s'an$ 1 45( 5(4" Bst,(^i`^0`" Bst,(^i`^1` 2 # 6 $!r 1 i = 0 # i ;= 3 # i++ 2 rint$ 1 4@n5( 5(4" st,(^i`^0`" st,(^i`^1` 2 # 6

There are two parts to the progra*Rin the irst part thro#gh a 8or loop we read in the val#es o roll noG and *ar9s, whereas, in second part thro#gh another 8or loop we print o#t these val#esG 7oo9 at the scan8= > state*ent #sed in the irst 8or loopP
s'an$ 1 45( 5(4" Bst,(^i`^0`" Bst,(^i`^1` 2 #

29)

%et .s C

$n studKiLK)L and studKiLK1L the irst s#bscript o the variable stud, is row n#*ber which changes or every st#dentG The second s#bscript tells which o the two col#*ns are we tal9ing abo#tRthe ;eroth col#*n which contains the roll noG or the irst col# *n which contains the *ar9sG "e*e*ber the co#nting o rows and col#*ns begin with ;eroG The co*plete array arrange*ent is shown belowG

colG noG ( row noG ( row noG ' row noG 2 row noG '2-4 '2'2 '4-4 '-'2

colG noG '


56 -%( !%

+ig#re %G4 Th#s, '2-4 is stored in studK)LK)L, 56 is stored in studK)LK1L and so onG The above arrange*ent highlights the act that a two< di*ensional array is nothing b#t a collection o a n#*ber o one< di*ensional arrays placed one below the otherG $n o#r sa*ple progra* the array ele*ents have been stored rowwise and accessed rowwiseG 2owever, yo# can access the array ele*ents col#*nwise as wellG Traditionally, the array ele*ents are being stored and accessed rowwise_ there ore we wo#ld also stic9 to the sa*e strategyG

*nitialising a 2@Di1ensional 'rra#


2ow do we initiali;e a two<di*ensional arrayc 1s si*ple as thisGGG

Chapter <0 !rrays


int st,(^4`^2` = 3 3 1234" 56 6" 3 1212" 33 6" 3 1434" 80 6" 3 1312" 78 6 6#

291

or even this wo#ld wor9GGG


int st,(^4`^2` = 3 1234" 56" 1212" 33" 1434" 80" 1312" 78 6 #

o co#rse with a corresponding loss in readabilityG $t is i*portant to re*e*ber that while initiali;ing a 2<0 array it is necessary to *ention the second >col#*n? di*ension, whereas the irst di*ension >row? is optionalG Th#s the declarations,
int arr^2`^3` = 3 12" 34" 23" 45" 56" 45 6 # int arr^ `^3` = 3 12" 34" 23" 45" 56" 45 6 #

are per ectly acceptable, whereas,


int arr^2`^ ` = 3 12" 34" 23" 45" 56" 45 6 # int arr^ `^ ` = 3 12" 34" 23" 45" 56" 45 6 #

wo#ld never wor9G

,e1or# ,ap o8 a 2@Di1ensional 'rra#


7et #s reiterate the arrange*ent o array ele*ents in a two< di*ensional array o st#dents, which contains roll nosG in one col#*n and the *ar9s in the otherG

292

%et .s C

The array arrange*ent shown in +ig#re %G4 is only concept#ally tr#eG This is beca#se *e*ory doesn@t contain rows and col#*nsG $n *e*ory whether it is a one<di*ensional or a two<di*ensional array the array ele*ents are stored in one contin#o#s chainG The arrange*ent o array ele*ents o a two<di*ensional array in *e*ory is shown belowP

s](^](^ s](^]'^ s]'^](^ s]'^]'^ s]2^](^ s]2^]'^ s]-^](^ s]-^]'^ '2-4 655(% 56 655'( '2'2 655'2 -655'4 '4-4 655'6 %( 655'% '-'2 6552( !% 65522

+ig#re %G5 We can easily re er to the *ar9s obtained by the third st#dent #sing the s#bscript notation as shown belowP
rint$ 1 4Par.s !$ thir( st,(ent = 5(4" st,(^2`^1` 2 #

Can we not re er the sa*e ele*ent #sing pointer notation, the way we did in one<di*ensional arraysc 1nswer is yesG 3nly the proced#re is slightly di ic#lt to #nderstandG So, read onGGG

!ointers and 2@Di1ensional 'rra#s


The C lang#age e*bodies an #n#s#al b#t power #l capabilityRit can treat parts o arrays as arraysG 5ore speci ically, each row o a two<di*ensional array can be tho#ght o as a one<di*ensional arrayG This is a very i*portant act i we wish to access array ele*ents o a two<di*ensional array #sing pointersG Th#s, the declaration,
int s^5`^2` #

Chapter <0 !rrays

293

can be tho#ght o as setting #p an array o 5 ele*ents, each o which is a one<di*ensional array containing 2 integersG We re er to an ele*ent o a one<di*ensional array #sing a single s#bscriptG Si*ilarly, i we can i*agine s to be a one<di*ensional array then we can re er to its ;eroth ele*ent as sK)L, the ne/t ele*ent as sK1L and so onG 5ore speci ically, sK)L gives the address o the ;eroth one<di*ensional array, sK1L gives the address o the irst one< di*ensional array and so onG This act can be de*onstrated by the ollowing progra*G
)* 0em!: 2-0 arra/ is an arra/ !$ arra/s *) main1 2 3 int s^4`^2` = 3 3 1234" 56 6" 3 1212" 33 6" 3 1434" 80 6" 3 1312" 78 6 6# int i # $!r 1 i = 0 # i ;= 3 # i++ 2 rint$ 1 4@nA((ress !$ 5( th 1-0 arra/ = 5,4" i" s^i` 2 # 6

1nd here is the o#tp#tGGG


A((ress !$ 0 th 1-0 arra/ = 65508 A((ress !$ 1 th 1-0 arra/ = 65512 A((ress !$ 2 th 1-0 arra/ = 65516 A((ress !$ 3 th 1-0 arra/ = 65520

7et@s ig#re o#t how the progra* wor9sG The co*piler 9nows that s is an array containing 4 one<di*ensional arrays, each containing 2 integersG .ach one<di*ensional array occ#pies 4 bytes >two bytes or each integer?G These one<di*ensional arrays are placed linearly >;eroth '<0 array ollowed by irst '<0 array, etcG?G 2ence

294

%et .s C

each one<di*ensional arrays starts 4 bytes #rther along than the last one, as can be seen in the *e*ory *ap o the array shown belowG

s](^](^ s](^]'^ s]'^](^ s]'^]'^ s]2^](^ s]2^]'^ s]-^](^ s]-^]'^ '2-4 655(% 56 655'( '2'2 655'2 -655'4 '4-4 655'6 %( 655'% '-'2 6552( !% 65522

+ig#re %G6 We 9now that the e/pressions sK)L and sK1L wo#ld yield the addresses o the ;eroth and irst one<di*ensional array respectivelyG +ro* +ig#re %G6 these addresses t#rn o#t to be 655(% and 655'2G )ow, we have been able to reach each one<di*ensional arrayG What re*ains is to be able to re er to individ#al ele*ents o a one< di*ensional arrayG S#ppose we want to re er to the ele*ent sK2LK1L #sing pointersG We 9now > ro* the above progra*? that sK2L wo#ld give the address 655'6, the address o the second one<di*ensional arrayG 3bvio#sly > 655'6 L ' ? wo#ld give the address 655'%G 3r = sK2L ? 1 > wo#ld give the address 655'%G 1nd the val#e at this address can be obtained by #sing the val#e at address operator, saying <= sK2L ? 1 >G 8#t, we have already st#died while learning one<di*ensional arrays that nu1KiL is sa*e as <= nu1 ? i >G Si*ilarly, <= sK2L ? 1 > is sa*e as, <= <= s ? 2 > ? 1 >G Th#s, all the ollowing e/pressions re er to the sa*e ele*ent,
s^2`^1` * 1 s^2` + 1 2 *1*1s+22+12

Chapter <0 !rrays

295

6sing these concepts the ollowing progra* prints o#t each ele*ent o a two<di*ensional array #sing pointer notationG
)* ?!inter n!tati!n t! a''ess 2-0 arra/ e%ements *) main1 2 3 int s^4`^2` = 3 3 1234" 56 6" 3 1212" 33 6" 3 1434" 80 6" 3 1312" 78 6 6# int i" 9 # $!r 1 i = 0 # i ;= 3 # i++ 2 3 rint$ 1 4@n4 2 # $!r 1 9 = 0 # 9 ;= 1 # 9++ 2 rint$ 1 45( 4" *1 *1 s + i 2 + 9 2 2 # 6 6

1nd here is the o#tp#tGGG


1234 1212 1434 1312 56 33 80 78

!ointer to an 'rra#
$ we can have a pointer to an integer, a pointer to a loat, a pointer to a char, then can we not have a pointer to an arrayc We certainly canG The ollowing progra* shows how to b#ild and #se itG

29"
)* Xsa-e !$ !inter t! an arra/ *) main1 2 3 int s^5`^2` = 3 3 1234" 56 6" 3 1212" 33 6" 3 1434" 80 6" 3 1312" 78 6 6# int 1 * 2^2` # int i" 9" * int # $!r 1 i = 0 # i ;= 3 # i++ 2 3 = Bs^i` # int = # rint$ 1 4@n4 2 # $!r 1 9 = 0 # 9 ;= 1 # 9++ 2 rint$ 1 45( 4" *1 int + 9 2 2 # 6 6

%et .s C

1nd here is the o#tp#tGGG


1234 1212 1434 1312 56 33 80 78

2ere p is a pointer to an array o two integersG )ote that the parentheses in the declaration o p are necessaryG 1bsence o the* wo#ld *a9e p an array o 2 integer pointersG 1rray o pointers is covered in a later section in this chapterG $n the o#ter 8or loop each ti*e we store the address o a new one<di*ensional arrayG Th#s irst ti*e thro#gh this loop p wo#ld contain the address o the ;eroth '<0 arrayG This address is then assigned to an integer pointer pintG 7astly, in the inner 8or loop #sing the pointer pint we

Chapter <0 !rrays

297

have printed the individ#al ele*ents o the '<0 array to which p is pointingG 8#t why sho#ld we #se a pointer to an array to print ele*ents o a 2<0 arrayG $s there any sit#ation where we can appreciate its #sage betterc The entity pointer to an array is i**ensely #se #l when we need to pass a 2<0 array to a #nctionG This is disc#ssed in the ne/t sectionG

!assing 2@D 'rra# to a Function


There are three ways in which we can pass a 2<0 array to a #nctionG These are ill#strated in the ollowing progra*G
)* 8hree Fa/s !$ a''essin- a 2-0 arra/ *) main1 2 3 int a^3`^4` = 3 1" 2" 3" 4" 5" 6" 7" 8" 9" 0" 1" 6

6# '%rs'r1 2 # (is %a/ 1 a" 3" 4 2 # sh!F 1 a" 3" 4 2 # rint 1 a" 3" 4 2 #

6 (is %a/ 1 int *H" int r!F" int '!% 2 3 int i" 9 # $!r 1 i = 0 # i ; r!F # i++ 2 3 $!r 1 9 = 0 # 9 ; '!% # 9++ 2 rint$ 1 45( 4" * 1 H + i * '!% + 9 2 2 #

29&
rint$ 1 4@n4 2 # 6 rint$ 14@n4 2 # 6 sh!F 1 int 1 *H 2^4`" int r!F" int '!% 2 3 int i" 9 # int * # $!r 1 i = 0 # i ; r!F # i++ 2 3 =H+i# $!r 1 9 = 0 # 9 ; '!% # 9++ 2 rint$ 1 45( 4" * 1 + 9 2 2 # rint$ 1 4@n4 2 # 6 rint$ 1 4@n4 2 # 6 rint 1 int H^ `^4`" int r!F" int '!% 2 3 int i" 9 # $!r 1 i = 0 # i ; r!F # i++ 2 3 $!r 1 9 = 0 # 9 ; '!% # 9++ 2 rint$ 1 45( 4" H^i`^9` 2 # rint$ 1 4@n4 2 # 6 rint$ 1 4@n4 2 # 6

%et .s C

1nd here is the o#tp#t:


1234 5678

Chapter <0 !rrays


9016 1234 5678 9016 1234 5678 9016

299

$n the displa#= > #nction we have collected the base address o the 2<0 array being passed to it in an ordinary int pointerG Then thro#gh the two 8or loops #sing the e/pression < = Q ? i < col ? W > we have reached the appropriate ele*ent in the arrayG S#ppose i is eH#al to 2 and W is eH#al to -, then we wish to reach the ele*ent aK2LK3LG 7et #s see whether the e/pression < = Q ? i < col ? W > does give this ele*ent or notG "e er +ig#re %G! to #nderstand thisG

'

&

'

655(2 :(4 :(6 :(% :'( :'2 :'4 :'6 :'% :2( :22 :24

+ig#re %G! The e/pression < = Q ? i < col ? W > beco*es < = "55)2 ? 2 < 4 ? 3>G This t#rns o#t to be < ="55)2 ? 11 >. Since "55)2 is address o an integer, < = "55)2 ? 11 > t#rns o#t to be W >"5524>G Val#e at this address is 6G This is indeed sa*e as aK2LK3LG 1 *ore general or*#la or accessing each array ele*ent wo#ld beP
* 1 &ase a((ress + r!F n!. * n!. !$ '!%,mns + '!%,mn n!. 2

$n the sho0= > #nction we have de ined Q to be a pointer to an array o 4 integers thro#gh the declarationP

3))
int 1 *H 2^4` #

%et .s C

To begin with, Q holds the base address o the ;eroth '<0 array, iGeG 4((' >re er +ig#re %G!?G This address is then assigned to p, an int pointer, and then #sing this pointer all ele*ents o the ;eroth '< 0 array are accessedG )e/t ti*e thro#gh the loop when i ta9es a val#e ', the e/pression Q ? i etches the address o the irst '<0 arrayG This is beca#se, Q is a pointer to ;eroth '<0 array and adding ' to it wo#ld give #s the address o the ne/t '<0 arrayG This address is once again assigned to p, and #sing it all ele*ents o the ne/t '<0 array are accessedG $n the third #nction print= >, the declaration o Q loo9s li9e thisP
int H^ `^4` #

This is sa*e as int = <Q >K4L, where Q is pointer to an array o 4 integersG The only advantage is that we can now #se the *ore a*iliar e/pression QKiLKWL to access array ele*entsG We co#ld have #sed the sa*e e/pression in sho0= > as wellG

'rra# o8 !ointers
The way there can be an array o ints or an array o 8loats, si*ilarly there can be an array o pointersG Since a pointer variable always contains an address, an array o pointers wo#ld be nothing b#t a collection o addressesG The addresses present in the array o pointers can be addresses o isolated variables or addresses o array ele*ents or any other addressesG 1ll r#les that apply to an ordinary array apply to the array o pointers as wellG $ thin9 a progra* wo#ld clari y the conceptG
main1 2 3 int *arr^4` # )* arra/ !$ inte-er !inters *)

Chapter <0 !rrays


int i = 31" 9 = 5" . = 19" % = 71" m # arr^0` = Bi # arr^1` = B9 # arr^2` = B. # arr^3` = B% # $!r 1 m = 0 # m ;= 3 # m++ 2 rint$ 1 45( 4" * 1 arr^m` 2 2 # 6

3)1

+ig#re %G% shows the contents and the arrange*ent o the array o pointers in *e*oryG 1s yo# can observe, arr contains addresses o isolated int variables i, W, G and lG The 8or loop in the progra* pic9s #p the addresses present in arr and prints the val#es present at these addressesG

i -' 655'6 arr](^ 655'6 655'%

Q 5 655'4 arr]'^ 655'4 6552(

k '& 655'2 arr]2^ 655'2 65522 arr]-^ 655'( 65524

lg !' 655'(

+ig#re %G% 1n array o pointers can even contain the addresses o other arraysG The ollowing progra* wo#ld Q#sti y thisG
main1 2 3 stati' int a^ ` = 3 0" 1" 2" 3" 4 6 #

3)2
int * ^ ` = 3 a" a + 1" a + 2" a + 3" a + 4 6 # rint$ 1 4@n5, 5, 5(4" " * " * 1 * 2 2 # 6

%et .s C

$ wo#ld leave it or yo# to ig#re o#t the o#tp#t o this progra*G

Three@Di1ensional 'rra#
We aren@t going to show a progra**ing e/a*ple that #ses a three< di*ensional arrayG This is beca#se, in practice, one rarely #ses this arrayG 2owever, an e/a*ple o initiali;ing a three<di*ensional array will consolidate yo#r #nderstanding o s#bscriptsP
int arr^3`^4`^2` = 3 3 3 2" 4 6" 3 7" 8 6" 3 3" 4 6" 3 5" 6 6 3 7" 6 6" 3 3" 4 6" 3 5" 3 6" 3 2" 3 6 3 8" 9 6" 3 7" 2 6" 3 3" 4 6" 3 5" 1 6"

6" 3

6" 3

6 6#

1 three<di*ensional array can be tho#ght o as an array o arrays o arraysG The o#ter array has three ele*ents, each o which is a

Chapter <0 !rrays

3)3

two<di*ensional array o o#r one<di*ensional arrays, each o which contains two integersG $n other words, a one<di*ensional array o two ele*ents is constr#cted irstG Then o#r s#ch one< di*ensional arrays are placed one below the other to give a two< di*ensional array containing o#r rowsG Then, three s#ch two< di*ensional arrays are placed one behind the other to yield a three< di*ensional array containing three 2<di*ensional arraysG $n the array declaration note how the co**as have been givenG +ig#re %G& wo#ld possibly help yo# in vis#alising the sit#ation betterG

2 2<0 1rray ' 2<0 1rray ( 2<0 1rray


th st

nd

% ! 2 ! 5 4 % 4 6 6 4 -

& 2 4 '

+ig#re %G& 1gain re*e*ber that the arrange*ent shown above is only concept#ally tr#eG $n *e*ory the sa*e array ele*ents are stored linearly as shown in +ig#re %G'(G

th

2<0 1rray

' 2<0 1rray

st

2 655'(

nd

2<0 1rray

2 4 ! % - 4 5 6 ! 6 - 4 5 - 2 - % & ! 2 - 4 5 ' 654!% 654&4

+ig#re %G'(

3)4

%et .s C

2ow wo#ld yo# re er to the array ele*ent ' in the above arrayc The irst s#bscript sho#ld be ]2^, since the ele*ent is in third two< di*ensional array_ the second s#bscript sho#ld be ]-^ since the ele*ent is in o#rth row o the two<di*ensional array_ and the third s#bscript sho#ld be ]'^ since the ele*ent is in second position in the one<di*ensional arrayG We can there ore say that the ele*ent ' can be re erred as arrK2LK3LK1LG $t *ay be noted here that the co#nting o array ele*ents even or a -<0 array begins with ;eroG Can we not re er to this ele*ent #sing pointer notationc 3 co#rse, yesG +or e/a*ple, the ollowing two e/pressions re er to the sa*e ele*ent in the -<0 arrayP
arr^2`^3`^1` *1 *1 *1 arr + 2 2 + 3 2 + 1 2

Su11ar#
>a? 1n array is si*ilar to an ordinary variable e/cept that it can store *#ltiple ele*ents o si*ilar typeG >b? Co*piler doesn@t per or* bo#nds chec9ing on an arrayG >c? The array variable acts as a pointer to the ;eroth ele*ent o the arrayG $n a '<0 array, ;eroth ele*ent is a single val#e, whereas, in a 2<0 array this ele*ent is a '<0 arrayG >d? 3n incre*enting a pointer it points to the ne/t location o its typeG >e? 1rray ele*ents are stored in contig#o#s *e*ory locations and so they can be accessed #sing pointersG > ? 3nly li*ited arith*etic can be done on pointersG

B3ercise
Si1ple arra#s
K'L What wo#ld be the o#tp#t o the ollowing progra*sP 1a2 main1 2

Chapter <0 !rrays


3 int n,m^26`" tem # n,m^0` = 100 # n,m^25` = 200 # tem = n,m^25` # n,m^25` = n,m^0` # n,m^0` = tem # rint$ 1 4@n5( 5(4" n,m^0`" n,m^25` 2 #

3)5

6 1&2 main1 2 3 int arra/^26`" i # $!r 1 i = 0 # i ;= 25 # i++ 2 3 arra/^i` = 'A' + i # rint$ 1 4@n5( 5'4" arra/^i`" arra/^i` 2 # 6 6 1'2 main1 2 3 int s,&^50`" i # $!r 1 i = 0 # i ;= 48 # i++ 2 # 3 s,&^i` = i # rint$ 1 4@n5(4" s,&^i` 2 # 6 6

K-L ,oint o#t the errors, i seg*entsP

any, in the

ollowing progra*

1a2 )* mixe( has s!me 'har an( s!me int =a%,es *) int 'har mixe(^100` # main1 2 3 int a^10`" i #

3)"
$!r 1 i = 1 # i ;= 10 # i++ 2 3 s'an$ 1 45(4" a^i` 2 # rint$ 1 45(4" a^i` 2 # 6 6 1&2 main1 2 3 int si:e # s'an$ 1 45(4" Bsi:e 2 # int arr^si:e` # $!r 1 i = 1 # i ;= si:e # i++ 2 3 s'an$ 1 45(4" arr^i` 2 # rint$ 1 45(4" arr^i` 2 # 6 6 1'2 main1 2 3 int i" a = 2" & = 3 # int arr^ 2 + 3 ` # $!r 1 i = 0 # i ; a+& # i++ 2 3 s'an$ 1 45(4" Barr^i` 2 # rint$ 1 4@n5(4" arr^i` 2 # 6 6 KCL 1nswer the ollowingP

%et .s C

>a? 1n array is a collection o 'G 2G -G 4G di erent data types scattered thro#gho#t *e*ory the sa*e data type scattered thro#gho#t *e*ory the sa*e data type placed ne/t to each other in *e*ory di erent data types placed ne/t to each other in *e*ory

Chapter <0 !rrays


>b? 1re the ollowing array declarations correctc
int a 1252 # int si:e = 10" &^si:e` # int ' = 30"1"26 #

3)7

>c? Which ele*ent o the array does this e/pression re erencec


n,m^4`

>d? What is the di erence between the 5@s in these two e/pressionsc >Select the correct answer?
int n,m^5` # n,m^5` = 11 #

'G irst is partic#lar ele*ent, second is type 2G irst is array si;e, second is partic#lar ele*ent -G irst is partic#lar ele*ent, second is array si;e 4G both speci y array si;e >e? State whether the ollowing state*ents are Tr#e or +alseP 'G The array int nu1K2"L has twenty<si/ ele*entsG 2G The e/pression nu1K1L designates the irst ele*ent in the array -G $t is necessary to initiali;e the array at the ti*e o declarationG 4G The e/pression nu1K27L designates the twenty<eighth ele*ent in the arrayG
KDL 1tte*pt the ollowingP

>a? Twenty< ive n#*bers are entered ro* the 9eyboard into an arrayG The n#*ber to be searched is entered thro#gh the 9eyboard by the #serG Write a progra* to ind i the n#*ber to be searched is present in the array and i it is present, display the n#*ber o ti*es it appears in the arrayG

3)&

%et .s C

>b? Twenty< ive n#*bers are entered ro* the 9eyboard into an arrayG Write a progra* to ind o#t how *any o the* are positive, how *any are negative, how *any are even and how *any oddG >c? $*ple*ent the Selection Sort, 8#bble Sort and $nsertion sort algorith*s on a set o 25 n#*bersG >"e er +ig#re %G'' or the logic o the algorith*s? f Selection sort f 8#bble Sort f $nsertion Sort

Selection Sort $teration '


(( '' ** && ## '' (( ** && ## '' (( ** && ## && (( ** '' ## ## (( ** '' &&

$teration 2
## (( ** '' && ## '' ** (( &&

,esult + ## # && & ** ' (( ( '' + ## # && & (( ' ** ( '' + ## # && & '' ' ** ( (( + ## # && & '' ' (( ( **

+ig#re %G'' >a?

Chapter <0 !rrays

3)9

-u66le Sort $teration '


+ (( # '' & ** ' && ( ## '' (( ** && ## '' (( ** && ## '' (( && ** ## + '' # (( & && ' ## ( **

$teration 2
+ '' # (( & && ' ## ( ** + '' # && & (( ' ## ( **

$teration + '' # && & ## ' (( ( ** + && # '' & ## ' (( ( ** + # & ' (

$teration 4
,esult && ## '' (( ** + ## # && & '' ' (( ( **

+ig#re %G'' >b?


*nsertion Sort $teration '
(( '' ** && ##

$teration 2
'' (( ** && ##

$teration '' (( ** && ##

$teration 4
&& '' (( ** ##

"es#lt
+ # & ' ( ## && '' (( **

+ig#re %G'' >c?

31)

%et .s C

>d? $*ple*ent the ollowing proced#re to generate pri*e n#*bers ro* ' to '(( into a progra*G This proced#re is called sieve o .ratosthenesG step ' step 2 step step 4 step 5 +ill an array nu1K1))L with n#*bers ro* ' to '(( Starting with the second entry in the array, set all its *#ltiples to ;eroG ,roceed to the ne/t non<;ero ele*ent and set all its *#ltiples to ;eroG "epeat step - till yo# have set #p the *#ltiples o all the non<;ero ele*ents to ;ero 1t the concl#sion o step 4, all the non<;ero entries le t in the array wo#ld be pri*e n#*bers, so print o#t these n#*bersG

,ore on arra#s4 'rra#s and pointers


KBL What wo#ld be the o#tp#t o the ollowing progra*sP 1a2 main1 2 3 int &^ ` = 3 10" 20" 30" 40" 50 6 # int i # $!r 1 i = 0 # i ;= 4 # i++ 2 rint$ 1 4@n5(4 *1 & + i 2 2 # 6 1&2 main1 2 3 int &^ ` = 3 0" 20" 0" 40" 5 6 # int i" *. # .=&# $!r 1 i = 0 # i ;= 4 # i++ 2 3 rint$ 1 4@n5(4 *. 2 #

Chapter <0 !rrays


6 6 1'2 main1 2 3 int a^ ` = 3 2" 4" 6" 8" 10 6 # int i # 'han-e 1 a" 5 2 # $!r 1 i = 0 # i ;= 4 # i++ 2 rint$1 4@n5(4" a^i` 2 # 6 'han-e 1 int *&" int n 2 3 int i # $!r 1 i = 0 # i ; n # i++ 2 *1 & + i 2 = *1 & + i 2 + 5 # 6 .++ #

311

1(2 main1 2 3 int a^5`" i" & = 16 # $!r 1 i = 0 # i ; 5 # i++ 2 a^i` = 2 * i # $ 1 a" & 2 # $!r 1 i = 0 # i ; 5 # i++ 2 rint$ 1 4@n5(4" a^i` 2 # rint$1 4@n5(4" & 2 # 6 $ 1 int *x" int / 2 3 int i # $!r 1 i = 0 # i ; 5 # i++ 2 *1 x + i 2 += 2 # / += 2 # 6

312
1e2 main1 2 3 stati' int a^5` # int i # $!r 1 i = 0 # i ;= 4 # i++ 2 rint$ 1 4@n5(4" a^i` 2 # 6 1$2 main1 2 3 int a^5` = 3 5" 1" 15" 20" 25 6 # int i" 9" . = 1" m # i = ++a^1` # 9 = a^1`++ # m = a^i++` # rint$ 1 4@n5( 5( 5(4" i" 9" m 2 # 6

%et .s C

KFL ,oint o#t the errors, i any, in the ollowing progra*sP 1a2 main1 2 3 int arra/^6` = 3 1" 2" 3" 4" 5" 6 6 # int i # $!r 1 i = 0 # i ;= 25 # i++ 2 rint$ 1 4@n5(4" arra/^i` 2 # 6 1&2 main1 2 3 int s,&^50`" i # $!r 1 i = 1 # i ;= 50 # i++ 2 3 s,&^i` = i # rint$ 1 4@n5(4 " s,&^i` 2 # 6 6

Chapter <0 !rrays


1'2 main1 2 3 int a^ ` = 3 10" 20" 30" 40" 50 6 # int 9 # 9 = a # )* st!re the a((ress !$ :er!th e%ement *) 9=9+3# rint$ 1 4@n5(4 *9 2 # 6

313

1(2 main1 2 3 $%!at a^ ` = 3 13.24" 1.5" 1.5" 5.4" 3.5 6 # $%!at *9 # 9=a# 9=9+4# rint$ 1 4@n5( 5( 5(4" 9" *9" a^4` 2 # 6 1e2 main1 2 3 $%!at a^ ` = 3 13.24" 1.5" 1.5" 5.4" 3.5 6 # $%!at *9" *. # 9=a# .=a+4# 9=9*2# .=.)2# rint$ 1 4@n5( 5(4" *9" *. 2 # 6 1$2 main1 2 3 int max = 5 # $%!at arr^max` # $!r 1 i = 0 # i ; max # i++ 2 s'an$ 1 45$4" Barr^i` 2 # 6

314
KGL 1nswer the ollowingP

%et .s C

>a? What wo#ld happen i yo# try to p#t so *any val#es into an array when yo# initiali;e it that the si;e o the array is e/ceededc 'G 2G -G 4G nothing possible syste* *al #nction error *essage ro* the co*piler other data *ay be overwritten

>b? $n an array int arrK12L the word arr represents the a o the array >c? What wo#ld happen i yo# p#t too ew ele*ents in an array when yo# initiali;e itc 'G 2G -G 4G nothing possible syste* *al #nction error *essage ro* the co*piler #n#sed ele*ents will be illed with (@s or garbage

>d? What wo#ld happen i yo# assign a val#e to an ele*ent o an array whose s#bscript e/ceeds the si;e o the arrayc 'G 2G -G 4G the ele*ent will be set to ( nothing, it@s done all the ti*e other data *ay be overwritten error *essage ro* the co*piler

>e? When yo# pass an array as an arg#*ent to a #nction, what act#ally gets passedc 'G 2G -G 4G address o the array val#es o the ele*ents o the array address o the irst ele*ent o the array n#*ber o ele*ents o the array

Chapter <0 !rrays


> ? Which o these are reasons or #sing pointersc 'G 2G -G 4G To *anip#late parts o an array To re er to 9eywords s#ch as 8or and i8 To ret#rn *ore than one val#e ro* a #nction To re er to partic#lar progra*s *ore conveniently

315

>g? $ yo# don@t initiali;e a static array, what wo#ld be the ele*ents set toc 'G 2G -G 4G ( an #ndeter*ined val#e a loating point n#*ber the character constant JZ(J

K2L State Tr#e or +alseP

>a? 1ddress o a loating<point variable is always a whole n#*berG >b? Which o the ollowing is the correct way o declaring a loat pointerP 5G loat ptr _ 6G loat Wptr _ !G W loat ptr _ %G )one o the above 1dd the *issing state*ent or the ollowing progra* to print -5G
main1 2 3 int 9" * tr # * tr = 35 # rint$ 1 4@n5(4" 9 2 # 6

>c?

31"

%et .s C

>d? i int sK5L is a one<di*ensional array o integers, which o the ollowing re ers to the third ele*ent in the arrayc &G '(G ''G '2G W> s L 2 ? W> s L - ? sLsL2

K*L 1tte*pt the ollowingP

>a? Write a progra* to copy the contents o one array into another in the reverse orderG >b? $ an array arr contains n ele*ents, then write a progra* to chec9 i arrK)L F arrKn@1L, arrK1L F arrKn@2L and so onG >c? +ind the s*allest n#*ber in an array #sing pointersG >d? Write a progra* which per or*s the ollowing tas9sP f f f f >e? initiali;e an integer array o '( ele*ents in 1ain= > pass the entire array to a #nction 1odi8#= > in 1odi8#= > *#ltiply each ele*ent o array by ret#rn the control to 1ain= > and print the new array ele*ents in 1ain= >

The screen is divided into 25 rows and %( col#*nsG The characters that are displayed on the screen are stored in a special *e*ory called V06 *e*ory >not to be con #sed with ordinary *e*ory?G .ach character displayed on the screen occ#pies two bytes in V06 *e*oryG The irst o these bytes contains the 1SC$$ val#e o the character being displayed, whereas, the second byte contains the colo#r in which the character is displayedG +or e/a*ple, the 1SC$$ val#e o the character present on ;eroth row and ;eroth col#*n on the screen is stored at

Chapter <0 !rrays

317

location n#*ber (/8%((((((G There ore the colo#r o this character wo#ld be present at location n#*ber (/8%(((((( L 'G Si*ilarly 1SC$$ val#e o character in row (, col ' will be at location (/8%(((((( L 2, and its colo#r at (/8%(((((( L -G With this 9nowledge write a progra* which when e/ec#ted wo#ld 9eep converting every capital letter on the screen to s*all case letter and every s*all case letter to capital letterG The proced#re sho#ld stop the *o*ent the #ser hits a 9ey ro* the 9eyboardG This is an activity o a ra*pant Vir#s called 0ancing 0ollsG >+or *onochro*e adapter, #se (/8((((((( instead o (/8%((((((?G

,ore than one di1ension


KVL What wo#ld be the o#tp#t o the ollowing progra*sP 1a2 main1 2 3 int n^3`^3` = 3 2" 4" 3" 6" 8" 5" 3" 5" 1 6# rint$ 1 4@n5( 5( 5(4" *n" n^3`^3`" n^2`^2` 2 # 6 1&2 main1 2 3 int n^3`^3` = 3 2" 4" 3" 6" 8" 5" 3" 5" 1

6# int i" * tr #

31&
tr = n # $!r 1 i = 0 # i ;= 8 # i++ 2 rint$ 1 4@n5(4" *1 tr + i 2 2 # 6 1'2 main1 2 3 int n^3`^3` = 3 2" 4" 3" 6" 8" 5" 3" 5" 1

%et .s C

6# int i" 9 # $!r 1 i = 0 # i ;= 2 # i++ 2 $!r 1 9 = 0 # 9 ;= 2 # 9++ 2 rint$ 1 4@n5( 5(4" n^i`^9`" *1 *1 n + i 2 + 9 2 2 # 6 K7L ,oint o#t the errors, i any, in the ollowing progra*sP 1a2 main1 2 3 int tF!(^ `^ ` = 3 2" 4" 6" 8 6# rint$ 1 4@n5(4" tF!( 2 # 6 1&2 main1 2 3 int three^3`^ ` = 3 2" 4" 3" 6" 8" 2" 2" 3 "1

6# rint$ 1 4@n5(4" three^1`^1` 2 #

Chapter <0 !rrays


6 KLL 1tte*pt the ollowingP

319

>a? 2ow will yo# initiali;e a three<di*ensional array threedK3LK2LK3Lc 2ow will yo# re er the irst and last ele*ent in this arrayc >b? Write a progra* to pic9 #p the largest n#*ber ro* any 5 row by 5 col#*n *atri/G >c? Write a progra* to obtain transpose o a 4 / 4 *atri/G The transpose o a *atri/ is obtained by e/changing the ele*ents o each row with the ele*ents o the corresponding col#*nG >d? Very o ten in airs we co*e across a p#;;le that contains '5 n#*bered sH#are pieces *o#nted on a ra*eG These pieces can be *oved hori;ontally or verticallyG 1 possible arrange*ent o these pieces is shown belowP

' % '4 '2

4 '( &

'5 2 6 5

! '' '-

+ig#re %G'2 1s yo# can see there is a blan9 at botto* right cornerG $*ple*ent the ollowing proced#re thro#gh a progra*P

32)

%et .s C

0raw the bo/es as shown aboveG 0isplay the n#*bers in the above orderG 1llow the #ser to hit any o the arrow 9eys >#p, down, le t, or right?G $ #ser hits say, right arrow 9ey then the piece with a n#*ber 5 sho#ld *ove to the right and blan9 sho#ld replace the original position o 5G Si*ilarly, i down arrow 9ey is hit, then '- sho#ld *ove down and blan9 sho#ld replace the original position o '-G $ le t arrow 9ey or #p arrow 9ey is hit then no action sho#ld be ta9enG The #ser wo#ld contin#e hitting the arrow 9eys till the n#*bers aren@t arranged in ascending orderG Keep trac9 o the n#*ber o *oves in which the #ser *anages to arrange the n#*bers in ascending orderG The #ser who *anages it in *ini*#* n#*ber o *oves is the one who winsG 2ow do we tac9le the arrow 9eysc We cannot receive the* #sing scan8= > #nctionG 1rrow 9eys are special 9eys which are identi ied by their Dscan codes@G 6se the ollowing #nction in yo#r progra*G $t wo#ld ret#rn the scan code o the arrow 9ey being hitG 0on@t worry abo#t how this #nction is writtenG We are going to deal with it laterG The scan codes or the arrow 9eys areP #p arrow 9ey F !2 down arrow 9ey F %( le t arrow 9ey F !5 right arrow 9ey F !!
)* >et,rns s'an '!(e !$ the .e/ that has &een hit *) Lin'%,(e 4(!s.h4 -et.e/1 2 3 ,ni!n >EJ7 i" ! #

Chapter <0 !rrays


Fhi%e 1 T.&hit1 2 2 # i.h.ah = 0 # int86 1 22" Bi" B! 2 # ret,rn 1 !.h.ah 2 # 6

321

>e? Those readers who are ro* an .ngineering=Science bac9gro#nd *ay try writing progra*s or ollowing proble*sG >'? >2? >-? >4? Write a progra* to add two 6 / 6 *atricesG Write a progra* to *#ltiply any two - / - *atricesG Write a progra* to sort all the ele*ents o a 4 / 4 *atri/G Write a progra* to obtain the deter*inant val#e o a 5 / 5 *atri/G

> ? 5atch the ollowing with re erence to the ollowing progra* seg*entP
int i" 9" = 25# int -pi. -pj / 0 j% 112 112 3- more lines of program -3 112 -pj / j 4 *% j / -pj 4 * % pj / 9 % -pi / i 4 j

.ach integer H#antity occ#pies 2 bytes o *e*oryG The val#e assigned to i begin at >he/adeci*al? address +&C and the val#e assigned to Q begins at address +&.G 5atch the val#e represented by le t hand side H#antities with the rightG
'G 2G -G 4G Ii IQ pQ WpQ aG bG cG dG -( +&. -5 +12

322
5G 6G !G %G &G '(G i pi Wpi > pi L 2 ? >Wpi L 2? W > pi L 2 ? eG G gG hG iG QG 9G lG +&C 6! #nspeci ied 65 +&. +&. +13 +&0

%et .s C

>g? 5atch the ollowing with re erence to the ollowing seg*entP int x^3`^5` = 3 " #. &. '. (. * ). " 5. 6. 7. 8. #+ ). " ##. #&. #'. #(. #* ) ). -n / 0x %
aG & bG 'cG 4 dG eG 2 G '2 gG '4 hG ! iG ' QG % 9G 5 lG '( *G 6 >h? 5atch the ollowing with re erence to the ollowing progra* seg*entP str,'t 3 int x" /# 6 s^ ` = 3 10" 20" 15" 25" 8" 75" 6" 2 6# int *i # i=s# 'G 2G -G 4G 5G 6G !G %G &G '(G W> W> / L 2 ? L '? W> W/ L 2 ? L 5 W> W> / L '? ? W> W> / ? L 2 ? L ' W > W> / L ' ? L - ? Wn W> n L2 ? >W>n L - ? L ' W>n L 5?L' LLWn

Chapter <0 !rrays


'G 2G -G 4G 5G 6G !G %G &G '(G W> i L - ? s]i]!^^G/ s] >s L 2?<by = -]$^^Gy i]i]'^<i]2^^ i]s]-^Gy^ > s L ' ?<b/ L 5 W> ' Li ?WW> i L 4 ? = Wi s]i](^ F i]4^^Gy L '( > W>s L W> i L '? = Wi ? ?G/ L 2 LLi]i]6^^ aG bG cG dG eG G gG hG iG QG 9G lG %5 2 6 ! '6 '5 25 % ' '(( '( 2(

323

>i? 5atch the ollowing with re erence to the ollowing progra* seg*entP
,nsi-ne( int arr^3`^3` = 3 2" 4" 6" 9" 1" 10" 16" 64" 5 6# 'G 2G -G 4G 5G 6G !G %G &G '(G WWarr WWarr a W> Warr L 2 ? W> arr L 2 ? = > W> Warr L ' ? b WWarr ? W> arr]'^ L ' ? Y arr]'^]2^ W> arr](^ ? Y W> arr]2^ ? arr]'^]'^ a arr](^]'^ arr]2^]]'^ I arr]2^](^ arr]2^]2^ Y arr](^]'^ arr](^]'^ V arr](^]2^ LLWWarr L <<arr]'^]'^ aG bG cG dG eG G gG hG iG QG 9G lG 64 '% 6 ( '6 ' '' 2( 2 5 4

>Q? Write a progra* that interchanges the odd and even co*ponents o an arrayG >9? Write a progra* to ind i a sH#are *atri/ is sy**etricG

324

%et .s C

>l? Write a #nction to ind the nor* o a *atri/G The nor* is de ined as the sH#are root o the s#* o sH#ares o all ele*ents in the *atri/G >*? Given an array pK5L, write a #nction to shi t it circ#larly le t by two positionsG Th#s, i p](^ X '5, p]'^X -(, p]2^ X 2%, p]-^X '& and p]4^ X 6' then a ter the shi t p](^ X 2%, p]'^ X '&, p]2^ X 6', p]-^ X '5 and p]4^ X -(G Call this #nction or a >4 / 5 ? *atri/ and get its rows le t shi tedG >n? 1 6 / 6 *atri/ is entered thro#gh the 9eyboard and stored in a 2<di*ensional array 1atK7LK7LG Write a progra* to obtain the 0eter*inant val#es o this *atri/G >o? +or the ollowing set o sa*ple data, co*p#te the standard deviation and the *eanG
-6" -12" 8" 13" 11" 6" 7" 2" -6" -9" -10" 11" 10" 9" 2

The or*#la or standard deviation is

> "i f " ? 2 n


where 3i is the data ite* and 3 is the *eanG >p? The area o a triangle can be co*p#ted by the sine law when 2 sides o the triangle and the angle between the* are 9nownG
Area = 11 ) 2 2 a& sin 1 an-%e 2

Given the ollowing 6 triang#lar pieces o land, write a progra* to ind their area and deter*ine which is largest,
,lot )oG ' 2 a '-!G4 '55G2 '4&Gb %(G& &2G62 &!G&angle (G!% (G%& 'G-5

Chapter <0 !rrays


4 5 6 '6(G( '55G6 '4&G! '((G25 6%G&5 '2(G( &G(( 'G25 'G!5

325

>H? +or the ollowing set o n data points >/, y?, co*p#te the correlation coe icient r, given by
rX

h "y f h "h y ]nh " f > h " ? ^ ]nh y


2 2

f > h y? 2 ^

/ -4G22 -&G%! 4'G%5 4-G24(G(6 5-G2& 5-G2& 54G'4 4&G'2 4(G!' 55G'5

y '(2G4'((G&&!G4&!G%' &%G-2 &%G-2 '((G(! &!G(% &'G5& &4G%5 &4G65

>r? +or the ollowing set o point given by =34 #> it a straight line given by
/ = a + &x

where,

aXy fb " bX
/ -G(

and

] n h " 2 f >h " ? 2 ^


y 'G5

nh y" f h " h y

32"
4G5 5G5 6G5 !G5 %G5 %G( &G( &G5 '(G( 2G( -G5 5G( 6G( !G5 &G( '(G5 '2G( '4G(

%et .s C

>s? The \ and S coordinates o '( di erent points are entered thro#gh the 9eyboardG Write a progra* to ind the distance o last point ro* the irst point >s#* o distance between consec#tive points?G

Puppetting &n Strings


e e e e What are Strings 5ore abo#t Strings ,ointers and Strings Standard 7ibrary String +#nctions strlen( ) strcpy> ? strcat> ? strcmp> ? Two<0i*ensional 1rray o Characters 1rray o ,ointers to Strings 7i*itation o 1rray o ,ointers to Strings Sol#tion S#**ary ./ercise

e e e e e

327

32&

%et .s C

n the last chapter yo# learnt how to de ine arrays o di ering si;es and di*ensions, how to initiali;e arrays, how to pass arrays to a #nction, etcG With this 9nowledge #nder yo#r belt, yo# sho#ld be ready to handle strings, which are, si*ply p#t, a special 9ind o arrayG 1nd strings, the ways to *anip#late the*, and how pointers are related to strings are going to be the topics o disc#ssion in this chapterG

/hat are Strings


The way a gro#p o integers can be stored in an integer array, si*ilarly a gro#p o characters can be stored in a character arrayG Character arrays are *any a ti*e also called stringsG 5any lang#ages internally treat strings as character arrays, b#t so*ehow conceal this act ro* the progra**erG Character arrays or strings are #sed by progra**ing lang#ages to *anip#late te/t s#ch as words and sentencesG 1 string constant is a one<di*ensional array o ter*inated by a n#ll > DZ(@ ?G +or e/a*ple,
'har name^ ` = 3 'U'" 'A'" 'E'" '7'" 'O'" 'E'" '>'" '@0' 6 #

characters

.ach character in the array occ#pies one byte o *e*ory and the last character is always DZ(@G What character is thisc $t loo9s li9e two characters, b#t it is act#ally only one character, with the Z indicating that what ollows it is so*ething specialG DZ(@ is called n#ll characterG )ote that DZ(@ and D(@ are not sa*eG 1SC$$ val#e o DZ(@ is (, whereas 1SC$$ val#e o D(@ is 4%G +ig#re &G' shows the way a character array is stored in *e*oryG )ote that the ele*ents o the character array are stored in contig#o#s *e*ory locationsG The ter*inating n#ll >DZ(@? is i*portant, beca#se it is the only way the #nctions that wor9 with a string can 9now where the string endsG $n act, a string not ter*inated by a DZ(@ is not really a string, b#t *erely a collection o charactersG

Chapter =0 #uppetting On trings

329
. " Z(

655'% 655'& 6552( 6552' 65522 6552- 65524 65525

+ig#re &G' C concedes the act that yo# wo#ld #se strings very o ten and hence provides a shortc#t or initiali;ing stringsG +or e/a*ple, the string #sed above can also be initiali;ed as,
'har name^ ` = 4UAE7OE>4 #

)ote that, in this declaration DZ(@ is not necessaryG C inserts the n#ll character a#to*aticallyG

,ore a6out Strings


$n what way are character arrays di erent than n#*eric arraysc Can ele*ents in a character array be accessed in the sa*e way as the ele*ents o a n#*eric arrayc 0o $ need to ta9e any special care o DZ(@c Why n#*eric arrays don@t end with a DZ(@c 0eclaring strings is o9ay, b#t how do $ *anip#late the*c d#estions galore44 Well, let #s settle so*e o these iss#es right away with the help o sa*ple progra*sG
)* ?r!-ram t! (em!nstrate rintin- !$ a strin- *) main1 2 3 'har name^ ` = 4_%insman4 # int i = 0 # Fhi%e 1 i ;= 7 2 3 rint$ 1 45'4" name^i` 2 # i++ # }

33)
}

%et .s C

1nd here is the o#tp#tGGG


_%insman

)o big dealG We have initiali;ed a character array, and then printed o#t the ele*ents o this array within a 0hile loopG Can we write the 0hile loop witho#t #sing the inal val#e !c We can_ beca#se we 9now that each character array always ends with a DZ(@G +ollowing progra* ill#strates thisG
main1 2 3 'har name^ ` = 4_%insman4 # int i = 0 # Fhi%e 1 name^i` T= a@0' 2 3 rint$ 1 45'4" name^i` 2 # i++ # 6 6

1nd here is the o#tp#tGGG


_%insman

This progra* doesn@t rely on the length o the string >n#*ber o characters in it? to print o#t its contents and hence is de initely *ore general than the earlier oneG 2ere is another version o the sa*e progra*_ this one #ses a pointer to access the array ele*entsG
main1 2 3 'har name^ ` = 4_%insman4 # 'har * tr #

Chapter =0 #uppetting On trings


tr = name # )* st!re &ase a((ress !$ strin- *) Fhi%e 1 * tr T= a@0' 2 3 rint$ 1 45'4" * tr 2 # tr++ # 6 6

331

1s with the integer array, by *entioning the na*e o the array we get the base address >address o the ;eroth ele*ent? o the arrayG This base address is stored in the variable ptr #sing,
tr = name #

3nce the base address is obtained in ptr, Wptr wo#ld yield the val#e at this address, which gets printed pro*ptly thro#gh,
rint$ 1 45'4" * tr 2 #

Then, ptr is incre*ented to point to the ne/t character in the stringG This derives ro* two actsP array ele*ents are stored in contig#o#s *e*ory locations and on incre*enting a pointer it points to the i**ediately ne/t location o its typeG This process is carried o#t till ptr doesn@t point to the last character in the string, that is, DZ(@G $n act, the character array ele*ents can be accessed e/actly in the sa*e way as the ele*ents o an integer arrayG Th#s, all the ollowing notations re er to the sa*e ele*entP
name^i` *1 name + i 2 *1 i + name 2 i^name`

332

%et .s C

.ven tho#gh there are so *any ways >as shown above? to re er to the ele*ents o a character array, rarely is any one o the* #sedG This is beca#se print8= > #nction has got a sweet and si*ple way o doing it, as shown belowG )ote that print8= > doesn@t print the DZ(@G
main1 2 3 'har name^ ` = 4_%insman4 # rint$ 1 45s4" name 2 # 6

The As #sed in print8= > is a or*at speci ication or printing o#t a stringG The sa*e speci ication can be #sed to receive a string ro* the 9eyboard, as shown belowG
main1 2 3 'har name^25` # rint$ 1 4Enter /!,r name 4 2 # s'an$ 1 45s4" name 2 # rint$ 1 4Ue%%! 5sT4" name 2 # 6

1nd here is a sa*ple r#n o the progra*GGG


Enter /!,r name 0e&ashish Ue%%! 0e&ashishT

)ote that the declaration char na1eK25L sets aside 25 bytes #nder the array na1eK L4 whereas the scan8= > #nction ills in the characters typed at 9eyboard into this array #ntil the enter 9ey is hitG 3nce enter is hit, scan8= > places a DZ(@ in the arrayG )at#rally, we sho#ld pass the base address o the array to the scan8= > #nctionG

Chapter =0 #uppetting On trings

333

While entering the string #sing scan8= > we *#st be ca#tio#s abo#t two thingsP >a? The length o the string sho#ld not e/ceed the di*ension o the character arrayG This is beca#se the C co*piler doesn@t per or* bo#nds chec9ing on character arraysG 2ence, i yo# carelessly e/ceed the bo#nds there is always a danger o overwriting so*ething i*portant, and in that event, yo# wo#ld have nobody to bla*e b#t yo#rselvesG >b? scan8( ) is not capable o receiving *#lti<word stringsG There ore na*es s#ch as D0ebashish "oy@ wo#ld be #nacceptableG The way to get aro#nd this li*itation is by #sing the #nction gets( )2 The #sage o #nctions gets( ) and its co#nterpart puts( ) is shown belowG
main1 2 3 'har name^25` # rint$ 1 4Enter /!,r $,%% name 4 2 # -ets 1 name 2 # ,ts 1 4Ue%%!T4 2 # ,ts 1 name 2 # 6

1nd here is the o#tp#tGGG


Enter /!,r name 0e&ashish >!/ Ue%%!T 0e&ashish >!/

The progra* and the o#tp#t are sel <e/planatory e/cept or the act that, puts= > can display only one string at a ti*e >hence the #se o two puts= > in the progra* above?G 1lso, on displaying a string, #nli9e print8= >, puts= > places the c#rsor on the ne/t lineG Tho#gh gets= > is capable o receiving only

334

%et .s C

one string at a ti*e, the pl#s point with gets= > is that it can receive a *#lti<word stringG $ we are prepared to ta9e the tro#ble we can *a9e scan8= > accept *#lti<word strings by writing it in this *annerP
'har name^25` # rint$ 1 4Enter /!,r $,%% name 4 2 # s'an$ 1 45^K@n`s4" name 2 #

Tho#gh wor9able this is the best o the ways to call a #nction, yo# wo#ld agreeG

!ointers and Strings


S#ppose we wish to store K2elloOG We *ay either store it in a string or we *ay as9 the C co*piler to store it at so*e location in *e*ory and assign the address o the string in a char pointerG This is shown belowP
'har str^ ` = 4Ue%%!4 # 'har * = 4Ue%%!4 #

There is a s#btle di erence in #sage o these two or*sG +or e/a*ple, we cannot assign a string to another, whereas, we can assign a char pointer to another char pointerG This is shown in the ollowing progra*G
main1 2 3 'har str1^ ` = 4Ue%%!4 # 'har str2^10` # 'har *s = 4J!!( P!rnin-4 # 'har *H #

Chapter =0 #uppetting On trings


str2 = str1 # )* err!r *) H = s # )* F!r.s *) 6

335

1lso, once a string has been de ined it cannot be initiali;ed to another set o charactersG 6nli9e strings, s#ch an operation is per ectly valid with char pointersG
main1 2 3 'har str1^ ` = 4Ue%%!4 # 'har * = 4Ue%%!4 # str1 = 4D/e4 # )* err!r *) = 4D/e4 # )* F!r.s *) 6

Standard Li6rar# String Functions


With every C co*piler a large set o #se #l string handling library #nctions are providedG +ig#re &G2 lists the *ore co**only #sed #nctions along with their p#rposeG

Function strlen strlwr str#pr strcat strncat

.se +inds length o a string Converts a string to lowercase Converts a string to #ppercase 1ppends one string at the end o another 1ppends irst n characters o a string at the end o another

33"
strcpy strncpy strc*p strnc*p strc*pi stric*p strnic*p strd#p strchr strrchr strstr strset strnset strrev

%et .s C
Copies a string into another Copies irst n characters o one string into another Co*pares two strings Co*pares irst n characters o two strings Co*pares two strings witho#t regard to case >`i` denotes that this #nction ignores case? Co*pares two strings witho#t regard to case >identical to strc*pi? Co*pares irst n characters o two strings witho#t regard to case 0#plicates a string +inds irst occ#rrence o a given character in a string +inds last occ#rrence o a given character in a string +inds irst occ#rrence o a given string in another string Sets all characters o string to a given character Sets irst n characters o a string to a given character "everses string

+ig#re &G2 3#t o the above list we shall disc#ss the #nctions strlen= >, strcp#= >, strcat= > and strc1p= >, since these are the *ost co**only #sed #nctionsG This will also ill#strate how the library #nctions in general handle stringsG 7et #s st#dy these #nctions one by oneG

strlen= >
This #nction co#nts the n#*ber o characters present in a stringG $ts #sage is ill#strated in the ollowing progra*G
main1 2 3 'har arr^ ` = 4Dam&!!:%e(4 # int %en1" %en2 #

Chapter =0 #uppetting On trings


%en1 = str%en 1 arr 2 # %en2 = str%en 1 4U,m t/ 0,m t/4 2 # rint$ 1 4@nstrin- = 5s %en-th = 5(4" arr" %en1 2 # rint$ 1 4@nstrin- = 5s %en-th = 5(4" 4U,m t/ 0,m t/4" %en2 2 # 6

337

The o#tp#t wo#ld beGGG


strin- = Dam&!!:%e( %en-th = 10 strin- = U,m t/ 0,m t/ %en-th = 13

)ote that in the irst call to the #nction strlen= >, we are passing the base address o the string, and the #nction in t#rn ret#rns the length o the stringG While calc#lating the length it doesn@t co#nt DZ(@G .ven in the second call,
%en2 = str%en 1 4U,m t/ 0,m t/4 2 #

what gets passed to strlen= > is the address o the string and not the string itsel G Can we not write a #nction 3strlen= > which i*itates the standard library #nction strlen= >c 7et #s give it a tryGGG
)* A %!!.-a%i.e !$ the $,n'ti!n str%en1 2 *) main1 2 3 'har arr^ ` = 4Dam&!!:%e(4 # int %en1" %en2 # %en1 = xstr%en 1 arr 2 # %en2 = xstr%en 1 4U,m t/ 0,m t/4 2 # rint$ 1 4@nstrin- = 5s %en-th = 5(4" arr" %en1 2 # rint$ 1 4@nstrin- = 5s %en-th = 5(4" 4U,m t/ 0,m t/4" %en2 2 # 6

33&
xstr%en 1 'har *s 2 3 int %en-th = 0 # Fhi%e 1 *s T= '@0' 2 3 %en-th++ # s++ # 6 ret,rn 1 %en-th 2 # 6

%et .s C

The o#tp#t wo#ld beGGG


strin- = Dam&!!:%e( %en-th = 10 strin- = U,m t/ 0,m t/ %en-th = 13

The #nction 3strlen= > is airly si*pleG 1ll that it does is 9eep co#nting the characters till the end o string is not *etG 3r in other words 9eep co#nting characters till the pointer s doesn@t point to DZ(@G

strcp#= >
This #nction copies the contents o one string into anotherG The base addresses o the so#rce and target strings sho#ld be s#pplied to this #nctionG 2ere is an e/a*ple o strcp#= > in actionGGG
main1 2 3 'har s!,r'e^ ` = 47a/!nara4 #

Chapter =0 #uppetting On trings


'har tar-et^20` # str' / 1 tar-et" s!,r'e 2 # rint$ 1 4@ns!,r'e strin- = 5s4" s!,r'e 2 # rint$ 1 4@ntar-et strin- = 5s4" tar-et 2 # 6

339

1nd here is the o#tp#tGGG


s!,r'e strin- = 7a/!nara tar-et strin- = 7a/!nara

3n s#pplying the base addresses, strcp#= > goes on copying the characters in so#rce string into the target string till it doesnJt enco#nter the end o so#rce string >DZ(@?G $t is o#r responsibility to see to it that the target string@s di*ension is big eno#gh to hold the string being copied into itG Th#s, a string gets copied into another, piece<*eal, character by characterG There is no short c#t or thisG 7et #s now atte*pt to *i*ic strcp#= >, via o#r own string copy #nction, which we will call 3strcp#= >.
main1 2 3 'har s!,r'e^ ` = 47a/!nara4 # 'har tar-et^20` # xstr' / 1 tar-et" s!,r'e 2 # rint$ 1 4@ns!,r'e strin- = 5s4" s!,r'e 2 # rint$ 1 4@ntar-et strin- = 5s4" tar-et 2 # 6 xstr' / 1 'har *t" 'har *s 2 3 Fhi%e 1 *s T= '@0' 2 3 *t = *s # s++ #

34)
t++ # 6 *t = '@0' # 6

%et .s C

The o#tp#t o the progra* wo#ld beGGG


s!,r'e strin- = 7a/!nara tar-et strin- = 7a/!nara

)ote that having copied the entire so#rce string into the target string, it is necessary to place a DZ(@ into the target string, to *ar9 its endG $ yo# loo9 at the prototype o strcp#= > standard library #nction, it loo9s li9e this:
str' / 1 'har *t" '!nst 'har *s 2 #

We didn@t #se the 9eyword const in o#r version o 3strcp#= > and still o#r #nction wor9ed correctlyG So what is the need o the const H#ali ierc What wo#ld happen i we add the ollowing lines beyond the last state*ent o 3strcp#= >cG
s=s-8# *s = '_' #

This wo#ld change the so#rce string to KKayonaraOG Can we not ens#re that the so#rce string doesn@t change even accidentally in 3strcp#= >c We can, by changing the de inition as ollowsP
=!i( xstr' / 1 'har *t" '!nst 'har *s 2 3 Fhi%e 1 *s T= '@0' 2 3

Chapter =0 #uppetting On trings


*t = *s # s++ # t+ +# 6 *t = '@0' # 6

341

8y declaring char <s as const we are declaring that the so#rce string sho#ld re*ain constant >sho#ld not change?G Th#s the const H#ali ier ens#res that yo#r progra* does not inadvertently alter a variable that yo# intended to be a constantG $t also re*inds anybody reading the progra* listing that the variable is not intended to changeG We can #se const in several sit#ationsG The ollowing code rag*ent wo#ld help yo# to i/ yo#r ideas abo#t const #rtherG
'har * = 4Ue%%!4 # )* !inter is =aria&%e" s! is strin- *) * = 'P' # )* F!r.s *) = 4D/e4 # )* F!r.s *) '!nst 'har *H = 4Ue%%!4 # )* strin- is $ixe( !inter is n!t *) *H = 'P' # )* err!r *) H = 4D/e4 # )* F!r.s *) 'har '!nst *s = 4Ue%%!4 # )* strin- is $ixe( !inter is n!t *) *s = 'P' # )* err!r *) s = 4D/e4 # )* F!r.s *) 'har * '!nst t = 4Ue%%!4 # )* !inter is $ixe( strin- is n!t *) *t = 'P' # )* F!r.s *) t = 4D/e4 # )* err!r *) '!nst 'har * '!nst , = 4Ue%%!4 # )* strin- is $ixe( s! is !inter *) *, = 'P' # )* err!r *) , = 4D/e4 # )* err!r *)

342

%et .s C

The 9eyword const can be #sed in conte/t o ordinary variables li9e int, 8loat, etcG The ollowing progra* shows how this can be doneG
main1 2 3 $%!at r" a # '!nst $%!at i = 3.14 # rint$ 1 4@nEnter ra(i,s !$ 'ir'%e 4 2 # s'an$ 1 45$4" Br 2 # a= i*r*r# rint$ 1 4@nArea !$ 'ir'%e = 5$4" a 2 # 6

strcat= >
This #nction concatenates the so#rce string at the end o the target stringG +or e/a*ple, K8o*bayO and K)agp#rO on concatenation wo#ld res#lt into a string K8o*bay)agp#rOG 2ere is an e/a*ple o strcat= > at wor9G
main1 2 3 'har s!,r'e^ ` = 4I!%.sT4 # 'har tar-et^30` = 4Ue%%!4 # str'at 1 tar-et" s!,r'e 2 # rint$ 1 4@ns!,r'e strin- = 5s4" s!,r'e 2 # rint$ 1 4@ntar-et strin- = 5s4" tar-et 2 # 6

1nd here is the o#tp#tGGG


s!,r'e strin- = I!%.sT tar-et strin- = Ue%%!I!%.sT

Chapter =0 #uppetting On trings

343

)ote that the target string has been *ade big eno#gh to hold the inal stringG $ leave it to yo# to develop yo#r own 3strcat= > on lines o 3strlen= > and 3strcp#= >.

strc1p= >
This is a #nction which co*pares two strings to ind o#t whether they are sa*e or di erentG The two strings are co*pared character by character #ntil there is a *is*atch or end o one o the strings is reached, whichever occ#rs irstG $ the two strings are identical, strc1p= > ret#rns a val#e ;eroG $ they@re not, it ret#rns the n#*eric di erence between the 1SC$$ val#es o the irst non<*atching pairs o charactersG 2ere is a progra* which p#ts strc1p= > in actionG
main1 2 3 'har strin-1^ ` = 4Cerr/4 # 'har strin-2^ ` = 4Ierr/4 # int i" 9" . # i = str'm 1 strin-1" 4Cerr/4 2 # 9 = str'm 1 strin-1" strin-2 2 # . = str'm 1 strin-1" 4Cerr/ &!/4 2 # rint$ 1 4@n5( 5( 5(4" i" 9" . 2 # 6

1nd here is the o#tp#tGGG


0 4 -32

$n the irst call to strc1p= >, the two strings are identicalRKNerryO and KNerryORand the val#e ret#rned by strc1p= > is ;eroG $n the second call, the irst character o KNerryO doesnJt *atch with the irst character o K+erryO and the res#lt is 4, which is the n#*eric

344

%et .s C

di erence between 1SC$$ val#e o DN@ and 1SC$$ val#e o D+@G $n the third call to strc1p= > KNerryO doesn@t *atch with KNerry boyO, beca#se the n#ll character at the end o KNerryO doesn@t *atch the blan9 in KNerry boyOG The val#e ret#rned is <-2, which is the val#e o n#ll character *in#s the 1SC$$ val#e o space, iGeG, DZ(@ *in#s D @, which is eH#al to <-2G The e/act val#e o *is*atch will rarely concern #sG 1ll we #s#ally want to 9now is whether or not the irst string is alphabetically be ore the second stringG $ it is, a negative val#e is ret#rned_ i it isn@t, a positive val#e is ret#rnedG 1ny non<;ero val#e *eans there is a *is*atchG Try to i*ple*ent this proced#re into a #nction 3strc1p= >G

T0o@Di1ensional 'rra# o8 Characters


$n the last chapter we saw several e/a*ples o 2<di*ensional integer arraysG 7et@s now loo9 at a si*ilar entity, b#t one dealing with charactersG 3#r e/a*ple progra* as9s yo# to type yo#r na*eG When yo# do so, it chec9s yo#r na*e against a *aster list to see i yo# are worthy o entry to the palaceG 2ere@s the progra*GGG
L(e$ine IQXE0 1 L(e$ine EQ8IQXE0 0 main1 2 3 'har master%ist^6`^10` = 3 4a.sha/4" 4 ara-4" 4raman4" 4srini=as4" 4-! a%4" 4ra9esh4 6# int i" $%a-" a # 'har /!,rname^10` #

Chapter =0 #uppetting On trings


rint$ 1 4@nEnter /!,r name 4 2 # s'an$ 1 45s4" /!,rname 2 # $%a- = EQ8IQXE0 # $!r 1 i = 0 # i ;= 5 # i++ 2 3 a = str'm 1 Bmaster%ist^i`^0`" /!,rname 2 # i$ 1 a == 0 2 3 rint$ 1 4Se%'!me" /!, 'an enter the a%a'e4 2 # $%a- = IQXE0 # &rea. # 6 6 i$ 1 $%a- == EQ8IQXE0 2 rint$ 1 47!rr/" /!, are a tres asser4 2 # 6

345

1nd here is the o#tp#t or two sa*ple r#ns o this progra*GGG


Enter /!,r name (inesh 7!rr/" /!, are a tres asser Enter /!,r name raman Se%'!me" /!, 'an enter the a%a'e

)otice how the two<di*ensional character array has been initiali;edG The order o the s#bscripts in the array declaration is i*portantG The irst s#bscript gives the n#*ber o na*es in the array, while the second s#bscript gives the length o each ite* in the arrayG $nstead o initiali;ing na*es, had these na*es been s#pplied ro* the 9eyboard, the progra* seg*ent wo#ld have loo9ed li9e thisGGG
$!r 1 i = 0 # i ;= 5 # i++ 2 s'an$ 1 45s4" Bmaster%ist^i`^0` 2 #

34"

%et .s C

While co*paring the strings thro#gh strc1p= >, note that the addresses o the strings are being passed to strc1p= >G 1s seen in the last section, i the two strings *atch, strc1p= > wo#ld ret#rn a val#e (, otherwise it wo#ld ret#rn a non<;ero val#eG The variable 8lag is #sed to 9eep a record o whether the control did reach inside the i8 or notG To begin with, we set 8lag to )3T+36)0G 7ater thro#gh the loop i the na*es *atch, 8lag is set to +36)0G When the control reaches beyond the 8or loop, i 8lag is still set to )3T+36)0, it *eans none o the na*es in the 1asterlistK LK L *atched with the one s#pplied ro* the 9eyboardG The na*es wo#ld be stored in the *e*ory as shown in +ig#re &G-G )ote that each string ends with a DZ(@G The arrange*ent as yo# can appreciate is si*ilar to that o a two<di*ensional n#*eric arrayG

65454 65464 654!4 654%4 654&4 655(4

a p r s g r

9 a a r o a

s r i p Q

h a n a e

a g n i l s

y Z( Z( v Z( h

Z(

* a

a Z(

Z( 655'>last location?

+ig#re &G-

Chapter =0 #uppetting On trings

347

2ere, 65454, 65464, 654!4, etcG are the base addresses o s#ccessive na*esG 1s seen ro* the above pattern so*e o the na*es do not occ#py all the bytes reserved or the*G +or e/a*ple, even tho#gh '( bytes are reserved or storing the na*e Ka9shayO, it occ#pies only ! bytesG Th#s, - bytes go wasteG Si*ilarly, or each na*e there is so*e a*o#nt o wastageG $n act, *ore the n#*ber o na*es, *ore wo#ld be the wastageG Can this not be avoidedc Ces, it can beGGG by #sing what is called an Darray o pointers@, which is o#r ne/t topic o disc#ssionG

'rra# o8 !ointers to Strings


1s we 9now, a pointer variable always contains an addressG There ore, i we constr#ct an array o pointers it wo#ld contain a n#*ber o addressesG 7et #s see how the na*es in the earlier e/a*ple can be stored in the array o pointersG
'har *names^ ` = 3 4a.sha/4" 4 ara-4" 4raman4" 4srini=as4" 4-! a%4" 4ra9esh4

6#

$n this declaration na1esK L is an array o pointersG $t contains base addresses o respective na*esG That is, base address o Ka9shayO is stored in na1esK)L, base address o KparagO is stored in na1esK1L and so onG This is depicted in +ig#re &G4G

34&
a9shayZ( '%2 gopalZ( 2'( ra*anZ( '&5 raQeshZ( 2'6 na*es] ^ '%2 655'4 '%& 655'6 '&5 655'% 2(' 6552( 2'(

%et .s C

srinivasZ( 2(' paragZ( '%&

2'6 65524

65522

+ig#re &G4 $n the two<di*ensional array o characters, the strings occ#pied 6( bytesG 1s against this, in array o pointers, the strings occ#py only 4' bytesRa net saving o '& bytesG 1 s#bstantial saving, yo# wo#ld agreeG 8#t reali;e that act#ally '& bytes are not saved, since '2 bytes are sacri iced or storing the addresses in the array na1esK LG Th#s, one reason to store strings in an array o pointers is to *a9e a *ore e icient #se o available *e*oryG 1nother reason to #se an array o pointers to store strings is to obtain greater ease in *anip#lation o the stringsG This is shown by the ollowing progra*sG The irst one #ses a two<di*ensional array o characters to store the na*es, whereas the second #ses an array o pointers to stringsG The p#rpose o both the progra*s is very si*pleG We want to e/change the position o the na*es Kra*anO and KsrinivasOG
)* Ex'han-e names ,sin- 2-0 arra/ !$ 'hara'ters *) main1 2 3 'har names^ `^10` = 3

Chapter =0 #uppetting On trings


4a.sha/4" 4 ara-4" 4raman4" 4srini=as4" 4-! a%4" 4ra9esh4 6# int i # 'har t # rint$ 1 4@nQri-ina%: 5s 5s4" Bnames^2`^0`" Bnames^3`^0` 2 # $!r 1 i = 0 # i ;= 9 # i++ 2 3 t = names^2`^i` # names^2` ^i` = names^3`^i` # names^3`^i` = t # 6 rint$ 1 4@nEeF: 5s 5s4" Bnames^2`^0`" Bnames^3`^0` 2 # 6

349

1nd here is the o#tp#tGGG


Qri-ina%: raman srini=as EeF: srini=as raman

)ote that in this progra* to e/change the na*es we are reH#ired to e/change corresponding characters o the two na*esG $n e ect, '( e/changes are needed to interchange two na*esG 7et #s see, i the n#*ber o e/changes can be red#ced by #sing an array o pointers to stringsG 2ere is the progra*GGG
main1 2 3 'har *names^ ` = 3

35)
4a.sha/4" 4 ara-4" 4raman4" 4srini=as4" 4-! a%4" 4ra9esh4 6# 'har *tem # rint$ 1 4Qri-ina%: 5s 5s4" names^2`" names^3` 2 # tem = names^2` # names^2` = names^3` # names^3` = tem # rint$ 1 4@nEeF: 5s 5s4" names^2`" names^3` 2 # 6

%et .s C

1nd here is the o#tp#tGGG


Qri-ina%: raman srini=as EeF: srini=as raman

The o#tp#t is sa*e as the earlier progra*G $n this progra* all that we are reH#ired to do is e/change the addresses >o the na*es? stored in the array o pointers, rather than the na*es the*selvesG Th#s, by e ecting Q#st one e/change we are able to interchange na*esG This *a9es handling strings very convenientG Th#s, ro* the point o view o e icient *e*ory #sage and ease o progra**ing, an array o pointers to strings de initely scores over a two<di*ensional character arrayG That is why, even tho#gh in principle strings can be stored and handled thro#gh a two< di*ensional array o characters, in act#al practice it is the array o pointers to strings, which is *ore co**only #sedG

Chapter =0 #uppetting On trings

351

Li1itation o8 'rra# o8 !ointers to Strings


When we are #sing a two<di*ensional array o characters we are at liberty to either initiali;e the strings where we are declaring the array, or receive the strings #sing scan8= > #nctionG 2owever, when we are #sing an array o pointers to strings we can initiali;e the strings at the place where we are declaring the array, b#t we cannot receive the strings ro* 9eyboard #sing scan8= >G Th#s, the ollowing progra* wo#ld never wor9 o#tG
main1 2 3 'har *names^6` # int i # $!r 1 i = 0 # i ;= 5 # i++ 2 3 rint$ 1 4@nEnter name 4 2 # s'an$ 1 45s4" names^i` 2 # 6 6

The progra* doesn@t wor9 beca#se_ when we are declaring the array it is containing garbage val#esG 1nd it wo#ld be de initely wrong to send these garbage val#es to scan8= > as the addresses where it sho#ld 9eep the strings received ro* the 9eyboardG

Solution
$ we are bent #pon receiving the strings ro* 9eyboard #sing scan8= > and then storing their addresses in an array o pointers to strings we can do it in a slightly ro#nd abo#t *anner as shown belowG
Lin'%,(e 4a%%!'.h4 main1 2

352
3 'har *names^6` # 'har n^50` # int %en" i # 'har * # $!r 1 i = 0 # i ;= 5 # i++ 2 3 rint$ 1 4@nEnter name 4 2 # s'an$ 1 45s4" n 2 # %en = str%en 1 n 2 # = ma%%!' 1 %en + 1 2 # str' / 1 " n 2 # names^i` = # 6 $!r 1 i = 0 # i ;= 5 # i++ 2 rint$ 1 4@n5s4" names^i` 2 # 6

%et .s C

2ere we have irst received a na*e #sing scan8= > in a string nK LG Then we have o#nd o#t its length #sing strlen= > and allocated space or *a9ing a copy o this na*eG This *e*ory allocation has been done #sing a standard library #nction called 1alloc= >G This #nction reH#ires the n#*ber o bytes to be allocated and ret#rns the base address o the ch#n9 o *e*ory that it allocatesG The address ret#rned by this #nction is always o the type %oid <G 2ence it has been converted into char < #sing a eat#re called typecastingG Typecasting is disc#ssed in detail in Chapter '5G The prototype o this #nction has been declared in the ile DallocGh@G 2ence we have Iincluded this ileG 8#t why did we not #se array to allocate *e*oryc This is beca#se with arrays we have to co**it to the si;e o the array at the ti*e o writing the progra*G 5oreover, there is no way to increase or decrease the array si;e d#ring e/ec#tion o the progra*G $n other words, when we #se arrays static *e*ory allocation ta9es placeG

Chapter =0 #uppetting On trings

353

6nli9e this, #sing 1alloc= > we can allocate *e*ory dyna*ically, d#ring e/ec#tionG The arg#*ent that we pass to 1alloc= > can be a variable whose val#e can change d#ring e/ec#tionG 3nce we have allocated the *e*ory #sing 1alloc= > we have copied the na*e received thro#gh the 9eyboard into this allocated space and inally stored the address o the allocated ch#n9 in the appropriate ele*ent o na1esK L, the array o pointers to stringsG This sol#tion s# ers in per or*ance beca#se we need to allocate *e*ory and then do the copying o string or each na*e received thro#gh the 9eyboardG

Su11ar#
>a? 1 string is nothing b#t an array o characters ter*inated by DZ(@G >b? 8eing an array, all the characters o a string are stored in contig#o#s *e*ory locationsG >c? Tho#gh scan8= > can be #sed to receive *#lti<word strings, gets= > can do the sa*e Qob in a cleaner wayG >d? 8oth print8= > and puts= > can handle *#lti<word stringsG >e? Strings can be operated #pon #sing several standard library #nctions li9e strlen= >, strcp#= >, strcat= > and strc1p= > which can *anip#late stringsG 5ore i*portantly we i*itated so*e o these #nctions to learn how these standard library #nctions are writtenG > ? Tho#gh in principle a 2<0 array can be #sed to handle several strings, in practice an array o pointers to strings is pre erred since it ta9es less space and is e icient in processing stringsG >g? 1alloc= > #nction can be #sed to allocate space in *e*ory on the ly d#ring e/ec#tion o the progra*G

B3ercise
Si1ple strings

354

%et .s C

K'L What wo#ld be the o#tp#t o the ollowing progra*sP

1a2 main1 2 3 'har '^2` = 4A4 # rint$ 1 4@n5'4" '^0` 2 # rint$ 1 4@n5s4" ' 2 # 6 1&2 main1 2 3 'har s^ ` = 4Jet !r-anise(T %earn +TT4 # rint$ 1 4@n5s4" Bs^2` 2 # rint$ 1 4@n5s4" s 2 # rint$ 1 4@n5s4" Bs 2 # rint$ 1 4@n5'4" s^2` 2 # 6 1'2 main1 2 3 'har s^ ` = 4E! tF! =ir,ses F!r. simi%ar%/4 # int i = 0 # Fhi%e 1 s^i` T= 0 2 3 rint$ 1 4@n5' 5'4" s^i`" *1 s + i 2 2 # rint$ 1 4@n5' 5'4" i^s`" *1 i + s 2 2 # i++ # 6 6 1(2 main1 2 3 'har s^ ` = 4+h,r'h-ate: n! 'h,r'h n! -ate4 # 'har t^25` # 'har *ss" *tt # ss = s # Fhi%e 1 *ss T= '@0' 2 *ss++ = *tt++ #

Chapter =0 #uppetting On trings


rint$ 1 4@n5s4" t 2 # 6

355

1e2 main1 2 3 'har str1^ ` = 3 [UR" [eR" [%R" [%R" [!R 6 # 'har str2^ ` = 4Ue%%!4 #
rint$ 1 4@n5s4" str1 2 # rint$ 1 4@n5s4" str2 2 # 6

1$2 main1 2 3 rint$ 1 5 + 4J!!( P!rnin- 4 2 # 6 1-2 main1 2 3 rint$ 1 45'4" 4a&'(e$-h4^4` 2 # 6 1h2 main1 2 3 rint$ 1 4@n5(5(4" si:e!$ 1 [3R 2" si:e!$ 1 434 2" si:e!$ 1 3 2 2 # 6
K-L ,oint o#t the errors, i any, in the ollowing progra*sP

1a2 main1 2 3 'har *str1 = 4Xnite(4 # 'har *str2 = 4Ir!nt4 # 'har *str3 # str3 = str'at 1 str1" str2 2 # rint$ 1 4@n5s4" str3 2 # 6 1&2 main1 2 3

35"
int arr^ ` = 3 [AR" [DR" [+R" [0R 6 # int i # $!r 1 i = 0 # i ;= 3 # i++ 2 rint$ 1 4@n5(4" arr^i` 2 # 6

%et .s C

1'2 main1 2 3 'har arr^8` = 4>h!m&,s4 # int i # $!r 1 i = 0 # i ;= 7 # i++ 2 rint$ 1 4@n5(4" *arr 2 # arr++ # 6
KCL +ill in the blan9sP

>a? `1` is a

while @1@ is a

>b? 1 string is ter*inated by a as G

character, which is written

>c? The array char na1eK1)L can consist o a *a/i*#* o charactersG >d? The array ele*ents are always stored in locationsG
KDL 1tte*pt the ollowingP

*e*ory

>a? Which is *ore appropriate or reading in a *#lti<word stringc


rint$1 2 s'an$1 2 ,ts1 2 >b? -ets1 2 $ the string `1lice in wonder land` is ed to the ollowing scan8= > state*ent, what will be the contents o the arrays str1, str2, str3 and str4c s'an$ 1 45s5s5s5s5s4" str1" str2" str3" str4 2 #

Chapter =0 #uppetting On trings

357

>c? Write a progra* that converts all lowercase characters in a given string to its eH#ivalent #ppercase characterG >d? Write a progra* that e/tracts part o the given string ro* the speci ied positionG +or e/a*ple, i the sting is `Wor9ing with strings is #n`, then i ro* position 4, 4 characters are to be e/tracted then the progra* sho#ld ret#rn string as `9ing`G 5oreover, i the position ro* where the string is to be e/tracted is given and the n#*ber o characters to be e/tracted is ( then the progra* sho#ld e/tract entire string >e? ro* the speci ied positionG > ? Write a progra* that converts a string li9e `'24` to an integer '24G Write a progra* that replaces two or *ore consec#tive blan9s in a string by a single blan9G +or e/a*ple, i the inp#t is
Jrim ret,rn t! the %anet !$ a esTT

the !,t ,t sh!,%( &e Jrim ret,rn t! the %anet !$ a esTT

T0o@di1ensional arra#4 'rra# o8 pointers to strings


KBL 1nswer the ollowingP

>a? 2ow *any bytes in *e*ory wo#ld be occ#pied by the ollowing array o pointers to stringsc 2ow *any bytes wo#ld be reH#ired to store the sa*e strings, i they are stored in a two<di*ensional character arrayc
'har *mess^ ` = 3 4Uammer an( t!n-s4" 48!!th an( nai%4"

35&
47 it an( !%ish4" 4G!, an( +4 6#

%et .s C

>b? Can an array o pointers to strings be #sed to collect strings ro* the 9eyboardc $ not, why notc
KFL 1tte*pt the ollowingP

>a? Write a progra* that #ses an array o pointers to strings str] ^G "eceive two strings str1 and str2 and chec9 i str1 is e*bedded in any o the strings in strK LG $ str' is o#nd, then replace it with str2G
'har *str^ ` = 3 4Se Fi%% tea'h /!, h!F t!...4" 4P!=e a m!,ntain4" 4Oe=e% a &,i%(in-4" 4Erase the ast4" 4Pa.e a mi%%i!n4" 4...a%% thr!,-h +T4

\_ +or e/a*ple i str1 contains `*o#ntain` and str2 contains `car`, then the second string in str sho#ld get changed to `5ove a car`G >b? Write a progra* to sort a set o na*es stored in an array in alphabetical orderG >c? Write a progra* to reverse the strings stored in the ollowing array o pointers to stringsP
'har *s^ ` = 3 48! err is h,man...4" 4D,t t! rea%%/ mess thin-s , ...4" 4Qne nee(s t! .n!F +TT4 6#

Chapter =0 #uppetting On trings

359

2intP Write a #nction 3strre% = string > which sho#ld reverse the contents o one stringG Call this #nction or reversing each string stored in sG >d? 0evelop a progra* that receives the *onth and year ro* the 9eyboard as integers and prints the calendar in the ollowing or*atG

Septe*ber 2((4 5on 6 '2( 2! T#e ! '4 2' 2% Wed ' % '5 22 2& Th# 2 & '6 2-( +ri '( '! 24 Sat 4 '' '% 25 S#n 5 '2 '& 26

)ote that according to the Gregorian calendar ('=('='&(( was 5ondayG With this as the base the calendar sho#ld be generatedG >e? 5odi y the above progra* s#itably so that once the calendar or a partic#lar *onth and year has been displayed on the

3")

%et .s C

screen, then #sing arrow 9eys the #ser *#st be able to change the calendar in the ollowing *annerP 6p arrow 9ey 0own arrow 9ey "ight arrow 9ey 7e t arrow 9ey P )e/t year, sa*e *onth P ,revio#s year, sa*e *onth P Sa*e year, ne/t *onth P Sa*e year, previo#s *onth

$ the escape 9ey is hit then the proced#re sho#ld stopG 2intP 6se the getGe#= > #nction disc#ssed in Chapter %, proble* n#*ber ]7^>c?G > ? 1 actory has - division and stoc9s 4 categories o prod#ctsG 1n inventory table is #pdated or each division and or each prod#ct as they are receivedG There are three independent s#ppliers o prod#cts to the actoryP >a? 0esign a data or*at to represent each transactionG (b) Write a progra* to ta9e a transaction and #pdate the inventory2 >c? $ the cost per ite* is also given write a progra* to calc#late the total inventory val#esG >g? 1 deH#e#e is an ordered set o ele*ents in which ele*ents *ay be inserted or retrieved ro* either endG 6sing an array si*#late a deH#e#e o characters and the operations retrieve le t, retrieve right, insert le t, insert rightG ./ceptional conditions s#ch as deH#e#e #ll or e*pty sho#ld be indicatedG Two pointers >na*ely, le t and right? are needed in this si*#lationG >h? Write a progra* to delete all vowels ro* a sentenceG 1ss#*e that the sentence is not *ore than %( characters longG >i? Write a progra* that will read a line and delete ro* it all occ#rrences o the word Dthe@G

Chapter =0 #uppetting On trings

3"1

>Q? Write a progra* that ta9es a set o na*es o individ#als and abbreviates the irst, *iddle and other na*es e/cept the last >9? na*e by their irst letterG Write a progra* to co#nt the n#*ber o occ#rrences o any two vowels in s#ccession in a line o te/tG +or e/a*ple, in the sentence K,leases read this application and give *e grat#ityO s#ch occ#rrences are ea, ea, #iG

1'

Structures
e Why 6se Str#ct#res 0eclaring a Str#ct#re 1ccessing Str#ct#re .le*ents 2ow Str#ct#re .le*ents are Stored e 1rray o Str#ct#res e 1dditional +eat#res o Str#ct#res e 6ses o Str#ct#res e S#**ary e ./ercise

3"3

3"4

%et .s C

hich *echanic is good eno#gh who 9nows how to repair only one type o vehiclec )oneG Sa*e thing is tr#e abo#t C lang#ageG $t wo#ldn@t have been so pop#lar had it been able to handle only all ints, or all 8loats or all chars at a ti*eG $n act when we handle real world data, we don@t #s#ally deal with little ato*s o in or*ation by the*selvesRthings li9e integers, characters and s#chG $nstead we deal with entities that are collections o things, each thing having its own attrib#tes, Q#st as the entity we call a Dboo9@ is a collection o things s#ch as title, a#thor, call n#*ber, p#blisher, n#*ber o pages, date o p#blication, etcG 1s yo# can see all this data is dissi*ilar, or e/a*ple a#thor is a string, whereas n#*ber o pages is an integerG +or dealing with s#ch collections, C provides a data type called Dstr#ct#re@G 1 str#ct#re gathers together, di erent ato*s o in or*ation that co*prise a given entityG 1nd str#ct#re is the topic o this chapterG

/h# .se Structures


We have seen earlier how ordinary variables can hold one piece o in or*ation and how arrays can hold a n#*ber o pieces o in or*ation o the sa*e data typeG These two data types can handle a great variety o sit#ationsG 8#t H#ite o ten we deal with entities that are collection o dissi*ilar data typesG +or e/a*ple, s#ppose yo# want to store data abo#t a boo9G Co# *ight want to store its na*e >a string?, its price >a loat? and n#*ber o pages in it >an int?G $ data abo#t say - s#ch boo9s is to be stored, then we can ollow two approachesP >a? Constr#ct individ#al arrays, one or storing na*es, another or storing prices and still another or storing n#*ber o pagesG >b? 6se a str#ct#re variableG 7et #s e/a*ine these two approaches one by oneG +or the sa9e o progra**ing convenience ass#*e that the na*es o boo9s wo#ld

Chapter />0 tructures

3"5

be single character longG 7et #s begin with a progra* that #ses arraysG
main1 2 3 'har name^3` # $%!at ri'e^3` # int a-es^3`" i # rint$ 1 4@nEnter names" ri'es an( n!. !$ a-es !$ 3 &!!.s@n4 2 # $!r 1 i = 0 # i ;= 2 # i++ 2 s'an$ 1 45' 5$ 5(4" Bname^i`" B ri'e^i`" B a-es^i` 2# rint$ 1 4@nAn( this is Fhat /!, entere(@n4 2 # $!r 1 i = 0 # i ;= 2 # i++ 2 rint$ 1 45' 5$ 5(@n4" name^i`" ri'e^i`" a-es^i` 2# 6

1nd here is the sa*ple r#nGGG


Enter names" ri'es an( n!. !$ a-es !$ 3 &!!.s A 100.00 354 + 256.50 682 I 233.70 512 An( this is Fhat /!, entere( A 100.000000 354 + 256.500000 682 I 233.700000 512

This approach no do#bt allows yo# to store na*es, prices and n#*ber o pagesG 8#t as yo# *#st have reali;ed, it is an #nwieldy approach that obsc#res the act that yo# are dealing with a gro#p o characteristics related to a single entityRthe boo9G

3""

%et .s C

The progra* beco*es *ore di ic#lt to handle as the n#*ber o ite*s relating to the boo9 go on increasingG +or e/a*ple, we wo#ld be reH#ired to #se a n#*ber o arrays, i we also decide to store na*e o the p#blisher, date o p#rchase o boo9, etcG To solve this proble*, C provides a special data typeRthe str#ct#reG 1 str#ct#re contains a n#*ber o data types gro#ped togetherG These data types *ay or *ay not be o the sa*e typeG The ollowing e/a*ple ill#strates the #se o this data typeG
main1 2 3 str,'t &!!. 3 'har name # $%!at ri'e # int a-es # 6# str,'t &!!. &1" &2" &3 # rint$ 1 4@nEnter names" ri'es B n!. !$ a-es !$ 3 &!!.s@n4 2 # s'an$ 1 45' 5$ 5(4" B&1.name" B&1. ri'e" B&1. a-es 2 # s'an$ 1 45' 5$ 5(4" B&2.name" B&2. ri'e" B&2. a-es 2 # s'an$ 1 45' 5$ 5(4" B&3.name" B&3. ri'e" B&3. a-es 2 # rint$ 1 4@nAn( this is Fhat /!, entere(4 2 # rint$ 1 4@n5' 5$ 5(4" &1.name" &1. ri'e" &1. a-es 2 # rint$ 1 4@n5' 5$ 5(4" &2.name" &2. ri'e" &2. a-es 2 # rint$ 1 4@n5' 5$ 5(4" &3.name" &3. ri'e" &3. a-es 2 # 6

1nd here is the o#tp#tGGG


Enter names" ri'es an( n!. !$ a-es !$ 3 &!!.s A 100.00 354 + 256.50 682 I 233.70 512

Chapter />0 tructures


An( this is Fhat /!, entere( A 100.000000 354 + 256.500000 682 I 233.700000 512

3"7

This progra* de*onstrates two #nda*ental aspects o str#ct#resP >a? declaration o a str#ct#re >b? accessing o str#ct#re ele*ents 7et #s now loo9 at these concepts one by oneG

Declaring a Structure
$n o#r e/a*ple progra*, the ollowing state*ent declares the str#ct#re typeP
str,'t &!!. 3 'har name # $%!at ri'e # int a-es # 6#

This state*ent de ines a new data type called struct 6ooGG .ach variable o this data type will consist o a character variable called na1e, a loat variable called price and an integer variable called pagesG The general or* o a str#ct#re declaration state*ent is given belowP
str,'t ;str,'t,re name< 3 str,'t,re e%ement 1 # str,'t,re e%ement 2 # str,'t,re e%ement 3 # ...... ......

3"&
6#

%et .s C

3nce the new str#ct#re data type has been de ined one or *ore variables can be declared to be o that typeG +or e/a*ple the variables 61, 62, 63 can be declared to be o the type struct 6ooG, as,
str,'t &!!. &1" &2" &3 #

This state*ent sets aside space in *e*oryG $t *a9es available space to hold all the ele*ents in the str#ct#reRin this case, ! bytes Rone or na1e, o#r or price and two or pagesG These bytes are always in adQacent *e*ory locationsG $ we so desire, we can co*bine the declaration o the str#ct#re type and the str#ct#re variables in one state*entG +or e/a*ple,
str,'t &!!. 3 'har name # $%!at ri'e # int a-es # 6# str,'t &!!. &1" &2" &3 #

is sa*e asGGG
str,'t &!!. 3 'har name # $%!at ri'e # int a-es # 6 &1" &2" &3 # !r e=en... str,'t

Chapter />0 tructures


3 'har name # $%!at ri'e # int a-es # 6 &1" &2" &3 #

3"9

7i9e pri*ary variables and arrays, str#ct#re variables can also be initiali;ed where they are declaredG The or*at #sed is H#ite si*ilar to that #sed to initiate arraysG
str,'t &!!. 3 'har name^10` # $%!at ri'e # int a-es # 6# str,'t &!!. &1 = 3 4Dasi'4" 130.00" 550 6 # str,'t &!!. &2 = 3 4?h/si's4" 150.80" 800 6 #

)ote the ollowing points while declaring a str#ct#re typeP >a? The closing brace in the str#ct#re type declaration *#st be ollowed by a se*icolonG >b? $t is i*portant to #nderstand that a str#ct#re type declaration does not tell the co*piler to reserve any space in *e*oryG 1ll a str#ct#re declaration does is, it de ines the D or*@ o the str#ct#reG >c? 6s#ally str#ct#re type declaration appears at the top o the so#rce code ile, be ore any variables or #nctions are de inedG $n very large progra*s they are #s#ally p#t in a separate header ile, and the ile is incl#ded >#sing the preprocessor directive Mincl#de? in whichever progra* we want to #se this str#ct#re typeG

37)
'ccessing Structure Ble1ents

%et .s C

2aving declared the str#ct#re type and the str#ct#re variables, let #s see how the ele*ents o the str#ct#re can be accessedG $n arrays we can access individ#al ele*ents o an array #sing a s#bscriptG Str#ct#res #se a di erent sche*eG They #se a dot >G? operatorG So to re er to pages o the str#ct#re de ined in o#r sa*ple progra* we have to #se,
&1. a-es

Si*ilarly, to re er to price we wo#ld #se,


&1. ri'e

)ote that be ore the dot there *#st always be a str#ct#re variable and a ter the dot there *#st always be a str#ct#re ele*entG

2o0 Structure Ble1ents are Stored


Whatever be the ele*ents o a str#ct#re, they are always stored in contig#o#s *e*ory locationsG The ollowing progra* wo#ld ill#strate thisP
)* Pem!r/ ma !$ str,'t,re e%ements *) main1 2 3 str,'t &!!. 3 'har name # $%!at ri'e # int a-es # 6# str,'t &!!. &1 = 3 'D'" 130.00" 550 6 # rint$ 1 4@nA((ress !$ name = 5,4" B&1.name 2 #

Chapter />0 tructures


rint$ 1 4@nA((ress !$ ri'e = 5,4" B&1. ri'e 2 # rint$ 1 4@nA((ress !$ a-es = 5,4" B&1. a-es 2 # 6

371

2ere is the o#tp#t o the progra*GGG


A((ress !$ name = 65518 A((ress !$ ri'e = 65519 A((ress !$ a-es = 65523

1ct#ally the str#ct#re ele*ents are stored in *e*ory as shown in the +ig#re '(G'G

b'Gna*e D8@ 655'% 655'&

b'Gprice '-(G((

b'Gpages 55( 6552-

+ig#re '(G'

'rra# o8 Structures
3#r sa*ple progra* showing #sage o str#ct#re is rather si*ple *indedG 1ll it does is, it receives val#es into vario#s str#ct#re ele*ents and o#tp#t these val#esG 8#t that@s all we intended to do anywayGGG show how str#ct#re types are created, how str#ct#re variables are declared and how individ#al ele*ents o a str#ct#re variable are re erencedG $n o#r sa*ple progra*, to store data o '(( boo9s we wo#ld be reH#ired to #se '(( di erent str#ct#re variables ro* 61 to 61)), which is de initely not very convenientG 1 better approach wo#ld be to #se an array o str#ct#resG +ollowing progra* shows how to #se an array o str#ct#resG

372
)* Xsa-e !$ an arra/ !$ str,'t,res *) main1 2 3 str,'t &!!. 3 'har name # $%!at ri'e # int a-es # 6# str,'t &!!. &^100` # int i #

%et .s C

$!r 1 i = 0 # i ;= 99 # i++ 2 3 rint$ 1 4@nEnter name" ri'e an( a-es 4 2 # s'an$ 1 45' 5$ 5(4" B&^i`.name" B&^i`. ri'e" B&^i`. a-es 2 # 6 $!r 1 i = 0 # i ;= 99 # i++ 2 rint$ 1 4@n5' 5$ 5(4" &^i`.name" &^i`. ri'e" &^i`. a-es 2 # 6 %in.$%!at1 2 3 $%!at a = 0" *& # & = Ba # )* 'a,se em,%at!r t! &e %in.e( *) a = *& # )* s, ress the Farnin- - =aria&%e n!t ,se( *) 6

)ow a ew co**ents abo#t the progra*P >a? )otice how the array o str#ct#res is declaredGGG
str,'t &!!. &^100` #

Chapter />0 tructures

373

This provides space in *e*ory or '(( str#ct#res o the type struct 6ooGG >b? The synta/ we #se to re erence each ele*ent o the array 6 is si*ilar to the synta/ #sed or arrays o ints and charsG +or e/a*ple, we re er to ;eroth boo9@s price as 6K)L.priceG Si*ilarly, we re er irst boo9@s pages as 6K1L.pagesG >c? $t sho#ld be appreciated what care #l tho#ght 0ennis "itchie has p#t into C lang#ageG 2e irst de ined array as a collection o si*ilar ele*ents_ then reali;ed that dissi*ilar data types that are o ten o#nd in real li e cannot be handled #sing arrays, there ore created a new data type called str#ct#reG 8#t even #sing str#ct#res progra**ing convenience co#ld not be achieved, beca#se a lot o variables >61 to 61)) or storing data abo#t h#ndred boo9s? needed to be handledG There ore he allowed #s to create an array o str#ct#res_ an array o si*ilar data types which the*selves are a collection o dissi*ilar data typesG 2ats o to the geni#s4 >d? $n an array o str#ct#res all ele*ents o the array are stored in adQacent *e*ory locationsG Since each ele*ent o this array is a str#ct#re, and since all str#ct#re ele*ents are always stored in adQacent locations yo# can very well vis#alise the arrange*ent o array o str#ct#res in *e*oryG $n o#r e/a*ple, 6K)L@s na1e, price and pages in *e*ory wo#ld be i**ediately ollowed by 6K1L@s na1e, price and pages, and so onG >e? What is the #nction linG8loat= > doing herec $ yo# don@t de ine it yo# are bo#nd to get the error `+loating ,oint +or*ats )ot 7in9ed` with *aQority o C Co*pilersG What ca#ses this error to occ#rc When parsing o#r so#rce ile, i the co*piler enco#nters a re erence to the address o a loat, it sets a lag to have the lin9er lin9 in the loating<point e*#latorG 1 loating point e*#lator is #sed to *anip#late loating point n#*bers in r#nti*e library #nctions li9e

374

%et .s C

scan8= > and ato8= >G There are so*e cases in which the re erence to the 8loat is a bit obsc#re and the co*piler does not detect the need or the e*#latorG The *ost co**on is #sing scan8= > to read a 8loat in an array o str#ct#res as shown in o#r progra*G 2ow can we orce the or*ats to be lin9edc That@s where the linG8loat= > #nction co*es inG $t orces lin9ing o the loating<point e*#lator into an applicationG There is no need to call this #nction, Q#st de ine it anywhere in yo#r progra*G

'dditional Features o8 Structures


7et #s now e/plore the intricacies o str#ct#res with a view o progra**ing convenienceG We wo#ld highlight these intricacies with s#itable e/a*plesP >a? The val#es o a str#ct#re variable can be assigned to another str#ct#re variable o the sa*e type #sing the assign*ent operatorG $t is not necessary to copy the str#ct#re ele*ents piece<*ealG 3bvio#sly, progra**ers pre er assign*ent to piece<*eal copyingG This is shown in the ollowing e/a*pleG
main1 2 3 str,'t em %!/ee 3 'har name^10` # int a-e # $%!at sa%ar/ # 6# str,'t em %!/ee e1 = 3 47an9a/4" 30" 5500.50 6 # str,'t em %!/ee e2" e3 # )* ie'e-mea% '! /in- *) str' / 1 e2.name" e1.name 2 # e2.a-e = e1.a-e #

Chapter />0 tructures


e2.sa%ar/ = e1.sa%ar/ # )* '! /in- a%% e%ements at !ne -! *) e3 = e2 # rint$ 1 4@n5s 5( 5$4" e1.name" e1.a-e" e1.sa%ar/ 2 # rint$ 1 4@n5s 5( 5$4" e2.name" e2.a-e" e2.sa%ar/ 2 # rint$ 1 4@n5s 5( 5$4" e3.name" e3.a-e" e3.sa%ar/ 2 # 6

375

The o#tp#t o the progra* wo#ld beGGG


7an9a/ 30 5500.500000 7an9a/ 30 5500.500000 7an9a/ 30 5500.500000

1bility to copy the contents o all str#ct#re ele*ents o one variable into the corresponding ele*ents o another str#ct#re variable is rather s#rprising, since C does not allow assigning the contents o one array to another Q#st by eH#ating the twoG 1s we saw earlier, or copying arrays we have to copy the contents o the array ele*ent by ele*entG This copying o all str#ct#re ele*ents at one go has been possible only beca#se the str#ct#re ele*ents are stored in contig#o#s *e*ory locationsG 2ad this not been so, we wo#ld have been reH#ired to copy str#ct#re variables ele*ent by ele*entG 1nd who 9nows, had this been so, str#ct#res wo#ld not have beco*e pop#lar at allG >b? 3ne str#ct#re can be nested within another str#ct#reG 6sing this acility co*ple/ data types can be createdG The ollowing progra* shows nested str#ct#res at wor9G
main1 2 3 str,'t a((ress

37"
3 'har h!ne^15` # 'har 'it/^25` # int in #

%et .s C

6# str,'t em 3 'har name^25` # str,'t a((ress a # 6# str,'t em e = 3 49er,4" 45310464" 4na- ,r4" 10 6# rint$ 1 4@nname = 5s h!ne = 5s4" e.name" e.a. h!ne 2 # rint$ 1 4@n'it/ = 5s in = 5(4" e.a.'it/" e.a. in 2 # 6

1nd here is the o#tp#tGGG


name = 9er, h!ne = 531046 'it/ = na- ,r in = 10

)otice the *ethod #sed to access the ele*ent o a str#ct#re that is part o another str#ct#reG +or this the dot operator is #sed twice, as in the e/pression,
e.a. in !r e.a.'it/

3 co#rse, the nesting process need not stop at this levelG We can nest a str#ct#re within a str#ct#re, within another str#ct#re, which is in still another str#ct#re and so onGGG till the ti*e we can co*prehend the str#ct#re o#rselvesG S#ch constr#ction however gives rise to variable na*es that can be s#rprisingly sel descriptive, or e/a*pleP
mar,ti.en-ine.&!%t.%ar-e.Ht/

Chapter />0 tructures

377

This clearly signi ies that we are re erring to the H#antity o large si;ed bolts that it on an engine o a *ar#ti carG >c? 7i9e an ordinary variable, a str#ct#re variable can also be passed to a #nctionG We *ay either pass individ#al str#ct#re ele*ents or the entire str#ct#re variable at one goG 7et #s e/a*ine both the approaches one by one #sing s#itable progra*sG
)* ?assin- in(i=i(,a% str,'t,re e%ements *) main1 2 3 str,'t &!!. 3 'har name^25` # 'har a,th!r^25` # int 'a%%n! # 6# str,'t &!!. &1 = 3 4Oet ,s +4" 4G?_4" 101 6 # (is %a/ 1 &1.name" &1.a,th!r" &1.'a%%n! 2 # 6 (is %a/ 1 'har *s" 'har *t" int n 2 3 rint$ 1 4@n5s 5s 5(4" s" t" n 2 # 6

1nd here is the o#tp#tGGG


Oet ,s + G?_ 101

3bserve that in the declaration o the str#ct#re, na1e and author have been declared as arraysG There ore, when we call the #nction displa#= > #sing,
(is %a/ 1 &1.name" &1.a,th!r" &1.'a%%n! 2 #

37&

%et .s C

we are passing the base addresses o the arrays na1e and author, b#t the val#e stored in callnoG Th#s, this is a *i/ed callRa call by re erence as well as a call by val#eG $t can be i**ediately reali;ed that to pass individ#al ele*ents wo#ld beco*e *ore tedio#s as the n#*ber o str#ct#re ele*ents go on increasingG 1 better way wo#ld be to pass the entire str#ct#re variable at a ti*eG This *ethod is shown in the ollowing progra*G
str,'t &!!. 3 'har name^25` # 'har a,th!r^25` # int 'a%%n! # 6# main1 2 3 str,'t &!!. &1 = 3 4Oet ,s +4" 4G?_4" 101 6 # (is %a/ 1 &1 2 # 6 (is %a/ 1 str,'t &!!. & 2 3 rint$ 1 4@n5s 5s 5(4" &.name" &.a,th!r" &.'a%%n! 2 # 6

1nd here is the o#tp#tGGG


Oet ,s + G?_ 101

)ote that here the calling o #nction displa#= > beco*es H#ite co*pact,
(is %a/ 1 &1 2 #

Chapter />0 tructures

379

2aving collected what is being passed to the displa#= > #nction, the H#estion co*es, how do we de ine the or*al arg#*ents in the #nctionG We cannot say,
str,'t &!!. &1 #

beca#se the data type struct 6ooG is not 9nown to the #nction displa#= >G There ore, it beco*es necessary to de ine the str#ct#re type struct 6ooG o#tside 1ain= >, so that it beco*es 9nown to all #nctions in the progra*G >d? The way we can have a pointer pointing to an int, or a pointer pointing to a char, si*ilarly we can have a pointer pointing to a structG S#ch pointers are 9nown as Dstr#ct#re pointers@G 7et #s loo9 at a progra* that de*onstrates the #sage o a str#ct#re pointerG
main1 2 3 str,'t &!!. 3 'har name^25` # 'har a,th!r^25` # int 'a%%n! # 6# str,'t &!!. &1 = 3 4Oet ,s +4" 4G?_4" 101 6 # str,'t &!!. * tr # tr = B&1 # rint$ 1 4@n5s 5s 5(4" &1.name" &1.a,th!r" &1.'a%%n! 2 # rint$ 1 4@n5s 5s 5(4" tr-<name" tr-<a,th!r" tr-<'a%%n! 2 # 6

The irst print8= > is as #s#alG The second print8= > however is pec#liarG We can@t #se ptr.na1e or ptr.callno beca#se ptr is not a str#ct#re variable b#t a pointer to a str#ct#re, and the dot

3&)

%et .s C

operator reH#ires a str#ct#re variable on its le tG $n s#ch cases C provides an operator @C, called an arrow operator to re er to the str#ct#re ele*entsG "e*e*ber that on the le t hand side o the MGO str#ct#re operator, there *#st always be a str#ct#re variable, whereas on the le t hand side o the D@CO operator there *#st always be a pointer to a str#ct#reG The arrange*ent o the str#ct#re variable and pointer to str#ct#re in *e*ory is shown in the +ig#re '(G2G

b'Gna*e 7et 6s C 654!2

b'Ga#thor C,K 654&! ptr 654!2 65524

b'Gcallno '(' 65522

+ig#re '(G2 Can we not pass the address o a str#ct#re variable to a #nctionc We canG The ollowing progra* de*onstrates thisG
)* ?assin- a((ress !$ a str,'t,re =aria&%e *) str,'t &!!. 3 'har name^25` # 'har a,th!r^25` # int 'a%%n! # 6# main1 2 3 str,'t &!!. &1 = 3 4Oet ,s +4" 4G?_4" 101 6 # (is %a/ 1 B&1 2 #

Chapter />0 tructures


6 (is %a/ 1 str,'t &!!. *& 2 3 rint$ 1 4@n5s 5s 5(4" &-<name" &-<a,th!r" &-<'a%%n! 2 # 6

3&1

1nd here is the o#tp#tGGG


Oet ,s + G?_ 101

1gain note that to access the str#ct#re ele*ents #sing pointer to a str#ct#re we have to #se the D@CO operatorG 1lso, the str#ct#re struct 6ooG sho#ld be declared o#tside 1ain= > s#ch that this data type is available to displa#= > while declaring pointer to the str#ct#reG >e? Consider the ollowing code snippetP
str,'t em 3 int a # 'har 'h # $%!at s # 6# str,'t em e # rint$ 1 45, 5, 5,4" Be.a" Be.'h" Be.s 2 #

$ we e/ec#te this progra* #sing TC=TCLL co*piler we get the addresses asP
65518 65520 65521

1s e/pected, in *e*ory the char begins i**ediately a ter the int and 8loat begins i**ediately a ter the charG

3&2

%et .s C

2owever, i we r#n the sa*e progra* #sing VCLL co*piler then the o#tp#t t#rns o#t to beP
1245044 1245048 1245052

$t can be observed ro* this o#tp#t that the 8loat doesn@t get stored i**ediately a ter the charG $n act there is a hole o three bytes a ter the charG 7et #s #nderstand the reason or thisG VCLL is a -2<bit co*piler targeted to generate code or a -2<bit *icroprocessorG The architect#re o this *icroprocessor is s#ch that it is able to etch the data that is present at an address, which is a *#ltiple o o#r *#ch aster than the data present at any other addressG 2ence the VCLL co*piler aligns every ele*ent o a str#ct#re at an address that is *#ltiple o o#rG That@s the reason why there were three holes created between the char and the 8loatG 2owever, so*e progra*s need to e/ercise precise control over the *e*ory areas where data is placedG +or e/a*ple, s#ppose we wish to read the contents o the boot sector > irst sector on the loppy=hard dis9? into a str#ct#reG +or this the byte arrange*ent o the str#ct#re ele*ents *#st *atch the arrange*ent o vario#s ields in the boot sector o the dis9G The Iprag1a pacG directive o ers a way to #l ill this reH#ire*entG This directive speci ies pac9ing align*ent or str#ct#re *e*bersG The prag*a ta9es e ect at the irst str#ct#re declaration a ter the prag*a is seenG T#rbo C=CLL co*piler doesn@t s#pport this eat#re, VCLL co*piler doesG The ollowing code shows how to #se this directiveG
L ra-ma a'.112 str,'t em 3 int a # 'har 'h # $%!at s # 6#

Chapter />0 tructures


L ra-ma a'.1 2 str,'t em e # rint$ 1 45, 5, 5,4" Be.a" Be.'h" Be.s 2 #

3&3

2ere, Iprag1a pacG = 1 > lets each str#ct#re ele*ent to begin on a '<byte bo#ndary as Q#sti ied by the o#tp#t o the progra* given belowP
1245044 1245048 1245049

.ses o8 Structures
Where are str#ct#res #se #lc The i**ediate application that co*es to the *ind is 0atabase 5anage*entG That is, to *aintain data abo#t e*ployees in an organi;ation, boo9s in a library, ite*s in a store, inancial acco#nting transactions in a co*pany etcG 8#t *ind yo#, #se o str#ct#res stretches *#ch beyond database *anage*entG They can be #sed or a variety o p#rposes li9eP >a? >b? >c? >d? >e? >? >g? >h? >i? >Q? >9? >l? Changing the si;e o the c#rsor Clearing the contents o the screen ,lacing the c#rsor at an appropriate position on screen 0rawing any graphics shape on the screen "eceiving a 9ey ro* the 9eyboard Chec9ing the *e*ory si;e o the co*p#ter +inding o#t the list o eH#ip*ent attached to the co*p#ter +or*atting a loppy 2iding a ile ro* the directory 0isplaying the directory o a dis9 Sending the o#tp#t to printer $nteracting with the *o#se

1nd that is certainly a very i*pressive list4 1t least i*pressive eno#gh to *a9e yo# reali;e how i*portant a data type a str#ct#re is and to be thoro#gh with it i yo# intend to progra* any o the

3&4

%et .s C

above applicationsG So*e o these applications wo#ld be disc#ssed in Chapters '6 to '&G

Su11ar#
>a? 1 str#ct#re is #s#ally #sed when we wish to store dissi*ilar data togetherG >b? Str#ct#re ele*ents can be accessed thro#gh a str#ct#re variable #sing a dot >G? operatorG >c? Str#ct#re ele*ents can be accessed thro#gh a pointer to a str#ct#re #sing the arrow ><b? operatorG >d? 1ll ele*ents o one str#ct#re variable can be assigned to another str#ct#re variable #sing the assign*ent >X? operatorG >e? $t is possible to pass a str#ct#re variable to a #nction either by val#e or by addressG > ? $t is possible to create an array o str#ct#resG

B3ercise
K'L What wo#ld be the o#tp#t o the ollowing progra*sP 1a2 main1 2 3 str,'t -!s e% 3 int n,m # 'har mess1^50` # 'har mess2^50` # 6m# m.n,m = 1 # str' / 1 m.mess1" 4I$ a%% that /!, ha=e is hammer4 2 # str' / 1 m.mess2" 4E=er/thin- %!!.s %i.e a nai%4 2 # )* ass,me that the str,',re is %!'ate( at a((ress 1004 *) rint$ 1 4@n5, 5, 5,4" Bm.n,m" m.mess1" m.mess2 2 #

Chapter />0 tructures


1&2 str,'t -!s e% 3 int n,m # 'har mess1^50` # 'har mess2^50` # 6 m1 = 3 2" 4I$ /!, are (ri=en &/ s,''ess4" 4ma.e s,re that it is a H,a%it/ (ri=e4 6# main1 2 3 str,'t -!s e% m2" m3 # m2 = m1 # m3 = m2 # rint$ 1 4@n5( 5s 5s4" m1.n,m" m2.mess1" m3.mess2 2 # 6

3&5

K-L ,oint o#t the errors, i any, in the ollowing progra*sP 1a2 main1 2 3 str,'t em %!/ee 3 'har name^25` # int a-e # $%!at &s # 6# str,'t em %!/ee e # str' / 1 e.name" 4Ua'.er4 2 # a-e = 25 # rint$ 1 4@n5s 5(4" e.name" a-e 2 # 6 1&2 main1 2 3 str,'t 3 'har name^25` #

3&"
'har %an-,a-e^10` # 6# str,'t em %!/ee e = 3 4Ua'.er4" 4+4 6 # rint$ 1 4@n5s 5(4" e.name" e.%an-,a-e 2 # 6 1'2 str,'t =ir,s 3 'har si-nat,re^25` # 'har stat,s^20` # int si:e # 6 =^2` = 3 4Gan.ee 0!!(%e4" 40ea(%/4" 1813" 40ar. A=en-er4" 4_i%%er4" 1795 6# main1 2 3 int i # $!r 1 i = 0 # i ;=1 # i++ 2 rint$ 1 4@n5s 5s4" =.si-nat,re" =.stat,s 2 # 6 1(2 str,'t s 3 'har 'h # int i # $%!at a # 6# main1 2 3 str,'t s =ar = 3 '+'" 100" 12.55 6 # $ 1 =ar 2 # - 1 B=ar 2 # 6 $ 1 str,'t s = 2 3 rint$ 1 4@n5' 5( 5$4" = -< 'h" = -< i" = -< a 2 # 6

%et .s C

Chapter />0 tructures


- 1 str,'t s *= 2 3 rint$ 1 4@n5' 5( 5$4" =.'h" =.i" =.a 2 # 6 1e2 str,'t s 3 int i # str,'t s * # 6# main1 2 3 str,'t s =ar1" =ar2 # =ar1.i = 100 # =ar2.i = 200 # =ar1. = B=ar2 # =ar2. = B=ar1 # rint$ 1 4@n5( 5(4" =ar1. -< i" =ar2. -< i 2 # 6 KCL 1nswer the ollowingP

3&7

>a? Ten loats are to be stored in *e*oryG What wo#ld yo# pre er, an array or a str#ct#rec >b? Given the state*ent,
mar,ti.en-ine.&!%ts = 25 #

which o the ollowing is Tr#ec 'G 2G -G 4G str#ct#re bolts is nested within str#ct#re engine str#ct#re engine is nested within str#ct#re *ar#ti str#ct#re *ar#ti is nested within str#ct#re engine str#ct#re *ar#ti is nested within str#ct#re bolts

>c? State Tr#e or +alseP 'G 1ll str#ct#re ele*ents are stored in contig#o#s *e*ory locationsG

3&&

%et .s C

2G 1n array sho#ld be #sed to store dissi*ilar ele*ents, and a str#ct#re to store si*ilar ele*entsG -G $n an array o str#ct#res, not only are all str#ct#res stored in contig#o#s *e*ory locations, b#t the ele*ents o individ#al str#ct#res are also stored in contig#o#s locationsG >d? str#ct ti*e 3 int h!,rs # int min,tes # int se'!n(s # 6t# str,'t time *tt # tt = Bt # 7oo9ing at the above declarations, which o the ollowing re ers to seconds correctlyP 'G ttGseconds 2G > Wtt ?Gseconds -G ti*eGt 4G tt <b seconds
KDL 1tte*pt the ollowingP

>a? Create a str#ct#re to speci y data on st#dents given belowP "oll n#*ber, )a*e, 0epart*ent, Co#rse, Cear o Qoining 1ss#*e that there are not *ore than 45( st#dents in the collageG >a? Write a #nction to print na*es o all st#dents who Qoined in a partic#lar yearG >b? Write a #nction to print the data o a st#dent whose roll n#*ber is givenG

Chapter />0 tructures

3&9

>b? Create a str#ct#re to speci y data o c#sto*ers in a ban9G The data to be stored isP 1cco#nt n#*ber, )a*e, 8alance in acco#ntG 1ss#*e *a/i*#* o 2(( c#sto*ers in the ban9G >a? Write a #nction to print the 1cco#nt n#*ber and na*e o each c#sto*er with balance below "sG '((G >b? $ a c#sto*er reH#est or withdrawal or deposit, it is given in the or*P 1cctG no, a*o#nt, code >' or deposit, ( or withdrawal? Write a progra* to give a *essage, KThe balance is ins# icient or the speci ied withdrawalOG >c? 1n a#to*obile co*pany has serial n#*ber or engine parts starting ro* 11( to ++&G The other characteristics o parts to be speci ied in a str#ct#re areP Cear o *an# act#re, *aterial and H#antity *an# act#redG >a? Speci y a str#ct#re to store in or*ation corresponding to a partG >b? Write a progra* to retrieve in or*ation on parts with serial n#*bers between 88' and CC6G >d? 1 record contains na*e o cric9eter, his age, n#*ber o test *atches that he has played and the average r#ns that he has scored in each test *atchG Create an array o str#ct#re to hold records o 2( s#ch cric9eter and then write a progra* to read these records and arrange the* in ascending order by average r#nsG 6se the Qusort= > standard library #nctionG >e? There is a str#ct#re called e1plo#ee that holds in or*ation li9e e*ployee code, na*e, date o QoiningG Write a progra* to create an array o the str#ct#re and enter so*e data into itG Then as9 the #ser to enter c#rrent dateG 0isplay the na*es o those e*ployees whose ten#re is - or *ore than - years according to the given c#rrent dateG > ? Write a *en# driven progra* that depicts the wor9ing o a libraryG The *en# options sho#ld beP

39)
'G 2G -G 4G 5G 6G !G 1dd boo9 in or*ation 0isplay boo9 in or*ation 7ist all boo9s o given a#thor 7ist the title o speci ied boo9 7ist the co#nt o boo9s in the library 7ist the boo9s in the order o accession n#*ber ./it

%et .s C

Create a str#ct#re called li6rar# to hold accession n#*ber, title o the boo9, a#thor na*e, price o the boo9, and lag indicating whether boo9 is iss#ed or notG >g? Write a progra* that co*pares two given datesG To store date #se str#ct#re say date that contains three *e*bers na*ely date, *onth and yearG $ the dates are eH#al then display *essage as `.H#al` otherwise `6neH#al`G >h? 7in9ed list is a very co**on data str#ct#re o ten #sed to store si*ilar data in *e*oryG While the ele*ents o an array occ#py contig#o#s *e*ory locations, those o a lin9ed list are not constrained to be stored in adQacent locationG The individ#al ele*ents are stored Kso*ewhereO in *e*ory, rather li9e a a*ily dispersed, b#t still bo#nd togetherG The order o the ele*ents is *aintained by e/plicit lin9s between the*G Th#s, a lin9ed list is a collection o ele*ents called nodes, each o which stores two ite* o in or*ationRan ele*ent o the list, and a lin9, iGeG, a pointer or an address that indicates e/plicitly the location o the node containing the s#ccessor o this list ele*entG Write a progra* to b#ild a lin9ed list by adding new nodes at the beginning, at the end or in the *iddle o the lin9ed listG 1lso write a #nction displa#= > which display all the nodes present in the lin9ed listG >i? 1 stac9 is a data str#ct#re in which addition o new ele*ent or deletion o e/isting ele*ent always ta9es place at the sa*e

Chapter />0 tructures

391

endG This end is o ten 9nown as Dtop@ o stac9G This sit#ation can be co*pared to a stac9 o plates in a ca eteria where every new plate ta9en o the stac9 is also ro* the Dtop@ o the stac9G There are several application where stac9 can be p#t to #seG +or e/a*ple, rec#rsion, 9eeping trac9 o #nction calls, eval#ation o e/pressions, etcG Write a progra* to i*ple*ent a stac9 #sing a lin9ed listG >Q? 6nli9e a stac9, in a H#e#e the addition o new ele*ent ta9es place at the end >called Drear@ o H#e#e? whereas deletion ta9es place at the other end >called D ront@ o H#e#e?G Write a progra* to i*ple*ent a H#e#e #sing a lin9ed listG

392

%et .s C

11

Console (nput)&utput
e Types o $=3 e Console $=3 +#nctions +or*atted Console $=3 +#nctions sprintf> ? and sscanf> ? +#nctions 6n or*atted Console $=3 +#nctions e S#**ary e ./ercise

393

394

%et .s C

s *entioned in the irst chapter, 0ennis "itchie wanted C to re*ain co*pactG $n 9eeping with this intention he deliberately o*itted everything related with $np#t=3#tp#t >$=3? ro* his de inition o the lang#ageG Th#s, C si*ply has no provision or receiving data ro* any o the inp#t devices >li9e say 9eyboard, dis9, etcG?, or or sending data to the o#tp#t devices >li9e say V06, dis9, etcG?G Then how do we *anage $=3, and how is it that we were we able to #se print8= > and scan8= > i C has nothing to o er or $=3c This is what we intend to e/plore in this chapterG

T#pes o8 *+(
Tho#gh C has no provision or $=3, it o co#rse has to be dealt with at so*e point or the otherG There is not *#ch #se writing a progra* that spends all its ti*e telling itsel a secretG .ach 3perating Syste* has its own acility or inp#tting and o#tp#tting data ro* and to the iles and devicesG $t@s a si*ple *atter or a syste* progra**er to write a ew s*all progra*s that wo#ld lin9 the C co*piler or partic#lar 3perating syste*@s $=3 acilitiesG The developers o C Co*pilers do Q#st thatG They write several standard $=3 #nctions and p#t the* in librariesG These libraries are available with all C co*pilersG Whichever C co*piler yo# are #sing it@s al*ost certain that yo# have access to a library o $=3 #nctionsG 0o #nderstand that the $=3 acilities with di erent operating syste*s wo#ld be di erentG Th#s, the way one 3S displays o#tp#t on screen *ay be di erent than the way another 3S does itG +or e/a*ple, the standard library #nction print8= > or 03S<based C co*piler has been written 9eeping in *ind the way 03S o#tp#ts characters to screenG Si*ilarly, the print8= > #nction or a 6ni/< based co*piler has been written 9eeping in *ind the way 6ni/ o#tp#ts characters to screenG We as progra**ers do not have to bother abo#t which print8= > has been written in what *annerG We sho#ld Q#st #se print8= > and it wo#ld ta9e care o the rest o the

Chapter //0 Console +nput?Output

395

details that are 3S dependentG Sa*e is tr#e abo#t all other standard library #nctions available or $=3G There are n#*ero#s library #nctions available or $=3G These can be classi ied into three broad categoriesP >a? Console $=3 #nctions < +#nctions to receive inp#t ro* 9eyboard and write o#tp#t to V06G +#nctions to per or* $=3 operations on a loppy dis9 or hard dis9G

>b?

+ile $=3 #nctions

<

$n this chapter we wo#ld be disc#ssing only Console $=3 #nctionsG +ile $=3 #nctions wo#ld be disc#ssed in Chapter '2G

Console *+( Functions


The screen and 9eyboard together are called a consoleG Console $=3 #nctions can be #rther classi ied into two categoriesR or*atted and #n or*atted console $=3 #nctionsG The basic di erence between the* is that the or*atted #nctions allow the inp#t read ro* the 9eyboard or the o#tp#t displayed on the V06 to be or*atted as per o#r reH#ire*entsG +or e/a*ple, i val#es o average *ar9s and percentage *ar9s are to be displayed on the screen, then the details li9e where this o#tp#t wo#ld appear on the screen, how *any spaces wo#ld be present between the two val#es, the n#*ber o places a ter the deci*al points, etcG can be controlled #sing or*atted #nctionsG The #nctions available #nder each o these two categories are shown in +ig#re ''G'G )ow let #s disc#ss these console $=3 #nctions in detailG

39"
Console $np#t=3#tp#t #nctions

%et .s C

For1atted 8unctions T#pe char int loat string *nput scan > ? scan > ? scan > ? scan > ? (utput print > ? print > ? print > ? print > ?

.n8or1atted 8unctions T#pe char int loat string *nput getch> ? getche> ? getchar> ? < < gets> ? (utput p#tch> ? p#tchar> ? < < p#ts> ?

+ig#re ''G'

For1atted Console *+( Functions


1s can be seen ro* +ig#re ''G' the #nctions print8= >4 and scan8= > all #nder the category o or*atted console $=3 #nctionsG These #nctions allow #s to s#pply the inp#t in a i/ed or*at and let #s obtain the o#tp#t in the speci ied or*G 7et #s disc#ss these #nctions one by oneG We have tal9ed a lot abo#t print8= >, #sed it reg#larly, b#t witho#t having introd#ced it or*allyG Well, better late than neverG $ts general or* loo9s li9e thisGGG
rint$ 1 4$!rmat strin-4" %ist !$ =aria&%es 2 #

The or*at string can containP >a? Characters that are si*ply printed as they are >b? Conversion speci ications that begin with a U sign

Chapter //0 Console +nput?Output


>c? .scape seH#ences that begin with a Z sign +or e/a*ple, loo9 at the ollowing progra*P
main1 2 3 int a=- = 346 # $%!at er = 69.2 # rint$ 1 4A=era-e = 5(@n?er'enta-e = 5$4" a=-" er 2 # 6

397

The o#tp#t o the progra* wo#ld beGGG


A=era-e = 346 ?er'enta-e = 69.200000

2ow does print8= > #nction interpret the contents o the or*at stringG +or this it e/a*ines the or*at string ro* le t to rightG So long as it doesn@t co*e across either a A or a Z it contin#es to d#*p the characters that it enco#nters, on to the screenG $n this e/a*ple '%erage F is d#*ped on the screenG The *o*ent it co*es across a conversion speci ication in the or*at string it pic9s #p the irst variable in the list o variables and prints its val#e in the speci ied or*atG $n this e/a*ple, the *o*ent Ad is *et the variable a%g is pic9ed #p and its val#e is printedG Si*ilarly, when an escape seH#ence is *et it ta9es the appropriate actionG $n this e/a*ple, the *o*ent En is *et it places the c#rsor at the beginning o the ne/t lineG This process contin#es till the end o or*at string is not reachedG

For1at Speci8ications
The Ad and A8 #sed in the print8= > are called or*at speci iersG They tell print8= > to print the val#e o a%g as a deci*al integer and the val#e o per as a loatG +ollowing is the list o or*at speci iers that can be #sed with the print8= > #nctionG

39&
Data t#pe $nteger short signed short #nsigned long singed long #nsigned #nsigned he/adeci*al #nsigned octal "eal Character String loat do#ble signed character #nsigned character For1at speci8ier Ud or U$ U# Uld Ul# U/ Uo U Ul Uc Uc Us

%et .s C

+ig#re ''G2 We can provide speci icationsG


Speci8ier dd G

ollowing optional speci iers in the

or*at

Description 0igits speci ying ield width 0eci*al point separating ield width ro* precision >precision stands or the n#*ber o places a ter the deci*al point? 0igits speci ying precision 5in#s sign or le t Q#sti ying the o#tp#t in the speci ied ield width

dd <

+ig#re ''G-

Chapter //0 Console +nput?Output

399

)ow a short e/planation abo#t these optional or*at speci iersG The ield<width speci ier tells print8= > how *any col#*ns on screen sho#ld be #sed while printing a val#eG +or e/a*ple, A1)d says, Kprint the variable as a deci*al integer in a ield o '( col#*nsOG $ the val#e to be printed happens not to ill #p the entire ield, the val#e is right Q#sti ied and is padded with blan9s on the le tG $ we incl#de the *in#s sign in or*at speci ier >as in A@1)d?, this *eans le t Q#sti ication is desired and the val#e will be padded with blan9s on the rightG 2ere is an e/a*ple that sho#ld *a9e this point clearG
main1 2 3 int Fei-ht = 63 # rint$ 1 4@nFei-ht is 5( .-4" Fei-ht 2 # rint$ 1 4@nFei-ht is 52( .-4" Fei-ht 2 # rint$ 1 4@nFei-ht is 54( .-4" Fei-ht 2 # rint$ 1 4@nFei-ht is 56( .-4" Fei-ht 2 # rint$ 1 4@nFei-ht is 5-6( .-4" Fei-ht 2 # 6

The o#tp#t o the progra* wo#ld loo9 li9e this GGG


+!%,mns 0123456789012345678901234567890 Fei-ht is 63 .Fei-ht is 63 .Fei-ht is 63 .Fei-ht is 63 .Fei-ht is 63 .-

Speci ying the ield width can be #se #l in creating tables o n#*eric val#es, as the ollowing progra* de*onstratesG
main1 2 3 rint$ 1 4@n5$ 5$ 5$4" 5.0" 13.5" 133.9 2 #

4))
rint$ 1 4@n5$ 5$ 5$4" 305.0" 1200.9" 3005.3 2 # 6

%et .s C

1nd here is the o#tp#tGGG


5.000000 13.500000 133.900000 305.000000 1200.900000 3005.300000

.ven tho#gh the n#*bers have been printed, the n#*bers have not been lined #p properly and hence are hard to readG 1 better way wo#ld be so*ething li9e thisGGG
main1 2 3 rint$ 1 4@n510.1$ 510.1$ 510.1$4" 5.0" 13.5" 133.9 2 # rint$ 1 4@n510.1$ 510.1$ 510.1$4" 305.0" 1200.9" 3005.3 2# 6

This res#lts into a *#ch better o#tp#tGGG


01234567890123456789012345678901 5.0 13.5 133.9 305.0 1200.9 3005.3

The or*at speci iers co#ld be #sed even while displaying a string o charactersG The ollowing progra* wo#ld clari y this pointP
)* I!rmattin- strin-s Fith rint$1 2 *) main1 2 3 'har $irstname1^ ` = 47an(/4 # 'har s,rname1^ ` = 4Pa%/a4 # 'har $irstname2^ ` = 4A9a/_,mar4 # 'har s,rname2^ ` = 4J,r,&axani4 # rint$ 1 4@n520s520s4" $irstname1" s,rname1 2 # rint$ 1 4@n520s520s4" $irstname2" s,rname2 2 #

Chapter //0 Console +nput?Output


6

4)1

1nd here@s the o#tp#tGGG


012345678901234567890123456789012345678901234567890 7an(/ Pa%/a A9a/_,mar J,r,&axani

The or*at speci ier A2)s reserves 2( col#*ns or printing a string and then prints the string in these 2( col#*ns with right Q#sti icationG This helps lining #p na*es o di erent lengths properlyG 3bvio#sly, the or*at A@2)s wo#ld have le t Q#sti ied the stringG

Bscape SeQuences
We saw earlier how the newline character, En, when inserted in a print8= >@s or*at string, ta9es the c#rsor to the beginning o the ne/t lineG The newline character is an Descape seH#ence@, so called beca#se the bac9slash sy*bol >Z? is considered as an Descape@ characterRit ca#ses an escape ro* the nor*al interpretation o a string, so that the ne/t character is recogni;ed as one having a special *eaningG The ollowing e/a*ple shows #sage o En and a new escape seH#ence Zt, called Dtab@G 1 Et *oves the c#rsor to the ne/t tab stopG 1 %(<col#*n screen #s#ally has '( tab stopsG $n other words, the screen is divided into '( ;ones o % col#*ns eachG ,rinting a tab ta9es the c#rsor to the beginning o ne/t printing ;oneG +or e/a*ple, i c#rsor is positioned in col#*n 5, then printing a tab ta9es it to col#*n %G
main1 2 3 rint$ 1 4G!,@tm,st@t&e@t'ra:/@nt!@thate@tthis@t&!!.4 2 # 6

4)2
1nd here@s the o#tp#tGGG
1 2 3 4 01234567890123456789012345678901234567890 G!, m,st &e 'ra:/ t! hate this &!!.

%et .s C

The En character ca#ses a new line to begin ollowing Dcra;y@G The tab and newline are probably the *ost co**only #sed escape seH#ences, b#t there are others as wellG +ig#re ''G4 shows a co*plete list o these escape seH#encesG

Bsc. SeQ. Zn Zb Z Z@ ZZ

!urpose )ew line 8ac9space +or* eed Single H#ote 8ac9slash

Bsc. SeQ. Zt Zr Za ZO

!urpose Tab Carriage ret#rn 1lert 0o#ble H#ote

+ig#re ''G4 The irst ew o these escape seH#ences are *ore or less sel < e/planatoryG E6 *oves the c#rsor one position to the le t o its c#rrent positionG Er ta9es the c#rsor to the beginning o the line in which it is c#rrently placedG Ea alerts the #ser by so#nding the spea9er inside the co*p#terG +or* eed advances the co*p#ter stationery attached to the printer to the top o the ne/t pageG Characters that are ordinarily #sed as deli*itersGGG the single H#ote, do#ble H#ote, and the bac9slash can be printed by preceding the* with the bac9slashG Th#s, the state*ent,
rint$ 1 4Ue sai(" @4Oet's (! itT@44 2 #

Chapter //0 Console +nput?Output


will printGGG
Ue sai(" 4Oet's (! itT4

4)3

So ar we have been describing print8= >Os speci ication as i we are orced to #se only Ad or an integer, only Ac or a char, only As or a string and so onG This is not tr#e at allG $n act, print8= > #ses the speci ication that we *ention and atte*pts to per or* the speci ied conversion, and does its best to prod#ce a proper res#ltG So*eti*es the res#lt is nonsensical, as in case when we as9 it to print a string #sing AdG So*eti*es the res#lt is #se #l, as in the case we as9 print8= > to print 1SC$$ val#e o a character #sing AdG So*eti*es the res#lt is disastro#s and the entire progra* blows #pG The ollowing progra* shows a ew o these conversions, so*e sensible, so*e weirdG
main1 2 3 'har 'h = ':' # int i = 125 # $%!at a = 12.55 # 'har s^ ` = 4he%%! there T4 # rint$ 1 4@n5' 5( 5$4" 'h" 'h" 'h 2 # rint$ 1 4@n5s 5( 5$4" s" s" s 2 # rint$ 1 4@n5' 5( 5$4"i "i" i 2 # rint$ 1 4@n5$ 5(@n4" a" a 2 # 6

1nd here@s the o#tp#t GGG


: 122 -9362831782501783000000000000000000000000000.000000 he%%! there T 3280 9362831782501783000000000000000000000000000.000000 6 125 -9362831782501783000000000000000000000000000.000000

4)4
12.550000 0

%et .s C

$ wo#ld leave it to yo# to analy;e the res#lts by yo#rselvesG So*e o the conversions yo# wo#ld ind are H#ite sensibleG 7et #s now t#rn o#r attention to scan8= >G scan8= > allows #s to enter data ro* 9eyboard that will be or*atted in a certain wayG The general or* o scan8= > state*ent is as ollowsP
s'an$ 1 4$!rmat strin-4" %ist !$ a((resses !$ =aria&%es 2 #

+or e/a*pleP
s'an$ 1 45( 5$ 5'4" B'" Ba" B'h 2 #

)ote that we are sending addresses o variables >addresses are obtained by #sing D O the Daddress o @ operator? to scan8= > #nctionG This is necessary beca#se the val#es received ro* 9eyboard *#st be dropped into variables corresponding to these addressesG The val#es that are s#pplied thro#gh the 9eyboard *#st be separated by either blan9>s?, tab>s?, or newline>s?G 0o not incl#de these escape seH#ences in the or*at stringG 1ll the or*at speci ications that we learnt in print8= > #nction are applicable to scan8= > #nction as wellG

sprintf( ) and sscanf( ) Functions


The sprint8= > #nction wor9s si*ilar to the print8= > #nction e/cept or one s*all di erenceG $nstead o sending the o#tp#t to the screen as print8= > does, this #nction writes the o#tp#t to an array o charactersG The ollowing progra* ill#strates thisG
main1 2 3

Chapter //0 Console +nput?Output


int i = 10 # 'har 'h = 'A' # $%!at a = 3.14 # 'har str^20` # rint$ 1 4@n5( 5' 5$4" i" 'h" a 2 # s rint$ 1 str" 45( 5' 5$4" i" 'h" a 2 # rint$ 1 4@n5s4" str 2 # 6

4)5

$n this progra* the print8= > prints o#t the val#es o i, ch and a on the screen, whereas sprint8= > stores these val#es in the character array strG Since the string str is present in *e*ory what is written into str #sing sprint8= > doesn@t get displayed on the screenG 3nce str has been b#ilt, its contents can be displayed on the screenG $n o#r progra* this was achieved by the second print8= > state*entG The co#nterpart o sprint8= > is the sscan8= > #nctionG $t allows #s to read characters ro* a string and to convert and store the* in C variables according to speci ied or*atsG The sscan8= > #nction co*es in handy or in<*e*ory conversion o characters to val#esG Co# *ay ind it convenient to read in strings ro* a ile and then e/tract val#es ro* a string by #sing sscan8= >G The #sage o sscan8= > is sa*e as scan8= >, e/cept that the irst arg#*ent is the string ro* which reading is to ta9e placeG

.n8or1atted Console *+( Functions


There are several standard library #nctions available #nder this categoryRthose that can deal with a single character and those that can deal with a string o charactersG +or openers let #s loo9 at those which handle one character at a ti*eG So ar or inp#t we have consistently #sed the scan8= > #nctionG 2owever, or so*e sit#ations the scan8= > #nction has one glaring wea9nessGGG yo# need to hit the .nter 9ey be ore the #nction can

4)"

%et .s C

digest what yo# have typedG 2owever, we o ten want a #nction that will read a single character the instant it is typed witho#t waiting or the .nter 9ey to be hitG getch= > and getche= > are two #nctions which serve this p#rposeG These #nctions ret#rn the character that has been *ost recently typedG The De@ in getche= > #nction *eans it echoes >displays? the character that yo# typed to the screenG 1s against this getch= > Q#st ret#rns the character that yo# typed witho#t echoing it on the screenG getchar= > wor9s si*ilarly and echo@s the character that yo# typed on the screen, b#t #n ort#nately reH#ires .nter 9ey to be typed ollowing the character that yo# typedG The di erence between getchar= > and 8getchar= > is that the or*er is a *acro whereas the latter is a #nctionG 2ere is a sa*ple progra* that ill#strates the #se o these #nctionsG
main1 2 3 'har 'h # rint$ 1 4@n?ress an/ .e/ t! '!ntin,e4 2 # -et'h1 2 # )* Fi%% n!t e'h! the 'hara'ter *) rint$ 1 4@n8/ e an/ 'hara'ter4 2 # 'h = -et'he1 2 # )* Fi%% e'h! the 'hara'ter t/ e( *) rint$ 1 4@n8/ e an/ 'hara'ter4 2 # -et'har1 2 # )* Fi%% e'h! 'hara'ter" m,st &e $!%%!Fe( &/ enter .e/ *) rint$ 1 4@n+!ntin,e G)E4 2 # $-et'har1 2 # )* Fi%% e'h! 'hara'ter" m,st &e $!%%!Fe( &/ enter .e/ *) 6

1nd here is a sa*ple r#n o this progra*GGG


?ress an/ .e/ t! '!ntin,e 8/ e an/ 'hara'ter D 8/ e an/ 'hara'ter S +!ntin,e G)E G

Chapter //0 Console +nput?Output

4)7

putch= > and putchar= > or* the other side o the coinG They print a character on the screenG 1s ar as the wor9ing o putch= > putchar= > and 8putchar= > is concerned it@s e/actly sa*eG The ollowing progra* ill#strates thisG
main1 2 3 'har 'h = 'A' # ,t'h 1 'h 2 # ,t'har 1 'h 2 # $ ,t'har 1 'h 2 # ,t'h 1 'b' 2 # ,t'har 1 'b' 2 # $ ,t'har 1 'b' 2 # 6

1nd here is the o#tp#tGGG


AAAbbb

The li*itation o putch= >4 putchar= > and 8putchar= > is that they can o#tp#t only one character at a ti*eG

gets( ) and puts( )


gets= > receives a string ro* the 9eyboardG Why is it neededc 8eca#se scan8= > #nction has so*e li*itations while receiving string o characters, as the ollowing e/a*ple ill#stratesGGG
main1 2 3 'har name^50` # rint$ 1 4@nEnter name 4 2 # s'an$ 1 45s4" name 2 # rint$ 1 45s4" name 2 #

4)&
6

%et .s C

1nd here is the o#tp#tGGG


Enter name C!nt/ >h!(es C!nt/

S#rprisedc Where did K"hodesO goc $t never got stored in the array na1eK L4 beca#se the *o*ent the blan9 was typed a ter KNontyO scan8= > ass#*ed that the na*e being entered has endedG The res#lt is that there is no way >at least not witho#t a lot o tro#ble on the progra**er@s part? to enter a *#lti<word string into a single variable >na1e in this case? #sing scan8= >. The sol#tion to this proble* is to #se gets= > #nctionG 1s said earlier, it gets a string ro* the 9eyboardG $t is ter*inated when an .nter 9ey is hitG Th#s, spaces and tabs are per ectly acceptable as part o the inp#t stringG 5ore e/actly, gets= > gets a newline >En? ter*inated string o characters ro* the 9eyboard and replaces the En with a E)G The puts= > #nction wor9s e/actly opposite to gets= > #nctionG $t o#tp#ts a string to the screenG 2ere is a progra* which ill#strates the #sage o these #nctionsP
main1 2 3 'har $!!t&a%%er^40` # ,ts 1 4Enter name4 2 # -ets 1 $!!t&a%%er 2 # )* sen(s &ase a((ress !$ arra/ *) ,ts 1 4Ua / $!!t&a%%in-T4 2 # ,ts 1 $!!t&a%%er 2 # 6

+ollowing is the sa*ple o#tp#tP


Enter name

Chapter //0 Console +nput?Output


C!nt/ >h!(es Ua / $!!t&a%%in-T C!nt/ >h!(es

4)9

Why did we #se two puts= > #nctions to print K2appy ootballing4O and KNonty "hodesOc 8eca#se, #nli9e print8= >4 puts= > can o#tp#t only one string at a ti*eG $ we atte*pt to print two strings #sing puts= >4 only the irst one gets printedG Si*ilarly, #nli9e scan8= >4 gets= > can be #sed to read only one string at a ti*eG

Su11ar#
>a? There is no 9eyword available in C or doing inp#t=o#tp#tG >b? 1ll $=3 in C is done #sing standard library #nctionsG >c? There are several #nctions available or per or*ing console inp#t=o#tp#tG >d? The or*atted console $=3 #nctions can orce the #ser to receive the inp#t in a i/ed or*at and display the o#tp#t in a i/ed or*atG >e? There are several or*at speci iers and escape seH#ences available to or*at inp#t and o#tp#tG > ? 6n or*atted console $=3 #nctions wor9 aster since they do not have the overheads o or*atting the inp#t or o#tp#tG

B3ercise
K'L What wo#ld be the o#tp#t o the ollowing progra*sP 1a2 main1 2 3 'har 'h # 'h = -et'har1 2 # i$ 1 is%!Fer 1 'h 2 2 ,t'har 1 t!, er 1 'h 2 2 # e%se ,t'har 1 t!%!Fer 1 'h 2 2 #

41)
6 1&2 main1 2 3 int i = 2 # $%!at $ = 2.5367 # 'har str^ ` = 4Oi$e is %i.e that4 # rint$ 1 4@n54(@t53.3$@t54s4" i" $" str 2 # 6 1'2 main1 2 3 rint$ 1 4P!re !$ten than @&@& n!t @rthe ers!n Fh! @ Fins is the !ne Fh! thin.s he 'anT4 2 # 6

%et .s C

1(2 'har ^ ` = 48he sixth si'. shei.h's sixth shi is si'.4 # main1 2 3 int i = 0 # Fhi%e 1 ^i` T= '@0' 2 3 ,t'h 1 ^i` 2 # i++ # 6 6 K-L ,oint o#t the errors, i any, in the ollowing progra*sP 1a2 main1 2 3 int i # 'har a^ ` = 4Ue%%!4 # Fhi%e 1 a T= '@0' 2 3 rint$ 1 45'4" *a 2 # a++ # 6 6

Chapter //0 Console +nput?Output


1&2 main1 2 3 (!,&%e (=a% # s'an$ 1 45$4" B(=a% 2 # rint$ 1 4@n0!,&%e ]a%,e = 5%$4" (=a% 2 # 6 1'2 main1 2 3 int i=a% # s'an$ 1 45(@n4" Bn 2 # rint$ 1 4@nInte-er ]a%,e = 5(4" i=a% 2 # 6

411

1(2 main1 2 3 'har *mess^5` # $!r 1 i = 0 # i ; 5 # i++ 2 s'an$ 1 45s4" mess^i` 2 # 6 1e2 main1 2 3 int ((" mm" // # rint$ 1 4@nEnter (a/" m!nth an( /ear@n4 2 # s'an$ 1 45(5*'5(5*'5(4" B((" Bmm" B// 2 # rint$ 1 48he (ate is: 5( - 5( - 5(4" ((" mm" // 2 # 6 1$2 main1 2 3 'har text # s rint$ 1 text" 454(@t52.2$@n5s4" 12" 3.452" 4Perr/ J! >!,n(4 2 # rint$ 1 4@n5s4" text 2 # 6

1-2 main1 2 3 'har &,$$er^50` #

412
int n! = 97# (!,&%e =a% = 2.34174 # 'har name^10` = 47hFeta4 # s rint$ 1 &,$$er" 45( 5%$ 5s4" n!" =a%" name 2 # rint$ 1 4@n5s4" &,$$er 2 # ss'an$ 1 &,$$er" 454( 52.2%$ 5s4" Bn!" B=a%" name 2 # rint$ 1 4@n5s4" &,$$er 2 # rint$ 1 4@n5( 5%$ 5s4" n!" =a%" name 2 # 6 KCL 1nswer the ollowingP

%et .s C

>a? To receive the string `We have got the g#ts, yo# get the glory44` in an array char strK1))L which o the ollowing #nctions wo#ld yo# #sec 'G scan > `Us`, str ? _ 2G gets > str ? _ -G getche > str ? _ 4G getchar > str ? _ >b? Which #nction wo#ld yo# #se i a single 9ey were to be received thro#gh the 9eyboardc 'G 2G -G 4G scan > ? gets> ? getche> ? getchar> ?

>c? $ an integer is to be entered thro#gh the 9eyboard, which #nction wo#ld yo# #sec 'G 2G -G 4G scan > ? gets> ? getche> ? getchar> ?

Chapter //0 Console +nput?Output

413

>d? $ a character string is to be received thro#gh the 9eyboard which #nction wo#ld wor9 asterc 'G scan > ? 2G gets> ? >e? What is the di erence between getchar= >, 8getchar= >, getch= > and getche= >c >? The or*at string o a print8= > #nction can containP 'G 2G -G >g? 4G Characters, or*at speci ications and escape seH#ences Character, integers and loats Strings, integers and escape seH#ences $nverted co**as, percentage sign and bac9slash character

1 ield<width speci ier in a print8= > #nctionP 'G 2G -G 4G Controls the *argins o the progra* listing Speci ies the *a/i*#* val#e o a n#*ber Controls the si;e o type #sed to print n#*bers Speci ies how *any col#*ns will be #sed to print the n#*ber

KDL 1nswer the ollowingP

>a? Write down two #nctions 3gets= > and 3puts= > which wor9 si*ilar to the standard library #nctions gets= > and puts= >G >b? Write down a #nction getint= >, which wo#ld receive a n#*eric string ro* the 9eyboard, convert it to an integer n#*ber and ret#rn the integer to the calling #nctionG 1 sa*ple #sage o getint= > is shown belowP
main1 2 3 int a #

414
a = -etint1 2 # rint$ 1 4/!, entere( 5(4" a 2 6

%et .s C

12

File (nput)&utput
e 0ata 3rgani;ation e +ile 3perations 3pening a +ile "eading ro* a +ile Tro#ble in 3pening a +ile Closing the +ile e Co#nting Characters, Tabs, Spaces, : e 1 +ile<copy ,rogra* Writing to a +ile e +ile 3pening 5odes e String >line? $=3 in +iles The 1w9ward )ewline e "ecord $=3 in +iles e Te/t +iles and 8inary +iles e "ecord $=3 "evisited e 0atabase 5anage*ent e 7ow 7evel 0is9 $=3 1 7ow 7evel +ile<copy ,rogra* e $=3 6nder Windows e S#**ary e ./ercise

415

41"

%et .s C

ten it is not eno#gh to Q#st display the data on the screenG This is beca#se i the data is large, only a li*ited a*o#nt o it can be stored in *e*ory and only a li*ited a*o#nt o it can be displayed on the screenG $t wo#ld be inappropriate to store this data in *e*ory or one *ore reasonG 5e*ory is volatile and its contents wo#ld be lost once the progra* is ter*inatedG So i we need the sa*e data again it wo#ld have to be either entered thro#gh the 9eyboard again or wo#ld have to be regenerated progra**aticallyG 3bvio#sly both these operations wo#ld be tedio#sG 1t s#ch ti*es it beco*es necessary to store the data in a *anner that can be later retrieved and displayed either in part or in wholeG This *edi#* is #s#ally a D ile@ on the dis9G This chapter disc#sses how ile $=3 operations can be per or*edG

Data (rganiHation
8e ore we start doing ile inp#t=o#tp#t let #s irst ind o#t how data is organi;ed on the dis9G 1ll data stored on the dis9 is in binary or*G 2ow this binary data is stored on the dis9 varies ro* one 3S to anotherG 2owever, this does not a ect the C progra**er since he has to #se only the library #nctions written or the partic#lar 3S to be able to per or* inp#t=o#tp#tG $t is the co*piler vendor@s responsibility to correctly i*ple*ent these library #nctions by ta9ing the help o 3SG This is ill#strated in +ig#re '2G'G

3#r progra*

C 7ibrary #nctions

3S

0is9

+ig#re '2G'

Chapter /40 &ile +nput?Output

417

File (perations
There are di erent operations that can be carried o#t on a ileG These areP >a? >b? >c? >d? >e? >? Creation o a new ile 3pening an e/isting ile "eading ro* a ile Writing to a ile 5oving to a speci ic location in a ile >see9ing? Closing a ile

7et #s now write a progra* to read a ile and display its contents on the screenG We will irst list the progra* and show what it does, and then dissect it line by lineG 2ere is the listing:
)* 0is %a/ '!ntents !$ a $i%e !n s'reen. *) L in'%,(e 4st(i!.h4 main1 2 3 IIOE *$ # 'har 'h # $ = $! en 1 4?>1.+4" 4r4 2 # Fhi%e 1 1 2 3 'h = $-et' 1 $ 2 # i$ 1 'h == EQI 2 &rea. # rint$ 1 45'4" 'h 2 # 6 6 $'%!se 1 $ 2 #

41&

%et .s C

3n e/ec#tion o this progra* it displays the contents o the ile D,"'GC@ on the screenG 7et #s now #nderstand how it does the sa*eG

(pening a File
8e ore we can read >or write? in or*ation ro* >to? a ile on a dis9 we *#st open the ileG To open the ile we have called the #nction 8open= >G $t wo#ld open a ile K,"'GCO in Dread@ *ode, which tells the C co*piler that we wo#ld be reading the contents o the ileG )ote that KrO is a string and not a character_ hence the do#ble H#otes and not single H#otesG $n act 8open= > per or*s three i*portant tas9s when yo# open the ile in KrO *odeP >a? +irstly it searches on the dis9 the ile to be openedG >b? Then it loads the ile ro* the dis9 into a place in *e*ory called b# erG >c? $t sets #p a character pointer that points to the irst character o the b# erG Why do we need a b# er at allc $*agine how ine icient it wo#ld be to act#ally access the dis9 every ti*e we want to read a character ro* itG .very ti*e we read so*ething ro* a dis9, it ta9es so*e ti*e or the dis9 drive to position the read=write head correctlyG 3n a loppy dis9 syste*, the drive *otor has to act#ally start rotating the dis9 ro* a standstill position every ti*e the dis9 is accessedG $ this were to be done or every character we read ro* the dis9, it wo#ld ta9e a long ti*e to co*plete the reading operationG This is where a b# er co*es inG $t wo#ld be *ore sensible to read the contents o the ile into the b# er while opening the ile and then read the ile character by character ro* the b# er rather than ro* the dis9G This is shown in +ig#re '2G2G

Chapter /40 &ile +nput?Output

419

,"'GC 5e*ory 4( 0$SK p 4( 8# er

+ig#re '2G2 Sa*e arg#*ent also applies to writing in or*ation in a ileG $nstead o writing characters in the ile on the dis9 one character at a ti*e it wo#ld be *ore e icient to write characters in a b# er and then inally trans er the contents ro* the b# er to the dis9G To be able to s#ccess #lly read ro* a ile in or*ation li9e *ode o opening, si;e o ile, place in the ile ro* where the ne/t read operation wo#ld be per or*ed, etcG has to be *aintainedG Since all this in or*ation is inter<related, all o it is gathered together by 8open= > in a str#ct#re called F*LBG 8open= > ret#rns the address o this str#ct#re, which we have collected in the str#ct#re pointer called 8pG We have declared 8p as
IIOE *$ #

42)

%et .s C

The F*LB str#ct#re has been de ined in the header ile KstdioGhO >standing or standard inp#t=o#tp#t header ile?G There ore, it is necessary to Iinclude this ileG

$eading 8ro1 a File


3nce the ile has been opened or reading #sing 8open= >, as we have seen, the ile@s contents are bro#ght into b# er >partly or wholly? and a pointer is set #p that points to the irst character in the b# erG This pointer is one o the ele*ents o the str#ct#re to which 8p is pointing >re er +ig#re '2G2?G To read the ile@s contents ro* *e*ory there e/ists a #nction called 8getc= >G This has been #sed in o#r progra* as,
'h = $-et' 1 $ 2 #

8getc= > reads the character ro* the c#rrent pointer position, advances the pointer position so that it now points to the ne/t character, and ret#rns the character that is read, which we collected in the variable chG )ote that once the ile has been opened, we no longer re er to the ile by its na*e, b#t thro#gh the ile pointer 8pG We have #sed the #nction 8getc= > within an inde inite 0hile loopG There has to be a way to brea9 o#t o this 0hileG When shall we brea9 o#tGGG the *o*ent we reach the end o ileG 8#t what is end o ilec 1 special character, whose 1SC$$ val#e is 26, signi ies end o ileG This character is inserted beyond the last character in the ile, when it is createdG While reading ro* the ile, when 8getc= > enco#nters this special character, instead o ret#rning the character that it has read, it ret#rns the *acro .3+G The .3+ *acro has been de ined in the ile KstdioGhOG $n place o the #nction 8getc= > we co#ld have as well #sed the *acro getc= > with the sa*e e ectG

Chapter /40 &ile +nput?Output

421

$n o#r progra* we go on reading each character ro* the ile till end o ile is not *etG 1s each character is read we display it on the screenG 3nce o#t o the loop, we close the ileG

Trou6le in (pening a File


There is a possibility that when we try to open a ile #sing the #nction 8open= >, the ile *ay not be openedG While opening the ile in KrO *ode, this *ay happen beca#se the ile being opened *ay not be present on the dis9 at allG 1nd yo# obvio#sly cannot read a ile that doesn@t e/istG Si*ilarly, while opening the ile or writing, 8open= > *ay ail d#e to a n#*ber o reasons, li9e, dis9 space *ay be ins# icient to open a new ile, or the dis9 *ay be write protected or the dis9 is da*aged and so onG Cr#/ o the *atter is that it is i*portant or any progra* that accesses dis9 iles to chec9 whether a ile has been opened s#ccess #lly be ore trying to read or write to the ileG $ the ile opening ails d#e to any o the several reasons *entioned above, the 8open= > #nction ret#rns a val#e )677 >de ined in KstdioGhO as Ide8ine 9.LL )?G 2ere is how this can be handled in a progra*GGG
Lin'%,(e 4st(i!.h4 main1 2 3 IIOE *$ # $ = $! en 1 4?>1.+4" 4r4 2 # i$ 1 $ == EXOO 2 3 ,ts 1 4'ann!t ! en $i%e4 2 # exit1 2 # 6

422
Closing the File

%et .s C

When we have inished reading ro* the ile, we need to close itG This is done #sing the #nction 8close= > thro#gh the state*ent,
$'%!se 1 $ 2 #

3nce we close the ile we can no longer read ro* it #sing getc= > #nless we reopen the ileG )ote that to close the ile we don@t #se the ilena*e b#t the ile pointer 8pG 3n closing the ile the b# er associated with the ile is re*oved ro* *e*oryG $n this progra* we have opened the ile or readingG S#ppose we open a ile with an intention to write characters into itG This ti*e too a b# er wo#ld get associated with itG When we atte*pt to write characters into this ile #sing 8putc= > the characters wo#ld get written to the b# erG When we close this ile #sing 8close= > three operations wo#ld be per or*edP >a? The characters in the b# er wo#ld be written to the ile on the dis9G >b? 1t the end o ile a character with 1SC$$ val#e 26 wo#ld get writtenG >c? The b# er wo#ld be eli*inated ro* *e*oryG Co# can i*agine a possibility when the b# er *ay beco*e #ll be ore we close the ileG $n s#ch a case the b# er@s contents wo#ld be written to the dis9 the *o*ent it beco*es #llG 1ll this b# er *anage*ent is done or #s by the library #nctionsG

Counting Characters4 Ta6s4 Spaces4 [


2aving #nderstood the irst ile $=3 progra* in detail let #s now try o#r hand at one *oreG 7et #s write a progra* that will read a ile and co#nt how *any characters, spaces, tabs and newlines are present in itG 2ere is the progra*:

Chapter /40 &ile +nput?Output


)* +!,nt 'hars" s a'es" ta&s an( neF%ines in a $i%e *) L in'%,(e 4st(i!.h4 main1 2 3 IIOE *$ # 'har 'h # int n!% = 0" n!t = 0" n!& = 0" n!' = 0 # $ = $! en 1 4?>1.+4" 4r4 2 # Fhi%e 1 1 2 3 'h = $-et' 1 $ 2 # i$ 1 'h == EQI 2 &rea. # n!'++ # i$ 1 'h == ' ' 2 n!&++ # i$ 1 'h == '@n' 2 n!%++ # i$ 1 'h == '@t' 2 n!t++ # 6 $'%!se 1 $ 2 # rint$ 1 4@nE,m&er !$ 'hara'ters = 5(4" n!' 2 # rint$ 1 4@nE,m&er !$ &%an.s = 5(4" n!& 2 # rint$ 1 4@nE,m&er !$ ta&s = 5(4" n!t 2 # rint$ 1 4@nE,m&er !$ %ines = 5(4" n!% 2 # 6

423

424
2ere is a sa*ple r#nGGG
E,m&er !$ 'hara'ters = 125 E,m&er !$ &%an.s = 25 E,m&er !$ ta&s = 13 E,m&er !$ %ines = 22

%et .s C

The above statistics are tr#e or a ile K,"'GCO, which $ had on *y dis9G Co# *ay give any other ilena*e and obtain di erent res#ltsG $ believe the progra* is sel <e/planatoryG $n this progra* too we have opened the ile or reading and then read it character by characterG 7et #s now try a progra* that needs to open a ile or writingG

' File@cop# !rogra1


We have already #sed the #nction 8getc= > which reads characters ro* a ileG $ts co#nterpart is a #nction called 8putc= > which writes characters to a ileG 1s a practical #se o these character $=3 #nctions we can copy the contents o one ile into another, as de*onstrated in the ollowing progra*G This progra* ta9es the contents o a ile and copies the* into another ile, character by characterG
Lin'%,(e 4st(i!.h4 main1 2 3 IIOE *$s" *$t # 'har 'h # $s = $! en 1 4 r1.'4" 4r4 2 # i$ 1 $s == EXOO 2 3 ,ts 1 4+ann!t ! en s!,r'e $i%e4 2 # exit1 2 #

Chapter /40 &ile +nput?Output


6 $t = $! en 1 4 r2.'4" 4F4 2 # i$ 1 $t == EXOO 2 3 ,ts 1 4+ann!t ! en tar-et $i%e4 2 # $'%!se 1 $s 2 # exit1 2 # 6 Fhi%e 1 1 2 3 'h = $-et' 1 $s 2 # i$ 1 'h == EQI 2 &rea. # e%se $ ,t' 1 'h" $t 2 # 6 $'%!se 1 $s 2 # $'%!se 1 $t 2 # 6

425

$ hope *ost o the st# in the progra* can be easily #nderstood, since it has already been dealt with in the earlier sectionG What is new is only the #nction 8putc= >G 7et #s see how it wor9sG

/riting to a File
The 8putc= > #nction is si*ilar to the putch= > #nction, in the sense that both o#tp#t charactersG 2owever, putch= > #nction always writes to the V06, whereas, 8putc= > writes to the ileG Which ilec The ile signi ied by 8tG The writing process contin#es till all characters ro* the so#rce ile have been written to the target ile, ollowing which the 0hile loop ter*inatesG

42"

%et .s C

)ote that o#r sa*ple ile<copy progra* is capable o copying only te/t ilesG To copy iles with e/tension G.A. or GC35, we need to open the iles in binary *ode, a topic that wo#ld be dealt with in s# icient detail in a later sectionG

File (pening ,odes


$n o#r irst progra* on dis9 $=3 we have opened the ile in read >KrO? *odeG 2owever, KrO is b#t one o the several *odes in which we can open a ileG +ollowing is a list o all possible *odes in which a ile can be openedG The tas9s per or*ed by 8open= > when a ile is opened in each o these *odes are also *entionedG `r` Searches ileG $ the ile is opened s#ccess #lly 8open= > loads it into *e*ory and sets #p a pointer which points to the irst character in itG $ the ile cannot be opened 8open= > ret#rns )677G 3perations possible F reading ro* the ileG `w` Searches ileG $ the ile e/ists, its contents are overwrittenG $ the ile doesn@t e/ist, a new ile is createdG "et#rns )677, i #nable to open ileG 3perations possible F writing to the ileG `a` Searches ileG $ the ile is opened s#ccess #lly 8open= > loads it into *e*ory and sets #p a pointer that points to the last character in itG $ the ile doesn@t e/ist, a new ile is createdG "et#rns )677, i #nable to open ileG 3perations possible < adding new contents at the end o ileG `rL` Searches ileG $ is opened s#ccess #lly 8open= > loads it into *e*ory and sets #p a pointer which points to the irst character in itG "et#rns )677, i #nable to open the ileG

Chapter /40 &ile +nput?Output

427

3perations possible < reading e/isting contents, writing new contents, *odi ying e/isting contents o the ileG `wL` Searches ileG $ the ile e/ists, its contents are overwrittenG $ the ile doesn@t e/ist a new ile is createdG "et#rns )677, i #nable to open ileG 3perations possible < writing new contents, reading the* bac9 and *odi ying e/isting contents o the ileG `aL` Searches ileG $ the ile is opened s#ccess #lly 8open= > loads it into *e*ory and sets #p a pointer which points to the irst character in itG $ the ile doesn@t e/ist, a new ile is createdG "et#rns )677, i #nable to open ileG 3perations possible < reading e/isting contents, appending new contents to end o ileG Cannot *odi y e/isting contentsG

String =line> *+( in Files


+or *any p#rposes, character $=3 is Q#st what is neededG 2owever, in so*e sit#ations the #sage o #nctions that read or write entire strings *ight t#rn o#t to be *ore e icientG "eading or writing strings o characters ro* and to iles is as easy as reading and writing individ#al charactersG 2ere is a progra* that writes strings to a ile #sing the #nction 8puts= >G
)* >e'ei=es strin-s $r!m .e/&!ar( an( Frites them t! $i%e *) Lin'%,(e 4st(i!.h4 main1 2 3 IIOE *$ # 'har s^80` #

42&
$ = $! en 1 4?QEP.8\84" 4F4 2 # i$ 1 $ == EXOO 2 3 ,ts 1 4+ann!t ! en $i%e4 2 # exit1 2 # 6 rint$ 1 4@nEnter a $eF %ines !$ text:@n4 2 # Fhi%e 1 str%en 1 -ets 1 s 2 2 < 0 2 3 $ ,ts 1 s" $ 2 # $ ,ts 1 4@n4" $ 2 # 6 $'%!se 1 $ 2 # 6

%et .s C

1nd here is a sa*ple r#n o the progra*GGG


Enter a $eF %ines !$ text: 7hinin- an( &ri-ht" the/ are $!re=er" s! tr,e a&!,t (iam!n(s" m!re s! !$ mem!ries" es e'ia%%/ /!,rs T

)ote that each string is ter*inated by hitting enterG To ter*inate the e/ec#tion o the progra*, hit enter at the beginning o a lineG This creates a string o ;ero length, which the progra* recogni;es as the signal to close the ile and e/itG We have set #p a character array to receive the string_ the 8puts= > #nction then writes the contents o the array to the dis9G Since 8puts= > does not a#to*atically add a newline character to the end o the string, we *#st do this e/plicitly to *a9e it easier to read the string bac9 ro* the ileG 2ere is a progra* that reads strings ro* a dis9 ileG

Chapter /40 &ile +nput?Output


)* >ea(s strin-s $r!m the $i%e an( (is %a/s them !n s'reen *) Lin'%,(e 4st(i!.h4 main1 2 3 IIOE *$ # 'har s^80` # $ = $! en 1 4?QEP.8\84" 4r4 2 # i$ 1 $ == EXOO 2 3 ,ts 1 4+ann!t ! en $i%e4 2 # exit1 2 # 6 Fhi%e 1 $-ets 1 s" 79" $ 2 T= EXOO 2 rint$ 1 45s4 " s 2 # $'%!se 1 $ 2 # 6

429

1nd here is the o#tp#tGGG


7hinin- an( &ri-ht" the/ are $!re=er" s! tr,e a&!,t (iam!n(s" m!re s! !$ mem!ries" es e'ia%%/ /!,rs T

The #nction 8gets= > ta9es three arg#*entsG The irst is the address where the string is stored, and the second is the *a/i*#* length o the stringG This arg#*ent prevents 8gets= > ro* reading in too long a string and over lowing the arrayG The third arg#*ent, as #s#al, is the pointer to the str#ct#re F*LBG When all the lines ro* the ile have been read, we atte*pt to read one *ore line, in which case 8gets= > ret#rns a 9.LLG

43)
The '0G0ard 9e0line

%et .s C

We had earlier written a progra* that co#nts the total n#*ber o characters present in a ileG $ we #se that progra* to co#nt the n#*ber o characters present in the above poe* >stored in the ile K,3.5GTATO?, it wo#ld give #s the character co#nt as '('G The sa*e ile i seen in the directory, wo#ld be reported to contain '(5 charactersG This discrepancy occ#rs beca#se when we atte*pt to write a KZnO to the ile #sing 8puts= >, 8puts= > converts the En to ErEn co*binationG 2ere Er stands or carriage ret#rn and En or line eedG $ we read the sa*e line bac9 #sing 8gets= > the reverse conversion happensG Th#s when we write the irst line o the poe* and a KZnO #sing two calls to 8puts= >, what gets written to the ile is
7hinin- an( &ri-ht" the/ are $!re=er"@r@n

When the sa*e line is read bac9 into the array sK L #sing 8gets= >, the array contains
7hinin- an( &ri-ht" the/ are $!re=er"@n@0

Th#s conversion o En to ErEn d#ring writing and ErEn conversion to En d#ring reading is a eat#re o the standard library #nctions and not that o the 3SG 2ence the 3S co#nts Er and En as separate charactersG $n o#r poe* there are o#r lines, there ore there is a discrepancy o o#r characters >'(5 < '('?G

$ecord *+( in Files


So ar we have dealt with reading and writing only characters and stringsG What i we want to read or write n#*bers ro*=to ilec +#rther*ore, what i we desire to read=write a co*bination o characters, strings and n#*bersc +or this irst we wo#ld organi;e this dissi*ilar data together in a str#ct#re and then #se 8print8= >

Chapter /40 &ile +nput?Output

431

and 8scan8= > library #nctions to read=write data ro*=to ileG +ollowing progra* ill#strates the #se o str#ct#res or writing records o e*ployeesG
)* Srites re'!r(s t! a $i%e ,sin- str,'t,re *) Lin'%,(e 4st(i!.h4 main1 2 3 IIOE *$ # 'har an!ther = 'G' # str,'t em 3 'har name^40` # int a-e # $%!at &s # 6# str,'t em e # $ = $! en 1 4EP?OQGEE.0A84" 4F4 2 # i$ 1 $ == EXOO 2 3 ,ts 1 4+ann!t ! en $i%e4 2 # exit1 2 # 6 Fhi%e 1 an!ther == 'G' 2 3 rint$ 1 4@nEnter name" a-e an( &asi' sa%ar/: 4 2 # s'an$ 1 45s 5( 5$4" e.name" Be.a-e" Be.&s 2 # $ rint$ 1 $ " 45s 5( 5$@n4" e.name" e.a-e" e.&s 2 # rint$ 1 4A(( an!ther re'!r( 1G)E2 4 2 # $$%,sh 1 st(in 2 # an!ther = -et'he1 2 # 6 $'%!se 1 $ 2 #

432
6

%et .s C

1nd here is the o#tp#t o the progra*GGG


Enter name" a-e an( &asi' sa%ar/: 7,ni% 34 1250.50 A(( an!ther re'!r( 1G)E2 G Enter name" a-e an( &asi' sa%ar/: 7ameer 21 1300.50 A(( an!ther re'!r( 1G)E2 G Enter name" a-e an( &asi' sa%ar/: >ah,% 34 1400.55 A(( an!ther re'!r( 1G)E2 E

$n this progra* we are Q#st reading the data into a str#ct#re variable #sing scan8= >, and then d#*ping it into a dis9 ile #sing 8print8= >. The #ser can inp#t as *any records as he desiresG The proced#re ends when the #ser s#pplies D)@ or the H#estion D1dd another record >C=)?@G The 9ey to this progra* is the #nction 8print8= >, which writes the val#es in the str#ct#re variable to the ileG This #nction is si*ilar to print8= >, e/cept that a F*LB pointer is incl#ded as the irst arg#*entG 1s in print8= >, we can or*at the data in a variety o ways, by #sing 8print8= >. $n act all the or*at conventions o print8= > #nction wor9 with 8print8= > as wellG ,erhaps yo# are wondering what or have we #sed the #nction 88lush= >G The reason is to get rid o a pec#liarity o scan8= >G 1 ter s#pplying data or one e*ployee, we wo#ld hit the enter 9eyG What scan8= > does is it assigns na*e, age and salary to appropriate variables and 9eeps the enter 9ey #nread in the 9eyboard b# erG So when it@s ti*e to s#pply C or ) or the H#estion D1nother e*ployee >C=)?@, getch= > will read the enter 9ey ro* the b# er thin9ing that #ser has entered the enter 9eyG To avoid this proble* we #se the #nction 88lush= >G $t is designed to re*ove or D l#sh o#t@ any data re*aining in the b# erG The arg#*ent to 88lush= > *#st be the b# er which we want to l#sh o#tG 2ere we have #sed Dstdin@, which *eans b# er related with standard inp#t deviceR 9eyboardG

Chapter /40 &ile +nput?Output

433

7et #s now write a progra* that reads the e*ployee records created by the above progra*G 2ere is how it can be doneGGG
)* >ea( re'!r(s $r!m a $i%e ,sin- str,'t,re *) Lin'%,(e 4st(i!.h4 main1 2 3 IIOE *$ # str,'t em 3 'har name^40` # int a-e # $%!at &s # 6# str,'t em e # $ = $! en 1 4EP?OQGEE.0A84" 4r4 2 # i$ 1 $ == EXOO 2 3 ,ts 1 4+ann!t ! en $i%e4 2 # exit1 2 # 6 Fhi%e 1 $s'an$ 1 $ " 45s 5( 5$4" e.name" Be.a-e" Be.&s 2 T= EQI 2 rint$ 1 4@n5s 5( 5$4" e.name" e.a-e" e.&s 2 # $'%!se 1 $ 2 # 6

1nd here is the o#tp#t o the progra*GGG


7,ni% 34 1250.500000 7ameer 21 1300.500000 >ah,% 34 1400.500000

434
Te3t Files and -inar# Files

%et .s C

1ll the progra*s that we wrote in this chapter so ar wor9ed on te/t ilesG So*e o the* wo#ld not wor9 correctly on binary ilesG 1 te/t ile contains only te/t#al in or*ation li9e alphabets, digits and special sy*bolsG $n act#ality the 1SC$$ codes o these characters are stored in te/t ilesG 1 good e/a*ple o a te/t ile is any C progra*, say ,"'GCG 1s against this, a binary ile is *erely a collection o bytesG This collection *ight be a co*piled version o a C progra* >say ,"'G.A.?, or *#sic data stored in a wave ile or a pict#re stored in a graphic ileG 1 very easy way to ind o#t whether a ile is a te/t ile or a binary ile is to open that ile in T#rbo C=CLLG $ on opening the ile yo# can *a9e o#t what is displayed then it is a te/t ile, otherwise it is a binary ileG 1s *entioned while e/plaining the ile<copy progra*, the progra* cannot copy binary iles s#ccess #llyG We can i*prove the sa*e progra* to *a9e it capable o copying te/t as well as binary iles as shown belowG
Lin'%,(e 4st(i!.h4 main1 2 3 IIOE *$s" *$t # int 'h # $s = $! en 1 4 r1.exe4" 4r&4 2 # i$ 1 $s == EXOO 2 3 ,ts 1 4+ann!t ! en s!,r'e $i%e4 2 # exit1 2 # 6 $t = $! en 1 4neF r1.exe4" 4F&4 2 #

Chapter /40 &ile +nput?Output


i$ 1 $t == EXOO 2 3 ,ts 1 4+ann!t ! en tar-et $i%e4 2 # $'%!se 1 $s 2 # exit1 2 # 6 Fhi%e 1 1 2 3 'h = $-et' 1 $s 2 # i$ 1 'h == EQI 2 &rea. # e%se $ ,t' 1 'h" $t 2 #

435

$'%!se 1 $s 2 # $'%!se 1 $t 2 # 6

6sing this progra* we can co* ortably copy te/t as well as binary ilesG )ote that here we have opened the so#rce and target iles in KrbO and KwbO *odes respectivelyG While opening the ile in te/t *ode we can #se either KrO or KrtO, b#t since te/t *ode is the de a#lt *ode we #s#ally drop the Dt@G +ro* the progra**ing angle there are three *ain areas where te/t and binary *ode iles are di erentG These areP >a? 2andling o newlines >b? "epresentation o end o ile >c? Storage o n#*bers 7et #s e/plore these three di erencesG

43"
Te3t %ersus -inar# ,odeD 9e0lines

%et .s C

We have already seen that, in te/t *ode, a newline character is converted into the carriage ret#rn<line eed co*bination be ore being written to the dis9G 7i9ewise, the carriage ret#rn<line eed co*bination on the dis9 is converted bac9 into a newline when the ile is read by a C progra*G 2owever, i a ile is opened in binary *ode, as opposed to te/t *ode, these conversions will not ta9e placeG

Te3t %ersus -inar# ,odeD Bnd o8 File


The second di erence between te/t and binary *odes is in the way the end<o < ile is detectedG $n te/t *ode, a special character, whose 1SC$$ val#e is 26, is inserted a ter the last character in the ile to *ar9 the end o ileG $ this character is detected at any point in the ile, the read #nction wo#ld ret#rn the .3+ signal to the progra*G 1s against this, there is no s#ch special character present in the binary *ode iles to *ar9 the end o ileG The binary *ode iles 9eep trac9 o the end o ile ro* the n#*ber o characters present in the directory entry o the ileG There is a *oral to be derived ro* the end o ile *ar9er o te/t *ode ilesG $ a ile stores n#*bers in binary *ode, it is i*portant that binary *ode only be #sed or reading the n#*bers bac9, since one o the n#*bers we store *ight well be the n#*ber 26 >he/adeci*al '1?G $ this n#*ber is detected while we are reading the ile by opening it in te/t *ode, reading wo#ld be ter*inated pre*at#rely at that pointG Th#s the two *odes are not co*patibleG See to it that the ile that has been written in te/t *ode is read bac9 only in te/t *odeG Si*ilarly, the ile that has been written in binary *ode *#st be read bac9 only in binary *odeG

Chapter /40 &ile +nput?Output


Te3t %ersus -inar# ,odeD Storage o8 9u16ers

437

The only #nction that is available or storing n#*bers in a dis9 ile is the 8print8= > #nctionG $t is i*portant to #nderstand how n#*erical data is stored on the dis9 by 8print8= >. Te/t and characters are stored one character per byte, as we wo#ld e/pectG 1re n#*bers stored as they are in *e*ory, two bytes or an integer, o#r bytes or a loat, and so onc )oG )#*bers are stored as strings o charactersG Th#s, '2-4, even tho#gh it occ#pies two bytes in *e*ory, when trans erred to the dis9 #sing 8print8= >, wo#ld occ#py o#r bytes, one byte per characterG Si*ilarly, the loating<point n#*ber '2-4G56 wo#ld occ#py ! bytes on dis9G Th#s, n#*bers with *ore digits wo#ld reH#ire *ore dis9 spaceG 2ence i large a*o#nt o n#*erical data is to be stored in a dis9 ile, #sing te/t *ode *ay t#rn o#t to be ine icientG The sol#tion is to open the ile in binary *ode and #se those #nctions >8read= > and 80rite= > which are disc#ssed later? which store the n#*bers in binary or*atG $t *eans each n#*ber wo#ld occ#py sa*e n#*ber o bytes on dis9 as it occ#pies in *e*oryG

$ecord *+( $e%isited


The record $=3 progra* that we did in an earlier section has two disadvantagesP >a? The n#*bers >basic salary? wo#ld occ#py *ore n#*ber o bytes, since the ile has been opened in te/t *odeG This is beca#se when the ile is opened in te/t *ode, each n#*ber is stored as a character stringG >b? $ the n#*ber o ields in the str#ct#re increase >say, by adding address, ho#se rent allowance etcG?, writing str#ct#res

43&

%et .s C

#sing 8print8( ), or reading the* #sing 8scan8( ), beco*es H#ite cl#*syG 7et #s now see a *ore e icient way o reading=writing records >str#ct#res?G This *a9es #se o two #nctions 8read= > and 80rite= >G We will write two progra*s, irst one wo#ld write records to the ile and the second wo#ld read these records ro* the ile and display the* on the screenG
)* >e'ei=es re'!r(s $r!m .e/&!ar( an( Frites them t! a $i%e in &inar/ m!(e *) Lin'%,(e 4st(i!.h4 main1 2 3 IIOE *$ # 'har an!ther = 'G' # str,'t em 3 'har name^40` # int a-e # $%!at &s # 6# str,'t em e # $ = $! en 1 4EP?.0A84" 4F&4 2 # i$ 1 $ == EXOO 2 3 ,ts 1 4+ann!t ! en $i%e4 2 # exit1 2 # 6 Fhi%e 1 an!ther == 'G' 2 3 rint$ 1 4@nEnter name" a-e an( &asi' sa%ar/: 4 2 # s'an$ 1 45s 5( 5$4" e.name" Be.a-e" Be.&s 2 # $Frite 1 Be" si:e!$ 1 e 2" 1" $ 2 # rint$ 1 4A(( an!ther re'!r( 1G)E2 4 2 #

Chapter /40 &ile +nput?Output


$$%,sh 1 st(in 2 # an!ther = -et'he1 2 # 6 $'%!se 1 $ 2 # 6

439

1nd here is the o#tp#tGGG


Enter name" a-e an( &asi' sa%ar/: 7,resh 24 1250.50 A(( an!ther re'!r( 1G)E2 G Enter name" a-e an( &asi' sa%ar/: >an9an 21 1300.60 A(( an!ther re'!r( 1G)E2 G Enter name" a-e an( &asi' sa%ar/: Uarish 28 1400.70 A(( an!ther re'!r( 1G)E2 E

5ost o this progra* is si*ilar to the one that we wrote earlier, which #sed 8print8= > instead o 80rite= >G )ote, however, that the ile K.5,G01TO has now been opened in binary *odeG The in or*ation obtained ro* the 9eyboard abo#t the e*ployee is placed in the str#ct#re variable eG Then, the ollowing state*ent writes the str#ct#re to the ileP
$Frite 1 Be" si:e!$ 1 e 2" 1" $ 2 #

2ere, the irst arg#*ent is the address o the str#ct#re to be written to the dis9G The second arg#*ent is the si;e o the str#ct#re in bytesG $nstead o co#nting the bytes occ#pied by the str#ct#re o#rselves, we let the progra* do it or #s by #sing the siHeo8= > operatorG The siHeo8= > operator gives the si;e o the variable in bytesG This 9eeps the progra* #nchanged in event o change in the ele*ents o the str#ct#reG

44)

%et .s C

The third arg#*ent is the n#*ber o s#ch str#ct#res that we want to write at one ti*eG $n this case, we want to write only one str#ct#re at a ti*eG 2ad we had an array o str#ct#res, or e/a*ple, we *ight have wanted to write the entire array at onceG The last arg#*ent is the pointer to the ile we want to write toG )ow, let #s write a progra* to read bac9 the records written to the dis9 by the previo#s progra*G
)* >ea(s re'!r(s $r!m &inar/ $i%e an( (is %a/s them !n ]0X *) Lin'%,(e 4st(i!.h4 main1 2 3 IIOE *$ # str,'t em 3 'har name^40` # int a-e # $%!at &s # 6# str,'t em e # $ = $! en 1 4EP?.0A84" 4r&4 2 # i$ 1 $ == EXOO 2 3 ,ts 1 4+ann!t ! en $i%e4 2 # exit1 2 # 6 Fhi%e 1 $rea( 1 Be" si:e!$ 1 e 2" 1" $ 2 == 1 2 rint$ 1 4@n5s 5( 5$4" e.name" e.a-e" e.&s 2 # 6 $'%!se 1 $ 2 #

Chapter /40 &ile +nput?Output

441

2ere, the 8read= > #nction ca#ses the data read ro* the dis9 to be placed in the str#ct#re variable eG The or*at o 8read= > is sa*e as that o 80rite= >G The #nction 8read= > ret#rns the n#*ber o records readG 3rdinarily, this sho#ld correspond to the third arg#*ent, the n#*ber o records we as9ed orGGG ' in this caseG $ we have reached the end o ile, since 8read= > cannot read anything, it ret#rns a (G 8y testing or this sit#ation, we 9now when to stop readingG 1s yo# can now appreciate, any database *anage*ent application in C *#st *a9e #se o 8read= > and 80rite= > #nctions, since they store n#*bers *ore e iciently, and *a9e writing=reading o str#ct#res H#ite easyG )ote that even i the n#*ber o ele*ents belonging to the str#ct#re increases, the or*at o 8read= > and 80rite= > re*ains sa*eG

Data6ase ,anage1ent
So ar we have learnt record $=3 in bits and piecesG 2owever, in any serio#s database *anage*ent application, we will have to co*bine all that we have learnt in a proper *anner to *a9e senseG $ have atte*pted to do this in the ollowing *en# driven progra*G There is a provision to 1dd, 5odi y, 7ist and 0elete records, the operations that are i*perative in any database *anage*entG +ollowing co**ents wo#ld help yo# in #nderstanding the progra* easilyP f 1ddition o records *#st always ta9e place at the end o e/isting records in the ile, *#ch in the sa*e way yo# wo#ld add new records in a register *an#allyG 7isting records *eans displaying the e/isting records on the screenG )at#rally, records sho#ld be listed ro* irst record to last recordG While *odi ying records, irst we *#st as9 the #ser which record he intends to *odi yG $nstead o as9ing the record

442

%et .s C

n#*ber to be *odi ied, it wo#ld be *ore *eaning #l to as9 or the na*e o the e*ployee whose record is to be *odi iedG 3n *odi ying the record, the e/isting record gets overwritten by the new recordG f $n deleting records, e/cept or the record to be deleted, rest o the records *#st irst be written to a te*porary ile, then the original ile *#st be deleted, and the te*porary ile *#st be rena*ed bac9 to originalG f 3bserve care #lly the way the ile has been opened, irst or reading I writing, and i this ails >the irst ti*e yo# r#n this progra* it wo#ld certainly ail, beca#se that ti*e the ile is not e/isting?, or writing and readingG $t is i*perative that the ile sho#ld be opened in binary *odeG f )ote that the ile is being opened only once and closed only once, which is H#ite logicalG f clrscr= > #nction clears the contents o the screen and goto3#= > places the c#rsor at appropriate position on the screenG The para*eters passed to goto3#= > are col#*n n#*ber ollowed by row n#*berG Given below is the co*plete listing o the progra*G
)* A men,-(ri=en r!-ram $!r e%ementar/ (ata&ase mana-ement *) Lin'%,(e 4st(i!.h4 main1 2 3 IIOE *$ " *$t # 'har an!ther" 'h!i'e # str,'t em 3 'har name^40` # int a-e # $%!at &s # 6#

Chapter /40 &ile +nput?Output


str,'t em e # 'har em name^40` # %!n- int re'si:e # $ = $! en 1 4EP?.0A84" 4r&+4 2 # i$ 1 $ == EXOO 2 3 $ = $! en 1 4EP?.0A84" 4F&+4 2 # i$ 1 $ == EXOO 2 3 ,ts 1 4+ann!t ! en $i%e4 2 # exit1 2 # 6 6 re'si:e = si:e!$ 1 e 2 # Fhi%e 1 1 2 3 '%rs'r1 2 # -!t!x/ 1 30" 10 2 # rint$ 1 41. A(( >e'!r(s4 2 # -!t!x/ 1 30" 12 2 # rint$ 1 42. Oist >e'!r(s4 2 # -!t!x/ 1 30" 14 2 # rint$ 1 43. P!(i$/ >e'!r(s4 2 # -!t!x/ 1 30" 16 2 # rint$ 1 44. 0e%ete >e'!r(s4 2 # -!t!x/ 1 30" 18 2 # rint$ 1 40. Exit4 2 # -!t!x/ 1 30" 20 2 # rint$ 1 4G!,r 'h!i'e4 2 # $$%,sh 1 st(in 2 # 'h!i'e = -et'he1 2 #

443

444
sFit'h 1 'h!i'e 2 3 'ase '1' : $see. 1 $ " 0 " 7EE__EE0 2 # an!ther = 'G' #

%et .s C

Fhi%e 1 an!ther == 'G' 2 3 rint$ 1 4@nEnter name" a-e an( &asi' sa%. 4 2 # s'an$ 1 45s 5( 5$4" e.name" Be.a-e" Be.&s 2 # $Frite 1 Be" re'si:e" 1" $ 2 # rint$ 1 4@nA(( an!ther >e'!r( 1G)E2 4 2 # $$%,sh 1 st(in 2 # an!ther = -et'he1 2 # 6 &rea. # 'ase '2' : reFin( 1 $ 2 # Fhi%e 1 $rea( 1 Be" re'si:e" 1" $ 2 == 1 2 rint$ 1 4@n5s 5( 5$4" e.name" e.a-e" e.&s 2 # &rea. # 'ase '3' : an!ther = 'G' # Fhi%e 1 an!ther == 'G' 2 3 rint$ 1 4@nEnter name !$ em %!/ee t! m!(i$/ 4 2 # s'an$ 1 45s4" em name 2 # reFin( 1 $ 2 # Fhi%e 1 $rea( 1 Be" re'si:e" 1" $ 2 == 1 2

Chapter /40 &ile +nput?Output


3

445

i$ 1 str'm 1 e.name" em name 2 == 0 2 3 rint$ 1 4@nEnter neF name" a-e B &s4 2 # s'an$ 1 45s 5( 5$4" e.name" Be.a-e" Be.&s 2 # $see. 1 $ " - re'si:e" 7EE__+X> 2 # $Frite 1 Be" re'si:e" 1" $ 2 # &rea. # 6

6 rint$ 1 4@nP!(i$/ an!ther >e'!r( 1G)E2 4 2 # $$%,sh 1 st(in 2 # an!ther = -et'he1 2 # 6 &rea. # 'ase '4' : an!ther = 'G' # Fhi%e 1 an!ther == 'G' 2 3 rint$ 1 4@nEnter name !$ em %!/ee t! (e%ete 4 2 # s'an$ 1 45s4" em name 2 # $t = $! en 1 48EP?.0A84" 4F&4 2 # reFin( 1 $ 2 # Fhi%e 1 $rea( 1 Be" re'si:e" 1" $ 2 == 1 2 3 i$ 1 str'm 1 e.name" em name 2 T= 0 2 $Frite 1 Be" re'si:e" 1" $t 2 # 6 $'%!se 1 $ 2 # $'%!se 1 $t 2 #

44"
rem!=e 1 4EP?.0A84 2 # rename 1 48EP?.0A84" 4EP?.0A84 2 # $ = $! en 1 4EP?.0A84" 4r&+4 2 # rint$ 1 40e%ete an!ther >e'!r( 1G)E2 4 2 # $$%,sh 1 st(in 2 # an!ther = -et'he1 2 # 6 &rea. # 'ase '0' : $'%!se 1 $ 2 # exit1 2 #

%et .s C

6 6 6

To #nderstand how this progra* wor9s, yo# need to be a*iliar with the concept o pointersG 1 pointer is initiated whenever we open a ileG 3n opening a ile a pointer is set #p which points to the irst record in the ileG To be precise this pointer is present in the str#ct#re to which the ile pointer ret#rned by 8open= > points toG 3n #sing the #nctions 8read= > or 80rite= >, the pointer *oves to the beginning o the ne/t recordG 3n closing a ile the pointer is deactivatedG )ote that the pointer *ove*ent is o #t*ost i*portance since 8read= > always reads that record where the pointer is c#rrently placedG Si*ilarly, 80rite= > always writes the record where the pointer is c#rrently placedG The re0ind= > #nction places the pointer to the beginning o the ile, irrespective o where it is present right nowG The 8seeG= > #nction lets #s *ove the pointer ro* one record to anotherG $n the progra* above, to *ove the pointer to the previo#s record ro* its c#rrent position, we #sed the #nction,

Chapter /40 &ile +nput?Output


$see. 1 $ " -re'si:e" 7EE__+X> 2 #

447

2ere, <recsiHe *oves the pointer bac9 by recsiHe bytes ro* the c#rrent positionG SBB7BC.$ is a *acro de ined in KstdioGhOG Si*ilarly, the ollowing 8seeG= > wo#ld place the pointer beyond the last record in the ileG
$see. 1 $ " 0" 7EE__EE0 2 #

$n act <recsiHe or ) are Q#st the o sets that tell the co*piler by how *any bytes sho#ld the pointer be *oved ro* a partic#lar positionG The third arg#*ent co#ld be SBB7BB9D, SBB7BC.$ or SBB7BSBTG 1ll these act as a re erence ro* which the pointer sho#ld be o setG SBB7BB9D *eans *ove the pointer ro* the end o the ile, SBB7BC.$ *eans *ove the pointer with re erence to its c#rrent position and SBB7BSBT *eans *ove the pointer with re erence to the beginning o the ileG $ we wish to 9now where the pointer is positioned right now, we can #se the #nction 8tell= >G $t ret#rns this position as a long int which is an o set ro* the beginning o the ileG The val#e ret#rned by 8tell= > can be #sed in s#bseH#ent calls to 8seeG= >G 1 sa*ple call to 8tell= > is shown belowP
!siti!n = $te%% 1 $ 2 #

where position is a long intG

Lo0 Le%el DisG *+(


$n low level dis9 $=3, data cannot be written as individ#al characters, or as strings or as or*atted dataG There is only one way data can be written or read in low level dis9 $=3 #nctionsRas a b# er #ll o bytesG

44&

%et .s C

Writing a b# er #ll o data rese*bles the 80rite= > #nctionG 2owever, #nli9e 80rite= >, the progra**er *#st set #p the b# er or the data, place the appropriate val#es in it be ore writing, and ta9e the* o#t a ter writingG Th#s, the b# er in the low level $=3 #nctions is very *#ch a part o the progra*, rather than being invisible as in high level dis9 $=3 #nctionsG 7ow level dis9 $=3 #nctions o er ollowing advantagesP >a? Since these #nctions parallel the *ethods that the 3S #ses to write to the dis9, they are *ore e icient than the high level dis9 $=3 #nctionsG >b? Since there are ewer layers o ro#tines to go thro#gh, low level $=3 #nctions operate aster than their high level co#nterpartsG 7et #s now write a progra* that #ses low level dis9 inp#t=o#tp#t #nctionsG

' Lo0 Le%el File@cop# !rogra1


.arlier we had written a progra* to copy the contents o one ile to anotherG $n that progra* we had read the ile character by character #sing 8getc= >G .ach character that was read was written into the target ile #sing 8putc= >G $nstead o per or*ing the $=3 on a character by character basis we can read a ch#n9 o bytes ro* the so#rce ile and then write this ch#n9 into the target ileG While doing so the ch#n9 wo#ld be read into the b# er and wo#ld be written to the ile ro* the b# erG While doing so we wo#ld *anage the b# er o#rselves, rather than relying on the library #nctions to do soG This is what is low<level abo#t this progra*G 2ere is a progra* which shows how this can be doneG
)* Ii%e-'! / r!-ram Fhi'h '! ies text" .'!m an( .exe $i%es *) Lin'%,(e 4$'nt%.h4 Lin'%,(e 4t/ es.h4 )* i$ resent in s/s (ire't!r/ ,se

Chapter /40 &ile +nput?Output


4':t'@@in'%,(e@@s/s@@t/ es.h4 *) Lin'%,(e 4stat.h4 )* i$ resent in s/s (ire't!r/ ,se 4':@@t'@@in'%,(e@@s/s@@stat.h4 *) main 1 int ar-'" 'har *ar-=^ ` 2 3 'har &,$$er^ 512 `" s!,r'e ^ 128 `" tar-et ^ 128 ` # int inhan(%e" !,than(%e" &/tes # rint$ 1 4@nEnter s!,r'e $i%e name4 2 # -ets 1 s!,r'e 2 # inhan(%e = ! en 1 s!,r'e" Q_>0QEOG W Q_DIEA>G 2 # i$ 1 inhan(%e == -1 2 3 ,ts 1 4+ann!t ! en $i%e4 2 # exit1 2 # 6 rint$ 1 4@nEnter tar-et $i%e name4 2 # -ets 1 tar-et 2 # !,than(%e = ! en 1 tar-et" Q_+>EA8 W Q_DIEA>G W Q_S>QEOG" 7_IS>I8E 2 # i$ 1 inhan(%e == -1 2 3 ,ts 1 4+ann!t ! en $i%e4 2 # '%!se 1 inhan(%e 2 # exit1 2 # 6 Fhi%e 1 1 2 3 &/tes = rea( 1 inhan(%e" &,$$er" 512 2 # i$ 1 &/tes < 0 2 Frite 1 !,than(%e" &,$$er" &/tes 2 # e%se

449

45)
&rea. # 6 '%!se 1 inhan(%e 2 # '%!se 1 !,than(%e 2 # 6

%et .s C

Declaring the -u88er


The irst di erence that yo# will notice in this progra* is that we declare a character b# er,
'har &,$$er^512` #

This is the b# er in which the data read ro* the dis9 will be placedG The si;e o this b# er is i*portant or e icient operationG 0epending on the operating syste*, b# ers o certain si;es are handled *ore e iciently than othersG

(pening a File
We have opened two iles in o#r progra*, one is the so#rce ile ro* which we read the in or*ation, and the other is the target ile into which we write the in or*ation read ro* the so#rce ileG 1s in high level dis9 $=3, the ile *#st be opened be ore we can access itG This is done #sing the state*ent,
inhan(%e = ! en 1 s!,r'e" Q_>0QEOG W Q_DIEA>G 2 #

We open the ile or the sa*e reason as we did earlierRto establish co**#nication with operating syste* abo#t the ileG 1s #s#al, we have to s#pply to open= >, the ilena*e and the *ode in which we want to open the ileG The possible ile opening *odes are given belowP 3B1,,.)0 < 3pens a ile or appending

Chapter /40 &ile +nput?Output


3BC".1T 3B"03)7C 3B"0W" 3BW"3)7C 3B8$)1"C 3BT.AT

451

< Creates a new ile or writing >has no e ect i ile already e/ists? < Creates a new ile or reading only < Creates a ile or both reading and writing < Creates a ile or writing only < Creates a ile in binary *ode < Creates a ile in te/t *ode

These D3< lags@ are de ined in the ile K cntlGhOG So this ile *#st be incl#ded in the progra* while #sng low level dis9 $=3G )ote that the ile KstdioGhO is not necessary or low level dis9 $=3G When two or *ore 3< lags are #sed together, they are co*bined #sing the bitwise 3" operator > Y ?G Chapter '4 disc#sses bitwise operators in detailG The other state*ent #sed in o#r progra* to open the ile is,
!,than(%e = ! en 1 tar-et" Q_+>EA8 W Q_DIEA>G W Q_S>QEOG" 7_IS>I8E 2 #

)ote that since the target ile is not e/isting when it is being opened we have #sed the 3BC".1T lag, and since we want to write to the ile and not read ro* it, there ore we have #sed 3BW"3)7CG 1nd inally, since we want to open the ile in binary *ode we have #sed 3B8$)1"CG Whenever 3BC".1T lag is #sed, another arg#*ent *#st be added to open= > #nction to indicate the read=write stat#s o the ile to be createdG This arg#*ent is called Dper*ission arg#*ent@G ,er*ission arg#*ents co#ld be any o the ollowingP SB$W"$T. SB$".10 < Writing to the ile per*itted < "eading ro* the ile per*itted

452

%et .s C

To #se these per*issions, both the iles KtypesGhO and KstatGhO *#st be Iincluded in the progra* alongwith K cntlGhOG

File 2andles
$nstead o ret#rning a +$7. pointer as 8open= > did, in low level dis9 $=3, open= > ret#rns an integer val#e called D ile handle@G This is a n#*ber assigned to a partic#lar ile, which is #sed therea ter to re er to the ileG $ open= > ret#rns a val#e o <', it *eans that the ile co#ldn@t be s#ccess #lly openedG

*nteraction 6et0een -u88er and File


The ollowing state*ent reads the ile or as *#ch o it as will it into the b# erP
&/tes = rea( 1 inhan(%e" &,$$er" 512 2 #

The read= > #nction ta9es three arg#*entsG The irst arg#*ent is the ile handle, the second is the address o the b# er and the third is the *a/i*#* n#*ber o bytes we want to readG The read= > #nction ret#rns the n#*ber o bytes act#ally readG This is an i*portant n#*ber, since it *ay very well be less than the b# er si;e >5'2 bytes?, and we will need to 9now Q#st how #ll the b# er is be ore we can do anything with its contentsG $n o#r progra* we have assigned this n#*ber to the variable 6#tesG +or copying the ile, we *#st #se both the read= > and the 0rite= > #nctions in a 0hile loopG The read= > #nction ret#rns the n#*ber o bytes act#ally readG This is assigned to the variable 6#tesG This val#e will be eH#al to the b# er si;e >5'2 bytes? #ntil the end o ile, when the b# er will only be partially #llG The variable 6#tes there ore is #sed to tell 0rite= >, as to how *any bytes to write ro* the b# er to the target ileG

Chapter /40 &ile +nput?Output

453

)ote that when large b# ers are #sed they *#st be *ade global variables otherwise stac9 over low occ#rsG

*+( .nder /indo0s


1s said earlier $=3 in C is carried o#t #sing #nctions present in the library that co*es with the C co*piler targeted or a speci ic 3SG Windows per*its several applications to #se the sa*e screen si*#ltaneo#slyG 2ence there is a possibility that what is written by one application to the console *ay get overwritten by the o#tp#t sent by another application to the consoleG To avoid s#ch sit#ations Windows has co*pletely abandoned console $=3 #nctionsG $t #ses a separate *echanis* to send o#tp#t to a window representing an applicationG The details o this *echanis* are disc#ssed in Chapter '!G Tho#gh #nder Windows console $=3 #nctions are not #sed, still #nctions li9e 8print8= >, 8scan8= >, 8read= >, 80rite= >, sprint8= >, sscan8= > wor9 e/actly sa*e #nder Windows as wellG

Su11ar#
>a? +ile $=3 can be per or*ed on a character by character basis, a line by line basis, a record by record basis or a ch#n9 by >b? ch#n9 basisG 0i erent operations that can be per or*ed on a ile areR creation o a new ile, opening an e/isting ile, reading ro* a >c? ile, writing to a ile, *oving to a speci ic location in a ile >d? >see9ing? and closing a ileG +ile $=3 is done #sing a b# er to i*prove the e iciencyG >e? 1 ile can be a te/t ile or a binary ile depending #pon its contentsG 7ibrary #nctions convert En to ErEn or vice versa while writing=reading to= ro* a ileG

454

%et .s C

> ? 5any library #nctions convert a n#*ber to a n#*eric string be ore writing it to a ile, thereby #sing *ore space on dis9G This can be avoided #sing #nctions 8read= > and 80rite= >G >g? $n low level ile $=3 we can do the b# er *anage*ent o#rselvesG

B3ercise
K'L ,oint o#t the errors, i any, in the ollowing progra*sP 1a2 Lin'%,(e 4st(i!.h4 main1 2 3 IIOE *$ # ! en$i%e 1 4P/$i%e.txt4" $ 2 # i$ 1 $ == EXOO 2 rint$ 1 4Xna&%e t! ! en $i%eV4 2 # 6 ! en$i%e 1 'har *$n" IIOE **$ 2 3 *$ = $! en 1 $n" 4r4 2 # 6 1&2 Lin'%,(e 4st(i!.h4 main1 2 3 IIOE *$ # 'har ' # $ = $! en 1 48>G.+4 "4r42 # i$ 1 $ == n,%% 2 3 ,ts 1 4+ann!t ! en $i%e4 2 # exit1 2 # 6 Fhi%e 1 1 ' = -et' 1 $ 2 2 T= EQI 2 ,t'h 1 ' 2 # $'%!se 1 $ 2 #

Chapter /40 &ile +nput?Output


6 1'2 main1 2 3 'har $name^ ` = 4':@@st,(ents.(at4 # IIOE *$ # $ = $! en 1 $name" 4tr4 2 # i$ 1 $ == EXOO 2 rint$ 1 4@nXna&%e t! ! en $i%e...4 2 # 6

455

1(2 main1 2 3 IIOE *$ # 'har str^80` # $ = $! en 1 48>G.+4" 4r4 2 # Fhi%e 1 $-ets 1 str" 80" $ 2 T= EQI 2 $ ,ts 1 str 2 # $'%!se 1 $ 2 # 6 1e2 Lin'%,(e 4st(i!.h4 3 ,nsi-ne( 'har # IIOE *$ # $ = $! en 1 4tria%4" 4r4 2 # Fhi%e 1 1 'h = -et' 1 $ 2 2 T= EQI 2 rint$ 1 45'4" 'h 2 # $'%!se 1 $ 2 # 6 1$2 main1 2 3 IIOE *$ # 'har name^25` # int a-e # $ = $! en 1 4GQX>74" 4r4 2 #

45"
Fhi%e 1 $s'an$ 1 $ " 45s 5(4" name" Ba-e 2 T= EXOO 2 $'%!se 1 $ 2 # 6 1-2 main1 2 3 IIOE *$ # 'har names^20` # int i # $ = $! en 1 4st,(ents.'4" 4F&4 2 # $!r 1 i = 0 # i ;= 10 # i++ 2 3 ,ts 1 4@nEnter name 4 2 # -ets 1 name 2 # $Frite 1 name" si:e !$ 1 name 2" 1" $ 2 # 6 '%!se 1 $ 2 # 6 1h2 main1 2 3 IIOE *$ # 'har name^20` = 4A9a/4 # int i # $ = $! en 1 4st,(ents.'4" 4r4 2 # $!r 1 i = 0 # i ;= 10 # i++ 2 $Frite 1 name" si:e!$ 1 name 2" 1" $ 2 # '%!se 1 $ 2 # 6 1i2 Lin'%,(e 4$'nt%.h4 main1 2 3 int $ # $ = ! en 1 4 r22.'4 " 4r4 2 # i$ 1 $ == -1 2 ,ts 1 4'ann!t ! en $i%e4 2 # e%se '%!se 1 $ 2 #

%et .s C

Chapter /40 &ile +nput?Output


6 (j) main( ) 3 int $ # $ = $! en 1 4st,(ents.'4" >EA0 W DIEA>G 2 # i$ 1 $ == -1 2 ,ts 1 4'ann!t ! en $i%e4 2 # e%se '%!se 1 $ 2 # 6

457

K-L 1nswer the ollowingP

>a? The *acro +$7. is de ined in which o the ollowing ilesP 'G 2G -G 4G stdlibGh stdioGc ioGh stdioGh

>b? $ a ile contains the line K$ a* a boyZrZnO then on reading this line into the array strK L #sing 8gets= > what wo#ld strK L containc 'G 2G -G 4G $ a* a boyZrZnZ( $ a* a boyZrZ( $ a* a boyZnZ( $ a* a boy

>c? State Tr#e or +alseP 'G The disadvantage o 2igh 7evel 0is9 $=3 #nctions is that the progra**er has to *anage the b# ersG 2G $ a ile is opened or reading it is necessary that the ile *#st e/istG -G $ a ile opened or writing already e/ists its contents wo#ld be overwrittenG

45&

%et .s C

4G +or opening a ile in append *ode it is necessary that the ile sho#ld e/istG >d? 3n opening a ile or reading which o the ollowing activities are per or*edP 'G The dis9 is searched or e/istence o the ileG 2G The ile is bro#ght into *e*oryG -G 1 pointer is set #p which points to the irst character in the ileG 4G 1ll the aboveG >e? $s it necessary that a ile created in te/t *ode *#st always be opened in te/t *ode or s#bseH#ent operationsc >? State Tr#e or +alseP 1 ile opened in binary *ode and read #sing 8getc= > wo#ld report the sa*e n#*ber o characters in the ile as reported by 03S@s 0$" co**andG While #sing the state*ent,
$ = $! en 1 4m/$i%e.'4" 4r4 2 #

>g?

what happens i , f D*y ileGc@ does not e/ist on the dis9 f D*y ileGc@ e/ists on the dis9 What is the p#rpose o the library #nction 88lush= >c While #sing the state*ent,
$ = $! en 1 4m/$i%e.'4" 4F&4 2 # what happens i ,

>h? >i?

>Q?

f D*y ileGc@ does not e/ist on the dis9G f D*y ileGc@ e/ists on the dis9 1 loating<point array contains percentage *ar9s obtained by st#dents in an e/a*inationG To store these *ar9s in a ile D*ar9sGc@, in which *ode wo#ld yo# open the ile and whyc

Chapter /40 &ile +nput?Output


KCL 1tte*pt the ollowingP

459

>a? Write a progra* to read a ile and display contents with its line n#*bersG >b? Write a progra* to ind the si;e o a te/t ile witho#t >c? traversing it character by characterG >d? Write a progra* to add the contents o one ile at the end o anotherG >e? S#ppose a ile contains st#dent@s records with each record containing na*e and age o a st#dentG Write a progra* to read > ? these records and display the* in sorted order by na*eG Write a progra* to copy one ile to anotherG While doing so >g? replace all lowercase characters to their eH#ivalent #ppercase charactersG Write a progra* that *erges lines alternately ro* two iles and writes the res#lts to new ileG $ one ile has less n#*ber o lines than the other, the re*aining lines ro* the larger ile sho#ld be si*ply copied into the target ileG Write a progra* to display the contents o a te/t ile on the screenG 5a9e ollowing provisionsP >h? 0isplay the contents inside a bo/ drawn with opposite corner co<ordinates being > (, ' ? and > !&, 2- ?G 0isplay the na*e o the ile whose contents are being displayed, and the page n#*bers in the ;eroth rowG The *o*ent one screen #l o ile has been displayed, lash a *essage D,ress any 9eyGGG@ in 24th rowG When a 9ey is hit, the ne/t page@s contents sho#ld be displayed, and so on till the end o ileG Write a progra* to encrypt=decrypt a ile #singP

4")

%et .s C

>'? 1n o set cipherP $n an o set cipher each character ro* the so#rce ile is o set with a i/ed val#e and then written to the target ileG +or e/a*ple, i character read ro* the so#rce ile is D1@, then convert this into a new character by o setting D1@ by a i/ed val#e, say '2%, and then writing the new character to the target ileG >2? 1 s#bstit#tion cipherP $n this each character read ro* the so#rce ile is s#bstit#ted by a corresponding predeter*ined character and this character is written to the target ileG +or e/a*ple, i character D1@ is read ro* the so#rce ile, and i we have decided that every D1@ is to be s#bstit#ted by D4@, then a D4@ wo#ld be written to the target ile in place o every D1@ Si*ilarly, every D8@ wo#ld be s#bstit#ted by D5@ and so onG >i? $n the ile DC6ST35."G01T@ there are '(( records with the ollowing str#ct#reP
str,'t ',st!mer 3 int a''n! # 'har name^30` # $%!at &a%an'e # 6#

$n another ile DT"1)S1CT$3)SG01T@ there are several records with the ollowing str#ct#reP
str,'t trans 3 int a''n! " 'har trans_t/ e #

Chapter /40 &ile +nput?Output


$%!at am!,nt # 6#

4"1

The para*eter trans:t#pe contains 0=W indicating deposit or withdrawal o a*o#ntG Write a progra* to #pdate DC6ST35."G01T@ ile, iGeG i the trans:t#pe is D0@ then #pdate the 6alance o DC6ST35."G01T@ by adding a1ount to balance or the corresponding accnoG Si*ilarly, i trans:t#pe is DW@ then s#btract the a1ount ro* 6alanceG 2owever, while s#btracting the a*o#nt *a9e s#re that the a*o#nt sho#ld not get overdrawn, iGeG at least '(( "sG Sho#ld re*ain in the acco#ntG >Q? There are '(( records present in a ile with the ollowing str#ct#reP
str,'t (ate 3 int (" m" / # 6# str,'t em %!/ee 3 int em '!(e^6` # 'har em name^20` # str,'t (ate 9!in_(ate # $%!at sa%ar/ # 6#

Write a progra* to read these records, arrange the* in ascending order o Woin:date and write the* in to a target ileG >9? 1 hospital 9eeps a ile o blood donors in which each record has the or*atP )a*eP 2( Col#*ns 1ddressP 4( Col#*ns

4"2
1geP 2 Col#*ns 8lood TypeP ' Col#*n >Type ', 2, - or 4?

%et .s C

Write a progra* to read the ile and print a list o all blood donors whose age is below 25 and blood is type 2G >l? Given a list o na*es o st#dents in a class, write a progra* to store the na*es in a ile on dis9G 5a9e a provision to display the nth na*e in the list >n is data to be read? and to display all na*es starting with SG >*? 1ss#*e that a 5aster ile contains two ields, "oll noG and na*e o the st#dentG 1t the end o the year, a set o st#dents Qoin the class and another set leavesG 1 Transaction ile contains the roll n#*bers and an appropriate code to add or delete a st#dentG Write a progra* to create another ile that contains the #pdated list o na*es and roll n#*bersG 1ss#*e that the 5aster ile and the Transaction ile are arranged in ascending order by roll n#*bersG The #pdated ile sho#ld also be in ascending order by roll n#*bersG >n? $n a s*all ir* e*ployee n#*bers are given in serial n#*erical order, that is ', 2, -, etcG f Create a ile o e*ployee data with ollowing in or*ationP e*ployee n#*ber, na*e, se/, gross salaryG f $ *ore e*ployees Qoin, append their data to the ileG f $ an e*ployee with serial n#*ber 25 >say? leaves, delete the record by *a9ing gross salary (G f $ so*e e*ployee@s gross salary increases, retrieve the record and #pdate the salaryG Write a progra* to i*ple*ent the above operationsG >o? Given a te/t ile, write a progra* to create another te/t ile deleting the words KaO, KtheO, KanO and replacing each one o the* with a blan9 spaceG

Chapter /40 &ile +nput?Output

4"3

>p? Co# are given a data ile .5,73C..G01T with the ollowing record str#ct#reP
str,'t em %!/ee 3 int em n! # 'har name^30` # int &asi'" -ra(e # 6#

.very e*ployee has a #niH#e e1pno and there are s#pposed to be no gaps between e*ployee n#*bersG "ecords are entered into the data ile in ascending order o e*ployee n#*ber, e1pnoG $t is intended to chec9 whether there are *issing e*ployee n#*bersG Write a progra* seg*ent to read the data ile records seH#entially and display the list o *issing e*ployee n#*bersG >H? Write a progra* to carry o#t the ollowingP f f f To read a te/t ile KT"$17GTATO consisting o a *a/i*#* o 5( lines o te/t, each line with a *a/i*#* o %( charactersG Co#nt and display the n#*ber o words contained in the ileG 0isplay the total n#*ber o o#r letter words in the te/t ileG

1ss#*e that the end o a word *ay be a space, co**a or a #ll<stop ollowed by one or *ore spaces or a newline characterG >r? Write a progra* to read a list o words, sort the words in alphabetical order and display the* one word per lineG 1lso give the total n#*ber o words in the listG 3#tp#t or*at sho#ld beP Total )#*ber o words in the list is 1lphabetical listing o words isP <<<<<< <<<<<<

4"4
<<<<<<

%et .s C

1ss#*e the end o the list is indicated by NNNNNN and there are *a/i*#* in 25 words in the Te/t ileG >s? Write a progra* to carry o#t the ollowingP >a? "ead a te/t ile D$),6TGTAT@ >b? ,rint each word in reverse order ./a*ple,
In ,t: IE0IA I7 PG +QXE8>G Q,t ,t: AI0EI 7I GP G>8EXQ+

1ss#*e that each word length is *a/i*#* o '( characters and each word is separated by newline=blan9 charactersG >t? Write a C progra* to read a large te/t ile D)3T.SGTAT@ and print it on the printer in c#t<sheets, introd#cing page brea9s at the end o every 5( lines and a pa#se *essage on the screen at the end o every page or the #ser to change the paperG

1*

+ore (ssues (n (nput)&utput


e e e e 6sing argc and argv 0etecting .rrors in "eading=Writing Standard $=3 0evices $=3 "edirection "edirecting the 3#tp#t "edirecting the $np#t 8oth Ways at 3nce e S#**ary e ./ercise

4"5

4""

%et .s C

n Chapters '' and '2 we saw how Console $=3 and +ile $=3 are done in CG There are still so*e *ore iss#es related with inp#t=o#tp#t that re*ain to be #nderstoodG These iss#es help in *a9ing the $=3 operations *ore elegantG

.sing argc and argv


To e/ec#te the ile<copy progra*s that we saw in Chapter '2 we are reH#ired to irst type the progra*, co*pile it, and then e/ec#te itG This progra* can be i*proved in two waysP >a? There sho#ld be no need to co*pile the progra* every ti*e to #se the ile<copy #tilityG $t *eans the progra* *#st be e/ec#table at co**and pro*pt >1b or Cb i yo# are #sing 5S<03S, Start Y "#n dialog i yo# are #sing Windows and i pro*pt i yo# are #sing 6ni/?G >b? $nstead o the progra* pro*pting #s to enter the so#rce and target ilena*es, we *#st be able to s#pply the* at co**and pro*pt, in the or*P
$i%e'! / ?>1.+ ?>2.+

where, ,"'GC is the so#rce ilena*e and ,"2GC is the target ilena*eG The irst i*prove*ent is si*pleG $n 5S<03S, the e/ec#table ile >the one which can be e/ec#ted at co**and pro*pt and has an e/tension G.A.? can be created in T#rbo C=CLL by #sing the 9ey +& to co*pile the progra*G $n VCLL co*piler #nder Windows sa*e can be done by #sing +! to co*pile the progra*G 6nder 6ni/ this is not reH#ired since in 6ni/ every ti*e we co*pile a progra* we always get an e/ec#table ileG The second i*prove*ent is possible by passing the so#rce ilena*e and target ilena*e to the #nction 1ain= >G This is ill#strated belowP

Chapter /30 @ore +ssues +n +nput?Output


Lin'%,(e 4st(i!.h4 main 1 int ar-'" 'har *ar-=^ ` 2 3 IIOE *$s" *$t # 'har 'h # i$ 1 ar-' T= 3 2 3 ,ts 1 4Im r! er n,m&er !$ ar-,ments4 2 # exit1 2 # 6 $s = $! en 1 ar-=^1`" 4r4 2 # i$ 1 $s == EXOO 2 3 ,ts 1 4+ann!t ! en s!,r'e $i%e4 2 # exit1 2 # 6 $t = $! en 1 ar-=^2`" 4F4 2 # i$ 1 $t == EXOO 2 3 ,ts 1 4+ann!t ! en tar-et $i%e4 2 # $'%!se 1 $s 2 # exit1 2 # 6 Fhi%e 1 1 2 3 'h = $-et' 1 $s 2 # i$ 1 'h == EQI 2 &rea. # e%se $ ,t' 1 'h" $t 2 #

4"7

4"&
$'%!se 1 $s 2 # $'%!se 1 $t 2 # 6

%et .s C

The arg#*ents that we pass on to 1ain= > at the co**and pro*pt are called co**and line arg#*entsG The #nction 1ain= > can have two arg#*ents, traditionally na*ed as argc and arg%G 3#t o these, arg% is an array o pointers to strings and argc is an int whose val#e is eH#al to the n#*ber o strings to which arg% pointsG When the progra* is e/ec#ted, the strings on the co**and line are passed to 1ain= >G 5ore precisely, the strings at the co**and line are stored in *e*ory and address o the irst string is stored in arg%K)L, address o the second string is stored in arg%K1L and so onG The arg#*ent argc is set to the n#*ber o strings given on the co**and lineG +or e/a*ple, in o#r sa*ple progra*, i at the co**and pro*pt we give,
$i%e'! / ?>1.+ ?>2.+

then,
argc F!,%( '!ntain 3 argv[0` F!,%( '!ntain &ase a((ress !$ the strin- M$i%e'! /N argv[1` F!,%( '!ntain &ase a((ress !$ the strin- M?>1.+N argv[2` F!,%( '!ntain &ase a((ress !$ the strin- M?>2.+N

Whenever we pass arg#*ents to 1ain= >, it is a good habit to chec9 whether the correct n#*ber o arg#*ents have been passed on to 1ain= > or notG $n o#r progra* this has been done thro#gh,
i$ 1 ar-' T= 3 2 3 rint$ 1 4Im r! er n,m&er !$ ar-,ments4 2 # exit1 2 # 6

Chapter /30 @ore +ssues +n +nput?Output

4"9

"est o the progra* is sa*e as the earlier ile<copy progra*G This progra* is better than the earlier ile<copy progra* on two co#ntsP >a? There is no need to reco*pile the progra* every ti*e we want to #se this #tilityG $t can be e/ec#ted at co**and pro*ptG >b? We are able to pass so#rce ile na*e and target ile na*e to 1ain( ), and #tili;e the* in 1ain( )2 3ne inal co**entGGG the 0hile loop that we have #sed in o#r progra* can be written in a *ore co*pact or*, as shown belowP
Fhi%e 1 1 'h = $-et' 1 $s 2 2 T= EQI 2 $ ,t' 1 'h" $t 2 #

This avoids the #sage o an inde inite loop and a 6reaG state*ent to co*e o#t o this loopG 2ere, irst 8getc = 8s > gets the character ro* the ile, assigns it to the variable ch, and then ch is co*pared against B(FG "e*e*ber that it is necessary to p#t the e/pression
'h = $-et' 1 $s 2

within a pair o parentheses, so that irst the character read is assigned to variable ch and then it is co*pared with B(FG There is one *ore way o writing the 0hile loopG $t is shown belowP
Fhi%e 1 T$e!$ 1 $s 2 2 3 'h = $-et' 1 $s 2 # $ ,t' 1 'h" $t 2 # 6

2ere, 8eo8= > is a *acro which ret#rns a ( i end o ile is not reachedG 2ence we #se the P operator to negate this ( to the tr#th val#eG When the end o ile is reached 8eo8= > ret#rns a non<;ero

47)

%et .s C

val#e, P *a9es it ( and since now the condition eval#ates to alse the 0hile loop gets ter*inatedG )ote that in each one o the* the ollowing three *ethods or opening a ile are sa*e, since in each one o the*, essentially a base address o the string >pointer to a string? is being passed to 8open= >G
$s = $! en 1 4?>1.+4 " 4r4 2 # $s = $! en 1 $i%ename" 4r4 2 # $s = $! en 1 ar-=^1` " 4r4 2 #

Detecting Brrors in $eading+/riting


)ot at all ti*es when we per or* a read or write operation on a ile are we s#ccess #l in doing soG )at#rally there *#st be a provision to test whether o#r atte*pt to read=write was s#ccess #l or notG The standard library #nction 8error= > reports any error that *ight have occ#rred d#ring a read=write operation on a ileG $t ret#rns a ;ero i the read=write is s#ccess #l and a non<;ero val#e in case o a ail#reG The ollowing progra* ill#strates the #sage o 8error= >G
Lin'%,(e 4st(i!.h4 main1 2 3 IIOE *$ # 'har 'h # $ = $! en 1 48>IAO4" 4F4 2 # Fhi%e 1 T$e!$ 1 $ 2 2 3 'h = $-et' 1 $ 2 # i$ 1 $err!r1 2 2 3

Chapter /30 @ore +ssues +n +nput?Output


rint$ 1 4Err!r in rea(in- $i%e4 2 # &rea. # 6 e%se 6 6 rint$ 1 45'4" 'h 2 #

471

$'%!se 1 $ 2 #

$n this progra* the 8getc= > #nction wo#ld obvio#sly ail irst ti*e aro#nd since the ile has been opened or writing, whereas 8getc= > is atte*pting to read ro* the ileG The *o*ent the error occ#rs 8error= > ret#rns a non<;ero val#e and the i8 bloc9 gets e/ec#tedG $nstead o printing the error *essage #sing print8= > we can #se the standard library #nction perror= > which prints the error *essage speci ied by the co*pilerG Th#s in the above progra* the perror= > #nction can be #sed as shown belowG
i$ 1 $err!r1 2 2 3 err!r 1 48>IAO4 2 # &rea. # 6

)ote that when the error occ#rs the error *essage that is displayed isP
8>IAO: ?ermissi!n (enie(

This *eans we can precede the syste* error *essage with any *essage o o#r choiceG $n o#r progra* we have Q#st displayed the ilena*e in place o the error *essageG

472
Standard *+( De%ices

%et .s C

To per or* reading or writing operations on a ile we need to #se the #nction 8open= >, which sets #p a ile pointer to re er to this ileG 5ost 3Ss also prede ine pointers or three standard ilesG To access these pointers we need not #se 8open= >G These standard ile pointers are shown in +ig#re '-G'

Standard File pointer stdin stdo#t stderr

Description standard inp#t device >Keyboard? standard o#tp#t device >V06? standard error device >V06?

+ig#re '-G' Th#s the state*ent ch F 8getc = stdin > wo#ld read a character ro* the 9eyboard rather than ro* a ileG We can #se this state*ent witho#t any need to #se 8open= > or 8close= > #nction callsG )ote that #nder 5S<03S two *ore standard ile pointers are availableRstdprn and stdau3G They stand or standard printing device and standard a#/iliary device >serial port?G The ollowing progra* shows how to #se the standard ile pointersG $t reads a ile ro* the dis9 and prints it on the printerG
)* ?rints $i%e '!ntents !n rinter *) Lin'%,(e 4st(i!.h4 main1 2 3 IIOE *$ # 'har 'h #

Chapter /30 @ore +ssues +n +nput?Output


$ = $! en 1 4 !em.txt4" 4r4 2 # i$ 1 $ == EXOO 2 3 rint$ 1 4+ann!t ! en $i%e4 2 # exit1 2 # 6 Fhi%e 1 1 'h = $-et' 1 $ 2 2 T= EQI 2 $ ,t' 1 'h" st( rn 2 # $'%!se 1 $ 2 # 6

473

The state*ent 8putc = ch4 stdprn > writes a character read ro* the ile to the printerG )ote that altho#gh we opened the ile on the dis9 we didn@t open stdprn, the printerG Standard iles and their #se in redirection have been dealt with in *ore details in the ne/t sectionG )ote that these standard ile pointers have been de ined in the ile KstdioGhOG There ore, it is necessary to incl#de this ile in the progra* that #ses these standard ile pointersG

*+( $edirection
5ost operating syste*s incorporate a power #l eat#re that allows a progra* to read and write iles, even when s#ch a capability has not been incorporated in the progra*G This is done thro#gh a process called Dredirection@G )or*ally a C progra* receives its inp#t ro* the standard inp#t device, which is ass#*ed to be the 9eyboard, and sends its o#tp#t to the standard o#tp#t device, which is ass#*ed to be the V06G $n other words, the 3S *a9es certain ass#*ptions abo#t where inp#t

474

%et .s C

sho#ld co*e ro* and where o#tp#t sho#ld goG "edirection per*its #s to change these ass#*ptionsG +or e/a*ple, #sing redirection the o#tp#t o the progra* that nor*ally goes to the V06 can be sent to the dis9 or the printer witho#t really *a9ing a provision or it in the progra*G This is o ten a *ore convenient and le/ible approach than providing a separate #nction in the progra* to write to the dis9 or printerG Si*ilarly, redirection can be #sed to read in or*ation ro* dis9 ile directly into a progra*, instead o receiving the inp#t ro* 9eyboardG To #se redirection acility is to e/ec#te the progra* ro* the co**and pro*pt, inserting the redirection sy*bols at appropriate placesG 7et #s #nderstand this process with the help o a progra*G

$edirecting the (utput


7et@s see how we can redirect the o#tp#t o a progra*, ro* the screen to a ileG We@ll start by considering the si*ple progra* shown belowP
)* Ii%e name: ,ti%.' *) Lin'%,(e 4st(i!.h4;+< main1 2 3 'har 'h # Fhi%e 1 1 'h = -et' 1 st(in 2 2 T= EQI 2 ,t' 1 'h" st(!,t 2 # 6

3n co*piling this progra* we wo#ld get an e/ec#table ile 6T$7G.A.G )or*ally, when we e/ec#te this ile, the putc= > #nction will ca#se whatever we type to be printed on screen, #ntil we don@t type Ctrl<E, at which point the progra* will ter*inate, as

Chapter /30 @ore +ssues +n +nput?Output

475

shown in the ollowing sa*ple r#nG The Ctrl<E character is o ten called end o ile characterG
+<X8IO.E\E erha s I ha( a Fi'.e( 'hi%(h!!(" erha s I ha( a misera&%e /!,th" &,t s!meFhere in m/ Fi'.e( misera&%e ast" there m,st ha=e &een a m!ment !$ tr,th Kb +<

)ow let@s see what happens when we invo9e this progra* ro* in a di erent way, #sing redirectionP
+<X8IO.E\E < ?QEP.8\8 +<

2ere we are ca#sing the o#tp#t to be redirected to the ile ,3.5GTATG Can we prove that this the o#tp#t has indeed gone to the ile ,3.5GTATc Ces, by #sing the TC,. co**and as ollowsP
+<8G?E ?QEP.8\8 erha s I ha( a Fi'.e( 'hi%(h!!(" erha s I ha( a misera&%e /!,th" &,t s!meFhere in m/ Fi'.e( misera&%e ast" there m,st ha=e &een a m!ment !$ tr,th +<

There@s the res#lt o o#r typing sitting in the ileG The redirection operator, Db@, ca#ses any o#tp#t intended or the screen to be written to the ile whose na*e ollows the operatorG )ote that the data to be redirected to a ile doesn@t need to be typed by a #ser at the 9eyboard_ the progra* itsel can generate itG 1ny o#tp#t nor*ally sent to the screen can be redirected to a dis9 ileG 1s an e/a*ple consider the ollowing progra* or generating the 1SC$$ table on screenP

47"
)* Ii%e name: as'ii.'*) main1 2 3 int 'h # $!r 1 'h = 0 # 'h ;= 255 # 'h++ 2 rint$ 1 4@n5( 5'4" 'h" 'h 2 # 6

%et .s C

When this progra* is co*piled and then e/ec#ted at co**and pro*pt #sing the redirection operator,
+<A7+II.E\E < 8ADOE.8\8

the o#tp#t is written to the ileG This can be a #se #l capability any ti*e yo# want to capt#re the o#tp#t in a ile, rather than displaying it on the screenG 03S prede ines a n#*ber o ilena*es or its own #seG 3ne o these na*es in ,"), which stands or the printerG 3#tp#t can be redirected to the printer by #sing this ilena*eG +or e/a*ple, i yo# invo9e the KasciiGe/eO progra* this wayP
+<A7+II.E\E < ?>E

the 1SC$$ table will be printed on the printerG

$edirecting the *nput


We can also redirect inp#t to a progra* so that, instead o reading a character ro* the 9eyboard, a progra* reads it ro* a ileG 7et #s now see how this can be doneG To redirect the inp#t, we need to have a ile containing so*ething to be displayedG S#ppose we #se a ile called ).W,3.5GTAT containing the ollowing linesP

Chapter /30 @ore +ssues +n +nput?Output


Oet's start at the =er/ &e-innin-" A =er/ -!!( %a'e t! startT

477

We@ll ass#*e that #sing so*e te/t editor these lines have been placed in the ile ).W,3.5GTATG )ow, we #se the inp#t redirection operator Da@ be ore the ile, as shown belowP
+<X8IO.E\E ; EES?QEP.8\8 Oet's start at the =er/ &e-innin-" A =er/ -!!( %a'e t! startT +<

The lines are printed on the screen with no #rther e ort on o#r partG 6sing redirection we@ve *ade o#r progra* 6T$7GC per or* the wor9 o the TC,. co**andG

-oth /a#s at (nce


"edirection o inp#t and o#tp#t can be #sed together_ the inp#t or a progra* can co*e ro* a ile via redirection, at the sa*e ti*e its o#tp#t can be redirected to a ileG S#ch a progra* is called a ilterG The ollowing co**and de*onstrates this processG
+<X8IO ; EES?QEP.8\8 < ?QE8>G.8\8

$n this case o#r progra* receives the redirected inp#t ro* the ile ).W,3.5GTAT and instead o sending the o#tp#t to the screen it wo#ld redirect it to the ile ,3.T"CGTATG Si*ilarly to send the contents o the ile ).W,3.5GTAT to the printer we can #se the ollowing co**andP
+<X8IO ; EES?QEP.8\8 < ?>E

While #sing s#ch *#ltiple redirections don@t try to send o#tp#t to the sa*e ile ro* which yo# are receiving inp#tG This is beca#se

47&

%et .s C

the o#tp#t ile is erased be ore it@s written toG So by the ti*e we *anage to receive the inp#t ro* a ile it is already erasedG "edirection can be a power #l tool or developing #tility progra*s to e/a*ine or alter data in ilesG Th#s, redirection is #sed to establish a relationship between a progra* and a ileG 1nother 3S operator can be #sed to relate two progra*s directly, so that the o#tp#t o one is ed directly into another, with no iles involvedG This is called Dpiping@, and is done #sing the operator DY@, called pipeG We won@t p#rs#e this topic, b#t yo# can read abo#t it in the 3S help=*an#alG

Su11ar#
>a? We can pass para*eters to a progra* at co**and line #sing the concept o Dco**and line arg#*ents@G >b? The co**and line arg#*ent arg% contains val#es passed to the progra*, whereas, argc contains n#*ber o arg#*entsG >c? We can #se the standard ile pointer stdin to ta9e inp#t ro* standard inp#t device s#ch as 9eyboardG >d? We can #se the standard ile pointer stdout to send o#tp#t to the standard o#tp#t device s#ch as a *onitorG >e? We can #se the standard ile pointers stdprn and stdau3 to interact with printer and a#/iliary devices respectivelyG > ? "edirection allows a progra* to read ro* or write to iles at co**and pro*ptG >g? The operators J and C are called redirection operatorsG

B3ercise
K'L 1nswer the ollowingP

>a? 2ow will yo# #se the ollowing progra* to f Copy the contents o one ile into anotherG f ,rint a ile on the printerG f Create a new ile and add so*e te/t to itG

Chapter /30 @ore +ssues +n +nput?Output


f 0isplay the contents o an e/isting ileG
Lin'%,(e 4st(i!.h4 main1 2 3 'har 'h" str^10` # Fhi%e 1 1 'h = -et' 1 st(in 2 2 T= -1 2 ,t' 1 'h" st(!,t 2 # 6

479

>b? State Tr#e or +alseP 'G We can send arg#*ents at co**and line even i we de ine 1ain= > #nction witho#t para*etersG 2G To #se standard ile pointers we don@t need to open the ile #sing 8open= >G -G 6sing stdau3 we can send o#tp#t to the printer i printer is attached to the serial portG 4G The ;eroth ele*ent o the arg% array is always the na*e o the e/e ileG >c? ,oint o#t the errors, i any, in the ollowing progra*
main 1 int a'" 'har 1 * 2 a=^ ` 2 3 rint$ 1 4@n5(4" a' 2 # rint$ 1 4@n5s4" a=^0` 2 # 6 K-L 1tte*pt the ollowingP

>a? Write a progra* to carry o#t the ollowingP >a? "ead a te/t ile provided at co**and pro*pt >b? ,rint each word in reverse order +or e/a*ple i the ile contains
IE0IA I7 PG +QXE8>G

3#tp#t sho#ld be

4&)
AI0EI 7I GP G>8EXQ+

%et .s C

>b? Write a progra* #sing co**and line arg#*ents to search or a word in a ile and replace it with the speci ied wordG The #sage o the progra* is shown belowG Cb change aold wordb anew wordb a ilena*eb >c? Write a progra* that can be #sed at co**and pro*pt as a calc#lating #tilityG The #sage o the progra* is shown belowG Cb calc aswitchb anb a*b Where, n and 1 are two integer operandsG s0itch can be any one o the arith*etic or co*parison operatorsG $ arith*etic operator is s#pplied, the o#tp#t sho#ld be the res#lt o the operationG $ co*parison operator is s#pplied then the o#tp#t sho#ld be True or FalseG

14

&perations &n ,its


e 8itwise 3perators 3ne@s Co*ple*ent 3perator "ight Shi t 3perator 7e t Shi t 3perator 8itwise 1)0 3perator 8itwise 3" 3perator 8itwise A3" 3perator e The showbits( ) +#nction e S#**ary e ./ercise

4&1

4&2

%et .s C

o ar we have dealt with characters, integers, loats and their variationsG The s*allest ele*ent in *e*ory on which we are able to operate as yet is a byte_ and we operated on it by *a9ing #se o the data type charG 2owever, we haven@t atte*pted to loo9 within these data types to see how they are constr#cted o#t o individ#al bits, and how these bits can be *anip#latedG 8eing able to operate on a bit level, can be very i*portant in progra**ing, especially when a progra* *#st interact directly with the hardwareG This is beca#se, the progra**ing lang#ages are byte oriented, whereas hardware tends to be bit orientedG 7et #s now delve inside the byte and see how it is constr#cted and how it can be *anip#lated e ectivelyG So let #s ta9e apart the byteGGG bit by bitG

-it0ise (perators
3ne o C@s power #l eat#res is a set o bit *anip#lation operatorsG These per*it the progra**er to access and *anip#late individ#al bits within a piece o dataG The vario#s 8itwise 3perators available in C are shown in +ig#re '4G'G

(perator S bb aa I Y V

,eaning 3ne@s co*ple*ent "ight shi t 7e t shi t 8itwise 1)0 8itwise 3" 8itwise A3">./cl#sive 3"?

+ig#re '4G' These operators can operate #pon ints and chars b#t not on 8loats and dou6lesG 8e ore *oving on to the details o the operators, let

Chapter /80 Operations On $its

4&3

#s irst ta9e a loo9 at the bit n#*bering sche*e in integers and charactersG 8its are n#*bered ro* ;ero onwards, increasing ro* right to le t as shown belowP

'

Character

'5 '4 '- '2 '' '( &

'

'6<bit $nteger

+ig#re '4G2 Thro#gho#t this disc#ssion o bitwise operators we are going to #se a #nction called sho06its= >, b#t we are not going to show yo# the details o the #nction i**ediatelyG The tas9 o sho06its= > is to display the binary representation o any integer or character val#eG We begin with a plain<Qane e/a*ple with sho06its= > in actionG
)* ?rint &inar/ eH,i=a%ent !$ inte-ers ,sin- showbits( ) $,n'ti!n *) main1 2 3 int 9 # $!r 1 9 = 0 # 9 ;;= 5 # 9++ 2 3 rint$ 1 4@n0e'ima% 5( is same as &inar/ 4" 9 2 # sh!F&its 1 9 2 # 6

4&4
6

%et .s C

1nd here is the o#tp#tGGG


0e'ima% 0 is same as &inar/ 0000000000000000 0e'ima% 1 is same as &inar/ 0000000000000001 0e'ima% 2 is same as &inar/ 0000000000000010 0e'ima% 3 is same as &inar/ 0000000000000011 0e'ima% 4 is same as &inar/ 0000000000000100 0e'ima% 5 is same as &inar/ 0000000000000101

7et #s now e/plore the vario#s bitwise operators one by oneG

(neOs Co1ple1ent (perator


3n ta9ing one@s co*ple*ent o a n#*ber, all '@s present in the n#*ber are changed to (@s and all (@s are changed to '@sG +or e/a*ple one@s co*ple*ent o '('( is ('('G Si*ilarly, one@s co*ple*ent o '''' is ((((G )ote that here when we tal9 o a n#*ber we are tal9ing o binary eH#ivalent o the n#*berG Th#s, one@s co*ple*ent o 65 *eans one@s co*ple*ent o (((( (((( ('(( (((', which is binary eH#ivalent o 65G 3ne@s co*ple*ent o 65 there ore wo#ld be, '''' '''' '('' '''(G 3ne@s co*ple*ent operator is represented by the sy*bol SG +ollowing progra* shows one@s co*ple*ent operator in actionG
main1 2 3 int 9" . # $!r 1 9 = 0 # 9 ;= 3 # 9++ 2 3 rint$ 1 4@n0e'ima% 5( is same as &inar/ 4" 9 2 # sh!F&its 1 9 2 # . = c9 # rint$ 1 4@nQneRs '!m %ement !$ 5( is 4" 9 2 #

Chapter /80 Operations On $its


6 6 sh!F&its 1 . 2 #

4&5

1nd here is the o#tp#t o the above progra*GGG


0e'ima% 0 is same as &inar/ 0000000000000000 QneRs '!m %ement !$ 0 is 1111111111111111 0e'ima% 1 is same as &inar/ 0000000000000001 QneRs '!m %ement !$ 1 is 1111111111111110 0e'ima% 2 is same as &inar/ 0000000000000010 QneRs '!m %ement !$ 2 is 1111111111111101 0e'ima% 3 is same as &inar/ 0000000000000011 QneRs '!m %ement !$ 3 is 1111111111111100

$n real<world sit#ations where co#ld the one@s co*ple*ent operator be #se #lc Since it changes the original n#*ber beyond recognition, one potential place where it can be e ectively #sed is in develop*ent o a ile encryption #tility as shown belowP
)* Ii%e en'r/ ti!n ,ti%it/ *) Lin'%,(e 4st(i!.h4 main1 2 3 en'r/ t1 2 # 6 en'r/ t1 2 3 IIOE *$s" *$t # 'har 'h # $s = $! en 1 47QX>+E.+4" 4r4 2 # )* n!rma% $i%e *) $t = $! en 1 48A>JE8.+N" 4F4 2 # )* en'r/ te( $i%e *) i$ 1 $s == EXOO WW $t == EXOO 2 3

4&"
rint$ 1 4@nIi%e ! enin- err!rT4 2 # exit 1 1 2 # 6 Fhi%e 1 1 'h = -et' 1 $s 2 2 T= EQI 2 ,t' 1 c'h" $t 2 # $'%!se 1 $s 2 # $'%!se 1 $t 2 # 6

%et .s C

2ow wo#ld yo# write the corresponding decrypt #nctionc Wo#ld there be any proble* in tac9ling the end o ile *ar9erc $t *ay be recalled here that the end o ile in te/t iles is indicated by a character whose 1SC$$ val#e is 26G

$ight Shi8t (perator


The right shi t operator is represented by bbG $t needs two operandsG $t shi ts each bit in its le t operand to the rightG The n#*ber o places the bits are shi ted depends on the n#*ber ollowing the operator >iGeG its right operand?G Th#s, ch CC 3 wo#ld shi t all bits in ch three places to the rightG Si*ilarly, ch CC 5 wo#ld shi t all bits 5 places to the rightG +or e/a*ple, i the variable ch contains the bit pattern ''('(''', then, ch CC 1 wo#ld give (''('('' and ch CC 2 wo#ld give ((''('('G )ote that as the bits are shi ted to the right, blan9s are created on the le tG These blan9s *#st be illed so*ehowG They are always illed with ;erosG The ollowing progra* de*onstrates the e ect o right shi t operatorG
main1 2 3

Chapter /80 Operations On $its


int i = 5225" 9" . # rint$ 1 4@n0e'ima% 5( is same as &inar/ 4" i 2 # sh!F&its 1 i 2 # $!r 1 9 = 0 # 9 ;= 5 # 9++ 2 3 . = i <<9 # rint$ 1 4@n5( ri-ht shi$t 5( -i=es 4" i" 9 2 # sh!F&its 1 . 2 # 6 6

4&7

The o#tp#t o the above progra* wo#ld beGGG


0e'ima% 5225 is same as &inar/ 0001010001101001 5225 ri-ht shi$t 0 -i=es 0001010001101001 5225 ri-ht shi$t 1 -i=es 0000101000110100 5225 ri-ht shi$t 2 -i=es 0000010100011010 5225 ri-ht shi$t 3 -i=es 0000001010001101 5225 ri-ht shi$t 4 -i=es 0000000101000110 5225 ri-ht shi$t 5 -i=es 0000000010100011

)ote that i the operand is a *#ltiple o 2 then shi ting the operand one bit to right is sa*e as dividing it by 2 and ignoring the re*ainderG Th#s,
64 << 1 -i=es 32 64 << 2 -i=es 16 128 << 2 -i=es 32

b#t,
27 << 1 is 13 49 << 1 is 24 .

4&&
' /ord o8 Caution

%et .s C

$n the e/planation a CC 6 i 6 is negative the res#lt is #npredictableG $ a is negative than its le t *ost bit >sign bit? wo#ld be 'G 3n so*e co*p#ter right shi ting a wo#ld res#lt in e/tending the sign bitG +or e/a*ple, i a contains <', its binary representation wo#ld be ''''''''''''''''G Witho#t sign e/tension, the operation a CC 4 wo#ld be ((((''''''''''''G 2owever, on the *achine on which we e/ec#ted this e/pression the res#lt t#rns o#t to be ''''''''''''''''G Th#s the sign bit ' contin#es to get e/tendedG

Le8t Shi8t (perator


This is si*ilar to the right shi t operator, the only di erence being that the bits are shi ted to the le t, and or each bit shi ted, a ( is added to the right o the n#*berG The ollowing progra* sho#ld clari y *y pointG
main1 2 3 int i = 5225" 9" . # rint$ 1 4@n0e'ima% 5( is same as 4" i 2 # sh!F&its 1 i 2 # $!r 1 9 = 0 # 9 ;= 4 # 9++ 2 3 . = i ;;9 # rint$ 1 4@n5( %e$t shi$t 5( -i=es 4" i" 9 2 # sh!F&its 1 . 2 # 6 6

The o#tp#t o the above progra* wo#ld beGGG


0e'ima% 5225 is same as &inar/ 0001010001101001

Chapter /80 Operations On $its


5225 %e$t shi$t 0 -i=es 0001010001101001 5225 %e$t shi$t 1 -i=es 0010100011010010 5225 %e$t shi$t 2 -i=es 0101000110100100 5225 %e$t shi$t 3 -i=es 1010001101001000 5225 %e$t shi$t 4 -i=es 0100011010010000

4&9

2aving acH#ainted o#rselves with the le t shi t and right shi t operators, let #s now ind o#t the practical #tility o these operatorsG $n 03S=Windows the date on which a ile is created >or *odi ied? is stored as a 2<byte entry in the -2 byte directory entry o that ileG Si*ilarly, a 2<byte entry is *ade o the ti*e o creation or *odi ication o the ileG "e*e*ber that 03S=Windows doesn@t store the date >day, *onth, and year? o ile creation as a % byte string, b#t as a codi ied 2 byte entry, thereby saving 6 bytes or each ile entry in the directoryG The bitwise distrib#tion o year, *onth and date in the 2<byte entry is shown in +ig#re '4G-G

'5 '4 '- '2 '' '( & C C C C C C year C

% 5

2 0 day

' 0

( 0

5 5 5 0 *onth

+ig#re '4G03S=Windows converts the act#al date into a 2<byte val#e #sing the ollowing or*#laP
(ate = 512 * 1 /ear - 1980 2 + 32 * m!nth + (a/

S#ppose (&=(-='&&( is the date, then on conversion the date will be,
(ate = 512 * 1 1990 - 1980 2 + 32 * 3 + 9 = 5225

49)

%et .s C

The binary eH#ivalent o 5225 is (((' ('(( (''( '(('G This binary val#e is placed in the date ield in the directory entry o the ile as shown belowG

'5 '4 '- '2 '' '( & ( ( ( ' ( ' ( year

% ! ( (

6 '

5 '

4 (

'

2 ( day

' (

( '

*onth

+ig#re '4G4 N#st to veri y this bit distrib#tion, let #s ta9e the bits representing the *onth,
m!nth = 0011 =1*2+1*1 =3

Si*ilarly, the year and the day can also be veri iedG When we iss#e the co**and 0$" or #se Windows ./plorer to list the iles, the ile@s date is again presented on the screen in the #s#al date or*at o **=dd=yyG 2ow does this integer to date conversion ta9e placec 3bvio#sly, #sing le t shi t and right shi t operatorsG When we ta9e a loo9 at +ig#re '4G4 depicting the bit pattern o the 2< byte date ield, we see that the year, *onth and day e/ist as a b#nch o bits in contig#o#s locationsG Separating each o the* is a *atter o applying the bitwise operatorsG +or e/a*ple, to get year as a separate entity ro* the two bytes entry we right shi t the entry by & to get the yearG N#st see, howGGG

Chapter /80 Operations On $its

491
5 ' 4 ( ' 2 ( day ' ( ( '

'5 '4 '- '2 '' '( ( ( ( ' year "ight shi ting by & gives '5 '4 '- '2 '' '( ( ( ( ( ( ( ( '

& (

% (

! (

6 '

*onth

& (

% (

! (

6 (

5 (

4 (

'

2 ( #ear

' '

( (

+ig#re '4G5 3n si*ilar lines, le t shi ting by !, ollowed by right shi ting by '2 yields *onthG

492

%et .s C

'5 '4 '- '2 '' '( ( ( year 7e t shi ting by ! gives, '5 '4 '- '2 '' '( ( ( ' ' ( '

&

! (

6 '

5 '

4 (

'

2 ( day

' (

( '

*onth

& ( day

% (

! '

6 (

5 (

4 (

'

2 (

' '

( (

*onth

"ight shi ting by '2 gives, '5 '4 '- '2 '' '( & ( ( ( ( ( ( ( % ( ! ( 6 ( 5 ( 4 ( ( 2 ( ' ' ( '

*onth

+ig#re '4G6 +inally, or obtaining the day, le t shi t date by '' and then right shi t the res#lt by ''G 7e t shi ting by '' gives ('(('(((((((((((G "ight shi ting by '' gives (((((((((((('(('G This entire logic can be p#t into a progra* as shown belowP
)* 0e'!(in- (ate $ie%( in (ire't!r/ entr/ ,sin- &itFise ! erat!rs *) main1 2 3 ,nsi-ne( int ( = 9" m = 3" / = 1990" /ear" m!nth" (a/" (ate # (ate = 1 / - 1980 2 * 512 + m * 32 + ( # rint$ 1 4@n0ate = 5,4" (ate 2 #

Chapter /80 Operations On $its


/ear = 1980 + 1 (ate << 9 2 # m!nth = 1 1(ate ;; 7 2 << 12 2 # (a/ = 1 1(ate ;; 11 2 << 11 2 # rint$ 1 4@nGear = 5, 4" /ear 2 # rint$ 1 4P!nth = 5, 4" m!nth 2 # rint$ 1 40a/ = 5,4" (a/ 2 # 6

493

1nd here is the o#tp#tGGG


0ate = 5225 Gear = 1990 P!nth = 3 0a/ = 9

-it0ise '9D (perator


This operator is represented as G "e*e*ber it is di erent than , the logical 1)0 operatorG The operator operates on two operandsG While operating #pon these two operands they are co*pared on a bit<by<bit basisG 2ence both the operands *#st be o the sa*e type >either char or int?G The second operand is o ten called an 1)0 *as9G The operator operates on a pair o bits to yield a res#ltant bitG The r#les that decide the val#e o the res#ltant bit are shown belowP

First 6it ( ( ' '

Second 6it ( ' ( '

First 6it ( ( ( '

Second 6it

+ig#re '4G!

494

%et .s C

This can be represented in a *ore #nderstandable or* as a DTr#th Table@ shown in +ig#re '4G%G

I ( '

( ( (

' ( '

+ig#re '4G% The e/a*ple given below shows *ore clearly what happens while 1)0ing one operand with anotherG The r#les given in the +ig#re '4G% are applied to each pair o bits one by oneG
! ' ! ' ! ' 6 ( 6 ' 6 ( 5 ' 5 ( 5 ( 4 ( 4 ( 4 ( ' ( (

2 ( 2 ( 2 (

' ( ' ( ' ' ' ' ( ' ( (

This operand when 1)0ed bitwise

With this operand yields

this res#lt

+ig#re '4G& Wor9 thro#gh the Tr#th Table and con ir* that the res#lt obtained is really correctG Th#s, it *#st be clear that the operation is being per or*ed on individ#al bits, and the operation per or*ed on one pair o bits is

Chapter /80 Operations On $its

495

co*pletely independent o the operation per or*ed on the other pairsG ,robably, the best #se o the 1)0 operator is to chec9 whether a partic#lar bit o an operand is 3) or 3++G This is e/plained in the ollowing e/a*pleG S#ppose, ro* the bit pattern '('(''(' o an operand, we want to chec9 whether bit n#*ber - is 3) >'? or 3++ >(?G Since we want to chec9 the bit n#*ber -, the second operand or the 1)0 operation sho#ld be ' W 2-, which is eH#al to %G This operand can be represented bitwise as (((('(((G Then the 1)0ing operation wo#ld be,
10101101 00001000 -------------00001000 Qri-ina% &it attern AE0 mas. >es,%tin- &it attern

The res#lting val#e we get in this case is %, iGe the val#e o the second operandG The res#lt t#rned o#t to be % since the third bit o the irst operand was 3)G 2ad it been 3++, the bit n#*ber - in the res#lting bit pattern wo#ld have eval#ated to ( and the co*plete bit pattern wo#ld have been ((((((((G Th#s, depending #pon the bit n#*ber to be chec9ed in the irst operand we decide the second operand, and on 1)0ing these two operands the res#lt decides whether the bit was 3) or 3++G $ the bit is 3) >'?, the res#lting val#e t#rns o#t to be a non<;ero val#e which is eH#al to the val#e o second operand, and i the bit is 3++ >(? the res#lt is ;ero as seen aboveG The ollowing progra* p#ts this logic into actionG
)* 8! test Fhether a &it in a n,m&er is QE !r QII *) main1 2 3

49"
int i = 65" 9 # rint$ 1 4@n=a%,e !$ i = 5(4" i 2 # 9 = i B 32 # i$ 1 9 == 0 2 rint$ 1 4@nan( its $i$th &it is !$$4 2 # e%se rint$ 1 4@nan( its $i$th &it is !n4 2 # 9 = i B 64 # i$ 1 9 == 0 2 rint$ 1 4@nFhereas its sixth &it is !$$4 2 # e%se rint$ 1 4@nFhereas its sixth &it is !n4 2 #

%et .s C

1nd here is the o#tp#tGGG


]a%,e !$ i = 65 an( its $i$th &it is !$$ Fhereas its sixth &it is !n

$n every ile entry present in the directory, there is an attrib#te byteG The stat#s o a ile is governed by the val#e o individ#al bits in this attrib#te byteG The 1)0 operator can be #sed to chec9 the stat#s o the bits o this attrib#te byteG The *eaning o each bit in the attrib#te byte is shown in +ig#re '4G'(G

Chapter /80 Operations On $its

497

-it nu16ers ! G G G G G G G ' 6 G G G G G G ' G 5 G G G G G ' G G 4 G G G G ' G G G G G G ' G G G G 2 G G ' G G G G G ' G ' G G G G G G ( ' G G G G G G G

,eaning

"ead only 2idden Syste* Vol#*e label entry S#b<directory entry 1rchive bit 6n#sed 6n#sed

+ig#re '4G'( )ow, s#ppose we want to chec9 whether a ile is a hidden ile or notG 1 hidden ile is one, which is never shown in the directory, even tho#gh it e/ists on the dis9G +ro* the above bit classi ication o attrib#te byte, we only need to chec9 whether bit n#*ber ' is 3) or 3++G So, o#r irst operand in this case beco*es the attrib#te byte o the ile in H#estion, whereas the second operand is the ' W 2' X 2, as disc#ssed earlierG Si*ilarly, it can be chec9ed whether the ile is a syste* ile or not, whether the ile is read<only ile or not, and so onG The second, and eH#ally i*portant #se o the 1)0 operator is in changing the stat#s o the bit, or *ore precisely to switch 3++ a partic#lar bitG

49&

%et .s C

$ the irst operand happens to be (((((''', then to switch 3++ bit n#*ber ', o#r 1)0 *as9 bit pattern sho#ld be ''''''('G 3n applying this *as9, we get,
00000111 11111101 -------------00000101 Qri-ina% &it attern AE0 mas. >es,%tin- &it attern

2ere in the 1)0 *as9 we 9eep the val#e o all other bits as ' e/cept the one which is to be switched 3++ >which is p#rpose #lly 9ept as (?G There ore, irrespective o whether the irst bit is 3) or 3++ previo#sly, it is switched 3++G 1t the sa*e ti*e the val#e ' provided in all the other bits o the 1)0 *as9 >second operand? 9eeps the bit val#es o the other bits in the irst operand #nalteredG 7et@s s#**ari;e the #ses o bitwise 1)0 operatorP >a? $t is #sed to chec9 whether a partic#lar bit in a n#*ber is 3) or 3++G >b? $t is #sed to t#rn 3++ a partic#lar bit in a n#*berG

-it0ise ($ (perator
1nother i*portant bitwise operator is the 3" operator which is represented as RG The r#les that govern the val#e o the res#lting bit obtained a ter 3"ing o two bits is shown in the tr#th table belowG

Y ( '

( ( '

' ' '

+ig#re '4G''

Chapter /80 Operations On $its

499

6sing the Tr#th table con ir* the res#lt obtained on 3"ing the two operands as shown belowG
11010000 00000111 ------------11010111 Qri-ina% &it attern Q> mas. >es,%tin- &it attern

8itwise 3" operator is #s#ally #sed to p#t 3) a partic#lar bit in a n#*berG 7et #s consider the bit pattern ''((((''G $ we want to p#t 3) bit n#*ber -, then the 3" *as9 to be #sed wo#ld be (((('(((G )ote that all the other bits in the *as9 are set to ( and only the bit, which we want to set 3) in the res#lting val#e is set to 'G

-it0ise \($ (perator


The A3" operator is represented as ] and is also called an ./cl#sive 3" 3peratorG The 3" operator ret#rns ', when any one o the two bits or both the bits are ', whereas A3" ret#rns ' only i one o the two bits is 'G The tr#th table or the A3" operator is given belowG

V ( '

( ( '

' ' (

+ig#re '4G'2 A3" operator is #sed to toggle a bit 3) or 3++G 1 n#*ber A3"ed with another n#*ber twice gives the original n#*berG This is shown in the ollowing progra*G

5))
main1 2 3 int & = 50 # & = & K 12 # rint$ 1 4@n5(4" & 2 # )* this Fi%% rint 62 *) & = & K 12 # rint$ 1 4@n5(4" & 2 # )* this Fi%% rint 50 *) 6

%et .s C

The showbits( ) Function


We have #sed this #nction H#ite o ten in this chapterG )ow we have s# icient 9nowledge o bitwise operators and hence are in a position to #nderstand itG The #nction is given below ollowed by a brie e/planationG
sh!F&its 1 int n 2 3 int i" ." an(mas. # $!r 1 i = 15 # i <= 0 # i-- 2 3 an(mas. = 1 ;; i # . = n B an(mas. # 6 6 . == 0 Z rint$ 1 404 2 : rint$ 1 414 2 #

1ll that is being done in this #nction is #sing an 1)0 operator and a variable and1asG we are chec9ing the stat#s o individ#al bitsG $ the bit is 3++ we print a ( otherwise we print a 'G +irst ti*e thro#gh the loop, the variable and1asG will contain the val#e '(((((((((((((((, which is obtained by le t<shi ting ',

Chapter /80 Operations On $its

5)1

i teen placesG $ the variable nOs *ost signi icant bit is (, then G wo#ld contain a val#e (, otherwise it wo#ld contain a non<;ero val#eG $ G contains ( then print8= > will print o#t ( otherwise it will print o#t 'G 3n the second go<aro#nd o the loop, the val#e o i is decre*ented and hence the val#e o and1asG changes, which will now be ('((((((((((((((G This chec9s whether the ne/t *ost signi icant bit is ' or (, and prints it o#t accordinglyG The sa*e operation is repeated or all bits in the n#*berG

Su11ar#
>a? To help *anip#late hardware oriented dataRindivid#al bits rather than bytes a set o bitwise operators are #sedG >b? The bitwise operators incl#de operators li9e one@s co*ple*ent, right<shi t, le t<shi t, bitwise 1)0, 3", and A3"G >c? The one@s co*ple*ent converts all ;eros in its operand to 's and all 's to (sG >d? The right<shi t and le t<shi t operators are #se #l in eli*inating bits ro* a n#*berReither ro* the le t or ro* the rightG >e? The bitwise 1)0 operators is #se #l in testing whether a bit is on=o and in p#tting o a partic#lar bitG > ? The bitwise 3" operator is #sed to t#rn on a partic#lar bitG >g? The A3" operator wor9s al*ost sa*e as the 3" operator e/cept one *inor variationG

B3ercise
K'L 1nswer the ollowingP

>a? The in or*ation abo#t colors is to be stored in bits o a char variable called colorG The bit n#*ber ( to 6, each represent ! colors o a rainbow, iGeG bit ( represents violet, ' represents

5)2

%et .s C

indigo, and so onG Write a progra* that as9s the #ser to enter a n#*ber and based on this n#*ber it reports which colors in the rainbow does the n#*ber representsG >b? 1 co*pany planning to la#nch a new newspaper in *ar9et cond#cts a s#rveyG The vario#s para*eters considered in the s#rvey were, the econo*ic stat#s >#pper, *iddle, and lower class? the lang#ages readers pre er >.nglish, 2indi, "egional lang#age? and category o paper >daily, s#pple*ent, tabloid?G Write a progra*, which reads data o '( respondents thro#gh 9eyboard, and stores the in or*ation in an array o integersG The bit<wise in or*ation to be stored in an integer is given belowP 8it )#*ber ( ' 2 4 5 6 ! % $n or*ation 6pper class 5iddle class 7ower class .nglish 2indi "egional 7ang#age 0aily S#pple*ent Tabloid

1t the end give the statistical data or n#*ber o persons who read .nglish daily, n#*ber o #pper class people who read tabloid and n#*ber o regional lang#age readersG >c? $n an inter<college co*petition, vario#s sports and ga*es are played between di erent colleges li9e cric9et, bas9etball, ootball, hoc9ey, lawn tennis, table tennis, caro* and chessG The in or*ation regarding the ga*es won by a partic#lar college is stored in bit n#*bers (, ', 2, -, 4, 5, 6, ! and % respectively o an integer variable called ga1eG The college

Chapter /80 Operations On $its

5)3

that wins in 5 or *ore than 5 ga*es is awarded the Cha*pion o Cha*pions trophyG $ a n#*ber is entered thro#gh the 9eyboard, then write a progra* to ind o#t whether the college won the Cha*pion o the Cha*pions trophy or not, along with the na*es o the ga*es won by the collegeG >d? 1n ani*al co#ld be either a canine >dog, wol , o/, etcG?, a eline >cat, lyn/, Qag#ar, etcG?, a cetacean >whale, narwhal, etcG? or a *ars#pial >9oala, wo*bat, etcG?G The in or*ation whether a partic#lar ani*al is canine, eline, cetacean, or *ars#pial is stored in bit n#*ber (, ', 2 and - respectively o a integer variable called t#peG 8it n#*ber 4 o the variable t#pe stores the in or*ation abo#t whether the ani*al is Carnivore or 2erbivoreG +or the ollowing ani*al, co*plete the progra* to deter*ine whether the ani*al is a herbivore or a carnivoreG 1lso deter*ine whether the ani*al is a canine, eline, cetacean or a *ars#pialG
str,'t anima% 3 'har name^30` # int t/ e # 6 str,'t anima% a = 3 4Q+EOQ84" 18 6 #

>e? The ti*e ield in the directory entry is 2 bytes longG 0istrib#tion o di erent bits which acco#nt or ho#rs, *in#tes and seconds is given belowG Write a #nction which wo#ld receive the two<byte ti*e entry and ret#rn to the calling #nction, the ho#rs, *in#tes and secondsG

5)4

%et .s C

'5 '4 '- '2 '' '( &

2 S

'

2 2 2 2 2 5 5 5 5 5 5 S

S S

+ig#re '4G'> ? $n order to save dis9 space in or*ation abo#t st#dent is stored in an integer variableG $ bit n#*ber ( is on then it indicates $st year st#dent, bit n#*ber ' to - stores $$nd year, $$$rd year and $Vth year st#dent respectivelyG The bit n#*ber 4 to ! stores strea* 5echanical, Che*ical, .lectronics and $TG "est o the bits store roo* n#*berG 8ased on the given data, write a progra* that as9s or the roo* n#*ber and displays the in or*ation abo#t the st#dent, i its data e/ists in the arrayG The contents o array are,
int (ata^ ` = 3 273" 548" 786" 1096 6 #

>g? What will be the o#tp#t o the ollowing progra*P


main1 2 3 int i = 32" 9 = 65" ." %" m" n" !" # . = i W 35 # % = c. # m = i B 9 # n = 9 K 32 # ! = 9 ;; 2 # = i << 5 # rint$ 1 4@n. = 5( % = 5( m = 5(4" ." %" m 2 # rint$ 1 4@nn = 5( ! = 5( = 5(4" n" !" 2 # 6

16

C -nder .indo/s
e e e e e e e e e e e Which Windows: $ntegers The 6se o typede ,ointers in the -2<bit World 5e*ory 5anage*ent 0evice 1ccess 03S ,rogra**ing 5odel Windows ,rogra**ing 5odel .vent 0riven 5odel Windows ,rogra**ing, a Closer 7oo9 The +irst Windows ,rogra* 2#ngarian )otation S#**ary ./ercise

535

53"

%et .s C

o ar we have learnt every single 9eyword, operator and instr#ction available in CG Th#s we are thro#gh with the lang#age ele*ents that were there to learnG We did all this learning by co*piling o#r progra*s #sing a '6<bit co*piler li9e T#rbo C=CLLG )ow it is ti*e to *ove on to *ore serio#s st# G To *a9e a beginning one has to ta9e a very i*portant decisionR sho#ld we atte*pt to b#ild progra*s that are targeted towards '6< bit environ*ents li9e 5S<03S or -2<bit environ*ents li9e Windows=7in#/G 3bvio#sly we sho#ld choose the -2<bit plat or* beca#se that is what is in co**ercial #se today and wo#ld re*ain so #ntil 64<bit environ*ent ta9es over in #t#reG That raises a very i*portant H#estionRis it #tile to learn C progra**ing #sing '6< bit co*piler li9e T#rbo C=CLLc 1bsol#tely not4 The typical -2<bit environ*ent o ers so *any eat#res that the beginner is li9ely to eel lostG Contrasted with this, '6<bit co*pilers o er a very si*ple environ*ent that a novice can *aster H#ic9lyG )ow that the C #nda*entals are o#t o the way and yo# are con ident abo#t the lang#age eat#res it is ti*e or #s to delve into the *odern -2<bit operating environ*entsG $n today@s co**ercial world '6<bit operating environ*ents li9e 03S are *ore or less deadG 5ore and *ore so tware is being created or -2<bit environ*ents li9e Windows and 7in#/G $n this chapter we wo#ld e/plore how C progra**ing is done #nder WindowsG Chapters 2( I 2' are devoted to e/ploring C #nder 7in#/G

/hich /indo0s[
To a co**on #ser the di erences a*ongst vario#s versions o Windows li9e Windows &5,&%, 5., )T, 2(((, A,, Server 2((- is li*ited to only vis#al appearancesRthings li9e color o the title bar, shape o the b#ttons, des9top, tas9 bar, progra*s *en# etcG 8#t the tr#th is *#ch arther than thatG 1rchitect#rally there are h#ge di erences a*ongst the*G So *any are the di erences that 5icroso t categori;es the di erent versions #nder two *aQor heads RCons#*er Windows and Windows )T +a*ilyG Windows

Chapter /:0 C .nder Aindows

537

&5, &%, 5. all #nder the Cons#*er Windows, whereas Windows )T, 2(((, A,, Server 2((- all #nder the Windows )T +a*ilyG Cons#*er Windows was targeted towards the ho*e or s*all o ice #sers, whereas )T a*ily was targeted towards b#siness #sersG 5icroso t no longer provides s#pport or Cons#*er WindowsG 2ence in this boo9 we wo#ld concentrate only on )T +a*ily WindowsG So in the rest o this boo9 whenever $ re er to Windows $ *ean Windows )T a*ily, #nless e/plicitly speci iedG 8e ore we start writing C progra*s #nder Windows let #s irst see so*e o the changes that have happened #nder Windows environ*entG

*ntegers
6nder '6<bit environ*ent the si;e o integer is o 2 bytesG 1s against this, #nder -2<bit environ*ent an integer is o 4 bytesG 2ence its range is <2'4!4%-64% to L2'4!4%-64!G Th#s there is no di erence between an int and a long intG 8#t what i we wish to store the age o a person in an integerc $t wo#ld be i*proper to sacri ice a 4<byte integer when we 9now that the n#*ber to be stored in it is hardly going to e/ceed h#ndredG $n s#ch as case it wo#ld be *ore sensible to #se a short int since it is only 2 bytes longG

The .se o8 typedef


Ta9e a loo9 at the ollowing declarationsP
+QOQ>>EI '!%!r # UAE0OE h # S?A>AP F # O?A>AP % # DQQO & #

53&

%et .s C

1re C373"".+, 21)07., etcG new datatypes that have been added in C #nder Windows co*pilerc )ot at allG They are *erely typede @s o the nor*al integer datatypeG 1 typical C #nder Windows progra* wo#ld contain several s#ch t#pede8sG There are two reasons why Windows<based C progra*s heavily *a9e #se o t#pede8sG These areP >a? 1 typical Windows progra* is reH#ired to per or* several co*ple/ tas9sG +or e/a*ple a progra* *ay print doc#*ents, send *ails, per or* ile $=3, *anage *#ltiple threads o e/ec#tion, draw in a window, play so#nd iles, per or* operations over the networ9 apart ro* nor*al data processing tas9sG )at#rally a progra* that carries o#t so *any tas9s wo#ld be very big in si;eG $n s#ch a progra* i we start #sing the nor*al integer data type to represent variables that hold di erent entities we wo#ld soon lose trac9 o what that integer val#e act#ally representsG This can be overco*e by s#itably typede ining the integer as shown aboveG >b? 1t several places in Windows progra**ing we are reH#ired to gather and wor9 with dissi*ilar b#t inter<related dataG This can be done #sing a str#ct#reG 8#t when we de ine any str#ct#re variable we are reH#ired to precede it with the 9eyword structG This can be avoided by #sing t#pede8 as shown belowP
str,'t re't 3 int t! # int %e$t # int ri-ht # int &!tt!m # 6# t/ e(e$ str,'t re't >E+8 # t/ e(e$ str,'t re't* ?>E+8 #

Chapter /:0 C .nder Aindows


>E+8 r # ?>E+8 r #

539

What have we achieved o#t o thisc $t *a9es #ser<de ined data types li9e str#ct#res loo9, act and behave si*ilar to standard data types li9e integers, loats, etcG Co# wo#ld agree that the ollowing declarations
>E+8 r # int i #

are *ore logical than


str,'t >E+8 r # int i #

$*agine a sit#ation where each progra**er t#pede8s the integer to represent a color in di erent waysG So*e o these co#ld be as ollowsP
t/ e(e$ int +QO # t/ e(e$ int +QOQ> # t/ e(e$ int +QOQX> # t/ e(e$ int +QOQ>>EI #

To avoid this chaos 5icroso t has done several t#pede8s or co**only reH#ired entities in Windows progra**ingG 1ll these have been stored in header ilesG These header iles are provided as part o -2<bit co*piler li9e Vis#al CLLG

!ointers in the 32@6it /orld


$n a '6<bit world >li9e 5S<03S? we co#ld r#n only one application at a ti*eG $ we were to r#n another progra* we were reH#ired to ter*inate the irst one be ore la#nching the secondG 1s only one progra* >tas9? co#ld r#n at a ti*e this environ*ent was

54)

%et .s C

called single<tas9ing environ*entG Since only one progra* co#ld r#n at any given ti*e entire reso#rces o the *achine li9e *e*ory and hardware devices were accessible to this progra*G 6nder -2< bit environ*ent li9e Windows several progra*s reside and wor9 in *e*ory at the sa*e ti*eG 2ence it is 9nown as a *#lti<tas9ing environ*entG 8#t the *o*ent there are *#ltiple progra*s r#nning in *e*ory there is a possibility o con lict i two progra*s si*#ltaneo#sly access the *achine reso#rcesG To prevent this, Windows does not per*it any application direct access to any *achine reso#rceG To channeli;e the access witho#t res#lting into con lict between applications several new *echanis*s were created in the 5icroprocessor I 3SG This had a direct bearing on the way the application progra*s are createdG This is not a Windows 3S boo9G So we wo#ld restrict o#r disc#ssion abo#t the new *echanis*s that have been introd#ced in Windows to topics that are related, to C progra**ingG These topics are D5e*ory 5anage*ent and 0evice 1ccess@G

,e1or# ,anage1ent
Since #sers have beco*e *ore de*anding, *odern day applications have to contend with these de*ands and provide several eat#res in the*G To add to this, #nder Windows several s#ch applications r#n in *e*ory si*#ltaneo#slyG The *a/i*#* allowable *e*oryR' 58Rthat was #sed in '6<bit environ*ent was Q#st too s*all or thisG 2ence Windows had to evolve a new *e*ory *anage*ent *odelG Since Windows r#ns on -2<bit *icroprocessors each C,6 register is -2<bit longG Whenever we store a val#e at a *e*ory location the address o this *e*ory location has to be stored in the C,6 register at so*e point in ti*eG Th#s a -2<bit address can be stored in these registersG This *eans that we can store 2-2 #niH#e addresses in the registers at di erent ti*esG 1s a res#lt, we can access 4 G8 o *e*ory locations #sing -2<bit registersG 1s pointers store addresses, every pointer #nder -2<bit environ*ent also beca*e a 4<byte entityG

Chapter /:0 C .nder Aindows

541

2owever, i we decide to install 4 G8 *e*ory it wo#ld cost a lotG 2ence Windows #ses a *e*ory *odel which *a9es #se o as *#ch o physical *e*ory >say '2% 58? as has been installed and si*#lates the balance a*o#nt o *e*ory >4 G8 F '2% 58? on the hard dis9G 8e aware that this balance *e*ory is si*#lated as and when the need to do so arisesG Th#s *e*ory *anage*ent is de*and basedG )ote that progra*s cannot e/ec#te straight<away ro* hard dis9G They have to be irst bro#ght into physical *e*ory be ore they can get e/ec#tedG S#ppose there are *#ltiple progra*s already in *e*ory and a new progra* starts e/ec#tingG $ this new progra* needs *ore *e*ory than what is available right now, then so*e o the e/isting progra*s >or their parts? wo#ld be trans erred to the dis9 in order to ree the physical *e*ory to acco**odate the new progra*G This operation is o ten called page<o#t operationG 2ere page stands or a bloc9 o *e*ory >#s#ally o si;e 4(&6 bytes?G When that part o the progra* that was paged o#t is needed it is bro#ght bac9 into *e*ory >called page<in operation? and so*e other progra*s >or their parts? are paged o#tG This 9eeps on happening witho#t a co**on #ser@s 9nowledge all the ti*e while wor9ing with WindowsG 1 ew *ore acts that yo# *#st note abo#t paging are as ollowsP >a? ,art o the progra* that is c#rrently e/ec#ting *ight also be paged o#t to the dis9G >b? When the progra* is paged in > ro* dis9 to *e*ory? there is no g#arantee that it wo#ld be bro#ght bac9 to the sa*e physical location where it was be ore it was paged o#tG )ow i*agine how the paging operations wo#ld a ect o#r progra**ingG S#ppose we have a pointer pointing to so*e data present in a pageG $ this page gets paged o#t and is later paged in to a di erent physical location then the pointer wo#ld obvio#sly have a wrong addressG 2ence #nder Windows the pointer never holds the physical address o any *e*ory locationG $t always holds a virt#al address o that locationG What is this virt#al addressc 1t

542

%et .s C

its na*e s#ggests it is certainly not a real addressG $t is a n#*ber, which contains three partsG These parts when #sed in conQ#nction with a C,6 register called C"- and contents o two tables called ,age 0irectory Table and ,age Table leads to the act#al physical addressG This is shown in +ig#re '6G'G

,age 0irG $nde/ ,age Table $nde/ ,age 8yte 3 set -' ,age 0irectory ,T( ,T' 2' ,age Table ,( ,' : '' Target ,age ,+) n (

,age +ra*es

,T n ,age 0irectory "egister

,n :

,+) ( ,hysical 5e*ory

+ig#re '6G' The C"- register holds the physical location o ,age 0irectory TableG The le t part o the -2<bit virt#al address holds the inde/ into the ,age 0irectory TableG The val#e present at this inde/ is the starting address o the ,age TableG The *iddle part o the -2< bit virt#al address holds the inde/ into the ,age TableG The val#e present at this inde/ is the starting address o the physical page in *e*oryG The right part o the -2<bit virt#al address holds the byte

Chapter /:0 C .nder Aindows

543

o set > ro* the start o the page? o the physical *e*ory location to be accessedG )ote that the C"- register is not accessible ro* an applicationG 2ence an application can never directly reach a physical addressG 1lso, as the paging activity is going on the 3S wo#ld s#itably 9eep #pdating the val#es in the two tablesG

De%ice 'ccess
1ll devices #nder Windows are shared a*ongst all the r#nning progra*sG 2ence no progra* is per*itted a direct access to any o the devicesG The access to a device is ro#ted thro#gh a device driver progra*, which inally accesses the deviceG There is a standard way in which an application can co**#nicate with the device driverG $t is device driver@s responsibility to ens#re that *#ltiple reH#ests co*ing ro* di erent applications are handled witho#t ca#sing any con lictG This standard way o co**#nication is disc#ssed in detail in Chapter '!G

D(S !rogra11ing ,odel


Typical '6<bit environ*ents li9e 03S #se a seH#ential progra**ing *odelG $n this *odel progra*s are e/ec#ted ro* top to botto* in an orderly ashionG The path along which the control lows ro* start to inish *ay vary d#ring each e/ec#tion depending on the inp#t that the progra* receives or the conditions #nder which it is r#nG 2owever, the path re*ains airly predictableG C progra*s written in this *odel begin e/ec#tion with 1ain= > >o ten called entry point? and then call other #nctions present in the progra*G $ yo# ass#*e so*e inp#t data yo# can easily wal9 thro#gh the progra* ro* beginning to endG $n this progra**ing *odel it is the progra* and not the operating syste* that deter*ines which #nction gets called and whenG The operating syste* si*ply loads and e/ec#tes the progra* and then waits or it to inishG $ the progra* wishes it can ta9e help o the 3S to carry

544

%et .s C

o#t Qobs li9e console $=3, ile $=3, printing, etcG +or other operations li9e generating graphics, carrying o#t serial co**#nication, etcG the progra* has to call another set o #nctions called "35<8$3S #nctionsG 6n ort#nately the 03S #nctions and the 8$3S #nctions do not have any na*esG 2ence to call the* the progra* had to #se a *echanis* called interr#ptsG This is a *essy a air since the progra**er has to re*e*ber interr#pt n#*bers or calling di erent #nctionsG 5oreover, co**#nication with these #nctions has to be done #sing C,6 registersG This lead to lot o di ic#lties since di erent #nctions #se di erent registers or co**#nicationG To an e/tent these di ic#lties are red#ced by providing library #nctions that in t#rn call the 03S=8$3S #nctions #sing interr#ptsG 8#t the library doesn@t have a parallel #nction or every 03S=8$3S #nctionG 03S #nctions either call 8$3S #nctions or directly access the hardwareG 1t ti*es the progra*s are needed to directly interact with the hardwareG This has to be done beca#se either there are no 03S=8$3S #nctions to do this, or i they are there their reach is li*itedG +ig#re '6G2 capt#res the essence o the 03S progra**ing *odelG

Chapter /:0 C .nder Aindows

545

*ain> ? [ #n> ? _ \ #n> ? [ : : \

3n e/ec#tion trans er control to progra* $nterr#pt I C,6 "egisters $nterr#pt I C,6 "egisters

03S 3S

03S +#nctions

8$3S +#nction

2ardware SeH#entially ./ec#ting 03S progra*

+ig#re '6G2 +ro* the above disc#ssion yo# can gather that there are several li*itations in the 03S progra**ing *odelG These have been listed belowP

9o True $euse
The library #nctions that are called ro* each progra* beco*e part o the e/ec#table ile >G.A.? or that progra*G Th#s the sa*e #nctions get replicated in several .A. iles, thereby wasting precio#s dis9 spaceG

54"
*nconsistent LooG and Feel

%et .s C

.very 03S progra* has a di erent #ser inter ace that the #ser has to get #sed to be ore he can start getting wor9 o#t o the progra*G +or e/a*ple, s#ccess #l 03S<based so tware li9e 7ot#s '<2<-, +o/pro, Wordstar o ered di erent types o *en#sG This happened beca#se 03S=8$3S doesn@t provide any #nctions or creating #ser inter ace ele*ents li9e *en#sG 1s the loo9 and eel o all 03S based progra*s is di erent, the #ser ta9es a lot o ti*e in learning how to interact with the progra*

,ess# Calling ,echanis1


$t is di ic#lt to re*e*ber interr#pt n#*bers and the registers that are to be #sed or co**#nication with 03S=8$3S #nctionsG +or e/a*ple, i we are to position the c#rsor on the screen #sing a 8$3S #nction we are reH#ired to re*e*ber the ollowing detailsP
Interr, t n,m&er A 16 +?X >e-isters t! &e ,se(: AU A 2 1ser=i'e n,m&er2 0U A >!F n,m&er Fhere ',rs!r is t! &e !siti!ne( 0O A +!%,mn n,m&er Fhere ',rs!r is t! &e !siti!ne(

While #sing these interr#pt n#*bers and registers there is always a chance o errorG

2ard0are Dependenc#
03S progra*s are always reH#ired to bother abo#t the details o the hardware on which they are r#nningG This is beca#se or every new piece o hardware introd#ced there are new interr#pt n#*bers and new register detailsG 2ence 03S progra**ers are #nder the constant ear that i the hardware on which the progra*s are r#nning changes then the progra* *ay crashG

Chapter /:0 C .nder Aindows

547

5oreover the 03S progra**er has to write lot o code to detect the hardware on which his progra* is r#nning and s#itably *a9e #se o the relevant interr#pts and registersG )ot only does this *a9e the progra* lengthy, the progra**er has to #nderstand a lot o technical details o the hardwareG 1s a res#lt the progra**er has to spend *ore ti*e in #nderstanding the hardware than in the act#al application progra**ingG

/indo0s !rogra11ing ,odel


+ro* the perspective o the #ser the shi t ro* 5S<03S to Windows 3S involves switching over to a Graphical 6ser $nter ace ro* the typical Te/t $nter ace that 5S<03S o ersG 1nother change that the #ser *ay eel and appreciate is the ability o Windows 3S to e/ec#te several progra*s si*#ltaneo#sly, switching e ortlessly ro* one to another by pointing at windows and clic9ing the* with the *o#seG 5astering this new G6$ environ*ent and getting co* ortable with the *#ltitas9ing eat#re is at the *ost a *atter o a wee9 or soG 2owever, ro* the progra**er@s point o view progra**ing or Windows is a whole new ball ga*e4 Windows progra**ing *odel is designed with a view toP >a? >b? >c? >d? .li*inate the *essy calling *echanis* o 03S ,er*it tr#e re#se o co**only #sed #nctions ,rovide consistent loo9 and eel or all applications .li*inate hardware dependency

7et #s disc#ss how Windows progra**ing *odel achieves thisG

-etter Calling ,echanis1


$nstead o calling #nctions #sing $nterr#pt n#*bers and registers Windows provides #nctions within itsel which can be called #sing na*esG These #nctions are called 1,$ >1pplication ,rogra**ing $nter ace? #nctionsG There are literally h#ndreds o

54&

%et .s C

1,$ #nctions availableG They help an application to per or* vario#s tas9s s#ch as creating a window, drawing a line, per or*ing ile inp#t=o#tp#t, etcG

True $euse
1 C #nder Windows progra* calls several 1,$ #nctions d#ring co#rse o its e/ec#tionG $*agine how *#ch dis9 space wo#ld have been wasted had each o these #nctions beco*e part o the .A. ile o each progra*G To avoid this, the 1,$ #nctions are stored in special iles that have an e/tension G077G 077 stands or 0yna*ic 7in9 7ibrariesG 1 077 is a binary ile that provides a library o #nctionsG The #nctions present in 077s can be lin9ed d#ring e/ec#tionG These #nctions can also be shared between several applications r#nning in WindowsG Since lin9ing is done dyna*ically the #nctions do not beco*e part o the e/ec#table ileG 1s a res#lt, the si;e o .A. iles does not go o#t o handG $t is also possible to create yo#r own 077sG Co# wo#ld li9e to do this or two reasonsP >a? Sharing co**on code between di erent e/ec#table ilesG >b? 8rea9ing an application into co*ponent parts to provide a way to easily #pgrade application@s co*ponentsG The Windows 1,$ #nctions co*e in three 077 ilesG +ig#re '6Glists these ilena*es along with p#rpose o eachG

Chapter /:0 C .nder Aindows

549

DLL 6S."-2G077

Description Contains #nctions that are responsible or window *anage*ent, incl#ding *en#s, c#rsors, co**#nications, ti*er etcG Contains #nctions or graphics drawing and painting Contains #nctions to handle *e*ory *anage*ent, threading, etcG

G0$-2G077 K.").7-2G077

+ig#re '6G-

Consistent LooG and Feel


Consistent loo9 and eel *eans that each progra* o ers a consistent and si*ilar #ser inter aceG 1s a res#lt, #ser doesn@t have to spend long periods o ti*e *astering a new progra*G .very progra* occ#pies a windowRa rectang#lar area on the screenG 1 window is identi ied by a title barG 5ost progra* #nctions are initiated thro#gh the progra*@s *en#G The display o in or*ation too large to it on a single screen can be viewed #sing scroll barsG So*e *en# ite*s invo9e dialog bo/es, into which the #ser enters additional in or*ationG 3ne dialog bo/ is o#nd in al*ost every Windows progra*G $t opens a ileG This dialog bo/ loo9s the sa*e >or very si*ilar? in *any di erent Windows progra*s, and it is al*ost always invo9ed ro* the sa*e *en# optionG 3nce yo# 9now how to #se one Windows progra*, yo#@re in a good position to easily learn anotherG The *en#s and dialog bo/es allow #ser to e/peri*ent with a new progra* and e/plore its eat#resG 5ost Windows progra*s have both a 9eyboard inter ace and a *o#se inter aceG 1ltho#gh *ost #nctions o Windows progra*s can be controlled thro#gh the 9eyboard, #sing the *o#se is o ten easier or *any choresG

55)

%et .s C

+ro* the progra**er@s perspective, the consistent #ser inter ace res#lts ro* #sing the Windows 1,$ #nctions or constr#cting *en#s and dialog bo/esG 1ll *en#s have the sa*e 9eyboard and *o#se inter aces beca#se WindowsRrather than the application progra*Rhandles this QobG

2ard0are *ndependent !rogra11ing


1s we saw earlier a Windows progra* can always call Windows 1,$ #nctionsG Th#s an application can easily co**#nicate with 3SG What is new in Windows is that the 3S can also co**#nicate with applicationG 7et #s #nderstand why it does so with the help o an e/a*pleG S#ppose we have written a progra* that contains a *en# ite*, which on selection is s#pposed to display a string K2ello WorldO in the windowG The *en# ite* can be selected either #sing the 9eyboard or #sing the *o#seG 3n e/ec#ting this progra* it will per or* the initiali;ations and then wait or the #ser inp#tG Sooner or later the #ser wo#ld press the 9ey or clic9 the *o#se to select the *en#<ite*G This 9ey<press or *o#se<clic9 is 9nown as an Devent@G The occ#rrence o this event is sensed by the 9eyboard or *o#se device driverG The device driver wo#ld now in or* Windows abo#t itG Windows wo#ld in t#rn noti y the application abo#t the occ#rrence o this eventG This noti ication is 9nown as a D*essage@G Th#s the 3S has co**#nicated with the applicationG When the application receives the *essage it co**#nicates bac9 with the 3S by calling a Windows 1,$ #nction to display the string K2ello WorldO in the windowG This 1,$ #nction in t#rn co**#nicates with the device driver o the graphics card >that drives the screen? to display the stringG Th#s there is a two<way co**#nication between the 3S and the applicationG This is shown in +ig#re '6G4G

Chapter /:0 C .nder Aindows

551

1pplication 1,$ Call 5essage

Windows 3S

0evice 0river

2ardware

+ig#re '6G4 S#ppose the 9eyboard and the *o#se are now replaced with a new 9eyboard and *o#seG 0oing so wo#ld not a ect the application at allG This is beca#se at no ti*e does the application carry o#t any direct co**#nication with the devicesG 1ny di erences that *ay be there in the new set o *o#se and 9eyboard wo#ld be handled the device driver and not by the application progra*G Si*ilarly, i the screen or the graphics card is replaced no change wo#ld be reH#ired in the progra*G $n short hardware independence at wor94 1t ti*es a change o device *ay necessitate a change in the device driver progra*, b#t never a change in the applicationG

B%ent Dri%en ,odel


When a #ser interacts with a Windows progra* a lot o events occ#rG +or each event a *essage is sent to the progra* and the progra* reacts to itG Since the order in which the #ser wo#ld interact with the #ser<inter ace ele*ents o the progra* cannot be predicted the order o occ#rrence o events, and hence the order o *essages, also beco*es #npredictableG 1s a res#lt, the order o

552

%et .s C

calling the #nctions in the progra* >that react to di erent *essages? is dictated by the order o occ#rrence o eventsG 2ence this progra**ing *odel is called D.vent 0riven ,rogra**ing 5odel@G That@s really all that is there to event<driven progra**ingG Co#r Qob is to anticipate what #sers are li9ely to do with yo#r application@s #ser inter ace obQects and have a #nction waiting, ready to e/ec#te at the appropriate ti*eG N#st when that ti*e is, no one e/cept the #ser can really sayG

/indo0s !rogra11ing4 a Closer LooG


There can be h#ndreds o ways in which the #ser *ay interact with an applicationG $n addition to this so*e events *ay occ#r witho#t any #ser interactionG +or e/a*ple, events occ#r when we create a window, when the window@s contents are to be drawn, etcG )ot only this, occ#rrence o one event *ay trigger a ew *ore eventsG Th#s literally h#ndreds o *essages *ay be sent to an application thereby creating a chaosG )at#rally, a H#estion co*esRin which order wo#ld these *essages get processed by the applicationG 3rder is bro#ght to this chaos by p#tting all the *essages that reach the application into a Dd#e#e@G The *essages in the H#e#e are processed in +irst $n +irst 3#t >+$+3? orderG $n act the 3S *aintains several s#ch H#e#esG There is one H#e#e, which is co**on or all applicationsG This H#e#e is 9nown as DSyste* 5essage d#e#e@G $n addition there is one H#e#e per applicationG S#ch H#e#es are called D1pplication 5essage d#e#es@G 7et #s #nderstand the need or *aintaining so *any H#e#esG When we clic9 a *o#se and an event occ#rs the device driver posts a *essage into the Syste* 5essage d#e#eG The 3S retrieves this *essage inds o#t with regard to which application the *essage has been sentG )e/t it posts a *essage into the

Chapter /:0 C .nder Aindows

553

1pplication 5essage d#e#e o the application in which the *o#se was clic9edG "e er +ig#re '6G5G

.vent 0evice 0river 5sgG

.vent 0evice 0river 5sgG Syste* 5sgG d#e#e

3ther 5ess

3S

3ther 5essa

1pplication'

1pplication' 5sgG d#e#e

1pplication2 5sgG d#e#e

1pplication2

+ig#re '6G5 $ thin9 now we have covered eno#gh gro#nd to be able to act#ally start C #nder Windows progra**ingG 2ere we go:

554
The First /indo0s !rogra1

%et .s C

To 9eep things si*ple we wo#ld begin with a progra* that *erely displays a K2elloO *essage in a *essage bo/G 2ere is the progra*:
Lin'%,(e ;Fin(!Fs.h< int _st('a%% SinPain 1 UIE78AE+E hInstan'e" UIE78AE+E h?re=Instan'e" O?78> % s:+m(%ine" int n+m(7h!F 2 3 Pessa-eD!x 1 0" MUe%%!TN" M8it%eN" 0 2 # ret,rn 1 0 2 # 6

)at#rally a H#estion wo#ld co*e to yo#r *indRhow do $ create and r#n this progra* and what o#tp#t does it prod#ceG +irstly ta9e a loo9 at the o#tp#t that it prod#cesG 2ere it is:

+ig#re '6G6 7et #s now loo9 at the steps that one needs to carry to create and e/ec#te this progra*P >a? Start VCLL ro* DStart Y ,rogra*s Y 5icroso t Vis#al CLL 6G(@G The VCLL $0. window will get displayedG >b? +ro* the +ile Y )ew *en#, select DWin-2 1pplication@, and give a proQect na*e, say, Dsa*ple'@G Clic9 on 3KG >c? +ro* the +ile Y )ew *en#, select DCLL So#rce +ile@, and give a s#itable ile na*e, say, Dsa*ple'@G Clic9 on 3KG >d? The DWin-2 1pplication<Step ' o '@ window will appearG Select D1n e*pty proQect@ option and clic9 D+inish@ b#ttonG

Chapter /:0 C .nder Aindows

555

>e? 1 D)ew ,roQect $n or*ation@ dialog will appearG Close it by clic9ing on 3KG > ? 1gain select D+ile Y )ew Y CLL So#rce +ile@G Give the ile na*e as Dsa*ple'Gc@G Clic9 on 3KG >g? Type the progra* in the Dsa*ple'Gc@ ile that gets opened in the VCLL $0.G >h? Save this ile #sing DSave@ option ro* the +ile *en#G To e/ec#te the progra* ollow the steps *entioned belowP >a? +ro* the 8#ild *en#, select D8#ild sa*ple'Ge/e@G >b? 1ss#*ing that no errors were reported in the progra*, select D./ec#te sa*ple'Ge/e@ ro* the 8#ild *en#G 7et #s now try to #nderstand the progra*G The way every C #nder 03S progra* begins its e/ec#tion with 1ain= >, every C #nder Windows progra* begins its e/ec#tion with /in,ain= >G Th#s /in,ain= > beco*es the entry point or a Windows progra*G 1 typical /in,ain= > loo9s li9e thisP
int st('a%% SinPain 1 UIE78AE+E hInstan'e" UIE78AE+E h?re=Instan'e" O?78> % s:+m(Oine" int n+m(7h!F 2

)ote the stdcall be ore /in,ain= >G $t indicates the calling convention #sed by the /in,ain= > #nctionG Calling Conventions indicate two thingsP >a? The order >le t to right or right to le t? in which the arg#*ents are p#shed onto the stac9 when a #nction call is *adeG >b? Whether the caller #nction or called #nction re*oves the arg#*ents ro* the stac9 at the end o the callG

3#t o the di erent calling conventions available *ost co**only #sed conventions are cdecl and B:stdcall G 8oth these calling conventions pass arg#*ents to #nctions ro* right to le tG $n cdecl the stac9 is cleaned #p by the calling #nction, whereas in case o stdcall the stac9 is cleaned #p by the called #nctionG 1ll

55"

%et .s C

1,$ #nctions #se stdcall calling conventionG $ not *entioned, cdecl calling convention is ass#*ed by the co*pilerG 2$)ST1)C. and 7,ST" are nothing b#t t#pede8sG The irst is an unsigned int and the second is a pointer to a charG These *acros are de ined in DwindowsGh@, This header ile *#st always be incl#ded while writing a C progra* #nder WindowsG h*nstance, h!re%*nstance, lpsHC1dLine and nC1dSho0 are si*ple variable na*esG $n place o these we can #se i, W, G and l respectivelyG 7et #s now #nderstand the *eaning o these para*eters as well as the rest o the progra*G f /in,ain= > receives o#r para*eters which are as #nderP h*nstanceP This is the Dinstance handle@ or the r#nning applicationG Windows creates this $0 n#*ber when the application startsG We will #se this val#e in *any Windows #nctions to identi y an application@s dataG 1 handle is si*ply a -2<bit n#*ber that re ers to an entityG The entity co#ld be an application, a window, an icon, a br#sh, a c#rsor, a bit*ap, a ile, a device or any s#ch entityG The act#al val#e o the handle is #ni*portant to yo#r progra*s, b#t the Windows *od#le that gives yo#r progra* the handle 9nows how to #se it to re er to an entityG What is i*portant is that there is a #niH#e handle or each entity and we can re er and reach the entity only #sing its handleG h!re%*nstanceP This para*eter is a re*nant o earlier versions o Windows and is no longer signi icantG )ow it always contains a val#e (G $t is being persisted with only to ens#re bac9ward co*patibilityG lpsHC1dLineP This is a pointer to a character string containing the co**and line arg#*ents passed to the progra*G This is si*ilar to the arg%, argc para*eters passed to 1ain= > in a 03S progra*G

Chapter /:0 C .nder Aindows

557

nC1dSho0P This is an integer val#e that is passed to the #nctionG This integer tells the progra* whether the window that it creates sho#ld appear *ini*i;ed, as an icon, nor*al, or *a/i*i;ed when it is displayed or the irst ti*eG f f f The ,essage-o3= > #nction pops #p a *essage bo/ whose title is DTitle@ and which contains a *essage D2ello4@G "et#rning ) ro* /in,ain= > indicates s#ccess, whereas, ret#rning a non;ero val#e indicates ail#reG $nstead o printing D2ello4@ in the *essage bo/ we can print the co**and line arg#*ents that the #ser *ay s#pply while e/ec#ting the progra*G The co**and line arg#*ents can be s#pplied to the progra* by e/ec#ting it ro* Start Y "#n as shown in +ig#re '6G!G

+ig#re '6G! )ote ro* +ig#re '6G! that D*yappGe/e@ is the na*e o o#r application, whereas, Dabc iQ9 /y;@ represents co**and line arg#*entsG The para*eter lpsHC1dline points to the string Kabc iQ9 /y;OG This string can be printed #sing the ollowing state*entP
Pessa-eD!x 1 0" % s:+m(%ine" 48it%e4" 0 2 #

$ the entire co**and line incl#ding the ilena*e is to be retrieved we can #se the GetCo11andLine= > #nction,

55&
2ungarian 9otation

%et .s C

2#ngarian )otation is a variable<na*ing convention so called in the honor o the legendary 5icroso t progra**er Charles Si*onyiG 1ccording to this convention the variable na*e begins with a lower case letter or letters that denotes the data type o the variableG +or e/a*ple, the sH pre i/ in sHC1dLine stands or Dstring ter*inated by ;ero@_ the pre i/ h in h*nstance stands or Dhandle@_ the pre i/ n in nC1dSho0 stands or intG ,re i/es are o ten co*bined to or* other pre i/es, as lpsH in lpsHC1dLine stands or Dlong pointer to a ;ero ter*inated string@G Tho#gh basically this notation is a good idea nowadays its #sage is disco#ragedG This is beca#se when a transition happens ro* say a '6<bit code to -2<bit code then a whole lot o variable na*es have to be changedG +or e/a*ple, s#ppose the '6<bit code #sed 2<byte and 4<byte integer variables called 0!ara1 and l!ara1, where 0 indicated a '6<bit integer >word? and a -2<bit integer >long? respectivelyG When this code is ported to a -2<bit environ*ent 0!ara1 had to be changed to l!ara1 since in this environ*ent every integer is 4 bytes longG Co# wo#ld agree that i we ollow the 2#ngarian notation then we wo#ld have to *a9e a whole lot o changes in the variable na*es when we port the code to a -2<bit or a 64<bit environ*entG 2ence the #sage o this convention is nowadays disco#ragedG

Su11ar#
>a? 6nder Windows an integer is o#r bytes longG To #se a two< byte integer pre<H#ali y it with shortG >b? 6nder Windows a pointer is o#r bytes longG >c? Windows progra**ing involves a heavy #sage o t#pede8sG >d? 03S #ses a SeH#ential ,rogra**ing 5odel, whereas, Windows #ses an .vent 0riven ,rogra**ing 5odelG >e? .ntry point o every Windows progra* is a #nction called /in,ain= >G

Chapter /:0 C .nder Aindows

559

> ? Windows does not per*it direct access to *e*ory or hardware devicesG >g? Windows #ses a 0e*and<based Virt#al 5e*ory 5odel to *anage *e*oryG >h? 6nder Windows there is two<way co**#nication between the progra* and the 3SG >i? Windows *aintains a syste* *essage H#e#e co**on or all applicationsG >Q? Windows *aintains an application *essage H#e#e per r#nning applicationG >9? Calling convention decides the order in which the para*eters are passed to a #nction and whether the calling #nction or the called #nction clears the stac9G >l? Co**only #sed calling conventions are cdecl and stdcallG >*? 2#ngarian notation tho#gh good its #sage is not reco**ended any *oreG

B3ercise
K'L State Tr#e or +alseP

>a? 5S<03S #ses a proced#ral progra**ing *odelG >b? 1 Windows progra* can directly call a device driver progra* or a deviceG >c? 1,$ #nctions #nder Windows do not have na*esG >d? 03S #nctions are called #sing an interr#pt *echanis*G >e? Windows #ses a 4 G8 virt#al *e*ory spaceG > ? Si;e o a pointer #nder Windows depends #pon whether it is near or 8arG >g? 6nder Windows the address stored in a pointer is a virt#al address and not a physical addressG >h? 3ne o the para*eters o /in,ain= > called h!re%*nstance is no longer relevantG

5")
K-L 1nswer the ollowingP

%et .s C

>a? Why is .vent<driven ,rogra**ing 5odel better than the SeH#ential ,rogra**ing 5odelc >b? What is the *eaning o di erent parts o the address stored in a pointer #nder Windows environ*entc >c? Why Windows does not per*it direct access to hardwarec >d? What is the di erence between an event and a *essagec >e? Why Windows *aintains a di erent *essage H#e#e or each applicationc > ? $n which di erent sit#ations *essages get posted into an application *essage H#e#ec
KCL 1tte*pt the ollowingP

>a? Write a progra* that prints the val#e o h*nstance in a *essage bo/G >b? Write a progra* that displays three b#ttons DCes@, D)o@ DCancel@ in the *essage bo/G >c? Write a progra* that receives a n#*ber as a co**and line arg#*ent and prints its actorial val#e in a *essage bo/G >d? Write a progra* that displays co**and line arg#*ents incl#ding ile na*e in a *essage bo/G

1!

.indo/s Progra00ing
e e e e The "ole o a 5essage 8o/ 2ere co*es the window: 5ore Windows 1 "eal<World Window Creation and 0isplaying o Window $nteraction with Window "eacting to 5essages e ,rogra* $nstances e S#**ary e ./ercise

5"1

5"2

%et .s C

event driven progra**ing reH#ires a change in *ind setG $ hope Chapter '6 has been able to bring abo#t this changeG 2owever this change wo#ld be bolstered by writing event driven progra*sG This is what this chapter intends to doG $ a* hope #l that by the ti*e yo# reach the end o this chapter yo# wo#ld be so co* ortable with it as i yo# have been #sing it all yo#r li eG

The $ole o8 a ,essage -o3


3 ten we are reH#ired to display certain res#lts on the screen d#ring the co#rse o e/ec#tion o a progra*G We do this to ascertain whether we are getting the res#lts as per o#r e/pectationsG $n a seH#ential 03S based progra* we can easily achieve this #sing print8= > state*entsG 6nder Windows screen is a shared reso#rceG So yo# can i*agine what chaos wo#ld it create i all r#nning applications are per*itted to write to the screenG Co# wo#ld not be able to *a9e o#t which o#tp#t is o what applicationG 2ence no Windows progra* is per*itted to write anything directly to the screenG That@s where a *essage bo/ enters the sceneG 6sing it we can display inter*ediate res#lts d#ring the co#rse o e/ec#tion o a progra*G $t can be dis*issed either by clic9ing the Dclose b#tton@ in its title bar or by clic9ing the 3K b#tton present in itG There are n#*ero#s variations that yo# can try with the ,essage-o3= >G So*e o these are given below
Pessa-eD!x 1 0" MAre /!, s,reN" M+a ti!nN" PD_GE7EQ 2 # Pessa-eD!x 1 0" M?rint t! the ?rinterN" M+a ti!nN" PD_GE7EQ +AE+EO2 # Pessa-eD!x 1 0" Mi'!n is a%% a&!,t st/%eN" M+a ti!nN" PD_Q_ W PD_I+QEIEIQ>PA8IQE 2 #

Co# can p#t the above state*ents within /in,ain= > and see the res#lts or yo#rsel G Tho#gh the above *essage bo/es give yo# le/ibility in displaying res#lts, b#tton, icons, there is a li*it to which yo# can stretch the*G What i we want to draw a ree hand drawing or display an i*age, etcG in the *essage bo/G This wo#ld

Chapter /;0 Aindows #rogramming

5"3

not be possibleG To achieve this we need to create a #ll< ledged windowG The ne/t section disc#sses how this can be doneG

2ere Co1es the 0indo0[


8e ore we proceed with the act#al creation o a window it wo#ld be a good idea to identi y the vario#s ele*ents o itG These are shown in +ig#re '!G'G
Caption 8ar $con

5ini*i;e 8o/ Close 8#tt on

5en# Vertical Client 1rea Scrol

2ori;ontal Scroll

+ig#re '!G' )ote that every window drawn on the screen need not necessarily have every ele*ent shown in the above ig#reG +or e/a*ple, a window *ay not contain the *ini*i;e bo/, the *a/i*i;e bo/, the scroll bars and the *en#G 7et #s now create a si*ple progra* that creates a window on the screenG 2ere is the progra*:
Lin'%,(e ;Fin(!Fs.h<

5"4

%et .s C

int _st('a%% SinPain 1 UIE78AE+E hInstan'e" UIE78AE+E h?re=Instan'e" O?78> % s:+m(Oine" int n+m(7h!F 2 3 USE0 h # h = +reateSin(!F 1 MDX88QEN" MUit PeN" S7_Q]E>OA??E0SIE0QS" 10" 10" 150" 100" 0" 0" i" 0 2 # 7h!FSin(!F 1 h" n+m(7h!F 2 # Pessa-eD!x 1 0" MUiTN" MSaitin-N" PD_Q_ 2 # ret,rn 0 # 6

2ere is the o#tp#t o the progra*:

+ig#re '!G2 7et #s now #nderstand the progra*G .very window enQoys certain propertiesRbac9gro#nd color, shape o c#rsor, shape o icon, etcG 1ll these properties ta9en together are 9nown as Dwindow class@G The *eaning o Dclass@ here is Dtype@G Windows insists that a window class sho#ld be registered with it be ore we atte*pt to create windows o that typeG 3nce a window class is registered we can create several windows o that typeG .ach o these windows wo#ld enQoy the sa*e properties that have been registered thro#gh the window classG There are several prede ined window classesG So*e o these are 86TT3), .0$T, 7$ST83A, etcG 3#r progra* has created one s#ch window #sing the prede ined 86TT3) classG

Chapter /;0 Aindows #rogramming

5"5

To act#ally create a window we need to call the 1,$ #nction Create/indo0= >G This #nction reH#ires several para*eters starting with the window classG The second para*eter indicates the te/t that is going to appear on the b#tton s#r aceG The third para*eter speci ies the window styleG WSB3V."71,,.0W$)03W is a co**only #sed styleG The ne/t o#r para*eters speci y the window@s initial position and si;e Rthe / and y screen coordinates o the window@s top le t corner and the window@s width and height in pi/elsG The ne/t three para*eters speci y the handles to the parent window, the *en# and the application instance respectivelyG The last para*eter is the pointer to the window<creation dataG We can easily devote a section o this boo9 to Create/indo0= > and its para*etersG 8#t don@t get scared o itG )obody is s#pposed to re*e*ber all the para*eters, their *eaning and their orderG Co# can always #se 5S0) >5icroso t 0eveloper )etwor9? help to #nderstand the *in#te details o each para*eterG This help is available as part o VCLL 6G( prod#ctG $t is also available on the net at httpP==wwwG*sdnG*icroso tGco*=libraryG )ote that Create/indo0= > *erely creates the window in *e*oryG We still are to display it on the screenG This can be done #sing the Sho0/indo0= > 1,$ #nctionG Create/indo0= > ret#rns handle o the created windowG 3#r progra* #ses this handle to re er to the window while calling Sho0/indo0= >, The second para*eter passed to Sho0/indo0= > signi ies whether the window wo#ld appear *ini*i;ed, *a/i*i;ed or nor*alG $ the val#e o this para*eter is S/:S2(/9($,'L we get a nor*al si;ed window, i it is S/:S2(/,*9*,*NBD we get a *ini*i;ed window and i it is S/:S2(/,*9*,*NBD we get a *a/i*i;ed windowG We have passed nC1dSho0 as the second para*eterG This variable contains S/:S2(/9($,'L by de a#ltG 2ence o#r progra* displays a nor*al si;ed windowG

5""

%et .s C

The WSB3V."71,,.0W$)03W style is a collection o the ollowing stylesP


S7_Q]E>OA??E0 W S7_+A?8IQE W S7_7G7PEEX W S7_8UI+_I>APE W S7_PIEIPIbEDQ\ W S7_PA\IPIbEDQ\

1s yo# can *a9e o#t ro* these *acros they essentially control the loo9 and eel o the window being createdG 1ll these *acros are Ide8ined in the DWindowsGh@ header ileG 3n e/ec#ting this progra* a window and a *essage bo/ appears on the screen as shown in the +ig#re '!G2G The window and the *essage bo/ disappear as soon as we clic9 on 3KG This is beca#se on doing so e/ec#tion o /in,ain= > co*es to an end and *oreover we have *ade no provision to interact with the windowG Co# can try to re*ove the call to ,essage-o3= > and see the res#ltG Co# wo#ld observe that no sooner does the window appear it disappearsG Th#s a call to ,essage-o3= > serves the si*ilar p#rpose as getch= > does in seH#ential progra**ingG

,ore /indo0s
)ow that we 9now how to create a window let #s create several windows on the screenG The progra* to do this is given belowG
Lin'%,(e ;Fin(!Fs.h< int _st('a%% SinPain 1 UIE78AE+E hInstan'e" UIE78AE+E h?re=Instan'e" O?78> % s:+m(Oine" int n+m(7h!F 2 3 USE0 h^10` # int x # $!r 1 x = 0 # x ;= 9 # x++ 2 3

Chapter /;0 Aindows #rogramming


h^x` = +reateSin(!F 1 4DX88QE4" 4?ress Pe4" S7_Q]E>OA??E0SIE0QS" x * 20" x * 20" 150" 100" 0" 0" i" 0 2 # 7h!FSin(!F 1 h^x`" % 2 # 6 Pessa-eD!x 1 0" 4UiT4" 4Saitin-4" 0 2 # ret,rn 0 # 6

5"7

+ig#re '!G)ote that each window created in this progra* is assigned a di erent handleG Co# *ay e/peri*ent a bit by changing the na*e o the window class to .0$T and see the res#ltG

' $eal@/orld /indo0


S#ppose we wish to create a window and draw a ew shapes in itG +or creating s#ch a window there is no standard window class availableG 2ence we wo#ld have to create o#r own window class, register it with Windows 3S and then create a window on the basis o itG $nstead o straightway Q#*ping to a progra* that draws

5"&

%et .s C

shapes in a window let #s irst write a progra* that creates a window #sing o#r window class and lets #s interact with itG 2ere is the progra*:
Lin'%,(e ;Fin(!Fs.h< Lin'%,(e 4he% er.h4 =!i( Qn0estr!/ 1 USE0 2 # int 3 P7J m # )* er$!rm a %i'ati!n initia%i:ati!n *) InitInstan'e 1 hInstan'e" n+m(7h!F" 4tit%e4 2 # )* messa-e %!! *) Fhi%e 1 JetPessa-e 1 Bm" 0" 0" 0 2 2 0is at'hPessa-e 1 Bm 2 # ret,rn 0 # 6 O>E7XO8 +AOODA+_ Sn(?r!' 1 USE0 hSn(" XIE8 messa-e" S?A>AP F?aram" O?A>AP %?aram 2 3 sFit'h 1 messa-e 2 3 'ase SP_0E78>QG : Qn0estr!/ 1 hSn( 2 # &rea. # (e$a,%t : ret,rn 0e$Sin(!F?r!' 1 hSn(" messa-e" F?aram" %?aram 2 # 6 ret,rn 0 # 6 st('a%% SinPain 1 UIE78AE+E hInstan'e" UIE78AE+E h?re=Instan'e" O?78> % s:+m(%ine" int n+m(7h!F 2

Chapter /;0 Aindows #rogramming


=!i( Qn0estr!/ 1 USE0 hSn( 2 3 ?!stY,itPessa-e 1 0 2 # 6

5"9

3n e/ec#tion o this progra* the window shown in +ig#re '!G4 appears on the screenG We can #se *ini*i;e and the *a/i*i;e b#tton it its title bar to *ini*i;e and *a/i*i;e the windowG We can stretch its si;e by dragging its bo#ndariesG +inally, we can close the window by clic9ing on the close window b#tton in the title barG

+ig#re '!G4 7et #s now try to #nderstand this progra* step by stepG

Creation and Displa#ing o8 /indo0


Creating and displaying a window on the screen is a 4<step processG These steps areP >a? >b? >c? >d? Creation o a window classG "egistering the window class with the 3SG Creation o a window based on the registered classG 0isplaying the window on the screenG

Creation o a window class involves setting #p o ele*ents o a str#ct#re called /9DCL'SSB\G This str#ct#re contains several

57)

%et .s C

ele*entsG They govern the properties o the windowG "egistration o a window class, creation o a window and displaying o a window involves calling o 1,$ #nctions $egisterClassB3= >, Create/indo0= > and Sho0/indo0= > respectivelyG Since all the 4 steps *entioned above wo#ld be reH#ired in al*ost every progra* in this chapter $ have written this code in a #ser<de ined #nction called *nit*nstance= > in the ile DhelperGh@G Tho#gh writing code in a header ile goes against the convention $ have still done so to achieve si*plicityG The co*plete listing o DhelperGh@ ile is available in 1ppendi/ +G 1lternatively yo# can download it ro* the ollowing lin9P wwwG9icitGco*=boo9s=let#sc=so#rcecode=helperGh 1s e/pected /in,ain= > starts o by calling the #nction *nit*nstance= > present in DhelperGh@ ileG This ile has been Iincluded at the beginning o the progra*G "e*e*ber to copy this ile to yo#r proQect directoryRthe directory in which yo# are going to create this progra*G 3nce the window has been created and displayed let #s see how we can interact with itG

*nteraction 0ith /indo0


1s and when the #ser interacts with the windowRby stretching its bo#ndaries or clic9ing the b#ttons in the title bar, etcG a s#itable *essage is posted into the *essage H#e#e o o#r applicationG 3#r application sho#ld now pic9 the* #p ro* the *essage H#e#e and process the*G 1 *essage contains a *essage id and so*e other additional in or*ation abo#t the *essageG +or e/a*ple, a *o#se clic9 *essage wo#ld contain additional in or*ation li9e handle to the window with which the #ser has interacted, the coordinates o

Chapter /;0 Aindows #rogramming

571

*o#se c#rsor and the stat#s o *o#se b#ttonsG Since it is di ic#lt to *e*ori;e the *essage ids they have been s#itably Ide8ined in DwindowsGh@G The *essage id and the additional in or*ation are stored in a str#ct#re called 5SGG $n /in,ain= > this 5SG str#ct#re is retrieved ro* the *essage H#e#e by calling the 1,$ #nction Get,essage= >, The irst para*eter passed to this #nction is the address o the ,SG str#ct#re variableG Get,essage= > wo#ld pic9 the *essage in o ro* the *essage H#e#e and place it in the str#ct#re variable passed to itG 0on@t bother abo#t the other para*eters right nowG 1 ter pic9ing #p the *essage ro* the *essage H#e#e we need to process itG This is done by calling the Dispatch,essage= > 1,$ #nctionG This #nction does several activitiesG These are as ollowsP >a? +ro* the ,SG str#ct#re that we pass to it, Displa#,essage= > e/tracts the handle o the window or which this *essage is *eant orG >b? +ro* the handle it ig#res o#t the window class based on which the window has been createdG >c? +ro* the window class str#ct#re it obtains the address o a #nction called /nd!roc= > >short or window proced#re?G Well $ didn@t tell yo# earlier that in *nit*nstance= > while illing the /9DCL'SSB\ str#ct#re one o the ele*ents has been set #p with the address o a #ser<de ined #nction called /nd!roc= >G >d? 6sing this address it calls the #nction /nd!roc= >G Since several *essages get posted into the *essage H#e#e pic9ing o the *essage and processing it sho#ld be done repeatedlyG 2ence calls to Get,esage= > and Dispatch,essage= > have been *ade in a 0hile loop in /in,ain= >G When Get,essage= > enco#nters a *essage with id /,:T.*T it ret#rns a )G )ow the control co*es o#t o the loop and /in,ain= > co*es to an endG

572
$eacting to ,essages

%et .s C

1s we saw in the previo#s section, or every *essage pic9ed #p ro* the *essage H#e#e the control is trans erred to the /nd!roc= > #nctionG This #nction is shown belowP
O>E7XO8 +AOODA+_ Sn(?r!' 1 USE0 hSn(" XIE8 messa-e" S?A>AP F?aram" O?A>AP %?aram 2

This #nction always receives o#r para*etersG The irst para*eter is the handle to the window or which the *essage has been receivedG The second para*eter is the *essage id, whereas, the third and o#rth para*eters contain additional in or*ation abo#t the *essageG L$BS.LT is a t#pede8 o a long int and represents the ret#rn val#e o this #nctionG C'LL-'C7 is a t#pede8 o stdcallG This t#pede8 has been done in DwindowsGh@G C'LL-'C7 indicates that the /nd!roc #nction has been registered with Windows >thro#gh /9DCL'SSB\ str#ct#re in *nit*nstance= > ? with an intention that Windows wo#ld call this bac9 >thro#gh Dispatch,essage= > #nction?G $n the /nd!roc= > #nction we have chec9ed the *essage id #sing a s0itchG $ the id is /,:DBST$(S then we have called the #nction (nDestro#= >G This *essage is posted to the *essage H#e#e when the #ser clic9s on the DClose Window@ b#tton in the title barG $n (nDestro#= > #nction we have called the 1,$ #nction !ostTuit,essage= >G This #nction posts a /,:T.*T *essage into the *essage H#e#eG 1s we saw earlier, when this *essage is pic9ed #p the *essage loop and /in,ain= > is ter*inatedG +or all *essages other than /,:DBST$(S the control lands in the de8ault cla#se o s0itchG 2ere we have si*ply *ade a call to De8/indo0!roc= > 1,$ #nctionG This #nction does the de a#lt

Chapter /;0 Aindows #rogramming

573

processing o the *essage that we have decided not to tac9leG The de a#lt processing or di erent *essage wo#ld be di erentG +or e/a*ple on do#ble clic9ing the title bar De8/indo0!roc= > *a/i*i;es the windowG 1ct#ally spea9ing when we close the window a /,:CL(SB *essage is posted into the *essage H#e#eG Since we have not handled this *essage the De8/indo0!roc= > #nction gets called to tac9le this *essageG The De8/indo0!roc= > #nction destroys the window and places a /,:DBST$(S *essage in the *essage H#e#eG 1s disc#ssed earlier, in /nd!roc= > we have *ade the provision to ter*inate the application on enco#ntering /,:DBST$(SG That brings #s to the end o a lonnngggg e/planation4 Co# can now heave a sigh o relie G $ wo#ld #rge yo# to go thro#gh the above e/planation till the ti*e yo# are absol#tely s#re that yo# have #nderstood every detail o itG 1 very clear #nderstanding o it wo#ld help yo# *a9e a good Windows progra**erG +or yo#r convenience $ have given a lowchart o the entire wor9ing in +ig#re '!G5G

574
ST1"T ./ec#tion Call $nit$nstance> ? +ill W)0C71SS.A str#ct#re to de ine window class

%et .s C

Call "egisterCall./> ? to register the window class with 3S Call CreateWindow> ? to create window in *e*ory Call ShowWindow> ? to display window on screen

,ic9 *essage ro* *essage H#e#e F Get5essage> ? $s the *essage W5Bd6$T )o ,rocess the *essage F 0ispatch5essage> ? Call Window ,roced#re

Ces

ST3,

$s the *essage W5B0.ST"3C

Ces

,ost W5Bd6$T F ,ostd#it5essage> ?

)o 0o de a#lt processing o *essage F 0e Window,roc> ?

+ig#re '!G5

Chapter /;0 Aindows #rogramming

575

!rogra1 *nstances
Windows allows yo# to r#n *ore than one copy o a progra* at a ti*eG This is handy or c#tting and pasting between two copies o )otepad or when r#nning *ore than one ter*inal session with a ter*inal e*#lator progra*G .ach r#nning copy o a progra* is called a Dprogra* instance@G Windows per or*s an interesting *e*ory opti*i;ation tric9G $t shares a single copy o the progra*@s code between all r#nning instancesG +or e/a*ple, i yo# get three instances o )otepad r#nning, there will only be one copy o )otepad@s code in *e*oryG 1ll three instances share the sa*e code, b#t will have separate *e*ory areas to hold the te/t data being editedG The di erence between handling o the code and the data is logical, as each instance o )otepad *ight edit a di erent ile, so the data *#st be #niH#e to each instanceG The progra* logic to edit the iles is the sa*e or every instance, so there is no reason why a single copy o )otepad@s code cannot be sharedG

Su11ar#
>a? 1 *essage bo/ can be displayed by calling the ,essage-o3= > 1,$ #nctionG >b? 5essage bo/es are o ten #sed to ascertain the low o a progra*G >c? 1ppearance o a *essage bo/ can be c#sto*i;edG >d? The Create/indo0= > 1,$ #nction creates the window in *e*oryG >e? The window that is created in *e*ory is displayed #sing the Sho0/indo0= > 1,$ 8#nctionG > ? 1 Dwindow class@ speci ies vario#s properties o the window that we are creatingG >g? The header ile DWindowsGh@ contains declaration o several *acros #sed in Windows progra**ingG

57"

%et .s C

>h? When the #ser clic9s in a window, or *oves *o#se pointer on the window, *essages are generated and posted in the application *essage H#e#eG >i? 1 *essage contains the *essage id and additional in or*ation abo#t the *essageG >Q? The Get,essage= ><Dispatch,essage= > loop brea9s when Get,essage= > enco#nters the /,:T.*T *essageG >9? $ we don@t handle a *essage received by o#r application then the De8/indo0!roc= > #nction is called to do the de a#lt processingG

B3ercise
K'L State Tr#e or +alseP

>a? ,essage-o3= > is an 1,$ #nctionG >b? Calling the ,essage-o3= > #nction displays the speci ied string in console windowG >c? The Create/indo0= > #nction creates and displays the window on the screenG >d? The Sho0/indo0= > #nction can display only the *a/i*i;ed windowG >e? .very window has to be created #sing pre<registered window classG > ? Window classes are si*ilar to classes in CLLG >g? We can #se the pre<de ined window classes b#t cannot create o#r ownG >h? The style WSB3V."71,,.0 Y WSBC1,T$3) Y WSB5$)$5$E.83A will create a window with caption bar and *ini*i;e bo/ onlyG >i? To be able to interact with a window it is necessary to i*ple*ent the *essage loopG
K-L 1nswer the ollowingP

>a? 3#tline the steps that a typical Windows progra* ollows d#ring e/ec#tionG

Chapter /;0 Aindows #rogramming

577

>b? "#n any Windows based progra* and see whether yo# can identi y all the ele*ents o the application windowG >c? 2ow wo#ld yo# *ini*i;e a window progra**aticallyc >d? What wo#ld happen i we do not place W5Bd6$T *essage in the *essage H#e#e when the #ser tries to close the windowG >e? ./plain the need o $egisterClassB3= > #nctionG > ? What is the di erence between Get,essage= > and Dispatch,essage= > #nctionc >g? Write a progra*, which receives an integer as a co**and line arg#*ent, creates a b#tton window, and based on the val#e o the integer displays b#tton window as *a/i*i;ed = *ini*i;ed = nor*alG >h? Try to display a window with di erent co*binations o window styles and observer the res#ltsG

57&

%et .s C

1# Graphics -nder
.indo/s
e e e e e e e e e e e Graphics as o )ow 0evice $ndependent 0rawing 2ello Windows 0rawing Shapes Types o ,ens Types o 8r#shes Code and "eso#rces +reehand 0rawing, the ,aintbr#sh Style Capt#ring the *o#se 0evice Conte/t, 1 Closer 7oo9 0isplaying a 8it*ap 1ni*ation at Wor9 W5BC".1T. and OnCreate( ) W5BT$5." and OnTimer( ) 1 +ew 5ore ,oints: Windows, the .ndless World: S#**ary ./ercise

e e e

579

5&)

%et .s C

ince ti*es i**e*orial colors and shapes have ascinated *an9ind li9e nothing elseG 3therwise people wo#ld have still been #sing the character oriented inter aces o 5S<03S or 6ni/G $n act the graphical ability o Windows has played a very i*portant role in its s#ccess storyG 3nce yo# get a hang o how to draw inside a window it wo#ld open #p i**ense possibilities that yo# never tho#ght were possibleG

Graphics as o8 9o0
World has progressed *#ch beyond '6 colors and 64( / 4%( resol#tion graphics that T#rbo C=CLL co*pilers o ered #nder 5S<03S environ*entG Today we are living in a world o '(24 / !6% resol#tion o ering '6G! *illion colorsG Graphical *en#s, icons, colored c#rsors, bit*aps, wave iles and ani*ations are the order o the dayG So *#ch so that a '6<color graphics progra* b#ilt #sing T#rbo C wor9ing on a poor resol#tion al*ost h#rts the eyeG 5oreover, with the whole lot o Windows 1,$ #nctions to s#pport graphics activity there is so *#ch that can be achieved in a graphics progra* #nder WindowsG $ a* s#re that this chapter will help yo# #nderstand and appreciate these new capabilitiesG

De%ice *ndependent Dra0ing


Windows allow progra**ers to write progra*s to display te/t or graphics on the screen witho#t concern over the speci ics o the video hardwareG 1 Windows progra* that wor9s on a VG1 display will wor9 witho#t *odi ication on an SVG1 or on a AG1 display that Windows s#pportsG The 9ey to this Ddevice independence@ is Windows@ #se o a Ddevice conte/t@G We will e/plore how the device conte/t can be #sed or both te/t and graphics o#tp#t, and how #sing the device conte/t 9eeps o#r progra*s ro* inter ering with each other on the screenG

Chapter /<0 -raphics .nder Aindows

5&1

0#ring the original design o Windows, one o the goals was to provide Ddevice independence@G 0evice independence *eans that the sa*e progra* sho#ld be able to wor9 #sing di erent screens, 9eyboards and printers witho#t *odi ication to the progra*G Windows ta9es care o the hardware, allowing the progra**er to concentrate on the progra* itsel G $ yo# have ever had to #pdate the code o an 5S<03S progra* or the latest printer, plotter, video display, or 9eyboard, yo# will recogni;e device independence as a h#ge advantage or the developerG Windows progra*s do not send data directly to the screen or printerG 1 Windows progra* 9nows where >screen=printer? its o#tp#t is being sentG 2owever, it does not 9now how it wo#ld be sent there, neither does it need to bother to 9now thisG This is beca#se Windows #ses a standard and consistent way to send the o#tp#t to screen=printerG This standard way #ses an entity called 0evice Conte/t, or si*ply a 0CG 0i erent 0C@s are associated with di erent devicesG +or e/a*ple, a screen 0C is associated with a screen, a printer 0C is associated with a printer, etcG 1ny drawing that we do #sing the screen 0C is directed to the screenG Si*ilarly, any drawing done #sing the printer 0C is directed to the printerG Th#s, the only thing that changes ro* drawing to screen and drawing to printer is the 0C that is #sedG 1 windows progra* obtains a handle >$0 val#e? or the screen or printer@s 0CG The o#tp#t data is sent to the screen=printer #sing its 0C, and then Windows and the 0evice 0river or the device ta9es care o sending it to the real hardwareG The advantage o #sing the 0C is that the graphics and te/t co**ands that we send #sing the 0C are always the sa*e, regardless o where the physical o#tp#t is showing #pG The part o Windows that converts the Windows graphics #nction calls to the act#al co**ands sent to the hardware is the G0$, or Graphics 0evice $nter aceG The G0$ is a progra* ile called G0$-2G077 and is stored in the Windows Syste* directoryG The

5&2

%et .s C

Windows environ*ent loads G0$-2G077 into *e*ory when it is needed or graphical o#tp#tG Windows also loads a Ddevice driver@ progra* i the hardware conversions are not part o G0$-2G077G Co**on e/a*ples are VG1GSCS or VG1 video screen and 2,,7CGSCS or the 2, 7aserNet printerG 0rivers are Q#st progra*s that assist the G0$ in converting Windows graphics co**ands to hardware co**andsG Th#s G0$ provides all the basic drawing #nctionality or Windows_ the device conte/t represents the device providing a layer o abstraction that ins#lates yo#r applications ro* the tro#ble o drawing directly to the hardwareG The G0$ provides this ins#lation by calling the appropriate device driver in response to windows graphics #nction callsG

2ello /indo0s
We wo#ld begin o#r tryst with graphics progra**ing #nder windows by displaying a *essage K2ello WindowsO in di erent ontsG )ote that tho#gh we are displaying te/t #nder Windows even te/t gets drawn graphically in the windowG +irst ta9e a loo9 at the progra* given below be ore we set o#t to #nderstand itG
L in'%,(e ;Fin(!Fs.h< L in'%,(e 4he% er.h4 =!i( Qn?aint 1 USE0 2 # =!i( Qn0estr!/ 1 USE0 2 # int st('a%% SinPain 1 UIE78AE+E hInstan'e" UIE78AE+E h?re=Instan'e" O?78> % s:+m(%ine" int n+m(7h!F 2 3 P7J m # )* ?er$!rm a %i'ati!n initia%i:ati!n *) InitInstan'e 1 hInstan'e" n+m(7h!F" 48ext4 2 #

Chapter /<0 -raphics .nder Aindows


)* Pain messa-e %!! *) Fhi%e 1 JetPessa-e 1 Bm" EXOO" 0" 0 2 2 0is at'hPessa-e1Bm2# ret,rn 0 # 6

5&3

O>E7XO8 +AOODA+_ Sn(?r!' 1 USE0 hSn(" XIE8 messa-e" S?A>AP F?aram" O?A>AP %?aram 2 3 sFit'h 1 messa-e 2 3 'ase SP_0E78>QG : Qn0estr!/ 1 hSn( 2 # &rea. # 'ase SP_?AIE8 : Qn?aint 1 hSn( 2 # &rea. # (e$a,%t : ret,rn 0e$Sin(!F?r!' 1 hSn(" messa-e" F?aram" %?aram 2 # 6 ret,rn 0 # 6 =!i( Qn0estr!/ 1 USE0 hSn( 2 3 ?!stY,itPessa-e 1 0 2 # 6 =!i( Qn?aint 1 USE0 hSn( 2 3 U0+ h(' # ?AIE878>X+8 s # UIQE8 h$!nt # OQJIQE8 $ = 3 0 6 # UJ0IQDC h!%($!nt # 'har *$!nts^ ` = 3 4Aria%4" 48imes EeF >!man4" 4+!mi' 7ans P74 6 # int i #

5&4
h(' = De-in?aint 1 hSn(" B s 2 # $!r 1 i = 0 # i ; 3 # i++ 2 3 str' / 1 $.%$Ia'eEame" $!nts^ i ` 2 # )* '! / $!nt name *) $.%$Uei-ht = 40 * 1 i + 1 2 # )* $!nt hei-ht *) $.%$Ita%i' = 1 # )* ita%i' *) h$!nt = +reateI!ntIn(ire't 1 B$ 2 # h!%($!nt = 7e%e'tQ&9e't 1 h('" h$!nt 2 # 7et8ext+!%!r 1 h('" >JD 1 0" 0" 255 2 2 # 8extQ,t 1 h('" 10" 70 * i" 4Ue%%! Sin(!Fs4" 13 2 # 7e%e'tQ&9e't 1 h('" h!%($!nt 2 # 0e%eteQ&9e't 1 h$!nt 2 # 6 En(?aint 1 hSn(" B s 2 # 6

%et .s C

3n e/ec#tion o this progra* the window shown in +ig#re '%G' appearsG

+ig#re '%G'

Chapter /<0 -raphics .nder Aindows

5&5

0rawing to a window involves handling the /,:!'*9T *essageG This *essage is generated whenever the client area o the window needs to be redrawnG This redrawing wo#ld be reH#ired in the ollowing sit#ationsP >a? When the Window is displayed or the irst ti*eG >b? When the window is *ini*i;ed and then *a/i*i;edG >c? When so*e portion o the window is overlapped by another window and the overlapped window is dis*issedG >d? When the si;e o the window changes on stretching its bo#ndariesG >e? When the window is dragged o#t o the screen and then bro#ght bac9 into the screenG Wo#ld a /,:!'*9T *essage be generated when the c#rsor is dragged in the windowc )oG $n this case the window saves the area overlapped by the c#rsor and restores it when the c#rsor *oves to another positionG When the s0itch@case str#ct#re inside /nd!roc= > inds that the *essage $0 passed to /nd!roc= > is /,:!'*9T, it calls the #nction (n!aint= >G Within (n!aint= > we have called the 1,$ #nction -egin!aint= >G This #nction obtains a handle to the device conte/tG 1dditionally it also ills the ,1$)TST"6CT str#ct#re with in or*ation abo#t the area o the window which needs to be repaintedG 7astly it re*oves /,:!'*9T ro* the *essage H#e#eG 1 ter obtaining the device conte/t handle, the control enters a loopG $nside the loop we have displayed K2ello WindowsO in three di erent ontsG .ach ti*e thro#gh the loop we have set#p a L(GF(9T str#ct#re 8G This str#ct#re is #sed to indicate the ont properties li9e ont na*e, ont height, italic or nor*al, etcG )ote that in addition to these there are other ont properties that *ay be set#pG The properties that we have not set#p in the loop are all initiali;ed to )G 3nce the ont properties have been set#p we have called the CreateFont*ndirect= > 1,$ #nction to create the ontG

5&"

%et .s C

This #nction loads the relevant ont ileG Then #sing the in or*ation in the ont ile and the ont properties set#p in the L(GF(9T str#ct#re it creates a ont in *e*oryG CreateFont*ndirect= > ret#rns the handle to the ont created in *e*oryG This handle is then passed to the Select(6Wect= > 1,$ #nction to get the ont into the 0CG This #nction ret#rns the handle to the e/isting ont in the 0C, which is preserved in hold8ont variableG )e/t we have #sed the SetTe3tColor= > 1,$ #nction to set the color o the te/t to be displayed thro#gh Te3t(ut= >G The $G-= > *acro #ses the red, green and bl#e co*ponent val#es to generate a -2<bit color val#eG )ote that each color co*ponent can ta9e a val#e ro* ) to 255G To Te3t(ut= > we have to pass the handle to the 0C, position where the te/t is to be displayed, the te/t to be displayed and its lengthG With h8ont only one ont can be associated at a ti*eG 2ence be ore associating another ont with it we have deleted the e/isting ont #sing the Delete(6Wect= > 1,$ #nctionG 3nce o#tside the loop we have called the Bnd!aint= > 1,$ #nction to release the 0C handleG $ not released we wo#ld be wasting precio#s *e*ory, beca#se the device conte/t str#ct#re wo#ld re*ain in *e*ory b#t we wo#ld not be able access itG $n place o Te3t(ut= > we can also #se the Dra0Te3t= > 1,$ #nctionG This #nction per*its iner control over the way the te/t is displayedG Co# can e/plore this #nction on yo#r ownG

Dra0ing Shapes
$ te/t is so near can graphics be ar behindc )ow that we 9now how to draw te/t in a window let #s now create a si*ple progra* that displays di erent shapes in a windowG $nstead o showing the entire progra* given below is the listing o (n!aint= >G The rest o the progra* is sa*e as in the previo#s sectionG 2ere onwards $ wo#ld be showing only the (n!aint= > handler #nless otherwise reH#iredG

Chapter /<0 -raphics .nder Aindows

5&7

=!i( Qn?aint 1 USE0 hSn( 2 3 U0+ h(' # ?AIE878>X+8 s # UD>X7U h&r # UJ0IQDC h!%(&r # ?QIE8 t^5` = 3 250" 150" 250" 300" 300" 350" 400" 300" 320" 190 6 # h(' = De-in?aint 1 hSn(" B s 2 # h&r = +reate7!%i(Dr,sh 1 >JD 1 255" 0" 0 2 2 # h!%(&r = 7e%e'tQ&9e't 1 h('" h&r 2 # P!=e8!Ex 1 h('" 10" 10" EXOO 2 # Oine8! 1 h('" 200" 10 2 # >e'tan-%e 1 h('" 10" 20" 200" 100 2 # >!,n(>e't 1 h('" 10" 120" 200" 220" 20" 20 2 # E%%i se 1 h('" 10" 240" 200" 340 2 # ?ie 1 h('" 250" 10" 350" 110" 350" 110" 350" 10 2 # ?!%/-!n 1 h('" t" 5 2 # 7e%e'tQ&9e't 1 h('" h!%(&r 2 # 0e%eteQ&9e't 1 h&r 2 # En(?aint 1 hSn(" B s 2 # 6

3n e/ec#tion o this progra* the window shown in +ig#re '%G2 appearsG

5&&

%et .s C

+ig#re '%G2 +or drawing any shape we need a pen to draw its bo#ndary and a br#sh to paint the area enclosed by itG The 0C contains a de a#lt pen and br#shG The de a#lt pen is a solid pen o blac9 color and the de a#lt br#sh is white in colorG $n this progra* we have #sed the de a#lt pen and a bl#e colored solid br#sh or drawing the shapesG 1s be ore, we begin by obtaining a handle to the 0C #sing -egin!aint= > #nctionG +or creating a solid colored br#sh we need to call the CreateSolid-rush= > 1,$ #nctionG The second para*eter o this #nction speci ies the color o the br#shG The #nction ret#rns the handle o the br#sh which we have preserved

Chapter /<0 -raphics .nder Aindows

5&9

in the h6r variableG )e/t we have selected this br#sh in the 0CG The handle o the de a#lt br#sh in 0C is collected in the hold6r variableG 3nce we have selected the br#sh into the 0C we are ready to draw the shapesG +or drawing the line we have #sed ,o%eToB3= > and LineTo= > 1,$ #nctionsG Si*ilarly or drawing a rectangle we have #sed the $ectangle= > #nctionG The $ound$ect= > #nction draws a rectangle with ro#nded cornersG $n $ound$ect = 314 #14 324 #24 334 #3 >4 314 #1 represents the " and y<coordinates o the #pper<le t corner o the rectangleG 7i9ewise, 32, #2 represent coordinates o the botto* right corner o the rectangleG 33, #3 speci y the width and height o the ellipse #sed to draw the ro#nded cornersG )ote that rectangle and the ro#nded rectangle are drawn ro* 314 #1 #p to 32@1, #2@1, ,ara*eters o Bllipse= > speci y coordinates o bo#nding rectangle o the ellipseG The !ie= > #nction draws a pie<shaped wedge by drawing an elliptical arc whose center and two endpoints are Qoined by linesG The center o the arc is the center o the bo#nding rectangle speci ied by 314 #1 and 324 #2, $n !ie= 314 #14 324 #24 334 #34 344 #4 >4 314 #1 and 324 #2 speci y the " and y<coordinates o the #pper le t corner and botto* right corner respectively, o the bo#nding rectangleG 334 #3 and 344 #4 speci y the " and y<coordinates o the arc@s starting point and ending point respectivelyG $n !ol#gon = lp!oints4 nCount >B lp!oints points to an array o points that speci ies the vertices o the polygonG .ach point in the array is a !(*9T str#ct#reG nCount speci ies the n#*ber o vertices stored in the arrayG The syste* closes the polygon a#to*atically, i necessary, by drawing a line ro* the last verte/ to the irstG

59)

%et .s C

3nce we are thro#gh with drawing the shapes the old br#sh is selected bac9 in the 0C and then the br#sh created by #s is deleted #sing Delete(6Wect= > #nctionG

T#pes o8 !ens
$n the previo#s progra* we have #sed the de a#lt solid blac9 pen o thic9ness ' pi/elG We can create pens o di erent style, color and thic9ness to do o#r drawingG The ollowing (n!aint= > handler shows how this can be achievedG
=!i( Qn?aint 1 USE0 hSn( 2 3 U0+ h(' # ?AIE878>X+8 s # U?EE h en # UJ0IQDC h!%( en # h(' = De-in?aint 1 hSn(" B s 2 # h en = +reate?en 1 ?7_0A7U" 1" >JD 1 255" 0" 0 2 2 # h!%( en = 7e%e'tQ&9e't 1 h('" h en 2 # P!=e8!Ex 1 h('" 10" 10" EXOO 2 # Oine8! 1 h('" 500" 10 2 # 7e%e'tQ&9e't 1 h('" h!%( en 2 # 0e%eteQ&9e't 1 h en 2 # h en = +reate?en 1 ?7_0Q8" 1" >JD 1 255" 0" 0 2 2 # h!%( en = 7e%e'tQ&9e't 1 h('" h en 2 # P!=e8!Ex 1 h('" 10" 60" EXOO 2 # Oine8! 1 h('" 500" 60 2 # 7e%e'tQ&9e't 1 h('" h!%( en 2 # 0e%eteQ&9e't 1 h en 2 #

Chapter /<0 -raphics .nder Aindows


h en = +reate?en 1 ?7_0A7U0Q8" 1" >JD 1 255" 0" 0 2 2 # h!%( en = 7e%e'tQ&9e't 1 h('" h en 2 # P!=e8!Ex 1 h('" 10" 110" EXOO 2 # Oine8! 1 h('" 500" 110 2 # 7e%e'tQ&9e't 1 h('" h!%( en 2 # 0e%eteQ&9e't 1 h en 2 # h en = +reate?en 1 ?7_0A7U0Q80Q8" 1" >JD 1 255" 0" 0 2 2 # h!%( en = 7e%e'tQ&9e't 1 h('" h en 2 # P!=e8!Ex 1 h('" 10" 160" EXOO 2 # Oine8! 1 h('" 500" 160 2 # 7e%e'tQ&9e't 1 h('" h!%( en 2 # 0e%eteQ&9e't 1 h en 2 # h en = +reate?en 1 ?7_7QOI0" 10" >JD 1 255" 0" 0 2 2 # h!%( en = 7e%e'tQ&9e't 1 h('" h en 2 # P!=e8!Ex 1 h('" 10" 210" EXOO 2 # Oine8! 1 h('" 500" 210 2 # 7e%e'tQ&9e't 1 h('" h!%( en 2 # 0e%eteQ&9e't 1 h en 2 # En(?aint 1 hSn(" B s 2 # 6

591

3n e/ec#tion o this progra* the window shown in +ig#re '%GappearsG

592

%et .s C

+ig#re '%G1 new pen can be created #sing the Create!en= > 1,$ #nctionG This #nction needs three para*etersRpen style, pen thic9ness and pen colorG 0i erent *acros li9e ,SBS37$0, ,SB03T, etcG have been de ined in DwindowsGh@ to represent di erent pen stylesG )ote that or pen styles other than ,SBS37$0 the pen thic9ness has to be ' pi/elG

T#pes o8 -rushes
The way we can create di erent types o pens, we can also create three di erent types o br#shesG These areRsolid br#sh, hatch br#sh and pattern br#shG 7et #s now write a progra* that shows how to b#ild these br#shes and then #se the* to ill rectanglesG 2ere is the (n!aint= > handler which achieves thisG
=!i( Qn?aint 1 USE0 hSn( 2 3 U0+ h(' # ?AIE878>X+8 s # UD>X7U h&r #

Chapter /<0 -raphics .nder Aindows


UJ0IQDC h!%(&r # UDI8PA? h&m # h(' = De-in?aint 1 hSn(" B s 2 # h&r = +reate7!%i(Dr,sh 1 >JD 1255" 0" 0 2 2 # h!%(&r = 7e%e'tQ&9e't 1 h('" h&r 2 # >e'tan-%e 1 h('" 5" 5" 105" 100 2 # 7e%e'tQ&9e't 1 h('" h!%(&r 2 # 0e%eteQ&9e't 1 h&r 2 # h&r = +reateUat'hDr,sh 1 U7_+>Q77" >JD 1 255" 0" 0 2 2 # h!%(&r = 7e%e'tQ&9e't 1 h('" h&r 2 # >e'tan-%e 1 h('" 125" 5" 225" 100 2 # 7e%e'tQ&9e't 1 h('" h!%(&r 2 # 0e%eteQ&9e't 1 h&r 2 #

593

h&m = O!a(Ditma 1 hInst" PA_EIE8>E7QX>+E 1 I0D_DI8PA?1 2 2 # h&r = +reate?atternDr,sh 1 h&m 2 # h!%(&r = 7e%e'tQ&9e't 1 h('" h&r 2 # >e'tan-%e 1 h('" 245" 5" 345" 100 2 # 7e%e'tQ&9e't 1 h('" h!%(&r 2 # 0e%eteQ&9e't 1 h&r 2 # 0e%eteQ&9e't 1 h&m 2 # En(?aint 1 hSn(" B s 2 # 6 0e%eteQ&9e't 1 h&r 2 #

594

%et .s C

3n e/ec#tion o this progra* the window shown in +ig#re '%G4 appearsG

+ig#re '%G4 $n the (n!aint= > handler we have drawn three rectanglesR irst #sing a solid br#sh, second #sing a hatched br#sh and third #sing a pattern br#shG Creating and #sing a solid br#sh and hatched br#sh is si*pleG We si*ply have to *a9e calls to CreateSolid-rush= > and Create2atch-rush= > respectivelyG +or the hatch br#sh we have #sed the style 2SBC"3SSG There are several other styles de ined in DwindowsGh@ that yo# can e/peri*ent withG +or creating a pattern br#sh we need to irst create a bit*ap >pattern?G $nstead o creating this pattern, we have #sed a ready*ade bit*ap ileG Co# can #se any other bit*ap ile present on yo#r hard dis9G 8it*aps, *en#s, icons, c#rsors that a Windows progra* *ay #se are its reso#rcesG When the co*pile s#ch a progra* we #s#ally want these reso#rces to beco*e a part o o#r .A. ileG $ so done we do not have to ship these reso#rces separatelyG To be able to #se a reso#rce >bit*ap ile in o#r case? it is not eno#gh to Q#st copy it in the proQect directoryG $nstead we need to carry o#t the steps *entioned below to add a bit*ap ile to the proQectG >a? +ro* the D$nsert@ *en# option o VCLL 6G( select the D"eso#rce@ optionG

Chapter /<0 -raphics .nder Aindows

595

>b? +ro* the dialog that pops #p select Dbit*ap@ ollowed by the i*port b#ttonG >c? Select the s#itable Gb*p ileG >d? +ro* the D+ile@ *en# select the save option to save the generated reso#rce script ile >Script'Grc?G When we select DSave@ one *ore ile called Dreso#rceGh@ also gets createdG >e? 1dd the DScript'Grc@ ile to the proQect #sing the ,roQect Y 1dd to ,roQect Y +iles optionG While #sing the bit*ap in the progra* it is always re erred #sing an idG The id is Ide8ined in the ile Dreso#rceGh@G So*ewhere in or*ation has to be stored lin9ing the id with the act#al Gb*p ile on the dis9G This is done in the DScript'Grc@ ileG We need to incl#de the Dreso#rceGh@ ile in the progra*G To create the pattern br#sh we irst need to load the bit*ap in *e*oryG We have done this #sing the Load-it1ap= > 1,$ #nctionG The irst para*eter passed to this #nction is the handle to the instance o the progra*G When *nit*nstance= > #nction is called ro* /in,ain= > it stores the instance handle in a global variable h*nstG We have passed this h*nst to Load-it1ap= >G The second para*eter passed to it is a string representing the bit*apG This string is created ro* the reso#rce id #sing the ,'7B*9T$BS(.$CB *acroG The Load-it1ap= > #nction ret#rns the handle to the bit*apG This handle is then passed to the Create!attern-rush= > #nctionG This br#sh is then selected into the 0C and then a rectangle is drawn #sing itG )ote that i the si;e o the bit*ap is bigger than the rectangle being drawn then the bit*ap is s#itably clippedG 3n the other hand i the bit*ap is s*aller than the rectangle it is s#itably replicatedG While doing the clean #p irstly the br#sh is deleted ollowed by the bit*apG

59"
Code and $esources

%et .s C

1 progra* consists o both instr#ctions and static dataG Static data is that portion o the progra* which is not e/ec#ted as *achine instr#ctions and which does not change as the progra* e/ec#tesG Static data are character strings, data to create onts, bit*aps, etcG The designers o Windows wisely decided that static data sho#ld be handled separately ro* the progra* codeG The Windows ter* or static data is D"eso#rce data@, or si*ply D"eso#rces@G 8y separating static data ro* the progra* code the creators o Windows were able to #se a standard C=CLL co*piler to create the code portion o the inished Windows progra*, and they only had to write a D"eso#rce co*piler@ to create the reso#rces that Windows progra*s #seG Separating the code ro* the reso#rce data has other advantages li9e red#cing *e*ory de*ands and *a9ing progra*s *ore portableG $t also *eans that a progra**er can wor9 on a progra*@s logic, while a designer wor9s on how the progra* loo9sG

Freehand Dra0ing4 the !aint6rush St#le


.ven i yo# are 9nee high in co*p#ters $ a* s#re yo# *#st have #sed ,aint8r#shG $t provides a acility to draw a reehand drawing #sing *o#seG 7et #s see i we too can achieve thisG We can indicate where the reehand drawing begins by clic9ing the le t *o#se b#ttonG Then as we *ove the *o#se on the table with the le t *o#se b#tton depressed the reehand drawing sho#ld get drawn in the windowG This drawing sho#ld contin#e till we do not release the le t *o#se b#ttonG The *o#se inp#t co*es in the or* o *essagesG +or ree hand drawing we need to tac9le three *o#se *essagesR /,:L-.TT(9D(/9 or le t b#tton clic9, /,:,(.SB,(5B or *o#se *ove*ent and /,:L-.TT(9.! or releasing the le t *o#se b#ttonG 7et #s now see how these *essages are tac9led or drawing reehandG The

Chapter /<0 -raphics .nder Aindows

597

/nd!roc= > #nction and the *essage handlers that per or* this tas9 are given below
int x1" /1" x2" /2 # O>E7XO8 +AOODA+_ Sn(?r!' 1 USE0 hSn(" XIE8 messa-e" S?A>AP F?aram" O?A>AP %?aram 2 3 sFit'h 1 messa-e 2 3 'ase SP_0E78>QG : Qn0estr!/ 1 hSn( 2 # &rea. # 'ase SP_ODX88QE0QSE : QnOD,tt!n0!Fn 1 hSn(" OQSQ>0 1 %?aram 2" UISQ>0 1 %?aram 2 2 # &rea. # 'ase SP_ODX88QEX? : QnOD,tt!nX 1 2 # &rea. # 'ase SP_PQX7EPQ]E : QnP!,seP!=e 1 hSn(" F?aram" OQSQ>0 1 %?aram 2" UISQ>0 1 %?aram 2 2 # &rea. # (e$a,%t: ret,rn 0e$Sin(!F?r!' 1 hSn(" messa-e" F?aram" %?aram 2 # 6 ret,rn 0 # 6 =!i( QnOD,tt!n0!Fn 1 USE0 hSn(" int x" int / 2 3 7et+a t,re 1 hSn( 2 # x1 = x #

59&
/1 = / # 6

%et .s C

=!i( QnP!,seP!=e 1 USE0 hSn(" int $%a-s" int x" int / 2 3 U0+ h(' # i$ 1 $%a-s == P__ODX88QE 2 )* is %e$t m!,se &,tt!n (e resse( *) 3 h(' = Jet0+ 1 hSn( 2 # x2 = x # /2 = / # P!=e8!Ex 1 h('" x1" /1" EXOO 2 # Oine8! 1 h('" x2" /2 2 # >e%ease0+ 1 hSn(" h(' 2 # x1 = x2 # /1 = /2 # 6 6 =!i( QnOD,tt!nX 1 2 3 >e%ease+a t,re1 2 # 6

3n e/ec#tion o this progra* the window shown in +ig#re '%G5 appearsG We can now clic9 the le t *o#se b#tton with *o#se pointer placed anywhere in the windowG We can then drag the *o#se on the table to draw the reehandG The reehand drawing wo#ld contin#e till we do not release the le t *o#se b#ttonG

Chapter /<0 -raphics .nder Aindows

599

+ig#re '%G5 $t appears that or drawing the reehand we sho#ld si*ply receive the *o#se coordinates as it is *oved and then highlight the pi/els at these coordinates #sing the Set!i3el= > 1,$ #nctionG 2owever, i we do so the reehand wo#ld be bro9en at several placesG This is beca#se #s#ally the *o#se is dragged pretty ast whereas the *o#se *ove *essages won@t arrive so astG 1 sol#tion to this proble* is to constr#ct the reehand #sing s*all little line seg*entsG This is what has been done in o#r progra*G These lines are so s*all is si;e that yo# wo#ld not even recogni;e that the reehand has been drawn by connecting these s*all linesG

"))

%et .s C

7et #s now disc#ss each *o#se handlerG When the /,:L-.TT(9D(/9 *essage arrives the /nd!roc= > #nction calls the handler (nL-uttonDo0n= >G While doing so, we have passed the *o#se coordinates where the clic9 occ#rredG These coordinates are obtained in l!ara1 in /nd!roc= >G $n l!ara1 the low order '6 bits contain the c#rrent / < coordinate o the *o#se whereas the high order '6 bits contain the y < coordinateG The L(/($D and 2*/($D *acros have been #sed to separate o#t these / and y < coordinates ro* l!ara1G $n (nL-uttonDo0n= > we have preserved the starting point o reehand in global variables 31 and #1G When (n,ouse,o%e= > gets called it chec9s whether the le t *o#se b#tton stands depressedG $ it stands depressed then the 8lags variable contains ,7:L-.TT(9G $ it does, then the c#rrent *o#se coordinates are set #p in the global variables 32, #2G 1 line is then drawn between 31, #1 and 32, #2 #sing the #nctions ,o%eToB3= > and LineTo= >G )e/t ti*e aro#nd 32, #2 sho#ld beco*e the starting o the ne/t lineG 2ence the c#rrent val#es o 32, #2 are stored in 31, #1G )ote that here we have obtained the 0C handle #sing the 1,$ #nction GetDC= >G This is beca#se we are carrying o#t the drawing activity in reaction to a *essage other than /,:!'*9TG 1lso, the handle obtained #sing GetDC= > sho#ld be released #sing a call to $eleaseDC= > #nctionG Co# can try #sing -egin!aint= > = Bnd!aint= > in *o#se handlers and GetDC= > = $eleaseDC= > in (n!aint= >G Can yo# draw any concl#sionsc

Capturing the ,ouse


$ in the process o drawing the reehand the *o#se c#rsor goes o#tside the client area then the window below o#r window wo#ld

Chapter /<0 -raphics .nder Aindows

")1

start getting *o#se *essagesG So o#r window wo#ld not receive any *essagesG $ this has to be avoided then we sho#ld ens#re that o#r window contin#es to receive *o#se *essages even when the c#rsor goes o#t o the client area o o#r windowG The process o doing this is 9nown as *o#se capt#ringG We have capt#red the *o#se in (nL-uttonDo0n= > handler by calling the 1,$ #nction SetCapture= >G 1s a res#lt, the progra* contin#es to respond to *o#se events d#ring reehand drawing even i the *o#se is *oved o#tside the client areaG $n the (nL-utton.p= > handler we have released the capt#red *o#se by calling the $eleaseCapture= > 1,$ #nctionG

De%ice Conte3t4 a Closer LooG


)ow that we have written a ew progra*s and are co* ortable with idea o selecting obQects li9e ont, pen and br#sh into the 0C, it is ti*e or #s to #nderstand how Windows achieves the device independent drawing #sing the concept o 0CG $n act a 0C is nothing b#t a str#ct#re that holds handles o vario#s drawing obQects li9e ont, pen, br#sh, etcG 1 screen 0C and its wor9ing is shown in +ig#re '%G6G

")2
1pp' Screen 0C 2,.) 2(( 28"6S2 4(( 28$T51, 6(( 2+3)T !(( . . . 3ther $n o 0rawing 3bQect 1rial 2+3)T X !(( Screen 3=, 0evice

%et .s C

1pp2 Screen 0C 2,.) &(( 28"6S2 '((( 28$T51, 6(( 2+3)T %(( . . . 3ther $n o 0rawing 3bQect "ed ,en &(( 8l#e 8r#sh '(((

8lac9 ,en 2(( 5onoG 8it*ap 6((

White 8r#sh 4(( +ont %((

0e a#lt 0rawing 3bQects

+ig#re '%G6 Co# can *a9e ollowing observations ro* +ig#re '%G6P >a? The 0C doesn@t hold the drawing obQects li9e pen, br#sh, etcG $t *erely holds their handlesG >b? With each 0C a de a#lt *onochro*e bit*ap o si;e ' pi/el / ' pi/el is associatedG >c? 0e a#lt obQects li9e blac9 pen, white br#sh, etcG are shared by di erent 0Cs in sa*e or di erent applicationsG

Chapter /<0 -raphics .nder Aindows

")3

>d? The drawing obQects that an application e/plicitly creates can be shared within 0Cs o the sa*e application, b#t is never >e? shared between di erent applicationsG Two di erent applications wo#ld need two di erent 0Cs > ? even tho#gh both wo#ld be #sed to draw to the sa*e screenG $n other words with one screen *#ltiple 0Cs can e/istG 1 co**on 0evice 0river wo#ld serve the drawing reH#ests co*ing ro* di erent applicationsG >Tr#ly spea9ing the reH#est co*es ro* G0$ #nctions that o#r application calls?G Screen and printer 0C is 3K, b#t what p#rpose wo#ld a *e*ory 0C servec Well, that is what the ne/t progra* wo#ld e/plainG

Displa#ing a -it1ap
We are a*iliar with drawing nor*al shapes on screen #sing a device conte/tG 2ow abo#t drawing i*ages on the screenc Windows does not per*it displaying a bit*ap i*age directly #sing a screen 0CG This is beca#se there *ight be color variations in the screen on which the bit*ap was created and the screen on which it is being displayedG To acco#nt or s#ch possibilities while displaying a bit*ap Windows #ses a di erent *echanis*Ra D5e*ory 0C@ The way anything drawn #sing a screen 0C goes to screen, anything drawn #sing a printer 0C goes to a printer, si*ilarly anything drawn #sing a *e*ory 0C goes to *e*ory >"15?G 8#t where in "15Rin the ' / ' pi/el bit*ap whose handle is present in *e*ory 0CG >)ote that this handle was o little #se $n case o screen=printer 0C?G Th#s i we atte*pt to draw a line #sing a *e*ory 0C it wo#ld end #p on the ' / ' pi/el bit*apG Co# wo#ld agree ' / ' is too s*all a place to draw even a s*all lineG 2ence we need to e/pand the si;e and color capability o this bit*apG 2ow can this be donec Si*ple, Q#st replace the handle o the ' / ' bit*ap with the handle o a bigger and colored bit*ap obQectG This is shown in +ig#re '%G!G

")4
0e a#lt 5e*ory 0C 2,.) 28"6S2 28$T51, 2+3)T 2(( 4(( 4(5 %(( . . . 3ther $n o 8lac9 ,en 2(( 0e a#lt 3=, 0evice 4(5 '/' 5onochro*e bit*ap %((

%et .s C

White 8r#sh 4(( +ont

0e a#lt 0rawing 3bQects

5e*ory 0C a ter selecting bit*ap 8lac9 ,en 2,.) 2(( 28"6S2 4(( 28$T51, 4(((( 2+3)T %(( . . . 3ther $n o 2(( )ew 3=, 0evice White 8r#sh 4(( +ont %(( 4(((( '&(/22( 24 Fcolor bit*ap

+ig#re '%G! What p#rpose wo#ld Q#st increasing the bit*ap si;e=color wo#ld servec Whatever we draw here wo#ld get drawn on the bit*ap b#t wo#ld still not be visibleG We can *a9e it visible by si*ply copying the bit*ap i*age >incl#ding what has been drawn on it? to the screen 0C by #sing the 1,$ #nction -it-lt= >G 8e ore trans erring the i*age to the screen 0C we need to *a9e the *e*ory 0C co*patible with the screen 0CG 2ere *a9ing co*patible *eans *a9ing certain adQ#st*ents in the contents o the *e*ory 0C str#ct#reG 7oo9ing at these val#es the screen device driver wo#ld s#itably adQ#st the colors when the pi/els in

Chapter /<0 -raphics .nder Aindows

")5

the bit*ap o *e*ory 0C is trans erred to screen 0C #sing -it-lt= > #nctionG 7et #s now ta9e a loo9 at the progra* that p#ts all these concepts in actionG The progra* *erely displays the i*age o a v#lt#re in a windowG 2ere is the code:
=!i( Qn?aint 1 USE0 hSn( 2 3 U0+ h(' # UDI8PA? h&m # U0+ hmem(' # UJ0IQDC h!%(&m # ?AIE878>X+8 s # h(' = De-in?aint 1 hSn(" B s 2 # h&m = O!a(Ditma 1 hInst" PA_EIE8>E7QX>+E 1 I0D_DI8PA?1 2 2 # hmem(' = +reate+!m ati&%e0+ 1 h(' 2 # h!%(&m = 7e%e'tQ&9e't 1 hmem('" h&m 2 # DitD%t 1 h('" 10" 20" 190" 220" hmem('" 0" 0" 7>++Q?G 2 # En(?aint 1 hSn(" B s 2 # 7e%e'tQ&9e't 1 hmem('" h!%(&m 2 # 0e%eteQ&9e't 1 h&m 2 # 0e%ete0+ 1 hmem(' 2 # 6

3n e/ec#ting the progra* we get the window shown in +ig#re '%G!G

")"

%et .s C

+ig#re '%G! 1s #s#al we begin o#r drawing activity in (n!aint= > by irst getting the screen 0C #sing the -egin!aint= > #nctionG )e/t we have loaded the v#lt#re bit*ap i*age in *e*ory by calling the Load-it1ap= > #nctionG $ts #sage is si*ilar to what we saw while creating a pattern br#sh in an earlier section o this chapterG Then we have created a *e*ory device conte/t and *ade its properties co*patible with that o the screen 0CG To do this we have called the 1,$ #nction CreateCo1pati6leDC= >G )ote that we have passed the handle to the screen 0C to this #nctionG The #nction in t#rn ret#rns the handle to the *e*ory 0CG 1 ter this we have selected the loaded bit*ap into the *e*ory 0CG 7astly, we have per or*ed a bit bloc9 trans er >a bit by bit copy? ro* *e*ory 0C to screen 0C #sing the #nction -it-lt= >G 1s a res#lt o this the v#lt#re now appears in the windowG We have *ade the call to -it-lt= > as shown belowP
DitD%t 1 h('" 10" 20" 190" 220" hmem('" 0" 0" 7>++Q?G 2 #

Chapter /<0 -raphics .nder Aindows


7et #s now #nderstand its para*etersG These are as #nderP hdc F 2andle to target 0C where the bit*ap is to be blitted '(, 2( F ,osition where the bit*ap is to be blitted '&(, 22( F Width and height o bit*ap being blitted

")7

(, ( F Top le t corner o the so#rce i*ageG $ we give '(, 2( then the i*age ro* '(, 2( to botto* right corner o the bit*ap wo#ld get blittedG S"CC3,C F Speci ies one o the raster<operation codesG These codes de ine how the color data or the so#rce rectangle is to be co*bined with the color data or the destination rectangle to achieve the inal colorG S"CC3,C *eans that the pi/el color o so#rce sho#ld be copied onto the destination pi/el o the targetG

'ni1ation at /orG
Speed is the essence o li eG So having the ability to display a bit*ap in a window is ine, b#t i we can add *ove*ent and so#nd to it then nothing li9e itG So let #s now see how to achieve this ani*ation and so#nd e ectG $ we are to ani*ate an obQect in the window we need to carry o#t the ollowing stepsP >a? Create an i*age that is to be ani*ated as a reso#rceG >b? ,repare the i*age or later displayG >c? "epeatedly display this prepared i*age at s#itable places in the window ta9ing care that when the ne/t i*age is displayed the previo#s i*age is erasedG >d? Chec9 or collisions while displaying the prepared i*ageG 7et #s now write a progra* that on e/ec#tion *a9es a red colored ball *ove in the windowG 1s the ball stri9es the walls o the

")&

%et .s C

window a noise occ#rsG )ote that the width and height o the red< colored ball is 22 pi/elsG Given below is the /nd!roc= > #nction and the vario#s *essage handlers that help achieve ani*ation and so#nd e ectG
UDI8PA? h&m # int x" / # U0+ hmem(' # UJ0IQDC h!%(&m # O>E7XO8 +AOODA+_ Sn(?r!' 1 USE0 hSn(" XIE8 messa-e" S?A>AP F?aram" O?A>AP %?aram 2 3 sFit'h 1 messa-e 2 3 'ase SP_0E78>QG : Qn0estr!/ 1 hSn( 2 # &rea. # 'ase SP_+>EA8E : Qn+reate 1 hSn( 2 # &rea. # 'ase SP_8IPE> : Qn8imer 1 hSn( 2 # &rea. # (e$a,%t : ret,rn 0e$Sin(!F?r!' 1 hSn(" messa-e" F?aram" %?aram 2 # 6 ret,rn 0 # 6 =!i( Qn+reate 1 USE0 hSn( 2 3 >E+8 r # U0+ h(' # h&m = O!a(Ditma 1 hInst" PA_EIE8>E7QX>+E 1 I0D_DI8PA?1 2 2 # h(' = Jet0+ 1 hSn( 2 #

Chapter /<0 -raphics .nder Aindows


hmem(' = +reate+!m ati&%e0+ 1 h(' 2 # h!%(&m = 7e%e'tQ&9e't 1 hmem('" h&m 2 # >e%ease0+ 1 hSn(" h(' 2 # sran( 1 time 1 EXOO 2 2 # Jet+%ient>e't 1 hSn(" Br 2 # x = ran(1 2 5 r.ri-ht - 22 # / = ran(1 2 5 r.&!tt!m - 22 # 7et8imer 1 hSn(" 1" 50" EXOO 2 # 6 =!i( Qn0estr!/ 1 USE0 hSn( 2 3 _i%%8imer 1 hSn(" 1 2 # 7e%e'tQ&9e't 1 hmem('" h!%(&m 2 # 0e%ete0+ 1 hmem(' 2 # 0e%eteQ&9e't 1 h&m 2 # ?!stY,itPessa-e 1 0 2 # 6 =!i( Qn8imer 1 USE0 hSn( 2 3 U0+ h(' # >E+8 r # '!nst int F( = 22" ht = 22 # stati' int (x = 10" (/ = 10 # h(' = Jet0+ 1 hSn( 2 # DitD%t 1 h('" x" /" F(" ht" hmem('" 0" 0" SUI8EEE77 2 # Jet+%ient>e't 1 hSn(" Br 2 # x += (x # i$ 1 x ; 0 2 3

")9

"1)

%et .s C
x=0# (x = 10 # ?%a/7!,n( 14'h!r(.Fa=4" EXOO" 7E0_IIOEEAPE W 7E0_A7GE+ 2 #

6 e%se i$ 1 x < 1 r.ri-ht - F( 2 2 3 x = r.ri-ht - F( # (x = -10 # ?%a/7!,n( 14'h!r(.Fa=4" EXOO" 7E0_IIOEEAPE W 7E0_A7GE+ 2 # 6 / += (/ # i$ 1 / ; 0 2 3 /=0# (/ = 10 # ?%a/7!,n( 14'h!r(.Fa=4" EXOO" 7E0_IIOEEAPE W 7E0_A7GE+ 2 # 6 e%se i$ 1 / < 1 r.&!tt!m - ht 2 2 3 / = r.&!tt!m - ht # (/ = -10 # ?%a/7!,n( 1 4'h!r(.Fa=4" EXOO" 7E0_IIOEEAPE W 7E0_A7GE+ 2# 6 DitD%t 1 h('" x" /" F(" ht" hmem('" 0" 0" 7>++Q?G 2 # >e%ease0+ 1 hSn(" h(' 2 # 6

+ro* the /nd!roc= > #nction yo# can observe that we have handled two new *essages hereR/,:C$B'TB and /,:T*,B$G +or these *essages we have called the handlers (nCreate= > and (nTi1er= > respectivelyG 7et #s now #nderstand these handlers one by one

/,:C$B'TB and OnCreate( )

Chapter /<0 -raphics .nder Aindows

"11

The /,:C$B'TB *essage arrives whenever a new window is createdG Since #s#ally a window is created only once, the one<ti*e activity that is to be carried o#t in a progra* is #s#ally done in (nCreate= > handlerG $n o#r progra* to *a9e the ball *ove we need to display it at di erent places at di erent ti*esG To do this it wo#ld be necessary to blit the ball i*age several ti*esG 2owever, we need to load the i*age only onceG 1s this is a one<ti*e activity it has been done in the handler #nction (nCreate= >G Co# are already a*iliar with the steps involved in preparing the i*age or blittingRloading the bit*ap, creating a *e*ory 0C, *a9ing it co*patible with screen 0C and selecting the bit*ap in the *e*ory 0CG 1part ro* preparing the i*age or blitting we have also done so*e intialialisations li9e setting #p val#es in so*e variables to indicate the initial position o the ballG We have also called the SetTi1er= > #nctionG This #nction tells Windows to post a *essage /,:T*,B$ into the *essage H#e#e o o#r application every 5( *illisecondsG

/,:T*,B$ and OnTimer( )


$ we are to per or* an activity at reg#lar intervals we have two choicesP >a? 6se a loop and *onitor within the loop when is it ti*e to per or* that activityG >b? 6se a Windows *echanis* o ti*erG This *echanis* when #sed posts a W5BT$5." *essage at reg#lar intervals to o#r applicationG The irst *ethod wo#ld serio#sly ha*per the responsiveness o the progra*G $ the control is within the loop and a new *essage arrives the *essage wo#ld not get processed #nless the control goes o#t o the loopG The second choice is better beca#se it *a9es the progra* event drivenG That is, whenever /,:T*,B$ arrives

"12

%et .s C

that ti*e its handler does the Qob that we want to get e/ec#ted periodicallyG 1t other ti*es the application is ree to handle other *essages that co*e to its H#e#eG 1ll that we have done in the (nTi1er= > handler is erase the ball ro* previo#s position and draw it at a new positionG We have also chec9ed i the ball has hit the bo#ndaries o the windowG $ so we have played a so#nd ile #sing the !la#Sound= > 1,$ #nction and then changed the direction o the ballG

' Fe0 ,ore !oints[


1 ew *ore points worth noting be ore we close o#r disc#ssion on ani*ation: >a? 3ne application can set #p *#ltiple ti*ers to do di erent Qobs at di erent intervalsG 2ence we need to pass the id o the ti*er that we want to set #p to the SetTi1er= > #nctionG $n o#r case we have speci ied the id as 'G >b? +or *#ltiple ti*ers Windows wo#ld post *#ltiple /,:T*,B$ *essagesG .ach ti*e it wo#ld pass the ti*er id >c? as additional in or*ation abo#t the *essageG +or drawing as well as erasing the ball we have #sed the sa*e #nctionR-it-lt= >G While erasing we have #sed the raster operation code /2*TB9BSSG When we #se this code the color val#es o the so#rce pi/els get ignoredG Th#s red colored >d? pi/els o ball wo#ld get ignored leading to eras#re o the ball in the windowG >e? The si;e o client area o the window can be obtained #sing the GetClient$ect= > 1,$ #nctionG We want that every ti*e we r#n the application the initial position o the ball sho#ld be di erentG To ens#re this we have generated its initial /, y coordinates #sing the standard library #nction rand= >G 2owever, this #nction doesn@t

Chapter /<0 -raphics .nder Aindows

"13

generate tr#e rando* n#*bersG To ens#re that we do get tr#e rando* n#*bers, so*ehow we need to tie the rando* n#*ber generation with ti*e, as ti*e o each e/ec#tion o o#r progra* wo#ld be di erentG This has been achieved by *a9ing the call
sran( 1 time 1 EXOO 2 2 #

2ere ti1e= > is #nction that ret#rns the ti*eG We have #rther passed this ti*e to the srand= > #nctionG > ? To be able to #se rand= > and srand= > #nctions incl#de the ile DstdlibGh@G Si*ilarly or ti1e= > #nction to wor9 incl#de >g? the ile Dti*eGh@G $n the call to the !la#Sound= > #nction the irst para*eter is the na*e o the wave ile that is to be playedG $ irst para*eter is ilena*e then the second has to be )677G The third para*eter is a set o lagsG S9D:F*LB9',B indicates that the irst para*eter is the ilena*e, whereas >h? S9D:'SS9C indicates that the so#nd sho#ld be played in the bac9gro#ndG To be able to #se the !la#Sound= > #nction we need to lin9 the library Dwin**Glib@G This is done by #sing D,roQect Y Settings@ *en# ite*G 3n selection o this ite* a dialog pops >i? #pG $n the D7in9@ tab o this dialog *ention the na*e Dwin**Glib@ in the D3bQect = 7ibrary *od#les@ edit bo/G When the application ter*inates we have to instr#ct Windows not to send /,:T*,B$ *essages to o#r application any *oreG +or this we have called the 7illTi1er= > 1,$ #nction passing to it the $0 o the ti*erG

/indo0s4 the Bndless /orld[


The biggest h#rdle in Windows progra**ing is a so#nd #nderstanding o its progra**ing *odelG $n this chapter and in the

"14

%et .s C

last two $ have tried to catch the essence o Windows@ .vent 0riven ,rogra**ing *odelG 3nce yo# have #nderstood it thoro#ghly rest is Q#st a *atter o #nderstanding and calling the s#itable 1,$ #nctions to get yo#r Qob doneG Windows 1,$ is tr#ly an endless worldG $t covers areas li9e )etwor9ing, $nternet progra**ing, Telephony, 0rawing and ,rinting, 0evice $=3, $*aging, 5essaging, 5#lti*edia, Windowing, 0atabase progra**ing, Shell progra**ing, to na*e a ewG The progra*s that we have written have *erely scratched the s#r aceG )o *atter how *any progra*s that we write #nder Windows, several still re*ain to be writtenG The intention o this chapter was to #nveil be ore yo#, to give yo# the irst gli*pse o what is possible #nder WindowsG The intention all along was not to catch ish or yo# b#t to show yo# how to catch ish so that yo# can do ishing all yo#r li eG 2aving *ade a so#nd beginning, rest is or yo# to e/ploreG Good l#c9 and happy ishing4

Su11ar#
>a? $n 03S, progra**ers had to write separate graphics code or every new video adapterG $n Windows, the code once written wor9s on any video adapterG >b? 1 Windows progra* cannot draw directly on an o#tp#t device li9e screen or printerG $nstead, it draws to the logical display s#r ace #sing device conte/tG >c? When the window is displayed or the irst ti*e, or when it is *oved or resi;ed (n!aint= > handler gets calledG >d? $t is necessary to obtain the device conte/t be ore drawing te/t or graphics in the client areaG >Q? 1 device conte/t is a str#ct#re containing in or*ation reH#ired to draw on a display s#r aceG The in or*ation incl#des color o pen and br#sh, screen resol#tion, color palettes, etcG >e? To draw #sing a new pen or br#sh it is necessary to select the* into the device conte/tG

Chapter /<0 -raphics .nder Aindows

"15

> ? $ we don@t select any br#sh or pen into the device conte/t then the drawing drawn in the client area wo#ld be drawn with the de a#lt pen >blac9 pen? and de a#lt br#sh >white br#sh?G >g? "G8 is a *acro representing the "ed, Green and 8l#e ele*ents o a colorG "G8 > (, (, ( ? gives blac9 color, whereas, "G8 > 255, 255, 255 ? gives white colorG >h? 1ni*ation involves repeatedly drawing the sa*e i*age at s#ccessive positionsG

B3ercise
K'L State Tr#e or +alseP

>a? 0evice independence *eans the sa*e progra* is able to wor9 #sing di erent screens, 9eyboards and printers witho#t *odi ications to the progra*G >b? The W5B,1$)T *essage is generated whenever the client area o the window needs to be redrawnG >c? The 1,$ #nction .nd,aint> ? is #sed to release the 0CG >d? The de a#lt pen in the 0C is a solid pen o white colorG >e? The pen thic9ness or the pen style other than ,SBS37$0 has to be ' pi/elG > ? 8egin,aint> ? and Get0C> ? can be #sed interchangeablyG >g? $ we drag the *o#se ro* >'(, '(? to >''(, '((?, '(( W5B536S.53V. *essages wo#ld be posted into the *essage H#e#eG >h? W5B,1$)T *essage is raised when the window contents are scrolledG >i? With each 0C a de a#lt *onochro*e bit*ap o si;e ' pi/el / ' pi/el is associatedG >Q? The W5BC".1T. *essage arrives whenever a window is displayedG K-L 1nswer the ollowingP >a? What is *eant by 0evice $ndependent 0rawing and how it is achievedc

"1"
>b? ./plain the signi icance o W5B,1$)T *essageG

%et .s C

>c? 2ow Windows *anages the code and vario#s reso#rces o a progra*c >d? ./plain the Windows *echanis* o ti*erG >e? What do yo# *ean by capt#ring a *o#sec > ? Write down the steps that need to be carried o#t to ani*ate an obQectG
KCL 1tte*pt the ollowingP

>a? Write a progra*, which displays `hello` at any place in the window where yo# clic9 the le t *o#se b#ttonG $ yo# clic9 the right *o#se b#tton the color o s#bseH#ent hellos sho#ld changeG >b? Write a progra* that wo#ld draw a line by Qoining the new point where yo# have clic9ed the le t *o#se b#tton with the last point where yo# clic9ed the le t *o#se b#ttonG >c? Write a progra* to gradient ill the entire client area with shades o bl#e colorG >d? Write a progra* to create chessboard li9e bo/es >% A %? in the client areaG $ the window is resi;ed the bo/es sho#ld also get resi;ed so that all the 64 bo/es are visible at all ti*esG >e? Write a progra* that displays only the #pper hal o a bit*ap o si;e 4( / 4(G > ? Write a progra* that displays di erent te/t in di erent colors and onts at di erent places a ter every '( secondsG

You might also like