Computer Programming Data Structures

Embed Size (px)

Citation preview

  • 8/13/2019 Computer Programming Data Structures

    1/594

    viii

    Contents

    1. Getting Started 1

    What is C 2Getting Started with C 4

    The C Character Set 5Constants, Variables and Keywords 6

    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 '2

    The +irst C rogra* '-Co*pilation and ./ec#tion '&"eceiving $np#t 2'C $nstr#ctions 2-

    Type 0eclaration $nstr#ction 241rith*etic $nstr#ction 25$nteger and +loat Conversions 2&Type Conversion in 1ssign*ents 2&ierarchy o 3perations -'1ssociativity o 3perators -4

    Control $nstr#ctions in C -!S#**ary -!./ercise -%

    2. The Decision Control Structure 49

    0ecisions 0ecisions 5(The if State*ent 5'

    The "eal Thing 55#ltiple State*ents within if 56

    The if-else State*ent 5%

  • 8/13/2019 Computer Programming Data Structures

    2/594

    i/

    )ested if-elses 6'+or*s o if 62

    se o 7ogical 3perators 64The else if Cla#se 66The 3perator !2ierarchy o 3perators "evisited !-

    1 Word o Ca#tion !-The Conditional 3perators !6

    S#**ary !!./ercise !%

    3. The Loop Control Structure 97

    7oops &%The while 7oop &&

    Tips and Traps '('ore 3perators '(5

    Thefor 7oop '(!)esting o 7oops ''4

    #ltiple $nitialisations in thefor 7oop ''5The 3dd 7oop ''6The break State*ent ''%The continue State*ent '2(The do-while 7oop '2'S#**ary '24./ercise '24

    4. The Case Control Structure 135

    0ecisions singswitch '-6The Tips and Traps '4(

    switch Vers#s if-else 7adder '44Thegoto Keyword '45S#**ary '4%./ercise '4&

  • 8/13/2019 Computer Programming Data Structures

    3/594

    /

    5. Functions !ointers 157

    What is a +#nction '5%Why se +#nctions '65

    assing Val#es between +#nctions '66Scope "#le o +#nctions '!'Calling Convention '!23ne 0icey $ss#e '!-

    1dvanced +eat#res o +#nctions '!4+#nction 0eclaration and rototypes '!5Call by Val#e and Call by "eerence '!%1n $ntrod#ction to ointers '!%ointer )otation '!&8ac9 to +#nction Calls '%6Concl#sions '%&"ec#rsion '%&"ec#rsion and Stac9 '&4

    1dding +#nctions to the 7ibrary '&!S#**ary 2('

    ./ercise 2('

    ". Data T#pes $e%isited 213

    $ntegers, long andshort 2'4$ntegers,signed and unsigned 2'6Chars,signed and unsigned 2'!+loats and 0o#bles 2'&1 +ew ore $ss#es: 22'Storage Classes in C 22-

    1#to*atic Storage Class 224

    "egister Storage Class 226Static Storage Class 22!./ternal Storage Class 2-(Which to se When 2--

    S#**ary 2-4./ercise 2-5

  • 8/13/2019 Computer Programming Data Structures

    4/594

    /i

    7. The C !reprocessor 241

    +eat#res o C reprocessor 242acro ./pansion 244

    acros with 1rg#*ents 24%acros vers#s +#nctions 252

    +ile $ncl#sion 25-

    Conditional Co*pilation 255#if and #elif 0irectives 25%iscellaneo#s 0irectives 26(

    #undef 0irective 26(#pragma 0irective 26'

    S#**ary 26-./ercise 264

    &. 'rra#s 2"9

    What are 1rrays 2!(

    1 Si*ple rogra* sing 1rray 2!2ore on 1rrays 2!5

    1rray $nitiali;ation 2!58o#nds Chec9ing 2!6assing 1rray .le*ents to a +#nction 2!!

    ointers and 1rrays 2!&assing an .ntire 1rray to a +#nction 2%6The "eal Thing 2%!

    Two 0i*ensional 1rrays 2%&$nitiali;ing a 2

  • 8/13/2019 Computer Programming Data Structures

    5/594

    /ii

    ./ercise -(4

    9. !uppetting (n Strings 327

    What are Strings -2%ore abo#t Strings -2&ointers and Strings --4Standard 7ibrary String +#nctions --5

    strlen( ) --!strcpy( ) --&strcat( ) -42strcmp( ) -4-

    Two

  • 8/13/2019 Computer Programming Data Structures

    6/594

    /iii

    sprintf( ) andsscanf( ) +#nctions 4(4nor*atted Console $=3 +#nctions 4(5

    S#**ary 4(&./ercise 4(&

    12. File *nput+(utput 415

    0ata 3rgani;ation 4'6

    +ile 3perations 4'!3pening a +ile 4'%"eading ro* a +ile 42(Tro#ble in 3pening a +ile 42'Closing the +ile 422

    Co#nting Characters, Tabs, Spaces, : 4221 +ileline? $=3 in +iles 42!

    The 1w9ward )ewline 4-(

    "ecord $=3 in +iles 4-(Te/t +iles and 8inary +iles 4-4"ecord $=3 "evisited 4-!0atabase anage*ent 44'7ow 7evel 0is9 $=3 44!

    1 7ow 7evel +ile

  • 8/13/2019 Computer Programming Data Structures

    7/594

    /iv

    "edirecting the $np#t 4!68oth Ways at 3nce 4!!

    S#**ary 4!%./ercise 4!%

    14. (perations (n -its 4&1

    8itwise 3perators 4%23ne@s Co*ple*ent 3perator 4%4"ight Shit 3perator 4%67et Shit 3perator 4%%8itwise 1)0 3perator 4&-8itwise 3" 3perator 4&%8itwise A3" 3perator 4&&

    Theshowbits( ) +#nction 5((S#**ary 5('./ercise 5('

    15. ,iscellaneous Features 5)5

    .n#*erated 0ata Type 5(6ses o .n#*erated 0ata Type 5(!

    "ena*ing 0ata Types with typedef 5'(Typecasting 5''8it +ields 5'-ointers to +#nctions 5'5+#nctions "et#rning ointers 5'%+#nctions with Variable )#*ber o 1rg#*ents 52(nions 524

    nion o Str#ct#res 5-(

    S#**ary 5-'./ercise 5-'

  • 8/13/2019 Computer Programming Data Structures

    8/594

  • 8/13/2019 Computer Programming Data Structures

    9/594

    /vi

    ello Windows 5%20rawing Shapes 5%6Types o ens 5&(Types o 8r#shes 5&2

    Code and "eso#rces 5&6+reehand 0rawing, the aintbr#sh Style 5&6

    Capt#ring the o#se 6((0evice Conte/t, a Closer 7oo9 6('

    0isplaying a 8it*ap 6(-1ni*ation at Wor9 6(!

    WBC".1T. and OnCreate( ) 6''WBT$." and OnTimer( ) 6''1 +ew ore oints: 6'2

    Windows, the .ndless World: 6'-S#**ary 6'4./ercise 6'5

    19. *nteraction /ith ard0are "17

    ardware $nteraction 6'%ardware $nteraction, 03S erspective 6'&ardware $nteraction, Windows erspective 62-Co**#nication with Storage 0evices 626

    TheReadector( ) +#nction 6-'1ccessing 3ther Storage 0evices 6--Co**#nication with Keyboard 6-4

    0yna*ic 7in9ing 6-5Windows oo9s 6-5

    Caps 7oc9ed, er*anently 6-!0id o# ress $t TTwwiiccee:: 64-

    angling Keys 644Key7ogger 645Where is This 7eading 646S#**ary 64!./ercise 64!

  • 8/13/2019 Computer Programming Data Structures

    10/594

    /vii

    2). C nder Linu "49

    What is 7in#/ 65(C rogra**ing nder 7in#/ 65'The Dello 7in#/@ rogra* 652rocesses 65-arent and Child rocesses 655ore rocesses 65&

    Eo*bies and 3rphans 66(3ne $nteresting +act 66-S#**ary 664./ercise 664

    21. ,ore Linu !rograing ""7

    Co**#nication #sing Signals 66%andling #ltiple Signals 6!'"egistering a Co**on andler 6!-8loc9ing Signals 6!5

    .vent 0riven rogra**ing 6!%Where 0o o# Go +ro* ere 6%4S#**ary 6%4./ercise 6%5

    !ppendi" !Frecedence Table 6%!!ppendi" $F tandard %ibrary &unctions 6&'!ppendi" CF Chasing the $ugs !('!ppendi" 'Fe"adecimal umbering !'-!ppendi" *F!C++ Chart !'&!ppendi" &Felper,h &ile !25

    !ppendi" F$oot arameters !2&!ppendi" F%inu" +nstallation !-5+nde" !-&

  • 8/13/2019 Computer Programming Data Structures

    11/594

    1 Getting Started What is C

    Getting Started with CThe C Character Set

    Constants, Variables and KeywordsTypes o C Constants"#les or Constr#cting $nteger Constants"#les or Constr#cting "eal Constants"#les or Constr#cting Character ConstantsTypes o C Variables"#les or Constr#cting Variable )a*esC Keywords

    The +irst C rogra*

    Co*pilation and ./ec#tion

    "eceiving $np#t

    C $nstr#ctions

    Type 0eclaration $nstr#ction1rith*etic $nstr#ction$nteger and +loat Conversionsierarchy o 3perations1ssociativity 3 3perators

    Control $nstr#ction in C

    S#**ary

    ./ercise

    1

  • 8/13/2019 Computer Programming Data Structures

    12/594

    -

    2 %et .s C

    eore we can begin to write serio#s progra*s in C, it wo#ldbe interesting to ind o#t what really is C, how it ca*e intoe/istence and how does it co*pare with other co*p#ter

    lang#ages $n this chapter we wo#ld briely o#tline these iss#es

    +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 ando#tp#t and how it lets yo# control the seH#ence o e/ec#tion oinstr#ctions in a progra* We wo#ld disc#ss the irst three o these

    b#ilding bloc9s in this chapter

    /hat is C

    C is a progra**ing lang#age developed at 1T I T@s 8ell7aboratories o S1 in '&!2 $t was designed and written by a*an na*ed 0ennis "itchie $n the late seventies C began to

    replace the *ore a*iliar lang#ages o that ti*e li9e 7=$,17G37, etc )o one p#shed C $t wasn@t *ade the Doicial@ 8ell7abs lang#age Th#s, witho#t any advertise*ent C@s rep#tationspread and its pool o #sers grew "itchie see*s to have beenrather s#rprised that so *any progra**ers preerred C to olderlang#ages li9e +3"T"1) or 7=$, or the newer ones li9e ascaland 17 8#t, thatJs what happened

    ossibly why C see*s so pop#lar is beca#se it is reliable, si*pleand easy to #se oreover, in an ind#stry where newer lang#ages,tools and technologies e*erge and vanish day in and day o#t, alang#age that has s#rvived or *ore than - decades has to be reallygood

    1n opinion that is oten heard today is F C has been alreadys#perceded by lang#ages li9e CLL, CM and Nava, so why bother to

  • 8/13/2019 Computer Programming Data Structures

    13/594

    Chapter /0 etting tarted 3

    learn C todayO $ serio#sly beg to dier with this opinion Thereare several reasons or thisP

    >a?

    >b?

    >c?

    >d?

    $ believe that nobody can learn CLL or Nava directly This isbeca#se while learning these lang#ages yo# have things li9eclasses, obQects, inheritance, poly*orphis*, te*plates,e/ception handling, reerences, etc do deal with apart ro*9nowing the act#al lang#age ele*ents 7earning these

    co*plicated concepts when yo# are not even co*ortablewith the basic lang#age ele*ents is li9e p#tting the cart beorethe horse ence one sho#ld irst learn all the lang#ageele*ents very thoro#ghly #sing C lang#age beore *igratingto CLL, CM or Nava Tho#gh this two step learning process*ay ta9e *ore ti*e, b#t at the end o it yo# will deinitelyind it worth the tro#ble

    CLL, CM or Nava *a9e #se o a principle called 3bQect3riented rogra**ing >33? to organi;e the progra* Thisorgani;ing principle has lots o advantages to oer 8#t evenwhile #sing this organi;ing principle yo# wo#ld still need agood hold over the lang#age ele*ents o C and the basic

    progra**ing s9ills

    Tho#gh *any CLL and Nava based progra**ing tools andra*ewor9s have evolved over the years the i*portance o Cis still #nchallenged beca#se 9nowingly or #n9nowingly while#sing these ra*ewor9s and tools yo# wo#ld be still reH#iredto #se the core C lang#age ele*entsRanother good reasonwhy one sho#ld learn C beore CLL, CM or Nava

    aQor parts o pop#lar operating syste*s li9e Windows,

    )$A, 7in#/ is still written in C This is beca#se even todaywhen it co*es to peror*ance >speed o e/ec#tion? nothing

    beats C oreover, i one is to e/tend the operating syste* towor9 with new devices one needs to write device driver

    progra*s These progra*s are e/cl#sively written in C

  • 8/13/2019 Computer Programming Data Structures

    14/594

  • 8/13/2019 Computer Programming Data Structures

    15/594

    Chapter /0 etting tarted 5

    a close analogy between learning .nglish lang#age and learning Clang#age The classical *ethod o learning .nglish is to irst learnthe alphabets #sed in the lang#age, then learn to co*bine thesealphabets to or* words, which in t#rn are co*bined to or*sentences and sentences are co*bined to or* paragraphs7earning C is si*ilar and easier $nstead o straight

  • 8/13/2019 Computer Programming Data Structures

    16/594

    " %et .s C

    1lphabets 1, 8, :, , E

    a, b, ::, y, ;

    0igits (, ', 2, -, 4, 5, 6, !, %, &

    Special sy*bols D M U I > ? B < L X Y Z [ \

    ] ^ P _ ` J , =

    +ig#re '2

    Constants aria6les and e#0ords

    The alphabets, n#*bers and special sy*bols when properlyco*bined or* constants, variables and 9eywords 7et #s see whatare Dconstants@ and Dvariables@ in C 1 constant is an entity that

    doesn@t change whereas a variable is an entity that *ay change

    $n any progra* we typically do lots o calc#lations The res#lts othese calc#lations are stored in co*p#ters *e*ory 7i9e h#*an*e*ory the co*p#ter *e*ory also consists o *illions o cellsThe calc#lated val#es are stored in these *e*ory cells To *a9ethe retrieval and #sage o these val#es easy these *e*ory cells>also called *e*ory locations? are given na*es Since the val#estored in each location *ay change the na*es given to theselocations are called variable na*es Consider the ollowinge/a*ple

    ere - is stored in a *e*ory location and a na*e is given to itThen we are assigning a new val#e 5 to the sa*e *e*ory location This wo#ld overwrite the earlier val#e -, since a *e*orylocation can hold only one val#e at a ti*e This is shown in +ig#re'-

  • 8/13/2019 Computer Programming Data Structures

    17/594

    Chapter /0 etting tarted 7

    / - / 5

    / X - / X 5

    +ig#re '-

    Since the location whose na*e is can hold dierent val#es atdierent ti*es is 9nown as a variable 1s against this, - or 5 donot change, hence are 9nown as constants

    T#pes o8 C Constants

    C constants can be divided into two *aQor categoriesP>a?>b?

    ri*ary ConstantsSecondary Constants

    These constants are #rther categori;ed as shown in +ig#re '4

  • 8/13/2019 Computer Programming Data Structures

    18/594

  • 8/13/2019 Computer Programming Data Structures

    19/594

    Chapter /0 etting tarted 9

    range is F-2!6% to -2!6! +or a -2

  • 8/13/2019 Computer Programming Data Structures

    20/594

    1) %et .s C

    $n e/ponential or* o representation, the real constant isrepresented in two parts The part appearing beore De@ is called*antissa, whereas the part ollowing De@ is called e/ponent

    +ollowing r#les *#st be observed while constr#cting realconstants e/pressed in e/ponential or*P

    (a)

    (b)

    (c)

    (d)

    (e)

    The *antissa part and the e/ponential part sho#ld be

    separated by a letter eThe *antissa part *ay have a positive or negative sign0ea#lt sign o *antissa part is positiveThe e/ponent *#st have at least one digit, which *#st be a

    positive or negative integer 0ea#lt sign is positive"ange o real constants e/pressed in e/ponential or* is

  • 8/13/2019 Computer Programming Data Structures

    21/594

    Chapter /0 etting tarted 11

    T#pes o8 C aria6les

    1s we saw earlier, an entity that *ay vary d#ring progra*e/ec#tion is called a variable Variable na*es are na*es given tolocations in *e*ory These locations can contain integer, real orcharacter constants $n any lang#age, the types o variables that itcan s#pport depend on the types o constants that it can handleThis is beca#se a partic#lar type o variable can hold only the sa*etype o constant +or e/a*ple, an integer variable can hold only aninteger constant, a real variable can hold only a real constant and acharacter variable can hold only a character constant

    The r#les or constr#cting dierent types o constants are dierentowever, or constr#cting variable na*es o all types the sa*e seto r#les apply These r#les are given below

    $ules 8or Constructing aria6le aes

    (a)

    (b)

    (c)

    (d)

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

    digits or #nderscores So*e co*pilers allow variable na*eswhose length co#ld be #p to 24! characters Still, it wo#ld besaer to stic9 to the r#le o -' characters 0o not create#nnecessarily long variable na*es as it adds to yo#r typingeortThe irst character in the variable na*e *#st be an alphabet or#nderscore

    )o co**as or blan9s are allowed within a variable na*e)o special sy*bol other than an #nderscore >as in gross:sal?can be #sed in a variable na*e

    Ex.: si_int

    m_hra!_e_89

    These r#les re*ain sa*e or all the types o pri*ary and secondaryvariables )at#rally, the H#estion ollows how is C able todierentiate between these variables This is a rather si*ple

  • 8/13/2019 Computer Programming Data Structures

    22/594

    12 %et .s C

    *atter C co*piler is able to disting#ish between the variablena*es by *a9ing it co*p#lsory or yo# to declare the type o anyvariable na*e that yo# wish to #se in a progra* This typedeclaration is done at the beginning o the progra* +ollowing arethe 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 beconstr#cted #sing the above

  • 8/13/2019 Computer Programming Data Structures

    23/594

    Chapter /0 etting tarted 13

    auto

    break

    double

    else

    int

    long

    struct

    switch

    case enum register typedef

    char extern return union

    const float short unsigned

    continue for signed void

    default goto sizeof volatile

    do if static while

    +ig#re '5

    )ote that co*piler vendors >li9e icrosot, 8orland, etc? providetheir own 9eywords apart ro* the ones *entioned above Theseincl#de e/tended 9eywords li9e near, 8ar, as, etc Tho#gh it has

    been s#ggested by the 1)S$ co**ittee that every s#ch co*pilerspeciic 9eyword sho#ld be preceded by two #nderscores >as in as ?, not every vendor ollows this r#le

    The First C !rogra

    1r*ed with the 9nowledge abo#t the types o variables, constantsI 9eywords the ne/t logical step is to co*bine the* to or*instr#ctions owever, instead o this, we wo#ld write o#r irst C

    progra* now 3nce we have done that we wo#ld see in detail theinstr#ctions that it *ade #se o

    8eore we begin with o#r irst C progra* do re*e*ber theollowing r#les that are applicable to all C progra*sP

    (a) .ach instr#ction in a C progra* is written as a separatestate*ent Thereore a co*plete C progra* wo#ld co*priseo a series o state*ents

  • 8/13/2019 Computer Programming Data Structures

    24/594

    14 %et .s C

    (b)

    (c)

    (d)

    (e)

    (f)

    The state*ents in a progra* *#st appear in the sa*e order inwhich we wish the* to be e/ec#ted_ #nless o co#rse the logico the proble* de*ands a deliberate DQ#*p@ or transer ocontrol to a state*ent, which is o#t o seH#ence

    8lan9 spaces *ay be inserted between two words to i*provethe readability o the state*ent owever, no blan9 spaces areallowed within a variable, constant or 9eyword

    1ll state*ents are entered in s*all case letters

    C has no speciic r#les or the position at which a state*ent isto be written That@s why it is oten called a ree

  • 8/13/2019 Computer Programming Data Structures

    25/594

    Chapter /0 etting tarted 15

    )ow a ew #se#l tips abo#t the progra*

    Co**ent abo#t the progra* sho#ld be enclosed within = =+or e/a*ple, the irst two state*ents in o#r progra* areco**ents

    Tho#gh co**ents are not necessary, it is a good practice tobegin a progra* with a co**ent indicating the p#rpose o theprogra*, its a#thor and the date on which the progra* waswritten

    1ny n#*ber o co**ents can be written at any place in theprogra* +or e/a*ple, a co**ent can be written beore thestate*ent, ater 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#larstate*ent in a progra* acco*plishes 1t s#ch ti*es it isworthwhile *entioning the p#rpose o the state*ent >or a seto state*ents? #sing a co**ent +or e/a*pleP

    )* $!rm,%a $!r sim%e interest *)si = * n * r ) 100 #

    3ten progra**ers see* to ignore writing o co**ents 8#twhen a tea* is b#ilding big sotware well co**ented code isal*ost essential or other tea* *e*bers to #nderstand it

  • 8/13/2019 Computer Programming Data Structures

    26/594

    1" %et .s C

    1ltho#gh a lot o co**ents are probably not necessary in thisprogra*, it is #s#ally the case that progra**ers tend to #setoo ew co**ents rather than too *any 1n adeH#ate n#*bero co**ents can save ho#rs o *isery and s#ering when yo#later try to ig#re o#t what the progra* does

    The nor*al lang#age r#les do not apply to te/t written within+< .. , it cannot be anything else 1llstate*ents that belong to ain= > are enclosed within a pair o

    braces [ \ as shown below

    main

    statement 1 #statement 2 #

  • 8/13/2019 Computer Programming Data Structures

    27/594

  • 8/13/2019 Computer Programming Data Structures

    28/594

  • 8/13/2019 Computer Programming Data Structures

    29/594

  • 8/13/2019 Computer Programming Data Structures

    30/594

    2) %et .s C

    progra*s in this boo9 wo#ld wor9 with all the co*pilersWherever there is a deviation $ wo#ld point it o#t that ti*e

    1ss#*ing that yo# are #sing a T#rbo C or T#rbo CLL co*pilerhere are the steps that yo# need to ollow to co*pile and e/ec#teyo#r irst C progra*:

    >a?

    >b?>c?>d?

    >e?>?

    Start the co*piler at C pro*pt The co*piler >TC.A. is

    #s#ally present in CETCE-* directory?Select e0 ro* the File *en#Type the progra*Save the progra* #sing F2 #nder a proper na*e >sayrogra*'c?se Ctrl ? F9 to co*pile and e/ec#te the progra*se 'lt ? F5 to view the o#tp#t

    )ote that on co*piling the progra* its *achine lang#ageeH#ivalent is stored as an .A. ile >rogra*'.A.? on the dis9This ile is called an e/ec#table ile $ we copy this ile to another

    *achine we can e/ec#te it there witho#t being reH#ired toreco*pile it $n act the other *achine need not even have aco*piler to be able to e/ec#te the ile

    1 word o ca#tion $ yo# r#n this progra* in T#rbo CLLco*piler, yo# *ay get an error R The #nction print sho#ldhave a prototypeO To get rid o this error, peror* the ollowingsteps and then reco*pile the progra*

    >a?

    >b?

    Select D3ptions@ *en# and then select DCo*piler Y CLL3ptions@ $n the dialog bo/ that pops #p, select DC always@in the Dse CLL Co*piler@ options

    1gain select D3ptions@ *en# and then select D.nviron*ent Y.ditor@ a9e s#re that the dea#lt e/tension is DC@ rather thanDC@

  • 8/13/2019 Computer Programming Data Structures

    31/594

  • 8/13/2019 Computer Programming Data Structures

    32/594

    22 %et .s C

    The irst print8= > o#tp#ts the *essage D.nter val#es o p, n, r@ onthe screen ere we have not #sed any e/pression in print8= >which *eans that #sing e/pressions in print8= > is optional

    )ote that the a*persand >? beore the variables in the scan8= >#nction is a *#st is an D1ddress o@ operator $t gives thelocation n#*ber #sed by the variable in *e*ory When we saya, we are telling scan8= > at which *e*ory location sho#ld it

    store the val#e s#pplied by the #ser ro* the 9eyboard Thedetailed wor9ing o the operator wo#ld be ta9en #p in Chapter5

    )ote that a blan9, a tab or a new line *#st separate the val#ess#pplied to scan8= > )ote that a blan9 is creating #sing a spacebar,tab #sing the Tab 9ey and new line #sing the .nter 9ey This isshown belowP

    ./P The three val#es separated by blan9

    1000 5 15.5

    ./P The three val#es separated by tab

    1000 5 15.5

    ./P The three val#es separated by newline

    1000515.5

    So *#ch or the tips ow abo#t another progra* to give yo# aeel o things

    )* C,st $!r $,n. A,th!r: D!! *)main

    int n,m #

    rint$ Enter a n,m&er #

  • 8/13/2019 Computer Programming Data Structures

    33/594

    Chapter /0 etting tarted 23

    san$ (" Bn,m #

    rint$ !F I am %ettin /!, !n a seret... #rint$ G!, hae ,st entere( the n,m&er (" n,m #

    C *nstructions

    )ow that we have written a ew progra*s let #s loo9 at theinstr#ctions that we #sed in these progra*s There are basicallythree types o instr#ctions in CP

    (a)

    (b)

    (c)

    Type 0eclaration $nstr#ction1rith*etic $nstr#ctionControl $nstr#ction

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

    (a)

    (b)

    (c)

    Type declaration instr#ction To declare the typeo variables #sed in aC progra*

    1rith*etic instr#ction To peror*arith*etic operations

    between con< stants andvariables

    Control instr#ction To control the seH#enceo e/ec#tion o vario#sstate< *ents in a C

    progra*Since, the ele*entary C progra*s wo#ld #s#ally contain only thetype declaration and the arith*etic instr#ctions_ we wo#ld disc#ssonly these two instr#ctions at this stage The other types oinstr#ctions wo#ld be disc#ssed in detail in the s#bseH#entchapters

  • 8/13/2019 Computer Programming Data Structures

    34/594

  • 8/13/2019 Computer Programming Data Structures

    35/594

    Chapter /0 etting tarted 25

    is not This is beca#se here we are trying to #se a even beoredeining it

    (c) The ollowing state*ents wo#ld wor9

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

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

    int a = & = = ( = 10 #

    3nce again we are trying to #se 6 >to assign to a? beoredeining it

    'rithetic *nstruction

    1 C arith*etic instr#ction consists o a variable na*e on the lethand side o X and variable na*es I constants on the right handside o X The variables and constants appearing on the right hand

    side o X are connected by arith*etic operators li9e ? @

  • 8/13/2019 Computer Programming Data Structures

    36/594

    2" %et .s C

    The variables and constants together are called Doperands@ that areoperated #pon by the Darith*etic operators@ and the res#lt isassigned, #sing the assign*ent operator, to the variable on leta?

    >b?

    >c?

    >d?

    C allows only one variable on letA? cannot be applied on a loat 1lso note that on#sing U the sign o the re*ainder is always sa*e as the signo the n#*erator Th#s F5 U 2 yields F', whereas, 5 U reer the 1SC$$ Table in 1ppendi/ .?

    1rith*etic operations can be peror*ed on ints, 8loats andchars

    Th#s the state*ents,

    har x" / #int #x = 'a' #/ = '&' # = x + / #

  • 8/13/2019 Computer Programming Data Structures

    38/594

    2& %et .s C

    are perectly valid, since the addition is peror*ed on the1SC$$ val#es o the characters and not on charactersthe*selves The 1SC$$ val#es o Da@ and Db@ are &! and &%,and hence can deinitely be added

    >e?

    >?

    )o operator is ass#*ed to be present $t *#st be writtene/plicitly $n the ollowing e/a*ple, the *#ltiplication

    operator ater b *#st be e/plicitly written

    a = .(.&x/ ,s,a% arithmeti statement& = * ( * & * x * / statement

    nli9e other high level lang#ages, there is no operator orperor*ing e/ponentiation operation Th#s ollowingstate*ents are invalid

    a = 3 ** 2 #& = 3 K 2 #

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

    Lin%,(e ;math.h #nction is a standard library #nction $t is being

    #sed to raise - to the power o 2 Iinclude Jath.h is apreprocessor directive $t is being #sed here to ens#re that thepo0= > #nction wor9s correctly We wo#ld learn *ore abo#tstandard library #nctions in Chapter 5 and abo#t preprocessorin Chapter !

  • 8/13/2019 Computer Programming Data Structures

    39/594

    Chapter /0 etting tarted 29

    *nteger and Float Con%ersions

    $n order to eectively develop C progra*s, it will be necessary to#nderstand the r#les that are #sed or the i*plicit conversion oloating point and integer val#es in C These are *entioned below

    )ote the* care#lly

    (a)

    (b)

    (c)

    1n arith*etic operation between an integer and integer

    always yields an integer res#lt

    1n operation between a real and real always yields a realres#lt

    1n operation between an integer and real always yields a realres#lt $n this operation the integer is irst pro*oted to a realand then the operation is peror*ed ence the res#lt is real

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

    (peration $esult (peration $esult

    5 = 2

    5( = 2

    5 = 2(

    5( = 2(

    2

    25

    25

    25

    2 = 5

    2( = 5

    2 = 5(

    2( = 5(

    (

    (4

    (4

    (4

    +ig#re '6

    T#pe Con%ersion in 'ssignents

    $t *ay so happen that the type o the e/pression and the type o thevariable on the let

  • 8/13/2019 Computer Programming Data Structures

    40/594

    3) %et .s C

    de*oted depending on the type o the variable on let-5? it cannot be stored in i since it is an int $ns#ch a case the 8loat is de*oted to an int and then its val#e isstored ence what gets stored in i is - ./actly opposite happensin the ne/t state*ent ere, -( is pro*oted to -((((((( and thenstored in 6, since 6 being a 8loat variable cannot hold anythinge/cept a 8loat val#e

    $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 apply +ore/a*ple, consider the ollowing progra* rag*ent

    $%!at a" &" #int s #s = a * & * ) 100 + 32 ) 4 - 3 * 1.1 #

    ere, in the assign*ent state*ent so*e operands are ints whereasothers are 8loats 1s we 9now, d#ring eval#ation o the e/pressionthe ints wo#ld be pro*oted to 8loats and the res#lt o thee/pression wo#ld be a 8loat 8#t when this 8loat val#e is assignedto s it is again de*oted to an int and then stored in s

    3bserve the res#lts o the arith*etic state*ents shown in +ig#re'! $t has been ass#*ed that is an integer variable and a is a realvariable

  • 8/13/2019 Computer Programming Data Structures

    41/594

  • 8/13/2019 Computer Programming Data Structures

    42/594

    32 %et .s C

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

    !riorit# (perators Description

    'st

    2nd

    rd

    = U

    L ? andthen type an e/pression inside it

    1 ew e/a*ples wo#ld clariy the iss#e #rther

    Baple 1.1 0eter*ine the hierarchy o operations and eval#atethe 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

  • 8/13/2019 Computer Programming Data Structures

    43/594

    Chapter /0 etting tarted 33

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

    )ote that 6 = 4 gives ' and not '5 This so happens beca#se 6 and4 both are integers and thereore wo#ld eval#ate to only an integerconstant Si*ilarly 5 = % eval#ates to ;ero, since 5 and % are integerconstants and hence *#st ret#rn an integer val#e

    Baple 1.2 0eter*ine the hierarchy o operations and eval#atethe 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 !erati!n: ) = 4 + 3 ) 8 + 3 !erati!n: * = 4 + 0 + 3 !erati!n: ) = 4 + 3 !erati!n: + = 7 !erati!n: +

    )ote that - = % gives ;ero, again or the sa*e reason *entioned inthe previo#s e/a*ple

    1ll operators in C are ran9ed according to their precedence 1nd*ind yo# there are as *any as 45 odd operators in C, and thesecan aect the eval#ation o an e/pression in s#btle and #ne/pectedways i we arenJt care#l nort#nately, there are no si*ple r#lesthat one can ollow, s#ch as 8301SO that tells algebra st#dentsin which order does an e/pression eval#ate We have not

  • 8/13/2019 Computer Programming Data Structures

    44/594

    34 %et .s C

    enco#ntered *any o#t o these 45 operators, so we won@t p#rs#ethe s#bQect o precedence any #rther here owever, it can bereali;ed at this stage that it wo#ld be al*ost i*possible tore*e*ber the precedence o all these operators So a #ll

  • 8/13/2019 Computer Programming Data Structures

    45/594

  • 8/13/2019 Computer Programming Data Structures

    46/594

    3" %et .s C

    3perator 7et "ight "e*ar9

    X a b or b X-

    7et operand is#na*big#o#s, "ight isnot

    X b or a X b - "ight operand is#na*big#o#s, 7et is not

    +ig#re '''

    Since both X have " to 7 associativity and only the second X has#na*big#o#s right operand >necessary condition or " to 7associativity? the second X is peror*ed earlier

    Consider yet another e/pression

    = a * & + ) ( #

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

    3perator 7et "ight "e*ar9

    a b 8oth operands are #na*big#o#s

    = c d 8oth operands are #na*big#o#s

    +ig#re ''2

    ere since let operands or both operators are #na*big#o#sCo*piler is ree to peror* < or + operation as per its convenience

  • 8/13/2019 Computer Programming Data Structures

    47/594

  • 8/13/2019 Computer Programming Data Structures

    48/594

    3& %et .s C

    >d?

    >e?

    >?

    >g?

    1n e/pression *ay contain any seH#ence o constants,variables and operators3perators having eH#al precedence are eval#ated #singassociativity7et to right associativity *eans that the let operand o aoperator *#st be #na*big#o#s whereas right to letassociativity *eans that the right operand o a operator *#st

    be #na*big#o#s

    $np#t=o#tp#t in C can be achieved #sing scan8= > and print8= >

    #nctions

    Bercise

    K' Which o the ollowing are invalid variable na*es and why

    DAIAOA>G _&asi &asi-hraLPEA r!,. 422!,%ati!n in 2006 !er time min(!ermatterOQA hEOOQ H,e,e.

    teamRsit!r/ ?%!t L 3 2015_a/

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

    >a? int X -'4562 '5( _

    >b? na*e X D1Qay@ _

    >c? varchar X D-@ _

    >d? -'4 r r h X volBoBcyl _

    >e? 9 X > a b ? > c L > 25a L b ? > d L e ? _

    >? *Binst X rate o interest a*o#nt in rs _

  • 8/13/2019 Computer Programming Data Structures

    49/594

    Chapter /0 etting tarted 39

    >g? si X principal rateointerest n#*beroyears = '(( _

    >h? area X -'4 r 2 _

    >i? vol#*e X -'4 r 2 h _

    >Q? 9 X > >a b ? L c ? > 25 a L b ? _

    >9? a X b X - X 4 _

    >l? co#nt X co#nt L ' _

    >*? date X J2 ar (4J _

    KC .val#ate the ollowing e/pressions and show their hierarchy

    >a? g X big = 2 L big 4 = big < big L abc = - _>abc X 25, big X 2, ass#*e g to be a loat?

    >b? on X in9 act = 2 L - = 2 act L 2 L tig _>in9 X 4, act X ', tig X -2, ass#*e on to be an int?

    >c? s X H#i add = 4 < 6 = 2 L 2 = - 6 = god _>H#i X 4, add X 2, god X 2, ass#*e s to be an int?

    >d? s X ' = - a = 4 < 6 = 2 L 2 = - 6 = g _>a X 4, g X -, ass#*e s to be an int?

    KD +ill the ollowing table or the e/pressions given below and

    then eval#ate the res#lt 1 sa*ple entry has been illed in thetable or e/pression >a?

  • 8/13/2019 Computer Programming Data Structures

    50/594

    4) %et .s C

    3perator 7et "ight "e*ar9

    = '( 5 or 5 = 2= '

    7et operand is#na*big#o#s, "ightis not

    >a? g X '( = 5 =2 = ' _

    >b? b X - = 2 L 5 4 = - _

    >c? a X b X c X - L 4 _

    KB Convert the ollowing eH#ations into corresponding Cstate*ents

    >a?

    >b?

    >c?

    >d?

    E =%% > a + b ? 2 = c < (5 + 2 a = > H +

    r ? > a +b ? > ' = * ?

    A =< b + > b b ? + 2 4ac

    2a

    " =2v + 622 > c + d ?

    g + v

    1 X!!b > /y L a ? = c < (% L 2b

    > / L a ? >' = y ?

    KF What wo#ld be the o#tp#t o the ollowing progra*sP

    a main

  • 8/13/2019 Computer Programming Data Structures

    51/594

  • 8/13/2019 Computer Programming Data Structures

    52/594

  • 8/13/2019 Computer Programming Data Structures

    53/594

    Chapter /0 etting tarted 43

    >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 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 o#@>2? D.nter val#es o , ), "@>-? D2-56.4? 1ll the above

    >h? The *a/i*#* val#e that an integer constant can have is>'? 2? -2!6!>-? '!('4eL-%>4? F'!('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-56 _>2? con X JTJ J1J _>-? this X JTJ 2( _>4? - L a X b _

  • 8/13/2019 Computer Programming Data Structures

    54/594

    44 %et .s C

    >9? Which o the ollowing shows the correct hierarchy oarith*etic operators in C>'? , or =, L or 2? , , =, L, -? , =, , L, 4? = or , < or L

    >l? $n b X 66 = a L 2 n _ which operation will be peror*edirst>'? 66 = a>2? a L 2>-? 2 n>4? 0epends #pon co*piler

    >*? Which o the ollowing is allowed in a C 1rith*eticinstr#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? s#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

    >'? 25>2? ->-? 2>4? (

    >p? The e/pression, a X ! = 22 > -'4 L 2 ? - = 5 _ eval#ates to

  • 8/13/2019 Computer Programming Data Structures

    55/594

    Chapter /0 etting tarted 45

    >'? %2%>2? 62%>-? -'4>4? (

    >H? The e/pression, a X -( '((( L 2!6% _ eval#ates to>'? -2!6%>2? -? ''-(4(>4? (

    >r? The e/pression / X 4 L 2 U < % eval#ates to>'? 2? 6>-? 4>4? )one o the above

    >s? ierarchy 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

  • 8/13/2019 Computer Programming Data Structures

    56/594

    4" %et .s C

    >2? yphen>-? 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 let side o X

    >y? Which o the ollowing shows the correct hierarchy oarith*etic operations in C>'? = L 2? < = L>-? L < = >4? = L ;? What will be the val#e o d i d is a loat ater the operationd 2 + 7.)>'? (>2? (2%5!>-? Cannot be deter*ined>4? )one o the above

    K Write C progra*s or the ollowingP

    >a? "a*esh@s basic salary is inp#t thro#gh the 9eyboard isdearness allowance is 4(U o basic salary, and ho#se rentallowance is 2(U o basic salary Write a progra* to calc#latehis gross salary

  • 8/13/2019 Computer Programming Data Structures

    57/594

    Chapter /0 etting tarted 47

    >b? The distance between two cities >in 9*? is inp#t thro#gh the9eyboard Write a progra* to convert and print this distancein *eters, eet, inches and centi*eters

    >c? $ the *ar9s obtained by a st#dent in ive dierent s#bQectsare inp#t thro#gh the 9eyboard, ind o#t the aggregate *ar9sand percentage *ar9s obtained by the st#dent 1ss#*e thatthe *a/i*#* *ar9s that can be obtained by a st#dent in each

    s#bQect is '((

    >d? Te*perat#re o a city in +ahrenheit degrees is inp#t thro#ghthe 9eyboard Write a progra* to convert this te*perat#reinto Centigrade degrees

    >e? The length I breadth o a rectangle and radi#s o a circle areinp#t thro#gh the 9eyboard Write a progra* to calc#late thearea I peri*eter o the rectangle, and the area Icirc#*erence o the circle

    >? Two n#*bers are inp#t thro#gh the 9eyboard into twolocations C and 0 Write a progra* to interchange thecontents o C and 0

    >g? $ a iveintP se the *od#l#s operator DU@?

    >h? $ a ivei? $ a o#rQ? $n a town, the percentage o *en is 52 The percentage ototal literacy is 4% $ total percentage o literate *en is -5 othe total pop#lation, write a progra* to ind the total n#*ber

  • 8/13/2019 Computer Programming Data Structures

    58/594

    4& %et .s C

    o illiterate *en and wo*en i the pop#lation o the town is%(,(((

    >9? 1 cashier has c#rrency notes o deno*inations '(, 5( and'(( $ the a*o#nt to be withdrawn is inp#t thro#gh the9eyboard in h#ndreds, ind the total n#*ber o c#rrency noteso each deno*ination the cashier will have to give to thewithdrawer

    >l? $ the total selling price o '5 ite*s and the total proit earnedon the* is inp#t thro#gh the 9eyboard, write a progra* toind the cost price o one ite*

    >*? $ a ive

  • 8/13/2019 Computer Programming Data Structures

    59/594

    2 The Decision Control Structure

    e 0ecisions 0ecisions

    e The if State*entThe "eal Thing#ltiple State*ents within if

    e The if-else State*ent)ested if-elses+or*s o if

    e se o 7ogical 3peratorsThe else if Cla#seThe 3peratorierarchy o 3perators "evisited

    e 1 Word o Ca#tion

    e The Conditional 3perators

    e S#**ary

    e ./ercise

    49

  • 8/13/2019 Computer Programming Data Structures

    60/594

    /5) %et .s C

    e all need to alter o#r actions in the ace o changingcirc#*stances $ the weather is ine, then $ will go or astroll $ the highway is b#sy $ wo#ld ta9e a diversion

    $ the pitch ta9es spin, we wo#ld win the *atch $ she says no, $wo#ld loo9 elsewhere $ yo# li9e this boo9, $ wo#ld write the ne/tedition o# can notice that all these decisions depend on so*econdition being *et

    C lang#age too *#st be able to peror* dierent sets o actionsdepending on the circ#*stances $n act this is what *a9es it worthits salt C has three *aQor decision *a9ing instr#ctionsRthe i8state*ent, the i8@else state*ent, and the s0itch state*ent 1o#rth, so*ewhat less i*portant str#ct#re is the one that #sesconditional operators $n this chapter we will e/plore all theseways >e/cept s0itch, which has a separate chapter devoted to it,later? in which a C progra* can react to changing circ#*stances

    DecisionsP DecisionsP

    $n the progra*s written in Chapter ' we have #sed seH#encecontrol str#ct#re in which the vario#s steps are e/ec#tedseH#entially, ie in the sa*e order in which they appear in the

    progra* $n act to e/ec#te the instr#ctions seH#entially, we don@thave to do anything at all 8y dea#lt the instr#ctions in a progra*are e/ec#ted seH#entially owever, in serio#s progra**ingsit#ations, seldo* do we want the instr#ctions to be e/ec#tedseH#entially any a ti*es, we want a set o instr#ctions to bee/ec#ted in one sit#ation, and an entirely dierent set oinstr#ctions to be e/ec#ted in another sit#ation This 9ind osit#ation is dealt in C progra*s #sing a decision control

    instr#ction 1s *entioned earlier, a decision control instr#ctioncan be i*ple*ented in C #singP

    >a?>b?>c?

    The i8 state*entThe i8@else state*entThe conditional operators

  • 8/13/2019 Computer Programming Data Structures

    61/594

    Chapter 40 The 'ecision Control tructure 51

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

    The if Stateent

    7i9e *ost lang#ages, C #ses the 9eyword i8 to i*ple*ent thedecision control instr#ction The general or* o i8 state*ent loo9sli9e thisP

    i$ this !n(iti!n is tr,e exe,te this statement #

    The 9eyword i8 tells the co*piler that what ollows is a decisioncontrol instr#ction The condition ollowing the 9eyword i8 isalways enclosed within a pair o parentheses $ the condition,whatever it is, is tr#e, then the state*ent is e/ec#ted $ thecondition is not tr#e then the state*ent is not e/ec#ted_ instead the

    progra* s9ips past it 8#t how do we e/press the condition itselin C 1nd how do we eval#ate its tr#th or alsity 1s a generalr#le, we e/press a condition #sing C@s Drelational@ operators The

    relational operators allow #s to co*pare two val#es to see whetherthey are eH#al to each other, #neH#al, or whether one is greaterthan the other ere@s how they loo9 and how they are eval#ated inC

    this epression is true i8

    / XX y

    / X y

    / y

    / y

    / X y

    / X y

    / 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 2'

  • 8/13/2019 Computer Programming Data Structures

    62/594

    52 %et .s C

    The relational operators sho#ld be a*iliar to yo# e/cept or theeH#ality operator and the ineH#ality operator P )ote that is#sed or assign*ent, whereas, is #sed or co*parison o twoH#antities ere is a si*ple progra*, which de*onstrates the #seo i8 and the relational operators

    )* em!nstrati!n !$ i$ statement *)main

    int n,m #

    rint$ Enter a n,m&er %ess than 10 #san$ (" Bn,m #

    i$ n,m ;= 10 rint$ Shat an !&e(ient serant /!, are T #

    3n e/ec#tion o this progra*, i yo# type a n#*ber less than oreH#al to '(, yo# get a *essage on the screen thro#gh print8= > $yo# type so*e other n#*ber the progra* doesn@t do anything Theollowing lowchart wo#ld help yo# #nderstand the low o controlin the progra*

  • 8/13/2019 Computer Programming Data Structures

    63/594

  • 8/13/2019 Computer Programming Data Structures

    64/594

    54 %et .s C

    ST1"T

    dis X (

    $)T

    Hty, rate

    isno

    Hty '((( yes

    dis X '(

    tot X Hty rate F Hty rate dis = '((

    "$)T

    tot

    +ig#re 2-

    ST3

    )* a%,%ati!n !$ t!ta% exenses *)main

    int Ht/" (is = 0 #

    $%!at rate" t!t #rint$ Enter H,antit/ an( rate #san$ ( $" BHt/" Brate #

    i$ Ht/ < 1000 (is = 10 #

  • 8/13/2019 Computer Programming Data Structures

    65/594

    Chapter 40 The 'ecision Co ntrol tructure 55

    t!t = Ht/ * rate - Ht/ * rate * (is ) 100 #rint$ !ta% exenses = >s. $" t!t #

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

    Enter H,antit/ an( rate 1200 15.50

    !ta% exenses = >s. 16740.000000

    Enter H,antit/ an( rate 200 15.50!ta% exenses = >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 '((( Thereore, the variabledis, which was earlier set to (, now gets a new val#e '( sing thisnew val#e total e/penses are calc#lated and printed

    $n the second r#n the condition eval#ates to alse, as 2(( >the val#eo Qt#? isn@t greater than '((( Th#s, dis, which is earlier set to (,

    re*ains (, and hence the e/pression ater the *in#s sign eval#atesto ;ero, thereby oering no disco#nt

    $s the state*ent dis ) necessary The answer is yes, since in C, avariable i not speciically initiali;ed contains so*e #npredictableval#e >garbage val#e?

    The $eal Thing

    We *entioned earlier that the general or* o the i state*ent is asollows

    i$ !n(iti!n statement #

    Tr#ly spea9ing the general or* is as ollowsP

  • 8/13/2019 Computer Programming Data Structures

    66/594

    5" %et .s C

    i$ exressi!n statement #

    ere the e/pression can be any valid e/pression incl#ding arelational e/pression We can even #se arith*etic e/pressions inthe i8 state*ent +or e/a*ple all the ollowing i8 state*ents arevalid

    i$ 3 + 2 5 rint$ his F!rs #

    i$ a = 10 rint$ Een this F!rs #

    i$ -5 rint$ ,rrisin%/ een this F!rs #

    )ote that in C a non

  • 8/13/2019 Computer Programming Data Structures

    67/594

    Chapter 40 The 'ecision Control tructure 57

    placed within a pair o braces as ill#strated in the ollowinge/a*ple

    Baple 2.2 The c#rrent year and the year in which thee*ployee Qoined the organi;ation are entered thro#gh the9eyboard $ the n#*ber o years or which the e*ployee hasserved the organi;ation is greater than - then a bon#s o "s 25((=yo#incl#ded? can #nderstand easily at a later date

    $n the above progra* an i8@else occ#rs within the elsebloc9 o theirst i8 state*ent Si*ilarly, in so*e other progra* an i8@else *ayocc#r in the i8 bloc9 as well There is no li*it on how deeply thei8s and the elses can be nested

    Fors o8 if

    The i8 state*ent can ta9e any o the ollowing or*sP

    a i$ !n(iti!n (! this #

    & i$ !n(iti!n

    (! this #an( this #

    i$ !n(iti!n

    (! this #e%se

    (! this #( i$ !n(iti!n

    (! this #

  • 8/13/2019 Computer Programming Data Structures

    73/594

    Chapter 40 The 'ecision Co ntrol tructure "3

    an( this #e%se

    (! this #an( this #

    e i$ !n(iti!n (! this #e%se

    i$ !n(iti!n (! this #

    e%se

    (! this #an( this #

    $ i$ !n(iti!n

    i$ !n(iti!n (! this #

    e%se

    (! this #an( this #

    e%se

    (! this #

  • 8/13/2019 Computer Programming Data Structures

    74/594

  • 8/13/2019 Computer Programming Data Structures

    75/594

    Chapter 40 The 'ecision Control tructure "5

    i$ er

  • 8/13/2019 Computer Programming Data Structures

    76/594

    "" %et .s C

    i$ er

  • 8/13/2019 Computer Programming Data Structures

    77/594

    Chapter 40 The 'ecision Co ntrol tructure "7

    )* e%se i$ %a((er (em! *)main

    int m1" m2" m3" m4" m5" er #

    er = m1+ m2 + m3 + m4+ m5 ) er #

    i$ er

  • 8/13/2019 Computer Programming Data Structures

    78/594

    "& %et .s C

    to only two answers +or e/a*ple, consider the ollowinge/a*pleP

    Baple 2.5 1 co*pany ins#res its drivers in the ollowingcasesP

    f $ the driver is *arried

    f $ the driver is #n*arried, *ale I above -( years o age

    f $ the driver is #n*arried, e*ale I above 25 years o age$n all other cases the driver is not ins#red $ the *arital stat#s, se/and age o the driver are the inp#ts, write a progra* to deter*inewhether the driver is to be ins#red or not

    ere ater chec9ing a co*plicated set o instr#ctions the inalo#tp#t o the progra* wo#ld be one o the twoR.ither the driversho#ld be ens#red or the driver sho#ld not be ens#red 1s*entioned above, since these are the only two o#tco*es this

    proble* can be solved #sing logical operators 8#t beore we dothat let #s write a progra* that does not *a9e #se o logical

    operators

    )* Ins,rane !$ (rier - Fith!,t ,sin %!ia% !erat!rs *)main

    har sex" ms #int ae #

    rint$ Enter ae" sex" marita% stat,s #san$ ( " Bae" Bsex" Bms #

    i$ ms == 'P' rint$ rier is ins,re( #e%se

    i$ sex == 'P'

  • 8/13/2019 Computer Programming Data Structures

    79/594

    Chapter 40 The 'ecision Control tructure "9

    i$ ae < 30 rint$ rier is ins,re( #

    e%se

    e%serint$ rier is n!t ins,re( #

    i$ ae < 25

    rint$ rier is ins,re( #e%se

    rint$ rier is n!t ins,re( #

    +ro* the progra* it is evident that we are reH#ired to *atchseveral i8s and elses and several pairs o braces $n a *ore real

  • 8/13/2019 Computer Programming Data Structures

    80/594

    7) %et .s C

    int ae #

    rint$ Enter ae" sex" marita% stat,s #san$ ( Bae" Bsex" Bms #

    i$ ms == 'P' WW ms == 'X' BB sex == 'P' BB ae < 30 WW ms == 'X' BB sex == '' BB ae < 25

    rint$ rier is ins,re( #

    e%se

    rint$ rier is n!t ins,re( #

    $n this progra* it is i*portant to note thatP

    f The driver will be ins#red only i one o the conditionsenclosed in parentheses eval#ates to tr#e

    f +or the second pair o parentheses to eval#ate to tr#e, eachcondition in the parentheses separated by *#st eval#ate totr#e

    f .ven i one o the conditions in the second parentheseseval#ates to alse, then the whole o the second parentheseseval#ates to alse

    f The last two o the above arg#*ents apply to third pair oparentheses as well

    Th#s we can concl#de that the and RR are #se#l in theollowing progra**ing sit#ationsP

    (a)

    (b)

    When it is to be tested whether a val#e alls within apartic#lar range or notWhen ater testing several conditions the o#tco*e is only oneo the two answers >This proble* is oten called yes=no

    proble*?

  • 8/13/2019 Computer Programming Data Structures

    81/594

    Chapter 40 The 'ecision Control tructure 71

    There can be one *ore sit#ation other than chec9ing ranges oryes=no proble* where yo# *ight ind logical operators #se#l Theollowing progra* de*onstrates it

    Baple 2." Write a progra* to calc#late the salary as per theollowing tableP

    Gender ears o8 Ser%ice uali8ications Salar#

    ale X '( ost

  • 8/13/2019 Computer Programming Data Structures

    82/594

    72 %et .s C

    e%se i$ == 'm' BB /!s ; 10 BB H,a% == 0 sa% = 7000 #

    e%se i$ == '$' BB /!s

  • 8/13/2019 Computer Programming Data Structures

    83/594

    Chapter 40 The 'ecision Control tructure 73

    This is another way o saying

    i$ $%a == 0

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

    ierarch# o8 (perators $e%isited

    Since we have now added the logical operators to the list ooperators we 9now, it is ti*e to review these operators and their

    priorities +ig#re 2! s#**ari;es the operators we have seen soar The higher the position o an operator is in the table, higher isits priority >1 #ll

  • 8/13/2019 Computer Programming Data Structures

    84/594

    74 %et .s C

    main

    int i #

    rint$ Enter a%,e !$ i #san$ (" Bi #i$ i = 5

    rint$ G!, entere( 5 #

    e%se

    rint$ G!, entere( s!methin !ther than 5 #

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

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

    S#rprising o# have entered 2(( and &&&&, and still yo# ind in

    either case the o#tp#t is Do# entered 5@ This is beca#se we havewritten the condition wrongly We have #sed the assign*entoperator instead o the relational operator 1s a res#lt, thecondition gets red#ced to i8 = 5 >, irrespective o what yo# s#pplyas the val#e o i 1nd re*e*ber that in C Dtr#th@ is always non alwayseval#ates to tr#e and hence the res#lt

    1nother co**on *ista9e while #sing the i8 state*ent is to write ase*icolon >;? ater the condition, as shown belowP

    main

    int i #

    rint$ Enter a%,e !$ i #san$ (" Bi #

  • 8/13/2019 Computer Programming Data Structures

    85/594

    Chapter 40 The 'ecision Co ntrol tructure 75

    i$ i == 5 #rint$ G!, entere( 5 #

    The _ *a9es the co*piler to interpret the state*ent as i yo# havewritten it in ollowing *annerP

    i$ i == 5 #

    rint$ G!, entere( 5 #

    ere, i the condition eval#ates to tr#e the _ >n#ll state*ent, whichdoes nothing on e/ec#tion? gets e/ec#ted, ollowing which theprint8= > gets e/ec#ted $ the condition ails then straightaway theprint8= > gets e/ec#ted Th#s, irrespective o whether the conditioneval#ates to tr#e or alse the print8= > is bo#nd to get e/ec#ted"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 awry oral is, beware o s#chpitalls

    The ollowing ig#re s#**ari;es the wor9ing o all the threelogical operators

    (perands $esults

    (

    #

    (

    P

    '

    P#

    '

    #

    (

    RR #

    (

    ( non

  • 8/13/2019 Computer Programming Data Structures

    86/594

    7" %et .s C

    The Conditional (perators

    The conditional operators U and are so*eti*es called ternaryoperators since they ta9e three arg#*ents $n act, they or* a 9indo oreshortened i

  • 8/13/2019 Computer Programming Data Structures

    87/594

    Chapter 40 The 'ecision Co ntrol tructure 77

    (a)

    (b)

    (c)

    $t@s not necessary that the conditional operators sho#ld be#sed only in arith*etic state*ents This is ill#strated in theollowing e/a*plesP

    Ex.: int i #san$ (" Bi # i == 1 Z rint$ Amit : rint$ A%% an( s,n(r/ #

    Ex.: har a = '' #rint$ " a a? There are three ways or ta9ing decisions in a progra* +irstway is to #se the i8

  • 8/13/2019 Computer Programming Data Structures

    88/594

    7& %et .s C

    >b?

    >c?

    >d?

    >e?>?

    >g?

    conditional operators and third way is to #se the s0itchstate*entThe dea#lt scope o the i8 state*ent is only the ne/tstate*ent So, to e/ec#te *ore than one state*ent they *#st

    be written in a pair o braces1n i8bloc9 need not always be associated with an elsebloc9owever, an else bloc9 is always associated with an i8state*ent

    $ the o#tco*e o an i8@else ladder is only one o two answersthen the ladder sho#ld be replaced either with an else@i8 cla#seor by logical operators and RR are binary operators, whereas, P is a #nary operator$n C every test e/pression is eval#ated in ter*s o ;ero andnon

  • 8/13/2019 Computer Programming Data Structures

    89/594

    Chapter 40 The 'ecision Co ntrol tructure 79

    main

    & = 300 # = 200 #rint$ @n( (" &" #

    int x = 10" / = 20 #

    i$ x == / #rint$ @n( (" x" / #

    ( main

    int x = 3" / = 5 #i$ x == 3

    rint$ @n(" x #e%se #

    rint$ @n(" / #

    e main

    int x = 3 #$%!at / = 3.0 #

    i$ x == / rint$ @nx an( / are eH,a% #

    e%se

    rint$ @nx an( / are n!t eH,a% #

    $ main

    int x = 3" /" #/ = x = 10 # = x ; 10 #rint$ @nx = ( / = ( = (" x" /" #

  • 8/13/2019 Computer Programming Data Structures

    90/594

    &) %et .s C

    main

    int = 35 #rint$ @n( ( (" == 35" = 50" < 40 #

    h main

    int i = 65 #har = [AR #i$ i ==

    rint$ M is SQSN #e%se

    rint$ is a hea(ahe #

    i main

    int a = 5" &" #

    & = a = 15 # = a ; 15 #rint$ @na = ( & = ( = (" a" &" #

    main

    int x = 15 #rint$ @n( ( (" x T= 15" x = 20" x ; 30 #

    K- oint o#t the errors, i any, in the ollowing progra*sP

    a main

    $%!at a = 12.25" & = 12.52 #i$ a = &

    rint$ @na an( & are eH,a% #

  • 8/13/2019 Computer Programming Data Structures

    91/594

    Chapter 40 The 'ecision Control tructure &1

    & main

    int = 10" = 12 #i$

  • 8/13/2019 Computer Programming Data Structures

    92/594

    &2 %et .s C

    main

    rint$ @narathians #

    int x = 30 " / = 40 #i$ x == /

    rint$ x is eH,a% t! / #

    e%sei$ x < / rint$ x is reater than / #

    e%sei$ x ; / rint$ x is %ess than / #

    h main

    int x = 10 #i$ x

  • 8/13/2019 Computer Programming Data Structures

    93/594

  • 8/13/2019 Computer Programming Data Structures

    94/594

    &4 %et .s C

    (k)

    (l)

    Given the coordinates = #> o a center o a circle and it@s radi#s,write a progra* which will deter*ine whether a point lies insidethe circle, on the circle or o#tside the circle

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

    Given a point = #>, write a progra* to ind o#t i it lies on the/ a '( ?

    > a 5 II c ?5 II c X % YY c

    '

    KD What wo#ld be the o#tp#t o the ollowing progra*sP

    a main

    int i = 4" = 12 #i$ i = 5 WW < 50

    rint$ @nean !$ st,(ents a$$airs #e%se

    rint$ @n!sa #

    & main

    int i = 4" = 12 #

  • 8/13/2019 Computer Programming Data Structures

    95/594

    Chapter 40 The 'ecision Control tructure &5

    i$ i = 5 BB < 5 rint$ @nOet ,s #

    e%se

    rint$ @nSish Fas $ree T #

    main

    int i = 4" = -1" = 0" F" x" /" #F = i WW WW #x = i BB BB #/ = i WW BB # = i BB WW #rint$ @nF = ( x = ( / = ( = (" F" x" /" #

    ( main

    int i = 4" = -1" = 0" /" #/ = i + 5 BB + 1 WW + 2 #

    = i + 5 WW + 1 BB + 2 #rint$ @n/ = ( = (" /" #

    e main

    int i = -3" = 3 #i$ Ti + T * 1

    rint$ @nPassar! #e%se

    rint$ @nDennari! #

    $ main

    int a = 40 #i$ a < 40 BB a ; 45

    rint$ a is reater than 40 an( %ess than 45 #

  • 8/13/2019 Computer Programming Data Structures

    96/594

    &" %et .s C

    e%se

    rint$ (" a #

    main

    int = 8" H = 20 #i$ == 5 BB H < 5

    rint$ @nSh/ n!t #e%se

    rint$ @ne$inite%/ T #

    h main

    int i = -1" = 1" "% # = i BB #% = i WW #rint$ ( (" I" #

    i main

    int x = 20 " / = 40 " = 45 #i$ x < / BB x <

    rint$ x is &i #e%se i$ / < x BB / <

    rint$ / is &i #e%se i$ < x BB < /

    rint$ is &i #

    main

    int i = -1" = 1" "% # = Ti BB #% = Ti WW #rint$ ( (" i" #

  • 8/13/2019 Computer Programming Data Structures

    97/594

    Chapter 40 The 'ecision Control tructure &7

    main

    int = 4" # = T5 BB #rint$ @n = (" #

    KB oint o#t the errors, i any, in the ollowing progra*sP

    a )* his r!ram)* is an exam%e !$)* ,sin O!ia% !erat!rs *)main

    int i = 2" = 5 #i$ i == 2 BB == 5

    rint$ @natis$ie( at %ast #

    & main

    int !(e" $%a #i$ !(e == 1 B $%a == 0

    rint$ @nhe ea%e has %an(e( #

    main

    har s/ = 'a'" assF!r( = '' #

    i$ s/ == 'a' !r assF!r( == '' rint$ @nA%% the &ir(s are sa$e in the nest #

    ( main

  • 8/13/2019 Computer Programming Data Structures

    98/594

    && %et .s C

    int i = 10" = 20 #i$ i = 5 BB i$ = 10

    rint$ @nUae a nie (a/ #

    a main

    int x = 10 " / = 20#

    i$ x

  • 8/13/2019 Computer Programming Data Structures

    99/594

    Chapter 40 The 'ecision Co ntrol tructure &9

    KF 1tte*pt the ollowingP

    (a)

    (b)

    1ny year is entered thro#gh the 9eyboard, write a progra* todeter*ine whether the year is leap or not se the logicaloperators and RR

    1ny character is entered thro#gh the 9eyboard, write aprogra* to deter*ine whether the character entered is acapital letter, a s*all case letter, a digit or a special sy*bol

    The ollowing table shows the range o 1SC$$ val#es orvario#s characters

    Characters 'SC** alues

    1 F E

    a F ;

    ( F &

    special sy*bols

    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#latepre*i#*

    >'? $ a person@s health is e/cellent and the person is between25 and -5 years o age and lives in a city and is a *alethen the pre*i#* is "s 4 per tho#sand and his policya*o#nt cannot e/ceed "s 2 la9hs

    >2? $ a person satisies all the above conditions e/cept thatthe se/ is e*ale then the pre*i#* is "s - per tho#sandand her policy a*o#nt cannot e/ceed "s ' la9h

    >-? $ a person@s health is poor and the person is between 25and -5 years o age and lives in a village and is a *ale

  • 8/13/2019 Computer Programming Data Structures

    100/594

    9) %et .s C

    then the pre*i#* is "s 6 per tho#sand and his policycannot e/ceed "s '(,(((

    >4? $n all other cases the person is not ins#red

    Write a progra* to o#tp#t whether the person sho#ld beins#red or not, his=her pre*i#* rate and *a/i*#* a*o#ntor which he=she can be ins#red

    (d)

    (e)

    1 certain grade o steel is graded according to the ollowingconditionsP

    >i? ardness *#st be greater than 5(>ii? Carbon content *#st be less than (!>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 *etGrade is % i conditions >ii? and >iii? are *etGrade is ! i conditions >i? and >iii? are *etGrade is 6 i only one condition is *etGrade is 5 i none o the conditions are *et

    Write a progra*, which will reH#ire the #ser to give val#es ohardness, carbon content and tensile strength o the steel#nder consideration and o#tp#t the grade o the steel

    1 library charges a ine or every boo9 ret#rned late +or irst5 days the ine is 5( paise, or 6

  • 8/13/2019 Computer Programming Data Structures

    101/594

    Chapter 40 The 'ecision Co ntrol tructure 91

    (f)

    (g)

    (h)

    (i)

    $ the three sides o a triangle are entered thro#gh the9eyboard, write a progra* to chec9 whether the triangle isvalid or not The triangle is valid i the s#* o two sides isgreater than the largest o the three sides

    $ the three sides o a triangle are entered thro#gh the9eyboard, write a progra* to chec9 whether the triangle isisosceles, eH#ilateral, scalene or right angled triangle

    $n a co*pany, wor9er eiciency is deter*ined on the basis othe ti*e reH#ired or a wor9er to co*plete a partic#lar Qob $the ti*e ta9en by the wor9er is between 2 F - ho#rs, then thewor9er is said to be highly eicient $ the ti*e reH#ired bythe wor9er is between - F 4 ho#rs, then the wor9er is orderedto i*prove speed $ the ti*e ta9en is between 4 F 5 ho#rs, thewor9er is given training to i*prove his speed, and i the ti*eta9en by the wor9er is *ore than 5 ho#rs, then the wor9er hasto leave the co*pany $ the ti*e ta9en by the wor9er is inp#tthro#gh the 9eyboard, ind the eiciency o the wor9er

    1 #niversity has the ollowing r#les or a st#dent to H#aliyor a degree with 1 as the *ain s#bQect and 8 as thes#bsidiary s#bQectP>a? e sho#ld get 55 percent or *ore in 1 and 45 percent or

    *ore in 8>b? $ he gets than 55 percent in 1 he sho#ld get 55 percent or

    *ore in 8 owever, he sho#ld get at least 45 percent in1

    >c? $ he gets less than 45 percent in 8 and 65 percent or *orein 1 he is allowed to reappear in an e/a*ination in 8 to

    H#aliy>d? $n all other cases he is declared to have ailed

    Write a progra* to receive *ar9s in 1 and 8 and 3#tp#twhether the st#dent has passed, ailed or is allowed toreappear in 8

  • 8/13/2019 Computer Programming Data Structures

    102/594

    92 %et .s C

    (j) The policy ollowed by a co*pany to process c#sto*er ordersis given by the ollowing r#lesP

    >a? $ a c#sto*er order is less than or eH#al to that in stoc9and has credit is 3K, s#pply has reH#ire*ent

    >b? $ has credit is not 3K do not s#pply Send hi*inti*ation

    >c? $ has credit is 39 b#t the ite* in stoc9 is less than hasorder, s#pply what is in stoc9 $nti*ate to hi* data the

    balance will be shipped

    Write a C progra* to i*ple*ent the co*pany policy

    Conditional operators

    KG What wo#ld be the o#tp#t o the ollowing progra*sP

    a main

    int i = -4" " n,m # = n,m ; 0 Z 0 : n,m * n,m #rint$ @n(" #

    & main

    int " n,m = 30 # = n,m < 5 Z n,m ;= 10 Z 100 : 200 : 500 #rint$ @n(" n,m #

    main

    int = 4 # T T= 1 Z rint$ @nSe%!me : rint$ @nJ!!( D/e #

  • 8/13/2019 Computer Programming Data Structures

    103/594

    Chapter 40 The 'ecision Control tructure 93

    K oint o#t the errors, i any, in the ollowing progra*sP

    a main

    int ta = 0" !(e = 1 #i$ ta == 0

    !(e < 1 Z rint$ @nUe%%! Z rint$ @nUi #e%se

    rint$ @nUe%%! Ui TT #

    & main

    int i = 65 #rint$ @ni

  • 8/13/2019 Computer Programming Data Structures

    104/594

    94 %et .s C

    $ main

    int = 65 "%% #%% = == 65 : rint$ @n is eH,a% t! 65 : rint$ @n is n!t

    eH,a% t! 65 #rint$ (" %% #

    main

    int x = 10" / = 20 #x == 20 BB / T= 10 Z rint$ r,e : rint$ a%se #

    K* "ewrite the ollowing progra*s #sing conditional operators

    a main

    int x" min" max #san$ @n( (" Bmax" Bx #

    i$ x < max max = x #

    e%se

    min = x #

    & main

    int !(e #san$ (" B!(e #i$ !(e < 1

    rint$ @nCer,sa%em #

    e%sei$ !(e ; 1

    rint$ @nE((ie #e%se

    rint$ @n Drain #

  • 8/13/2019 Computer Programming Data Structures

    105/594

    Chapter 40 The 'ecision Co ntrol tructure 95

    main

    $%!at sa% #rint$ Enter the sa%ar/ #san$ $" Bsa% #i$ sa% ; 40000 BB sa% < 25000

    rint$ Panaer #

    e%sei$ sa% ; 25000 BB sa% < 15000

    rint$ A!,ntant #e%se

    rint$ %er #

    KV 1tte*pt the ollowingP

    (a)

    (b)

    (c)

    sing conditional operators deter*ineP

    >'? Whether the character entered thro#gh the 9eyboard is a

    lower case alphabet or not>2? Whether a character entered thro#gh the 9eyboard is a

    special sy*bol or not

    Write a progra* #sing conditional operators to deter*inewhether a year entered thro#gh the 9eyboard is a leap year ornot

    Write a progra* to ind the greatest o the three n#*bersentered thro#gh the 9eyboard #sing conditional operators

  • 8/13/2019 Computer Programming Data Structures

    106/594

    9" %et .s C

  • 8/13/2019 Computer Programming Data Structures

    107/594

    T

    7oops

    The while 7oopTips and Trapsore 3perators

    Thefor 7oop)esting o 7oops#ltiple $nitialisations in thefor 7oop

    The 3dd 7oop

    The break State*entThe continue State*ent

    The do-while 7oop

    S#**ary

    ./ercise

    he progra*s that we have developed so ar #sed either aseH#ential or a decision control instr#ction $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#teddepending #pon the o#tco*e o the condition being tested >or alogical decision being ta9en?

    97

  • 8/13/2019 Computer Programming Data Structures

    108/594

    9& %et .s C

    These progra*s were o li*ited nat#re, beca#se when e/ec#ted,they always peror*ed the sa*e series o actions, in the sa*e way,e/actly once 1l*ost always, i so*ething is worth doing, it@sworth doing *ore than once o# can probably thin9 o severale/a*ples o this ro* real lie, s#ch as eating a good dinner orgoing or a *ovie rogra**ing is the sa*e_ we reH#ently needto peror* an action over and over, oten with variations in thedetails each ti*e The *echanis*, which *eets this need, is the

    Dloop@, and loops are the s#bQect o this chapter

    Loops

    The versatility o the co*p#ter lies in its ability to peror* a set oinstr#ctions repeatedly This involves repeating so*e portion othe progra* either a speciied n#*ber o ti*es or #ntil a partic#larcondition is being satisied This repetitive operation is donethro#gh a loop control instr#ction

    There are three *ethods by way o which we can repeat a part o a

    progra* They areP

    >a? sing a 8or state*ent>b? sing a 0hile state*ent>c? sing a do@0hile state*ent

    .ach o these *ethods is disc#ssed in the ollowing pages

    The while Loop$t is oten the case in progra**ing that yo# want to do so*ethinga i/ed n#*ber o ti*es erhaps yo# want to calc#late grosssalaries o ten dierent persons, or yo# want to convertte*perat#res ro* centigrade to ahrenheit or '5 dierent cities

  • 8/13/2019 Computer Programming Data Structures

    109/594

  • 8/13/2019 Computer Programming Data Structures

    110/594

    1)) %et .s C

    Fhi%e !,nt ;= 3

    rint$ @nEnter a%,es !$ " n an( r #san$ ( ( $" B" Bn" Br #si = * n * r ) 100 #rint$ im%e interest = >s. $" si #

    !,nt = !,nt + 1 #

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

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

    The progra* e/ec#tes all state*ents ater the 0hile - ti*es Thelogic or calc#lating the si*ple interest is written within a pair o

    braces i**ediately ater the 0hile 9eyword These state*entsor* what is called the Dbody@ o the 0hile loop The parenthesesater the 0hile contain a condition So long as this conditionre*ains tr#e all state*ents within the body o the 0hile loop 9eepgetting e/ec#ted repeatedly To begin with the variable count isinitiali;ed to ' and every ti*e the si*ple interest logic is e/ec#tedthe val#e o count is incre*ented by one The variable count is*any a ti*es called either a Dloop co#nter@ or an Dinde/ variable@

    The operation o the 0hile loop is ill#strated in the ollowingig#re

  • 8/13/2019 Computer Programming Data Structures

    111/594

    Chapter 30 The %oop Control tructure 1)1

    ST1"T

    initialise

    test

    +alse

    Tr#e

    body o loop

    ST3

    incre*ent

    +ig#re -2

    Tips and Traps

    The general or* o 0hile is as shown belowP

    initia%ise %!! !,nter #Fhi%e test %!! !,nter ,sin a !n(iti!n

    (! this #an( this #inrement %!! !,nter #

    )ote the ollowing points abo#t 0hile...

    The state*ents within the 0hile loop wo#ld 9eep on gettinge/ec#ted till the condition being tested re*ains tr#e When the

  • 8/13/2019 Computer Programming Data Structures

    112/594

  • 8/13/2019 Computer Programming Data Structures

    113/594

    Chapter 30 The %oop Control tructure 1)3

    This is an indeinite loop, since i re*ains eH#al to ' oreverThe correct or* wo#ld be as #nderP

    main

    int i = 1 #Fhi%e i ;= 10

    rint$ (@n" i #i = i + 1 #

    $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#tedrepeatedly This is shown belowP

    main

    int i = 5 #Fhi%e i ain(r!s !n r!ses... #rint$ ...an( Fhisers !n ittens #a = a + 0.1 #

  • 8/13/2019 Computer Programming Data Structures

    114/594

    1)4 %et .s C

    .ven loating point loop co#nters can be decre*ented 3nceagain the incre*ent and decre*ent co#ld be by any val#e, notnecessarily '

    What do yo# thin9 wo#ld be the o#tp#t o the ollowingprogra*

    main

    int i = 1 #Fhi%e i ;= 32767

    rint$ (@n" i #i = i + 1 #

    )o, itdoesn@t print n#*bers ro* ' to -2!6! $t@s anindeinite loop To begin with, it prints o#t n#*bers ro* ' to

    -2!6! 1ter that val#e o i is incre*ented by ', thereore ittries to beco*e -2!6%, which alls o#tside the valid integerrange, so it goes to other side and beco*es

  • 8/13/2019 Computer Programming Data Structures

    115/594

    Chapter 30 The %oop Control tructure 1)5

    This is another indeinite loop, and it doesn@t give any o#tp#tat all The reason is, we have carelessly given a ; ater the0hile This wo#ld *a9e the loop wor9 li9e this

    Fhi%e i ;= 10 #

    rint$ (@n" i #i = i + 1 #

    Since the val#e o i is not getting incre*ented the controlwo#ld 9eep rotating within the loop, eternally )ote thatenclosing print8= > and i i ?1 within a pair o braces is notan error $n act we can p#t a pair o braces aro#nd anyindivid#al state*ent or set o state*ents witho#t aecting thee/ec#tion o the progra*

    ,ore (perators

    There are variety o operators which are reH#ently #sed with0hile To ill#strate their #sage let #s consider a proble* whereinn#*bers ro* ' to '( are to be printed on the screen The progra*or peror*ing this tas9 can be written #sing 0hile in theollowing dierent waysP

    a main

    int i = 1 #Fhi%e i ;= 10

    rint$ (@n" i #i = i + 1 #

  • 8/13/2019 Computer Programming Data Structures

    116/594

  • 8/13/2019 Computer Programming Data Structures

    117/594

    Chapter 30 The %oop Control tructure 1)7

    rint$ (@n" i #

    $n the state*ent 0hile = i?? J 1) >, irstly the co*parison oval#e o i with '( is peror*ed, and then the incre*entationo i ta9es place Since the incre*entation o i happens ater its#sage, here the ?? operator is called a post, i has already

    been incre*ented, hence i *#st be initiali;ed to (

    e main

    int i = 0 #Fhi%e ++i ;= 10

    rint$ (@n" i #

    $n the state*ent 0hile = ??i J 1) >, irstly incre*entation oi ta9es place, then the co*parison o val#e o i with '( is

    peror*ed Since the incre*entation o i happens beore its#sage, here the ?? operator is called a prea? Setting a loop co#nter to an initial val#e>b? Testing the loop co#nter to deter*ine whether its val#e has

    reached the n#*ber o repetitions desired>c? $ncreasing the val#e o loop co#nter each ti*e the progra*

    seg*ent within the loop has been e/ec#ted

  • 8/13/2019 Computer Programming Data Structures

    118/594

    1)& %et .s C

    The general or* o 8or state*ent is as #nderP

    $!r initia%ise !,nter # test !,nter # inrement !,nter

    (! this #an( this #an( this #

    7et #s write down the si*ple interest progra* #sing 8or Co*parethis progra* with the one, which we wrote #sing 0hile Thelowchart is also given below or a better #nderstanding

  • 8/13/2019 Computer Programming Data Structures

    119/594

    INP!bs

    Chapter 30 The %oop Control tructure 1)9

    ST1"T

    co#nt X '

    co#nt X co#nt L '

    is )oco#nt X -

    es

    $)T

    p, n, rST3

    si X p n r = '((

    "$)Tsi

    +ig#re --

    )* a%,%ati!n !$ sim%e interest $!r 3 sets !$ " n an( r *)main

    int " n" !,nt #$%!at r" si #

    $!r !,nt = 1 # !,nt ;= 3 # !,nt = !,nt + 1

    rint$ Enter a%,es !$ " n" an( r #san$ ( ( $" B" Bn" Br #

    si = * n * r ) 100 #rint$ im%e Interest = >s.$@n" si #

  • 8/13/2019 Computer Programming Data Structures

    120/594

    11) %et .s C

    $ this progra* is co*pared with the one written #sing 0hile, itcan be seen that the three stepsRinitiali;ation, testing andincre*entationRreH#ired or the loop constr#ct have now beenincorporated in the 8or state*ent

    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#eo count is set to an initial val#e '

    )ow the condition count J 3 is tested Since count is ' thecondition is satisied and the body o the loop is e/ec#ted orthe irst ti*e

    pon reaching the closing brace o 8or, control is sent bac9 tothe 8or state*ent, where the val#e o count gets incre*ented

    by '

    1gain the test is peror*ed to chec9 whether the new val#e

    ocount e/ceeds -

    $ the val#e o count is still within the range ' to -, thestate*ents within the braces o 8or are e/ec#ted again

    The body o the 8or loop contin#es to get e/ec#ted tillcount

    doesn@t e/ceed the inal val#e -

    When count reaches the val#e 4 the control e/its ro* the loopand is transerred to the state*ent >i any? i**ediately ater

    the body o 8or

    The ollowing ig#re wo#ld help in #rther clariying the concepto e/ec#tion o the 8or loop

  • 8/13/2019 Computer Programming Data Structures

    121/594

    Chapter 30 The %oop Control tructure 111

    ST1"T

    initialise

    test +alse

    Tr#e

    body o loopST3

    incre*ent

    +ig#re -4

    $t is i*portant to note that the initiali;ation, testing andincre*entation part o a 8or loop can be replaced by any valide/pression Th#s the ollowing 8or loops are perectly o9

    $!r i = 10 # i # i -- rint$ (" i #

    $!r i ; 4 # = 5 # = 0 rint$ (" i #

    $!r i = 1# i ;=10 # rint$ ("i++ #

    $!r san$ (" Bi # i ;= 10 # i++

    rint$ (" i #

    7et #s now write down the progra* to print n#*bers ro* ' to '(in dierent ways This ti*e we wo#ld #se a 8or loop instead o a0hile loop

  • 8/13/2019 Computer Programming Data Structures

    122/594

    112 %et .s C

    a main

    int i #$!r i = 1 # i ;= 10 # i = i + 1

    rint$ (@n" i #

    )ote that the initialisation, testing and incre*entation o loop

    co#nter is done in the 8or state*ent itsel $nstead o i i ? 1,the state*ents i?? or i ? 1 can also be #sed

    Since there is only one state*ent in the body o the 8or loop,the pair o braces have been dropped 1s with the 0hile, thedea#lt scope o 8or is the i**ediately ne/t state*ent ater8or

    & main

    int i #$!r i = 1 # i ;= 10 #

    rint$ (@n" i #i = i + 1 #

    ere, the incre*entation is done within the body o the 8orloop and not in the 8or state*ent )ote that inspite o this these*icolon ater the condition is necessary

    main

    int i = 1 #$!r # i ;= 10 # i = i + 1

    rint$ (@n" i #

  • 8/13/2019 Computer Programming Data Structures

    123/594

    Chapter 30 The %oop Control tructure 113

    ere the initialisation is done in the declaration state*entitsel, b#t still the se*icolon beore the condition is necessary

    ( main

    int i = 1 #$!r # i ;= 10 #

    rint$ (@n" i #i = i + 1 #

    ere, neither the initialisation, nor the incre*entation is donein the 8or state*ent, b#t still the two se*icolons arenecessary

    e main

    int i #

    $!r i = 0 # i++ ; 10 # rint$ (@n" i #

    ere, the co*parison as well as the incre*entation is donethro#gh the sa*e state*ent, i?? J 1) Since the ?? operatorco*es ater i irstly co*parison is done, ollowed byincre*entation )ote that it is necessary to initiali;e i to (

    $ main

    int i #

    $!r i = 0 # ++i ;= 10 # rint$ (@n" i #

  • 8/13/2019 Computer Programming Data Structures

    124/594

    114 %et .s C

    ere, both, the co*parison and the incre*entation is donethro#gh the sa*e state*ent, ??i J 1) Since ?? precedes iirstly incre*entation is done, ollowed by co*parison )otethat it is necessary to initiali;e i to (

    esting o8 Loops

    The way i8 state*ents can be nested, si*ilarly 0hiles and 8ors canalso be nested To #nderstand how nested loops wor9, loo9 at the

    progra* given belowP

    )* em!nstrati!n !$ neste( %!!s *)main

    int r" " s,m #$!r r = 1 # r ;= 3 # r++ )* !,ter %!! *)

    $!r = 1 # ;= 2 # ++ )* inner %!! *)

    s,m = r + #rint$ r = ( = ( s,m = (@n" r" " s,m #

    When yo# r#n this progra* yo# will get the ollowing o#tp#tP

    r = 1 = 1 s,m = 2r = 1 = 2 s,m = 3r = 2 = 1 s,m = 3r = 2 = 2 s,m = 4

    r = 3 = 1 s,m = 4r = 3 = 2 s,m = 5

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

  • 8/13/2019 Computer Programming Data Structures

    125/594

    Chapter 30 The %oop Control tructure 115

    ter*inates when the val#e o c e/ceeds 2, and the o#ter loopter*inates when the val#e o r e/ceeds -

    1s yo# can see, the body o the o#ter 8or loop is indented, and thebody o the inner 8or loop is #rther indented These *#ltipleindentations *a9e the progra* easier to #nderstand

    $nstead o #sing two state*ents, one to calc#late su and another

    to print it o#t, we can co*pact this into one single state*ent bysayingP

    rint$ r = ( = ( s,m = (@n" r" " r + #

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

    ,ultiple *nitialisations in thefor Loop

    The initialisation e/pression o the 8or loop can contain *ore thanone state*ent separated by a co**a +or e/a*ple,

    $!r i = 1" = 2 # ;= 10 # ++

    #ltiple state*ents can also be #sed in the incre*entatione/pression o 8or loop_ ie, yo# can incre*ent >or decre*ent? twoor *ore variables at the sa*e ti*e owever, only one e/pressionis allowed in the test e/pression This e/pression *ay containseveral conditions lin9ed together #sing logical operators

    se o *#ltiple state*ents in the initialisation e/pression alsode*onstrates why se*icolons are #sed to separate the threee/pressions in the 8or loop $ co**as had been #sed, they co#ldnot also have been #sed to separate *#ltiple state*ents in theinitialisation e/pression, witho#t con#sing the co*piler

  • 8/13/2019 Computer Programming Data Structures

    126/594

    11" %et .s C

    The (dd Loop

    The loops that we have #sed so ar e/ec#ted the state*ents withinthe* a inite n#*ber o ti*es owever, in real lie progra**ingone co*es across a sit#ation when it is not 9nown beorehand how*any ti*es the state*ents in the loop are to be e/ec#ted Thissit#ation can be progra**ed as shown belowP

    )* Exe,ti!n !$ a %!! an ,nn!Fn n,m&er !$ times *)main

    har an!ther #int n,m #(!

    rint$ Enter a n,m&er #san$ (" Bn,m #rint$ sH,are !$ ( is (" n,m" n,m * n,m #rint$ @nSant t! enter an!ther n,m&er /)n #

    san$ " Ban!ther # Fhi%e an!ther == '/' #

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

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

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

  • 8/13/2019 Computer Programming Data Structures

    127/594

    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 beacco*plished #sing 8or and 0hile loops as shown belowP

    )* !(( %!! ,sin a $!r %!! *)main

    har an!ther = '/' #

    int n,m #$!r # an!ther == '/' #

    rint$ Enter a n,m&er #san$ (" Bn,m #rint$ sH,are !$ ( is (" n,m" n,m * n,m #rint$ @nSant t! enter an!ther n,m&er /)n #san$ " Ban!ther #

    )* !(( %!! ,sin a Fhi%e %!! *)

    main

    har an!ther = '/' #int n,m #

    Fhi%e an!ther == '/'

    rint$ Enter a n,m&er #san$ (" Bn,m #rint$ sH,are !$ ( is (" n,m" n,m * n,m #rint$ @nSant t! enter an!ther n,m&er /)n #san$ " Ban!ther #

  • 8/13/2019 Computer Programming Data Structures

    128/594

    11& %et .s C

    The break Stateent

    We oten co*e across sit#ations where we want to Q#*p o#t o aloop instantly, witho#t waiting to get bac9 to the conditional testThe 9eyword 6rea allows #s to do this When 6rea isenco#ntered inside any loop, control a#to*atically passes to theirst state*ent ater the loop 1 6rea is #s#ally associated with ani8 1s an e/a*ple, let@s consider the ollowing e/a*ple

    Baple Write a progra* to deter*ine whether a n#*ber ispri*e or not 1 pri*e n#*ber is one, which is divisible only by 'or itsel

    1ll we have to do to tes