You are on page 1of 268
Data Structures Using C Second Edition Reema Thareja OXFORD UNIVERSITY PRESS ay 99% eee toe 862 ez est iz zr eet su 825 xp 229 siomsuy°9 xpuoddy 025 pos woneynayeg sseippy 4 Xpueddy 81g ou Suypuer an 3 xpusddy 91 wogo1y smydesor :q xpuaddy PLs Susesy2eg -9 xpueddy 21g vonoonag eBeqie9 g xpuaddy $05 swesBorg 9 w vonesoy Lowey y xpuaddy uoneziuebio st8y) pue solid “9 uotsio9 pue BuyseH “Sh Suyiog pure Suyyoives “y) sudep “ep sdeoH “21 saa yoreag AEM-HINWN “L} sea, Areulg We! “OL soa 6 senenp “¢ sy98S “LZ 53817 paxury “9 suojun pue seunjonag °s sbuis *y sheuy ‘€ suiyjuoBly pue sesmonas eye 0} UOREMPONUT "Z ‘9 0} uoHOMPONU “L Br wos ay oo 08 ent puooas auc eoeeid sjuajuog joug Detailed Contents Preface tothe Second Edit Introduction to C 1 1.1 Intodvction 1 12 Mee nd Keywords 2 13 Basic Data Types 2 4 Variables and Constants 3 18 TypeConversion and Typecasting 16 1.9 Control Statements 17 192 1.9.3 Brek and Continue Statements 27 1.10 Functions 28 Functions Needed?) 29 22 Classification of Data Structures 45 2.3 Operations on Data Structures 49 24 Abstact Data Type 50 25 Algorithms 50 2.6 Different Approaches to Designing an Algorithm 51 2.7 Control Structures Used in Algorithms 52 2.8 Time and Space Complexity 54 2.8.1 Worst-case, Average-cas, Best-case, and Amortized Time Complexity 54 282 Time-Space Trade 55 283 Expressing Time and Space Complexity $5 2.84 Algorithm Efficiency 55 3.5 Traversing an Array 77 3.52 Inserting an Element in an Amy 76 3.53 Deleting an Blement from an Amy 79 3.54 Merging Two Arrays 82 36 Passing Amays to Functions 86 3.61 Passing Individual Elements 86 3.62 Pasting the Entire Array 87 3.7 PointersanéArrays 90 38 AnaysoofPoisters 92 39 Two-dimensional Arrays 93 3.9.1 Declaring Two-dimensional ee Two-dimensionalAnays 96 3.10 Operations on Two-Dimessional Arrays 99 3.11 Passing Two-dimensional Amays to Functions 103 3.12 Pointers and Two-dimensional 43 Arrays of Stings 129 44 Pointersand Strings 132 5. Structures and Unions 138 15 Structure 141 5.1.5 Copying and Comparing Structures 142 52 Nested Structures 144 53 AnaysofStuctures 146 $4 Structures and Functions 148 /Menibers 19 19 56.1 Declaring a Union 156 5.62 Accessing a Member of 3 Union 156 5.63 Initializing Unions 156 5.7 Ammayscof Union Variables 157 los Inside Structures 155 162 New Node in reular Linked List 181 6.32 Deleting « No Doubly Linked List FT woqudiy sreysen, ¥ av seamig PytT 60> wyodiy speysnry € EI 20 wxppoy sag zre1 sop say Buuueds um E1 SOF Suiys08 yy wRd IsSUOUS gE] 0p Ba1u0g jeorBopod0), 268 ‘wyofy yamos 1g 166 HIG HEMEL (ET 6€ suguosty xoney, yaeID ey of wonsuasardoy SFU SoumeY eet 066 vowoussandny sr Aouselpy 75 €1 88 vouRUssiley 86 sudeap jo uonenosaidey set 486 swnoduog perowm0s ig yet 99¢ dep Patoag #J0 ainsoy> aanssumy, EE ge yds porsaug 2 30 Afojouruusy eee, sydesp “ey 646 sdeoy jo suonwonddy s-zy 6£ sdeoy woouogta touig ceurg Jo UosuRdN0) Zp yg sd03q1 rpoewogiy vo suonmadd Z¢°Z1 £4¢ sdeay poeuoges Jo anus FEL ELE Sdooy woeu0gE ETL 996 siv0H emoug wo suonesd9 7721 99¢ dese yoo Jo uouewosudoy payury 1ZZI s9¢ sdeOq jemom 7 bor sdeoy Ksemg jo suopeonddy gz] pot dean cou © wioy wowayg ue BuNPIeG Cz AX sono pov z96 drag Kou 2 yromaig aye SemsosUy 196 steoy Sremg Tz] soe sdeoH “z) SE OL STL ose say ez 8 wy wou we BuNA|IC ETT aS 30 ur uoworg AON 2 Buprasy HSE SOIL ut yuouogg ue og Buyainas ESE sau, ese ou, $e MON UI Ue SUND!C ZT GSE 9m He unwary MON v SUBARU [Ett Is SL4a C1) OSE soon, qosuoneanddy yzT1 oof a, 48 woy womr(g we FunapeC 9g au, qv ur wowrg MON e SumsOSUY Zz, OPE 201) © ur uoUDyy ue soy BuyouPES 17 SHE SOIL TH PAE sll, Yo1e9§ £e4-H4 01 voRONPOAU pre S044, youBag AemenINW “LL ru ore s2n, Ses 30 soeueapesi piv sodeueary 79 EE S20] Ads wo suonmedo 19°01 2e€ se Ads 901 dee som, spererpou yo someday es 0 of sy Jpeg p94 w SoHE Zs01 Sf SLL PUIELPEMyO sonsAdo S01 Af SNL PUIEEHOU S01 Zif say Tavue poy 09 Fnpses LIE. seL-TAV Uo SueNED’D L¥01 SIE SSALTAV OL HIE au, fooung popeany eSutssamy 9 soar Asie papesiul Cor A yor (eu eM pon iss8iey ap Fupury 6'ZOL S€ 24, 03095 ewig em 2pON wa[EUIS 99 BupULY gz SOE a. yote9s Aaeug w Jo anu omy om Zuputs 97D sug sonand yo suonvonddy ¢y eee snand dus FYR ce fF ‘coug eo fog Su Sean hag | Ave wo Spon 8 Bed COI 108 su 4oms Aang var ap0N HN BUNT. ZZOK og 334 ors Kew 062 SppasjosvoneandY L 22e Bong ad 9 sce wopendo dog 751 vee wonwsedg yng [SL fee wpaspoyury ew suaneidg, 5 22 Sms JovormDHtg POET FL Zee wonedo reed Cet ee wonedg dog TEL ze vowemous Pe ze ase set) CL ace SpesouoRMUDHIOY KY ZL 412 8PM oLvONEAPORE, FL sy9eIS “L 68 SDR, WpIO-IAIT PYG 69 ese] PpIOAEEA C6 892 psENeI LIHO-U Z¥’6 28¢ eso pean 6 18t MU Geog eBusseeL y6 BLE 9g¢_ 244 e213) rao sou, Gears Sane 6 99 S24 wouew9}, 9:76 $8¢_ Say wossaiteg 576 $8¢ Se Yomas Geng +76 8c S311 Keug €76 oe s82104 776 oz. soy ye2009 17% oe sexy 0 UK 7 6¢2 S@orouuwsy 109 | 642 von 1g wonewasaxdoy pruousio 189 661 SSFTPEAUT gnog se}IAND 59 : 161 $7 p9yT Signo. e woy 2pON BNApA zg suse pope, sol Detaled Contents 138.6 Modified Wershall’s Algorithm 417 13:9 Applications of Graphs 419 14, Searching and Sorting 424 14.1 Introduction to Searching 424 142 Linear Search 424 14.3 Binary Search 426 144 Interpolation Search 428 145 Jump Search 430 146 Introduction to Sort 14.62 Practical Considerations for Intemal Sorting 434 14.7 Bubble Sot 434 14.8 Insertion Sort 438 9 Selection Son 440 Merge Sort 443 14.11 Quick Son 446 14.12 Radix Sort 450 14.13 Heap Sot 454 14.14 Shell Sort 456 TreeSon 458 14.16 Comparison of Sorting Algorithms 460 14.17 External Sorting 460 15. Hashing and Collision 464 1.1 Intodvetion 464 152 Hash Tables 465 15.3 Hash Functions 4656 154 Different Hash Fu Appendix A: Memory Alloc Programs 505 Appendix B: Garbage Collect Appendic C: Backtracking 514 Appendix D: Josephus Problem $16 Appendis E: File Handing in C518 Appendix F: Address Appendix G: Answers 522 5r 520 Index 528 sion Resolution by Open Addressing 469 155.2 Collision Resolution By Chaining 481 15.6 Pros and Cons of Hashing 485 157 Applications of Hashing 485 16. Files and Their Organization 489 1644 Text and Binary Files 491 16.5 Basic File Operations 492 166 File Organization 493 a3 16.63 Indexed Sequeatial Fi Organization 495 167 Indexing 495 16.7.1 Ondered Indices 496 16.7.2 Dense and Sparse Indices 497 1675 Inverted Indices 499 1676 B-Tree Indices 500 16.7.7 Hashed Indices 501 CHAPTER 4 Introduction to C LEARNING OBJECTIVE ‘This tok ee ih iy of sate tough Bere gig in sled yi dat sucrose oe as consis oC Const, vais, pa and opt fenton ar ote, 4.1 INTRODUCTION UNIX operating system, ‘Structure ofa Program “sayquisa yo spubyatseq ow sods aBenBaey 3 ‘oH st ep 2 2:0 Sel tp toe a or SENDE a tgtUEN YTS, ro8 ‘eoneoo} asoys ap © 0 OAS aE ySuRUEaU! © SB POUYRP # ‘SANVISNOD ONY STTAVINVA WF dy rep soy Ae xt on paoue 184 sapun aw 281 1 An SHEA PIE Je pas aun uo edu Sq © ane OE S000 ‘puod aoe} ep 38m 94 sv pp 3499 0 SHELEA 217 SONS sun pup pelts) sagtoads us ons —Sioipot no] sod iuex> 103 52909 11OSV 00) kya 8 129.0 }OU SIE en 29510} pasidins wang =n Wa “i SuoapEN Wa9x9 (399 ‘yzeu vorenund so si212esey9 pyoads Au apy 9p ue sp] werBoud 2 u pow A1aN3, SQUOMASY ONY SUIHIILNAO! 2°b ion "2euanbos (uN ay:9948 01 Fup» paBUELE syuauals JO 4 Date Sirsctures Using € ‘Numeric Variables bles canbe wed to store either integer values or floating p 20d ues. Modis like used with numeric variables, The difference between unsigned varibles can only be positive. ‘increase the mariinum positive range; When we omit the eigned/unstgned modifier, C language ‘automatically makes ita signed variable. To declare an unsigned variable, the unsignee modifi rst be explicitly added during the declaration of the variable. Character Variables Char variables are just single characters enclosed within single quotes. These characters acter fom te ASCII character set—etes, could be a Declaring Variables To declare a variable, ays be meaning usage inthe program. InC, variable declaration always ends Constants Constants are identifiers whose values donot change. While values of variables can be ckange ny time, values of constants can never be changed, Constants are used to define fixed like ior the charge om an electon So that thee value does not get changed in the progr by mistake Declaring Constants ‘To declare a constant, precde the normal variable dee value cst keyword and assign it Inaction ¢ 1.5 WRITING THE FIRST ¢ PROGRAM. en a text editor ITyou are To write a C program, we fist need to write the cde. For that, op ‘Windows user, you nay use Notepad and if you prefer working on UNIX/Linux, you can use eng or vi, Once the text editor is opened on your screen, type the following statements as fest. [After writing the code, select the directory of your choice and save the () Thetwo curly brackets are used to group all the related statements ofthe wat Drint#("\n Welcane to the world of function is defined in the stato.» text om the soreen. The een is enclosed e brackets. isan escape sequence and represents anew return 0; valve 0 tothe operating sy there were no errors dr es with 2 san 4 pond won} Arora ssxppe 3 ou pana ay sess HON 448 aH en". sep 20 Jo ajgeres # oor ayquses 2x jo oueu 9 fq ‘soyguuva ig gossayppe a 2 Pt ‘sou usonfes a0} 01 posns 41g 8 2q 1H qidop uP MonDUn 9 ‘patois pu pours ov, osm ou Aq paras $0 ‘saypods adh gamed "Lage ut wan axe wor}ouy su2s 9p szoyrads ad a4 sn a4 ION} Peas oq or poroadea s suep sys nou sreapur ose pear 2q 01 Sty EN EP Jo-adA ay soytoods AA jonseyo ajqjusauooun we 20 aoeds ary stoynoou9 uonouny $9838 24) Jt BAONO}T ‘eos 990} Suose2eY9 Jo aqua wanuoUN oi Sods exp yusKM TE (aqyeao|Aaowow ant pasos ou) pasouB Inq wHeaNS ay OH pea! 29 pos EP exp soieoyp 5 Ploy wid 9.30 WouNLSseSassaddns yay uous yeuondo Ue st « 24s [sourpou] (099) “se uang 29 wes uns omsog oo adoyod oy, vue’ ‘etoe “xave quatre 21p &q parted suoreo0) Azouur ap w paxrs pue pioogke ‘2 wioy pourage aq 0 sey ey etep ax fo Tumey pax ad ap samioads Bu doe ee “eae “Taunus 10 ‘se uaa aq ve vorrouny (osteos ayo xen a “pg fo4 24 HoH rep panes peas 1 pasn S| wopaURYC)9¥e25 9B susfxd ay Jo SurBaq ap yauaWs Huo a4 TIO su USING snanopnda pops soen purify Seg dng pEpURS se NOK Amato Dre sony ost SuoIo anon po AueD eo peop 2) suONDUN AL a pani ioe pt ao! 7 JUD oy yes Spas eM posts] woo jst woud og) $PreooAay oy woy Hp spe ey oy pound tee a8 0; a ‘ajdutexa 304 j=, soezedo mousse agp Sus sajqees 01 sone ‘1 axoys Sy “aotaap indino preps w ot kesdeud ain Aq poonpod exep a4 ‘nda prepuess © wo sages snd idsooe os ureoxd 3 w ur wore fi ‘suorury mine pue ind pozipsepueis sy 9 suonsuny snoauyy pasta 210 15: 4 suowouny Bumpuey Suns 3) + 48 ‘9pnyout soy s9peay prep out axe siysdwoa 2 je Kq papinaud ay) ou iow op ay, sar ayy axouo4 PU i an 'SBuins om) soreduio> say Jo so[duegsqy Jopsay puspuns ws Ssuovouny yong "BoM Suonsy s5aH1 noy 30 swouinsze Sats se 304 50.4 vont ou. ‘uy ang “jy 29pe0y 2 Bana 29 ‘4 pauyp st yon ‘uonduny (43472 pose aamy aM MU ‘Soll 12p09H prepuers dono yuowour ay meson Jo aes an Suuyop ut do si, S90pursBoud ay en 906 ssa «jo dora ye wau09 & ind shane 0 G64 pood W198 MD Se pst tion a}gopumsz9pun poo a ayeU or SuesBosd ut poppe Ah axe Aan Se jon Posoult xe Aan, sayy aapdweo xp Aq pasaoxe ou are LIES OURO Ie SN (ansousmod ar sis}reyo 204) uoDH 249 stuousieS pu Ue papuD st 4) ysIuouDyES adq|aU! HoREIOD O1 Posh st 4) © ‘waUDyeS BUS v HOUND OF PASH Sty) « sustatoo jo sad omy stioddns 3 ‘soop ursdoud «yn Sue] Jo fem e ye uso swwewuog busy “SpE alow apoo ay ‘4005/5 8a an wo ene povou 0 pawopu Lang aay sunUS ws PLE Rd 340 tion a 03 aston “SHRM wa. to poeydp ap wezdd ajo nino aay xu 04 ay wots Banna esa yXINA 205 ‘Sd fy roan a we ayo Wm Edo ay pu pander 99 ub Pua] 2° sno Udo 0} pao no 542049 a 2 yoy bo pus ape ney nok (ye eG Mo “westou yw soy uw as simp wend > nok apo 01 Susp semanas ng 9 nine scan tucton. peint#() ‘The print fiction used to display information requized by the user and also prints the values printf (‘eontrol string”, are,ares ‘After the contol sting, the function can have as many arguments as specified in the contol string. The control sting contains format specifiers which ar he order so that thes printed such as readable. re ist be enough arguments because if there are not enough arguments, then ‘he result willbe completely unpredictable. However, iby mistake you specify more number of. arguments, the excess arguments will simply be ignored. The prototype ofthe contol string can ie given as below: {tags ]Iwdeh){preisten}fnodifertype Each control string must begin with 8% sign, fags i an optional argument, which specifies output justification lke decimal pont, numerical sigh, tiling zeros or cctadecinal ot hexadeciaal prefixes. Table 6 shows diferent types of flags with ther descriptions. Iniraducton 0 © 9 EPEEEE | PEPLe er printf. 90 prineecomer, 4.7 OPERATORS AND EXPRESSIONS en a ferent types of operator, which ean be used with variables and cons Raaa ae tors Tere opestr tn be exter in the loving mao Tou: . «Relational operators «Arithmetic operators + equality operators 1 ray operators + Bitwite operators their syntax, and usage in C language. Faule 17 Ahmet opens operation [__Sterator nantly ‘width isan optional agument which species the minimum numberof positions that tke output characters will oceup. Ifthe numberof output characters is smaller than the specified width, then the output would be right justified with blank spaces to the lef. Howe poi umber of characters to print froma string ‘modifier field is same as given for sar) function, {ype'swsed to define the type and the interpretation ofthe value ofthe corresponding argument ‘The ype specifiers statements he rls of © tango enclosed in the quotation tobe displayed on the screen, For oa x= 800.76 the following examples show output under different format specifications muee coe. Cele] ofol[rleLe ‘sand (on which the operators applied) ae called operands. Arithmetic operators cat be applied to any integer ar floating point number. The addition, subeact ‘and ) operators are the wsual arithmetic ope Tire the operate % gt be newt you The mus operator) finds he es) ofa tger vision. This operator can be apie only on iteger operands and cant Be we le performing modulo division, the sig of the result is always the sign of te fist operand (the dividend). Therefore, performed as alvays xvod sxgaud @ uy “xyfsod pu 70 “anyea sane ser soap Gory Semod9g aera ep ‘reun Bastdde 20yy nea annjsod vsayajqeuea aneoq or- = © s1uossandxo sty jo sayy, soeiodo wote109p pur uaua!5u Suu eum ‘aie Koy, soreod Asean sony suoddns afentun 3 spusiodo aus wo ine suovezodo Areap, sioyeiadg Aveup) aynsos ap 20194 “9.01 poudisse st 3 Jo anjea ayy 0 = #1 oF + 99 8S. '9 = @JO-NIRA 9 HON, LON [P0180] 30 91g ge ay “182 ' ssonpoud poe anyes cua szonpoud poe uotsaudyo aya av {o a) WOrRafo)oeme um uF AREL ) 4a ve01607 > pur e wom syed st a2 ans axe suoiscoxda og J uo any st worssoudea ojoyy 2, Ce ware “aydume 204 ‘e200 ue sna wigarsireiedo(euone|ay suoIsaudyo ‘om ssoo 1p aves oe 1 owado uosreduoa w se unouy ose sown ft sioqune uted Saynoy ue re sputiodo oq slog fees deumne io sored seymour 30) 2043 untad vos oe Parnes ou fg un hie app ea 12 Data Sowenes Using C equivalent o writing equivalent to writing ‘operators. Andifinan expression we have move than one unary operator then they are evaluated from right to let Conditional Operator ‘The syntax ofthe conditional operator is ‘twise XOR ‘When we use the bitwise XOR operator, the bitin the first operands XORed with the conesponding ate 113th blo bie XOR is | and 0 otherwise. For example roo1010 * Bitwise NOT (-) ‘Shift Operators CC suppons two bitwise shift operators. They are shift left (<=) and shift ight (>>). The syntax operation can be gi operand op a ‘where the its inthe operand ae shifed lef or right depending on the oper ‘operator is >>) by numberof places denoted by nun the statement on i Jo stowed 34 veg savepace.g soeredg s0eds ae 1 3 103 0 pty 236d see ep JioHEND 8 Jo ess ast term 2 Kg puta snk 0 Uo PUE “a sjuouaiouuoyp“e syuowsou thes 1040 shone ogoromeyes em ato tan oye nan | 10yezado eumUHOd ay ‘sroyesDd0 aL = " wongta sor Per a og pure age oars 0) "oa a0 spuaiado om sy oqeod0 ries oat OED O81 51 YotGe emiodo euWOD 24 eronan suonex(sop ajgetea Surnonoy ap aay any) RENEE] SON ueyg e2uepeaaig ayy Ouysp suorssavdxg jo sayduery vem aovipzedsiojagy gy ane se poreneso st nat for=> ease soedo Busy 9 SE 2 or wowonpaunuy ens 16 Data Srucrars Using C 1.9 CONTROL STATEMENTS 1.8 TYPE CONVERSION AND TYPECASTING of variables refers to changing a variable of one datatype into ,castingasto be done: Type Conversion i “Type conversion is done when the expression has variables of different dat types. So 0 evaluate romoted from lower to higher leve where the hierarchy of data Typecasting “Typecast also known as forced conversion. Iti done when the value of one datatype has to beconverted into the value of ancther datatype, The code to perform typecasting can be given as: at) salary: point numbers are converted to integers the digits after the decimal are truncated, when floating point representations are converied to integral representations. n datatype has to be converted. Hence, we conclude one data type to act like a variable of another corresponding floating point number. $6 ts = s6.o00000 ‘Tillnow we know that the cote in the C program isexceuned sequentially tom thei line, Thats, the second statement is executed afer the ist, the (ed statements tbe exceuted, Control flow statements enable programmers fo conditional exgeute a particular block of code, There are three types of control statements: decision e oping), and jump statements. While branching means deciding whet astions have to be taken, looping, on the other hand, decides how many times th action has 10 De taken. Jump nsf 1.9.4 Decision Control Statements CC supports decision control statements that can alter the law of a sequence of instructions. These Ip to jump from ane part ofthe program to aniher depending on whether part used indecision making. [om |S = |S || The 4 block may pression is evaluated. Ifthe in an s¢ block is any valid C language that evaluate ues 919599-47 40 xEuhs 1 Big ur usa sp owes $8-25T2-3t : Sana 24 po ome oa eu idm, ¢ “ane 8 rwowones a5 aduis © Seasn ue 251)» suas Uossoudy9 1p wn Susi fe hina ns seta ster sipe im tant eucie wo kan Sue ag 81) st uorssauda C1 8g opus ey parprs a8ey agi aways @519-57 1 UoHo poinaox9 99 st urestoud sip so yadyno ay. "usots ay to p 1 staement is mult-way decision statement that isa simplified version ofan if- statement is shown in Fig 1.5. Figure 5 ‘The power of nested 4s expression in * When there is only one: ‘+ When many conditions are being tested for se statement matches, the statement block of fitch case statement? Dé 3 the variable doesnot match with any ofthe se is executed when no match is found berween the values of ere are no statements tobe executed. Although the defi always recommended to include it sit handles any unexpected case. iatement, we have used another keyword break. The and execute th to breakout ofthe ea ‘Advantages of Using a switch-case Statement susteh-case statement is preferred by programmers due to the following reasons: + Easy to debug « asy to read and understand + Ease of maintenance as compared to 1 Like ss-etee salem Enter ny character © kona sone arena oF wrod 8 a, 257 souoaag worspv0e 2 24) doo ext ay sams ‘doo arr e Buin szoqumu gy 81g amp sw apo9 Burmoyfo 29 “aduex9 204 2]qeIS99 ssiou st gory doo} soyur Ue ORE un ‘si Stuo29q Jona Buoy se anna i, Pu2 [Tn doo} ayy ways sure yorya uompuoo sist “Joo| ott» 24) 50 ‘woutpuoa agi arepda rweysuoo oy paou am reghseofo t's" “lg Jo WHIBHIP wy 24p UL 019 doo] arr9# a4 4 yuowtoyes on dun ys ona a 2s St wp U9 a Squauoies ey usp uo “enn St Uompu ay 3 -pRDeND St 2019, p30 Aue a1ojaq poser st uonpue> amp doo] ate ay UTR SION, pismo uowoyesoyetpour 2 8D o1uoHRpa enasuoa doo array andi mane awe f doo 114 Jo wy 2u28 ywuton ious 30 au0 ada wonpuoo, rome a sways 259 SSMS U9 00 are fay, “suauzss ‘sudoo] se unouy ose swuauayns aanesa so sod aa syodns 3 “spe Sauooag vorssaudta pyinods ua yun sowie jo 2ouonbas ojo wonncaxa sip adas post ale UD siuauarers anne 3 Ban samonas ong xe 2 Date Srctrs Using © =] | syntax of do-shite Loop | sescenee ick « paste the Conair ‘ “Borestion > waite statenent ys me Nero Figare 1.7 oo-shsteconsvuct, Note that ‘est condition is enclosed in parentheses and followed by a semi-colon. The statements in the statement block are enclosed within curly brackets, The culy brackets are optional if thee is only one statement in the body ofthe do-ste loop, The do-wile loop continues to execute while the condition is tre and when the condition lowing the do-wsite loop, ‘Themajor disadvantage ofusinga co-wsite loop is tat it always executes at least once, so even ifthe user enters some invalid data the loop will execute. However, ‘used fo pina list of options for me code, nese esto.» sin) driven programs. For exarapl, ct 6. Wate progam the avenge of fst numbers. Sint wain() = ‘ fost avg = 0.05 as rSnte("\n Enter the value of # £5 Scant, 88) & ‘ mien © what teen) * tsi; pelnceCyn the sum of Best 34 nurbers = Xn, suns FoLneeC"\n The average of 6st M4 rurbers = K2F", n, aves return 0, > Outpat SURE nln of 90° ecu r e ) ars = 0 OREN Shr amet 08 Loe ee ee tot for Loop Lie thse and o-wsteos ew The tyne gener om of foo is ena ig il apaicular ar oop provides a mechanism to repeats initialization | Laop Variable ‘ymax of for Loop Controming candstisn or Loop for (inititszation; condition; tyrtante Encrowent/derenant/upante) d Peatennt ys c statenent blocks | | paste the Figure 1.8. for oopoorstuct ‘When a for loop is used, the Ouyen yt eyoroas santa ‘poo farmoioy 2m toptsuns'ayduev9 104 “xquer doo) req sgsne yusuEHES Brute a oo] sos © angen pane ‘sop eq 9p09 a 0: ‘saxamop worse ‘aq pr dooy arr a “soy Busojoua ue nog tuo oWAIRS BT 3L8D o HUSDIES 989283 ojoo.quas 849 pao sow ap Jo uoqod paddeys are door. 2p ue doo] #50 §p09 snus pao a ant ojduns ab sxe “do oo-doo| ai 2 pau dl Su re uocyes anus2e03 a uD. Yeu 993901 ouayes anur3u0> sy Bessey Kp0q ung rod fue wou dooy x yx9 or post doo ar xp Suywoyfoy owores 2p 0 sun jonuoo ox pus poynaexo st yaousers yea.m a‘ 0 fonbo $9u1099q +S OOS SY nding pe.) p0Ta i} 0} pass yuBUDTES E09 yoy uy ou ap SOS 80} UDA oxLDL uojoo as » 49 pono} e019 prong ss nf jdt a0 1 xouks sy ‘sade woumsys e009 241 yon de pwuausies ap 0) assed oso a oan e249 soyuno2U9 osn djopu stuounnas equ waWN ‘ony ut doo} ousayeys 42939 ‘Stuowayers onujeog pue yeasg ¢°6b 1 Jeworenpasny Se “mu sae Te nding, ‘ fo was anu “toque sad © 55 pe warwtad Hew *weaqnu aytsodion © sy 9 WA)sAUSE = ena ‘ Feog , (0 = yam )s5 Suuauato doo 41 Bumepdp,-parepdn aq anu 2iqetea doo ip owes one ‘24139 oF wontpuoo 24) oyBus scWs doo, a fo rE 1wada1 0; anunuoo pynoys 28 Data Sractres Using C encountered, 0 the (Statement i skipped and the control ‘estcondition ofthe loop Its generally used to restart satement sequence wien an eror occurs, 1.10 FUNCTIONS Serre mee ee sete rata ecco ee i it ha oan carn is completely insulated from the other functions. aera any other function. Fr example, look at Fig, 1-10 which 3g another, andthe other Funeton in tum elling some other funtion SEE Figure 110-Funcon aing anther tncon ode is meant to print numbers from 0 to 10. But as soon as 4 becomes equal lement is somewhat the opposite ofthe beesk statement. ke place, skipping any code in between itself andthe Introduction 9029 110.1 Why are Functions Needed? Let us analyse the reasons why segmenting a program into manageable chunks i an important aspect of programming. ‘Dividing the program into separate for one big function. + Ifa big program bas tobe developed without using any funtion othe than a willbe countes lines in the nin() function and msintsining that program wil be diffi task, + All he libraries in C contain a set of functions that the programmers are free to we i programs, These Functions have been pre-wrilten and pre-ested, so the program tse them without worrying about thet code dels. This speeds up program development, by allowing the programmer to conceirate only on the code that he has to wrt. ‘Like libraries, programmers can also write ther own functions and se them from diferent points inthe main program or any other ‘+ When big program s broken into compara ‘working on that project can divide the we 4.10.2 Using Functions ‘A funetion can be compare to black box that takes rocesss it and then outputs result, However, we may’ any inputs a all, ora fnetion does notretur any value at all, While using functions, we will be using the following terminolos * A finetion fthat wes another function gis known as the calling function, and gis known as the eae function. «+ The inputs that a function takes are known a arguments. led function returns some result back tothe calling function, called ‘body of the funtion coat Function Declaration Before using a function, the compil parameters that the function expects to to make a check onthe argumens used “The general format for delarng function that accepts arguments and etumns value ‘canbe given as return datsype function nare( datatype van Here, function none that are followed (eu (p= vorszuny 23 BATTED auojaq anu 40 angen 2uL Mw, aM Coren 9 ser)ore pron po.oyes 100 Bi "moyRq uaa apo 24p s9pssuoD “daoUo SA puESi9pUN O] ss]geures ain jo Xdoo 240} ape ae so Buoy ow unopod oy uous yerse a fo Ao wsosn oH passed sjuuiie oo anjen a4 9301801 syqetea mou sqea9 to) anyen Aa 1189 wotoury kg passed ane sojgeuea jo sossouppe ayy souauayar qe) 9.4 0} wrung Bae ‘onsuny pores ay}oyWonsunj Zure9 ap Aq passed ae sageuen a josonyeaaqy, ayes ren ouvir woxiswni//—‘Gur)ppouone groves enue notny Sutsn pp so wana st socumia 2 oIpoM py oO weMBoad LIA "8 1 De1wovonpauny HO "roqgenuen “rajgetuentouee vorzany = sueu"sreTseh 889» yons u"NoRDuN paje> ay 01 Suossaudxo Jo wtuny op passed 9 a ssjqeues yo (sad Po a4 oF oR sessed joven wesfoxd aq) ‘pEIND2x2 st Ho died © are yep squowin uy uonouny 2p sayoaur OWT ajo 29 9940 “wouoUny rey sn payoaur uo oars eouenenumas “ > Cooraraersen oft even “rotates 266 raepawesuapanny Ode MED so wows? ag uno uorrusop wonaury 30 vey 24), ‘Kp0q vonoung « :9proy uonsung « sd 043 jo sosudiuos 120d gauyp s! uonsuny #134, ‘wong uonsuny ‘onguyop uonoury y As : jefe yee ow were S24 Bore veo pus ame ue um ou wi una sep et oY. TOTS "88 si uuoyad oy sydoooe uonouny papa ain ey surouresed Jo sound no0] ose ae Kay ona ny Bea ayy wo passed ave sojqeue as ‘sed wp poyods jo sae, ZoTgeTUEN adh" eep “TOTgETIEN 24K“) ‘wonuy porto out Sq pouuopodBursoo0ad a 40 sos # se ei one ajo 24 rep am sagtoads aA exep-wamaos ‘wong Buea ayo pousmas Busy semanas (Vn The value oF mun after calling the function =e", num); etuen 0 > vod acne 9) ‘ nen 105 Drinté("\n The value oF mum in the called function + Rd, 0); ‘+ When arguments are passed by value, the called function creates new variables ofthe same datatype asthe arguments passed tit + The values ofthe arguments passed by the calling function are copied into the ney created variables, ‘+ Values ofthe variables inthe calling functions remain unaffected when the arguments ane passed using the call-by-value technique. Pros and cons ve technique is that arguments ean be passed as rawback shat copying data consumes additional to copy thereby resuling in performance penalty, ‘specially ifthe function is called many times Call by Reference ‘Whes the calling function passes arguments to the called function using the call ‘he only way to return the modified value of the argument to the caller isc fetumn statement. better option isto pass arguments using the eall-by technique. In , we declare the function parameters as references rather than normal variables, lone, ny changes made by the function tothe arguments it received are also visible in the calling function, an argument is passed using call by reference, an asterisk ameter ist, *eference metho function receives an implicitreference tothe argument, its value. Therefore, the function can modify the vale ofthe variable and reflected inthe calling funtion as well. The following code illustrates this The valve of sun before valve of fun after ci Vota atating %0) Introduction 938 1; 18 The value of sun sn the called function = 24°, to; ‘Output “he value of mum before calling the function = 2 ‘The value of ru func ‘he value of run af ‘he function = 32 tates . adreniags of wing the a-ring ing mene 7H, Snow rgumen oe mi cod the new rae ove renter nea Se « Thefmaon an chang thea of te argument andthe ching etd in te cing finctn + A function can return only one value. Incase we need to return those arguments by reference, so thatthe modified values are visible inthe calling Disadvantages However the rebckof sng tiststniquls th inavertet changes cassdto vals in called function then these changes would be relected in calling funetion as original values would have been overwritten. ‘Consider the code given below which swaps the value of two integers, Note the value ofintexers inthe calling function an called function, J aR 3 34 I EAL ‘ams Buia Sas 0 yeast 6001 9004 4001 9004 S001 F001 _G00b 1 UY Baa jfa9Krouur 24 ZpIsUOD Ad oyu aM Jo sUE}UO agnor en saudoo pur ) nent a4) Sona snerado #2 °*J0SSouppE aM pouBisse sae yuauaqes ie an uy 2qget7 qu Ue,o1 sod, ‘soja oygpEA suo seayu Ty gens 2980) ue Jo Ssauppe ay) a3 1149 Saytoods aut ax pe a}gerEs sod w yd et) s9u09 219 suogur 94) 2jqeuEA Z2yuOd a yo weU aN Std uoWDyES >.Oge OM “spoo weiBoxd sno ur Suis psp ajgusen say J9 82. we arnjop sn] MON “uns oy Su}08 stapes ayy axaya uo; aM Uo puadep EA. ‘dna Ky a0eds yous Moy He IOWA 34 Ut 29eds jo ROWE UNE 9p Kdn290 8 AND ‘sedi wapyoazyp 0; 010d (ays pew wn) synod any 8 YSU 94K mp poytoads ‘41 jo aqgauea © 01 aod 0 pasepap s aygeues squid v siueUazEs aAoge a Jo YEO UL “sexo e401 od sono 2 ye ayes 4 Jo 9 ep ay 28 ene 0H, Inve ndy 24617007 omaaq ewan 09 ue Sqqes uted Supp Jo KES 093 94), ‘Saiqenen sequiog Gupeweg PLE E (suridoad 2 u wopesoye ows 0 y mpooddly 238) ajgeunae J YontDoje romans au 205 pase ate sag « wee ‘yoeis peyuy “isu pay san se yons ssunocas ep xapduoo sons {SM soos 34 suoLnBe wojny se Bus pus ska seed oy posn (ELE Ue Jo siuaUtoy pete spat ou S909" 0 Kem sHeuDHS U8 aprnoud Ssauiog “jou unuesfond 29 oyqoussiawiog » ope ssed 01 post aye sotuiog Sogn sou # un tay gp ar um stony ona gj Yong on smn jo om 24S se9 upto ~ (pou aouainjah 8 TE Tea pur z =e - (roy ob 1.11.2 Pointer Expressions and Pointer Arithmetic Like other variables, ointer variables can also be used in expressions. For example, if ptt nd ing statements ae valid nt nant = 2, nun = 3, son = 0, ml « 0, ety nt tote, eps pera» bunt * (spteDs pteay/(tr2) = 395 nC, the programmer may ad intepers oor subtract i pets om po as well as subtract th the pointer variables as we weexpressions. For example, ‘operators have ge equivalent dereference operatar (+) Therefore, the express greater operator precedence than *. Th ‘ow points to the next memory le atement *pervs doesnt do the of te variable whose address is stored in pt, 1.11.3 Null Pointers So far, we have snied tata pointer variable pointer toa variable of some datatype. However, in some eases, we may prefer to havea mull pointer which isa special pointer value and does not point to any value. This means tat #11 pointer doesnot point to any valid memory adress, To declare a nul pointer, youmay use the predefined constant wa which is defined in several standard header files ‘stelim, and «strings, Att inluding any ofthese files in your program, you can write ‘You can always check whether a given pointer variable stores the addres of some variable or contains wut by writing, 36 (ptr = MLL) ‘ sea pointer @ ml pointer by using the constant 0 use mut to declare a when itis unable to rsorthe generic variables of any datatype. tis declared like ' normal pointer varible the vod Keyword asthe pointer's data ype, For example, ved ptr: In, since you cannot have a varsble of type vse, the void pointer will therefore not po any data and, thus, cannot be deeferenced. You need to cast avoid pointer to another kind of pointer before using it ‘Generic pointers are often used when you want a pointer to poi ferent times, For example, tke a look atthe following code. nt moun) ‘ to data of different types at 1 Genenic pointer points to the Sateger value = ay *Cint*)en Generic pointer naw points to the characters Ke", *(ohar*)ep): > Output Generic pointer potas to te snteger value = 10 enerdc pointer now points to the character = 8 is always recommended to avoid using void pointers unless absolutely necessary, as they ly allow you to evo type checking, 9, Write a prograi to add two integers using oilers and fumicions. nee tao. ney St $80); prineé(°\n, Eten the fost munber EeantC%8, tuna) anctour, snuma, &tota); Total = 6", totaly old sun (Int ¢2, Ant tb, Ent #0) c d Output otal = 57 4.11.5 Pointer to Pointers nC, you can also use pi ‘ua om ppe o pao ax “sand oy sumed 209 of | re ep sou sm aoauea Aue 0 0d ou | sop yi aqgets sod yesads © 1 Ka ut aise my pao ase. voNDTY PED =O. "sees ue 90 our umd on ae woe AEMETS nen A i 305 209 | sigan ag feo voy 2904909944 | pasonoy worauy ap soep ip Ape oxcuny | sos ‘par ayo am to aoa wonoON 6 Dorwonmpony Supsada oy sup stuosaaueoad aA, =a peor pada uns ys sy a MEP ns gays or posnspesade Kane 909215 ‘aang sano} ‘ny ojo euto9 ‘sada pe 20007¥ que dui van yo wauaysuc9 s.ouo soanposd iuamajduioa 10 dyes. ‘aso ne oy Seay PERU ty aouopooaid samo} anny sioseiado spueado 2109 20 04 uo ou pe oyu wo po 2q v0 we) sored "aojeedo joa pu euneoo uous 1107 01s paw susie 5 uD OILED KrouauumoIEUR UP O} Aun s Hd quod 1 proto 2juod wasn nok ‘fseutoom pasa seam soyqeua 2 ‘pos Buymory ap s9pIsu0D ‘ydexD 304 40 Data Strucares Using © 4. What do you understand by Heaters and eswond? ‘plain te ters ables and costs, How inty typeset vibe spore by Cr 6, Wie dos the dia of viable igi? cash note on Bas dl pes aie C lange ports “ Wy do we ce tio in pips? ata ele Epa it gence. ets on pit and scan fino shot te on Operas avaible in C tang 12. Draw he oper preedence char 13, Dilferetiate between typecasing and type ison onl Salemtete Explain in 18. Dierentate ftwcen fiction declaration and function dfn. tion dsmtionsiterent pled roe tofncton dfn? between ul pointer and 24. How are generic Aires from pointer variables? 25, Wit sor note on pointers to pointers Programming Exercises 2 Wicareanm opine naan mates between 1-200. Also rit ther sum, 4 ates roger Hosting poi un, ‘Display the rightmost digi of the integral part of | theronbe, aul 7. Wie posal sil tees and conpomnd eet 4 tea pognn clots afatnlyee siven his Base ay (0 be entered y Bes), RRA IO%otaebsepy, TASK tts uy. Dele As Theo em ‘tis pachasd and its pie por anit the bili aefttowing fora four decimal places: ad (c) comectto ight decimal pes 4 program to find the smallest of three sng fonctions. 14 Write 2 progam wo caleulae ares ofa tangle sing fection 15, Waite program to find whether number is ing functions. Progamming in Cis 18, Write program to add thee floating point should coma only wo digits 2, Waite « program w display sum umber frm 199, Use fo loop. od umber from me at $5. Which ofthe following isthe cmesin chance aswel wit shot integer? bog soy ean ‘afer sand gp 3 ut SmUEBoud yo 1.9 u suesBoxd 3 JAu93r80 ONINEVAT swuyjuobjy pue saunjonys eyed 0} uoHONpoU| Z waldvHO ony psa or uonauny Sues ak | Passage aqyossampe ‘pouty “1 ir JoYSUED voNREpsonsuny “07 se waouy ae soy von 4 en san UL “6 | seus voouy agony sane “eee 2a 09° gen 2 0 Suumjsap mu ape 29 Ue afgeen ¥ “TT ‘asa 020 0S BPSD —— “TH 1 a sp 8010 9 “OF 1 an wo HEP So BoRAURY—— s ‘ong Sumas wines 49 Kpoa a gy psmsap 29 Ue MONE ON, Teao st wonouy jo e094, we aouoposod any any 08300 5 ss 46 Daas sures Using © ‘Data structures are used in almost every program or software system, Some common examples of ota structures are arays, queues, stacks, inary toes, and hash tables. Daa structures are widely applied inthe following areas: 4 Compiler design Operating system * DBMS + Simulation ty DBMS asa subject, 3 jer sens inde Nv a es raph era dat model nes ed RDENIS ep Spe stars cueing of many efisenaguitecer ty ee he penis tomnagehge sna antienty Se at deog ee {nd opuning ngage cops aa sce tal ignite ee, {ornate en This ca epennig nates eee sins The may Bu ofs programs sae hts pon aia A itoson snr ntnaton wach Del ane apliton os pope da rt proves the st eticint sition A solution i sd tobe effin if ave the pablon weer ress cin ike heal gcc avalible sta cast An betstslons bone reqs eae Morover te coast se anountotiaeaes Bosal essed in ms oneeytnuce nc euiain mee tober nome conn Totty compat: propenne do eto gn: or sey tons be achivd adn ink ens propa dates ete ea png dies wih por inden ea tac caep goat aoe, {Ejl adnate wh whitey cn work confauby Nc spaoian tes Sereno or be poe st hed and ie may nt oes eae rapedel ope troguh ec sperm: ols ih nce atin, sto ply anthem daa sacrosanct amv aves ple. he lonngsepr mae te shite ptonderin econ 2. Qanily erence co the performance goals meets these requirements. Thisthte step approsch to select an appropriate data structure forthe problem at hand supports ‘a dat-centred view ofthe design proces. Inthe approach, the first concem i a are tobe performed anthem. The second concer is the representation ofthe daa, ‘andthe final concern isthe implementation ofthat rep a " ‘Tete are diferent types of data structures that the C str may permit adding of new data items only atthe beginniny beadéed at any postion, While one data struture may allow acces the other ay allow random access of data. So, sel 2.1.1 Elementary Data Structure Organization Data stretures ae building blocks of a program. A program built using improper data structures ‘may not work as expected, So asa programmer it is mandatory to choose most appropriate data structures fora program, “The term data means a value or set of values. I speciis either the value of a variable or constant (¢., matks of students, name of an employee, adress ofa customer, value ofp et.) While a dat example, last name—but ‘A recond isa coll obtained are indivi record, ‘A file isa collection of related records. For exampl data items, But all these data items can be grouped together to form = a class, then ly, we the customers of there are 60 stude there are 60 records ofthe students. All these related records ae stored ina file. can have a fie ofall the employees working in an organization, a fle of company, aie of al the sup Moreov 5, 90 on ado forth ‘each record in a file may consist of multiple data items but the value ofa eetain ein a student's in such field ae called keys or key values. Forex umber, name, address course, and marks obtained, the field roll number the fields (name, address, cours, and marks) cannot serve as primary re students may have the same name, or may have the same adres (as they might be staying athe same place) or may be enzlled in the same course, or have obiained same marks. This organization and hirarchy of dat structures, which is discussed in Section 2.2. is vaken further to form more complex types of data 2.2 CLASSIFICATION OF DATA STRUCTURES e and Data structures are generally categorized into two classes: pi structures, Primitive and Mon-primitive Data Structures ata structures ac the fundamental d basi datatypes are integer, nt primitve datatype are ofienusod interchangeably es which are crealed using primitive dats ked lists, stacks, es, and grap data structures Linear and Non-linear Structures 1° ty u waoys onanb ap sopisu0r -Ajaanndsa poe suonsjp arya wos, ono ep P29 we suo eos pu 3815 Sy aa 1543 sy pox 20 san soto Sum fq pod 9 wo saran‘syoes 2971 2s01 24 pq pla 240 ap OY potas fue Je py peso ve poppe ave aonb ew Susu 0 WL 34020 2, Sosy pouosu snp uo a yong ut somonsS Ep (Qs) Ho“ "USI w ano Y sonang “dua Apraye ey ons wou ota we aR|Rp 0} 2m way SuNo90 HoRPIOD NOBEL Uy supa opapun.o} 93549 st 3 YOR mouafp ue Sune(p 0} ELIS oUF 0A a Uap 1090 OAD tao ue Suns2su 22099 9AOHOH, fepmoyun) oes nf wu Souda ay Jo sea a4 Sut Hola dnd 2 puy ons 9930 doy ag toy aU ay sO4OURS VoNEIdo od 34 DE 3 J 630 eau sppetoneredo wnt ay ond pu od sn sonia 89 Sa OG 268 Y ‘mis a 2:27 uomtsod st ye suop 2q jE SuoNA} Pu SUOMUASU! O8 'y = eon eZ Sig ype eo uopenasidas Keay ez any 6 2 4 9 ¢ vem ¢ zy 0 ry 8: pes ay uo T+ 6g pe dna st yrAs a EN SHE ‘say euo worsod sn 8 "YH au jo mawaye Isouidoy a4 Jo sssUPpE a oy um paeosse os ajgoura sug yous 224g "oRIse Jo uoneyuata|dusl Ken ayy soy asnesoq asmonas (gr 3N0-8y ‘pus evo sjuo ve 2unp ate sow Jo wn2.p pus uoMasuF Ya TVR ep seu GEE Pe EEL thf ekt fe ‘sepou u2Ads J 8 poxUy © SOME 77 2 tout jo yunoure ap quo postu sts & 09 poppe 39 Ae wep sepo8 JO 4 Mb wowojo yy ogy pe ur swwowoj9 9] ueie0o tw &g poouarajsaze pu {yo swawaye uaeagog pourmute od st Souadeipe Jo di 2s a4 ur apow rou ay 01 pou yey 01 spuods31n9 ews wep Mio KuP 40 =p Burwoqoy a sursuoo spew Kona 4 poy eu 20}, 35249 2pou Ka94g se a 0 pp arucanso anblyoys Sueiou gogo oun 0 iousuerZoad oy syquusauney spp 2 BH 39 Sao td no nog Am ou poo uid ene ai oy nes09 15 2 ay (9p0u po ‘seu ioe azou sens wo sway 0 Sn gee sh yu }goxd 29 wes swam jo wonazpp pe wo 300] Kou snonBinuo> u payos a SHOUD et a pxy joa sean swoneyuy Summon} 2 26 equ ing eps 246 eras o snow fie 21050} wom am vay, Swe 0 eu ve uoneunante ue [elovew falsvew [Jovew fisyew [slovow (pisvew f)syew [zsvew [swe (lve tains usa tag Fanwae uae one ae ae en 2s Keue og soma ap | 9 sH0ya!9q uD} os pu sums xaput eas 2° up swig} sul ‘ojos Buymoqoy 4p Bupsn pasepap ae shea ‘3 up wot (Gduosgns ay se uno os) x9pus ouau antnaostod pasos xe Seue apf SAO ‘944 sep owes om aay sivoway wip aso “sjuawofa wip snus Jo uonDa|09 Bt Kez Ky sheuy “seudeyp yonbosgns u jepp wt passasip 29 pjnos. 424) pur soins ep asamp aonposit nou hm 9 Sinton ep Jo LEA © ‘side8 pue sax apnou 1 vq ‘tops0 jentonbos © ut pours you ae aamons 48 Date Secs Using Figure 2.4 ray representation of 2 que Here, front = oand rear « 5. If we want to add one more value ‘add another clement with the value 45, then the nese would be ‘would be stored at the position pointed by the eer. The queue, after the addt shown in Fig. 25. Here, front = and reer ~ 6. Everytime a new element isto be added, we will repeat the same procedare. Figure 25, Queve afer insorion ofa naw dmant "Now if we wantto delete an element rom the queue, then the value of front willbe incremented, Deletions are done only fom this end ofthe ueve. The queue afer the deletion wil be as shown in Fig. 26. Figure 2.6. Ouave ater deletion ofan cement However, before inserting an element in the queue, we must check for overflow cot overflow occurs when we try to inset an element into a queue that ‘when rear = 1X3, where nas the sizeof the queue, that is wax spect ‘of elements inthe queue, Noe that we have written ax-1 because the index starts from 0, Sinilry, before deleting an element from the queue, we must check for underflow ‘An underflow condition occurs when we try t delete an elem ‘a queve that is already empty, If front « mL and rear = nt, then there is no element inthe queue Trees Atreis non-linear data strata “order. One ofthe nodes is des into disjoint sets such that each consists ofa collection of odes arranged ina hierarchical root node, and the remsining nodes canbe partitioned sree of the root ‘ree. A binary tree consists ofa root node an left and leftpointer ‘Theroot element is the topmost node which is pointed by a ‘oo! pointer. Ifrsot = utt then the sa binary tee, where isthe root nade and non-empty, then, is sai to bethe let successor the right successor off Figure 2.7- Biante oe _tadcion Data Siac and Agoriens $8 “Intig 27, node? ste eid anda ithe MEINE. serenaze: rvs ick ser, srt, and dete peratons ‘savage Competes dation Aan Graphs called nodes) and edges that as a generalization of the tee stuctue, wl other hand relaxes ll sul kinds of restrictions. Figure 28 shows 3 graph with five nodes ‘Anode in the graph may representa city andthe edges connecting the nodes can represent road ‘A graph can also be usd to representa computer network where the nodes ae worksta the edges are the network connections. Grapis have so many ap mathematics that several algorithms have been writen to perform © ine pape ® © nodes are connected via an edge, the two nodes are known as neighbours. For ‘Nanple Pig 28, noe chao sghbour vendo, o@ Fron 28 Gash 2.3 OPERATIONS ON DATA STRUCTURES MITTEN ses best mos eet stations Dasramage Se auth ae su ad vr complx ‘This section discusses the diferent operations that canbe performed on the various data structures previously mentioned ns to aveess each data item exactly once so that it can be processed. For item from the given collection of da items. For example, to delete the name ofa student who hes left the course. Sorting Data items can be aranged in some order like ascending order or descend Merging Listsoftwo sorted data tems can be combined to forma single lis of sorted dita items ‘pourgos ‘gquodeazduoo 2m o uBlsap og) tun paweodss st ssso0xd sy -soqNpout [ano siya uso} 01 a4 pagans are snpou [ana ow 2 FY =IMpouL ja] JaYFEYwuaOy O2479304 padaaid ane sojnpo 29 Buss fq panou avoid uot pu Sapo 249 UT yoeoxe unop-doy yo 9104019 wowtouyar _2ypiny ow saxmbas yey poysest st [ana enum saxo] 2px5u09 az0W ones pouyos Susp SN “dass yoro w way) ue wisop yoensqe ue wou} as 24 "ypeaudlo unop-dey wu soja) mmpott-ans aro 20 0 ow pasodwonap 9q Jung Uo so[apotu sey, s9pU toU 40 3u0 ‘nur uo x9|dtoo a Supinp Aq ses yoooxde Sisap uaop-dosy yoeoaddo uaop-dey wedi ue Cuutsep jo saseonce way 6 Nb saynpou-ansaiow 10 suo oy popup 2q ued oMpow eS GOO O00) ooG ei—Laeee) «fie wate} |_|. cron ‘Gia aes ope ‘62 Sty ur umoys se yovosdde <énstonog pur yoeaxdde umop-dor—unuo8}e ue uBisap oy sayopordde wear om) ae 2104) “unqso8 jesono ay Jo coumueror pur ‘Buyusunaop Bunsa “BusSBngop‘vorrvewy dt soya cary vt yoiys sop a Aun Seroueyuo Agaznn pazoUst 29 Wed so|npow 9m J step 2qp‘ajnpow ouo Bunisep arny wuapuadepus pouBisop 2q ueoojnpoul Yoeg« wauojdun pu uSisop 01 aydars ung xapdao2 uy Saye « monty se are uonezur|npou:jo oBequeape £04 24), uonezsMpoUpajeD st sonpoun ott uno Oe Supuapjossoud uy s2[mpous pte suum sq cpu paprap uago swaping xeyuo> y ‘ep patos a wo suoneiodo wnopsod on pasn ane sunjioe ‘samionas| ‘apts BupHoM wayyy “sITpONNS Ep utpouTRIe® mp ae WaPw Pose ae suAIUOB|Y WHLIHODTW Nv ONINDISHO O1 SAHOVOUddY LNaUIIJIO 9'2 sao8}e ap Jo vapdtuoo soeds pu aun an wo pup sn unsof(e sepoqued e yo sotoy> sip my waygoud aus xp apyoe 01 sujuodye add net] 0}Uourwoaun yu st wa; gaud va eat a0 +49 ‘9 om ade Jo taudonyg 220 apr ue anny an 2909 ‘aay stexoumute pousp su ‘sey dsj:nqame ayo angldsSnorsyenpeed Dana qo papons 1 ohoa mons ayer ease aes once Sept amnesia onde Ban adsense pes et 15 supuoiiy pun soamonas emg os uononpauy “send ouoy » Bsn powuawayd 29 aos Buuey0d 30} sunpoooid pauyoy ese ayasa stuioud pos eas 240U SLav 6u/sn jo abejuerpy oe lum ova mow 8H" pyeoys ou) repo HO oi posn Bulag rom spor ay oy ym peuseodon 2g ou ps AM, 298M 940 Hoge pou29u09 ‘Bue moge pamseou09 fquo ase pu wtp 0 2p mo Karo spoyjaur ayy MOU opmuoueydn 0 21 waif wodo pauopysuco saad seams Bep Jo 21400 3H DENSGE, pow IY, BUSY ) a anna © noge ype 9m UNA pout 3 un sad ep atsey tp eat ura ejoadiy ag odd ng juueow i snostp uo 1 goonsge, 2m soransuowop sty, sf poyuyt © 40 Keue ue Furs syay asa 0G ByQ-LaWue jo sojdwexa yo}.od are sananb pue yous ‘jdusex> s04 go" S009 pu Soop 1 ey uo Bueno} ‘aunonus ep 63 YOO] om fam Mt (LEV) AG np eMEGO UY 3dAl VIVO LovUISEY 72 2 Data Sractres Using C Top-down vs bottom-up approach Whether the top-down strategy should be folowed or @ botom-up is @ question that can be answered depending onthe application at hand. inement by decomposing the algorithm into other hand defines a module and then groups Top-down approach is highly appreciated for oftest eases, Implementation of code, and debugging. However itis also critic in isolation without concentrating on i le attention is paid tr daa, thereby ignoring the ‘Although the bottom-up approach allows information hiding as it ist identifies what has to be excapsulted within a module and then provides an abstract interface to define the module’ boundaries as seen from the clients. But al this is dificult tobe done in a tictbattom-p strategy Sone top-down activities need tobe performed for this, E ign of complex algorithms must nt be constrained to proceed according to & fixed pattern but shouldbe a blend of top-down and botom-up approaches. i 2.7 CONTROL STRUCTURES USED IN ALGORITHMS 3, Some steps may involve ploy one of the following ear - making and repetition, sructures: 2) sequence, Seqsence [By sequence, we mean thateach step of an ‘executed in a specified onde. Let us writ an algorithm to add two numbers. Ths algorithm performs the steps in a purely sequential order, as shown in Fig, 2.10 Decision Figme 2.10 sgt to add wo rumbrs Decision statements are used when the execution of (ee process depends onthe outeome of some condition. For step 4: 0 example if = y, then print ran. So the general form ofrrconsruct ean be given as % endian Then process ly known as the 1F-£LsE construct, Here, if the condition is a 2s enecuted, Figure 2.11 shows aa algorithm to check pus (a seuond 29 aro foutouye 2m 219 '9$ 029} doo au Jo 2qUuNU 3 Joys Su Jo SOquUM “9H, Sycat80r8)08 30]9qu2At8 doo 21 prsuoc ayduexo axoge ayy ut usogs se se vans 9q us sdooy sou yo ase ayy ut run) yesusd amp sonaqySuonRn Jo 9quM ‘on yeuoyodosd éiooup st Kouoroyp wen pres Apeaye axe 294207985 doo| aM)! ODI 39H (rrtoop riot ues .mojoq wan dooy a s9prsuoo“ayduexo 404 “suo aqui agp st 2104 ore doo ayy srE5HF) 29} deoy apo} YeuonLodosdKis9up st suOWEEDE 40 saquinu 2g asneo0q 1s “Pomnaox> 9q fH Joo] ayy uF suo ap Sum Jo JaquiN 2, ‘Uap Yay 0} pas am “doy afSus w sey we UNALOSTE UE Jo KoutouyD am aLERO|ED | ‘doo sesury ‘uyuode ue Jo Souotoyys xp auuna.p Sdooy yoy u SoFe9 aseyEp Japs sm 12] ~uuquodye ap wt doo ype Jo au Sura pe sdoo o a9qumu ‘nwo Sixpuodap Kren Sous unpoBe ro Jo Kosar ay UaKy “sdoo} SUE; ‘saxamoH]‘SuHeu09 Hf suononasu Jo s9qumu amy se uaA(8 9g UeD WALES eK 50 ‘9 20 wrod wey so Kouozoyso amp “(suojinaay 30 sdooy Aue yt Aouo.ayy3 wiquobty 8° faxaauoo a 30j punog rd 24) sopinond won sou © Hig a4 1 (¥)s wonsany sn Ssaudxo 0} uoREIW Posh AYPPU 80K a], ‘worougo sou sym HOB ‘249 pg 01 paou 2 put wojgoadu>qifw oj wonnjs 8 puy My suo jd ame aD « *esvo1ou wojgoxd aun jo 321s yndu se xaqdeuos yo woud Joss ap ypend OL TEA 394 & ‘oqo pants st faeoyduno ayn Sussand-ponjosfuloqwiajgoxd ay Jo 20unU uasI8 ‘271s nd am sv aay (o)s uonuny » Busn pasaudxa 2q usa Aysajduioo soeds puw an > ‘Ayxoyduiog coeds pue owns Guissaxdyy '9'Z “soeds aout jo 1900 a9 8 2}M99x9 oy au IL Sys EON asooy> nyu au0 wy ‘jreasuoo sofew stow “semuo® ay UO “a /4dZ HOU JO 1800 og 2oedsssy say yup esoud asonyo Iu 3uo Uap aEASHOD Hig est >oecs 3 “OS ‘suujiuo8ye Suoure yo-apen aoeds-ou sno ara “ouny eyo ay 30) Fup a4o aoyueS 0} uourodAM Jou fx smh “INDEED 0} aun 449 $82} annbox Kew oypo am a Soeds AaowoU s$0j anor Sets sup “wa; ga4d none « 26105 0} anuo3yeauo weNpa10U 29 ueD aay ASE TBE BU st HALOS ‘we yons Sumisep eooead ing ‘uornoexe st aa4duioo oy au $85 834 pue aveds ot ‘so snmbau 4 avo 243 aqnop ou st puny Ye woqqosd seRoqzed v axos OF npIOSTE 199 SUL o-2peu} aoeds-owy, 2°8°2 3 opin ps cg eg vee ; pepuouiusoot Senge st sourusoyid os ruuopiadasep-siom ayy pe aoueuLopiod Bere ay 20 450g an Uo uotsaap ano a8eqfypuey 99 "uozgod e wo§e ue Jo 1asyoq paisodxa ay sogtoads je we Jo aun Sumuuns aseooerose any om 1p puosag 08 sou fo wun ap rey 200 aseb-siom Jo 8poymouy amp Butaay ‘azoosouy, nda Sue 205 ou $s] uyyuofe uv Jo aun Burs aseo-ss0m ay. sours yada xp 502503 p or oodsan ua cuyjoSe we jo snoxseyg am $}0u9p St, ap Tyna 950-8104 ‘yro}dwog eu, pozsyowy pue ‘ase-sog ‘ase2-ofesony “@see-80m 182 suaquode jo fouarouy oum Suns og wo syenusou seo 20 ave yp soxgeuvs paimonas soy pu YRS ‘woud oy uresaud wos sues yf 20d gout 249 Buuinp Aeoumeusp 200d p ‘oysnat oj papaau 300ds amy (Goaryons pue skexe 2 SBupoys 4 papoou 2onds ayn sued om Bum {geuea pauryans pue‘soqqeuea ‘Smet uy 3 tajgoad ot woqgoxt! wey sae 0} 9 uo spuadap tuerBoxd» Xa papsau aaods 4 osm wquogie pu yndu s,uesBoud ay J0 as yp uo opuadop Kyewud st aqui sty. Aixofdup9 aun 1R9 s Sonaoxo wreoud yoryis Suonarusul guyomus Jo s9qu ap "Sp1oN 240 ats nda Jo UoRDUry 8S rynoaxp wed aap Susp pausba stp ‘ow odio yo wnowe 99st uAUO8ye we Jo Aixayduoo 2oods an roms“ so uoyoury ese wexdoud yo un Susuns ap Aiyso}9eqSt uN We yo Gxapduoo om, ‘uxa|duuoo 29eds pu aun 3 Suna uy pages St wigs ws 5 Ays2jduo Jo Coustow? as ‘syndy saqunu Aree ue uo. pow 1 pouisap fess ae suo -=yNINK a pp (Gsowaur pur oun se yons) soomosas jo tinour ap Surauasip SusoU ayWUOBe we Bussey ‘ALINGTAWI09 39VdS ONV NLL 82 aa 2 a is. anina 35 is aor 0 a] 1 eges + W9e s wy dns io Pita des seo 2 dis Oeste Tas: as nde 31 ons ‘sequin jane Hy Jo ums oy puy Or unoBje wea *S trol isn mong 9g ‘We have seen that in linear loops, the loop updation statement either adds or subtracts the Joop-contolling variable. However, logerithmic loops, the loop-controling variable is either of theloop. For example, look a the loops given below: general ferms, we ean conclude that the efficiency of oops tions divide or multiply the loop-contalling variables canbe given as Nested Loops Loops that contain loops are known as neste loop. In order 0, ¥ a2 ny then bound for F(0. 0(e(0)) and eC) isan asymptotically tight upper Examples of fnetions in ofr) include: n, (uta #2 + a0 elu gu Apuer = uayas Bt 2) neo 998% Jo apse 2g P= 29ND #952 20U/E Fo “atogorou, 26 voy soya tv 8/6 mg TuepiAD Yeap "> Jo nea xp ENA OL, Smaart ep nontan nora ‘onnyop mH (do = 62 + oor ein mous 2-2 OEE TOW UA 5 ay 5 0 Suojanoyy Ts uo SIL werse 65 suc pun camanas meq 01 wONPaY, yo anes ain surau9p 0 ye alogaou Tu ua nue sep 29520 JO ane a4 BUTDIBP 01 NON ‘yo sunny aay 1 sogeRGo oe ZZ AREL uusoyod 9qpjnow ip suonpiodo jo quit eat Gxoydwo> au uuu up uoBe aw eu} « 18 Saja oun Su urquOsE + fe Jo satundoneo warp any 2004 28 uonmou O 81g 2p 0: BuIpIODdy susoiy 19 soyobayeg Poul Kuss “Taye are ae aa 3 sonjes ywesuoo ogy F070 EE peg aio (os pu (u)8 waaasag dmsuowes a Saou 12 z 24gBL (0s pu (08 Jo s2jdurex> OS We oO] $024 ON, (0 9800 som se aus sueaur 9 ous Aud 9 gF « ‘Apes Kare ayy uous 13669 809 24) feat we uasosuay oparxd 0 "ung s2moy4ygssod st andut yo suoneuiquoo ij 30 punog san ue saquosop © 25091509] © ; ‘szueuuns 0), 2201 + HRS 0-4", :apmppu (0 HU SuONDURY Jo SqduuEN i 2 8usp smog oe 85 o Data Sutures Using C ‘Limitations of Big 0 Notation ‘There are certain limitations withthe Big © notation of expressing the complexity of algorithms. These aviour of the algorithm inthe average case + Big O analysis only tells us how the algorithm grows with the sizeof the problem, not how ficient it is, a it does nat consider the programming effort. I ignores important constants. For example, ifone algorithm takes 0) time to execute and the ther takes (200000) time to execute, then as per Big O, both algorithm have equal time complexity. In real-time systems, ths may be a serious consideration 2.10 OMEGA NOTATION (0) ‘The Omega notation provides ight lower bound for). This means thatthe function can never do better than the specified value but it may do worse. notation is simply written as, #(a) € Q(g(), where nis the problem size and ‘¢e(00) = ay: 3 postive constants «> O, Such that 0 eg(a) [hoy W 2 my) Hence, we can say that Og¢0)) comprises a set ofall dhe Functions nin) that ae greater than orequal to eg(n) forall values of» > n, Heg(n) « #40), € >0).Va ny then F) €a(g(o)} and g() isan asymptotial lower bound for 400) Examples of funetions in (0 Examples of functions natin To summarize, ‘Best case (describes a lower bound forall combinations of input, This implies that function can never get any beter than the specified value. For example, when sorting an aray the best cae is when the array is alteady comectly sorted ‘+ Worst ease 9 describes ower bound for worst case input combinations. Its possibly greater than best ase, For example, when sorting an array the worst case is when the array is sorted in reverse order « Ifwe simply write ©, it means same as best case. include: wn, m+n? ncde: 22%, Example 2.8 Show that Sa? +10n= Oe). Solution By the definition, we can write 0s cain) ¢ Hm) Dividing by 0 fet 5 ela & See» aOn/n? e256 itn S+10n= 5 Therefore, 0 <5. Hence, <= § ‘Now to determine the value ofp, (0 Data Sructures and Algor Example 2.6 Show that m #2492) Solution By the d 0 < cain) s Mm) Osan Dividing by of, we get ye scat 5 Tet “Thus fiom the above statement, we see that the value ofc depends on the value of. There does not exist a value ofthat sass the coniton as increases. Tis coud fairy be posible i « =O butts not allowed asthe definition by jon, we can write 2.11 THETA NOTATION (2) ‘Theta notation provides an asymptotically tight bound for ¢(0). © notation is 0) € OLE), where nis the problem size and c¢¢ny)= (0): 3 postive constants, «,, and, such that o««a(n) $hem) Seale), Wo: Hence, we ean sy that cca) comprises ast of al the functions h(n that are between and gg(n) for al values of n>, jatev ad g(r), Vn2rythen to) oad (6) 8 amongst n(n inthe set 9) and g(r isan asymptotically To summarize, ‘The best case is not used, ‘bounds for worst case combination of input values, «If we simply write @, it means same as worst case ©. Example 2.7 Show that e2—2o= OG) — Solution By the deinion, wo can write ato) $ mm) cto) cpa mn Sept Dividing by , we get PUN Lan = ani & eg Cia ang ‘This means ¢ = 1/2 because lim 1/2 -2in= 1/2 (Big O notation) “To determinec, using © notation, we can write 0< Gs) = a ‘We see that 0 2 yoo ‘yduexe 20g Ken oxp Jo ewe? YoeD 205 ae op ‘nd of panos st doo} 0 830 at T9824 porous py a oy ones Suryndu Aq popu 29 uD Ku uy preoghay ous woy soni Guyynday wey | 23885 now ayeo0H snevap sexe o wopcvenu) se ambiy [se ula le shee 2 Smous sini ‘sores um pq a noua paisa aq eu ay gu 9g) senfes Jo zaqunu 2tp J eH BION “IUD i joo aq x34 ey Aah ‘ajdumx 104 Sone Seu soured oy ‘wanese>op Jost oy ye eu (else fee 8 51S Sey Abie ap Jo Wout plooas ap Sup noua ay ay “sp WO|D 2304) wey sonyea 2u0u ras o. St onjea K22n9 pue siyDEIq AM feat 2q woo ear ue jo swuswajo a4, ‘vonesey2eq Guunp skewy Buxyeyy) ‘eur ue sayen Suuog. ge amnbiy ‘wewo fenppu oy samen uBtssy : Preonkey ap wo wow eg 24 Sonpe nduy eae sanen Supers Uuonerepep Gun suewore aun e2yeM total number of elements, or performing any process on thee el data structure (because alts eemens forma sequence, traversing and staightorvard, The algorithm for aay travers i give 9: (imviaiearen) ser {oo oF oor) | * ae the index tothe lower bound ofthe ara. Ja Step 2, atte loop is lerent as specified by the areay name and index the next array element could be processed. The 0p in Step 2is executed until all hee less than or equal tothe upper bound of the array. 1. Wiite progr to read and display numbers using an aay ‘inciuae in ming ‘ arr[20]; small, pos; Printf(*\n Enter the numberof elements in the array Scant" bn); : Drintf(*\n enter the elerents *)s foetseorens srall = se] feetisisessee) © seeretijesan) ¢ sath = aeet; fore > ) se, sno); Aotf("\o he smallest element $8.26", smal); Print Toe goition of te saaieet Sarr the ary 38 = 2, ots fesuen 0; , ouput . . tnver the clenets #7 65. 3, Tpee F nooeseT Be pay Fee $ Sv eTT sums af 0 S55 Meaie oy UF SauSTD Jo saguNY 9 280 nding « svopy spate ‘Kee we Burn sioquine ujo ise] puooas am puy oy wesdoxd eon “p 1 Sy fesse 89 up sumuoTe sorte ays st stouy 4 Dot Srctres Using C 4.5.2 Inserting an Elementi Step 1: Set oper tod» uper tows et an ray Sep 2 Set spr buna) Sc Sep ar an existing cay, then gui sinpl, We st ve [| the memos sp comin 10 eens, bw cant it a ony § cence ea woacemmotie wo noe elemets, Buta oie to add another element to it. ‘s Fre 1 show lord inser nw enon increment he ao hep dn Sep ee Ce The aa is dhe sot te mas of al esd in 54 students and ane std coms andi ake oe cae student would be stored in sarks(s5). Assuming that the srdent secured 68 mat Fetes i that red 68 masks, we will assign gue 3.19 13ppen a new erent oan cay lu is stored atthe pi us assume an array has been declared as 8. Now, suppose there are ore However, insert an element in the (Onan average, we might have to move as muc ‘order to accommodate space for the new element, For example, consider an aay whose elements are element has o be added, do this, we must first the elements (that have a so that space canbe created: we have Example 3.3 ost isan array that is decated as ant Osa(30}; and contains the fi ving Calculate the length of the array. a Find th per toon and ve foe (©) Show the memory represetaton of the (@) ta new dt ckment (©) seta new Solon Lengi ofthe anay = member af elements Therefore, iret of the array = 0 (b) By det © ay, inthe value 75 has tobe inserted, find is posit element 75 and show the memory representation after the If an element has to be inserted at the end of [ ‘Algorithe to insert an Element inthe Middle of an Array The algorithm zest will be decared as nsERT (Aw, Pos, vat). The arguments are (@) 4, the aray in which the element as to be inserted (©) W the numberof elements in the tray (6) 75, the positon at which the element has tobe inserted (4) vat the valu that has tobe inserted - Inthe algorithm given in Fig 3.14, in Step 1, we with the total number of elements tp 2, a write loop is executed Step: SEY AOS] = VAL Step 7: ext ‘Now, let us visualize this algorithm by tl an example. Figure 3.18 goin to inet an element inthe mite oan ara. Initial stat) is given as Below. C=] ay ata PR Le Dwale) BG) la) BAT to the fllowing processing Calling sen (oats, 6, 3, 200) wi Cals] = Le ps Le Goale] tala] OaLa] OeaLa] Ove) BALE] u[lels [ss Doxala] BRAT GHIA] pals] ote] « [sls zee] Ba[o) Ova Baa Onala] tay wata(e) ae ee Ls |» alo] ea] Watley OoaLa) kaa] Deals] UALS Wei ny uy soysowos wosy 15, we put 15 asthe first element inthe merged array. We then Compare the 2nd element ofthe second aay withthe Ist element of the fst aray. Since 20< ‘2, now 20 s stored asthe second element ofthe merged array. Next, the 2nd element ofthe fist ‘ray is compared with the 2nd element of the second array. Since 30> 22, westore 22. ‘lementof the merged arty. Now, we will compare the 2nd element of the fis array i ‘element ofthe sevond array, Because 30 31, we store 30 asthe ath elem t ‘Ths procedure will be repeated until elements of both the arrays are placed inthe right location inthe merged aay. Fcc ll 12,_ Write a program to meige two sorted arrays. | ‘incluge cero. int asin) | clneer prantf(cin Enter the nusber of elements $n Sorayl a", ba): nin ener the elanents of the est afray"); Forcisostentsse) i eins (0Qn ara] =") 1s Seant (om, Baera(AT)5 y Frioee(own Enter the munber of elements in array2 *) i m2); ter the elements of the second array")s fon(is0stemies) print" a feat ? WhileCindex first ¢ mt 8& index second < n2) ‘ Anais 88 sf(orra[inde fest] nde second) 4 sera{index) = arrafindex fest] ; frst; se 4 sen) = arin scot) . 2 , [1 etenents of the fost ary are over and the second array tas sme elenents| Sfcindee fest = ot) ( hie (Snsen_secondend) rand second ) 11 elena of the second array are over and the fist array has sone eleneats (se S# (index second == #2) ‘ nsle(éndex srstent) ¢ arr3{ande) = aera(andex fest); Output Fnter the punter of elements $n arrayt © 3 areifo) = sretla) © 3 arvala) = 5 Enter the punter of elanents in array? © 3 Enter the elevents of the second array ‘wotrouny #01 Ae uw sed oy soyuod jo 2gn a re w ssdonl Sumo 29187001 “au ao ad wep 29 a0} 00> onioy app dus ue uys09 se Kee ue tp ose ee Jo sUONEOUIPO Teuooquen jo 2d Aue susnoad sry ‘wououy poe ah Aq Sut Ueto e se polo! 24 ssw deue a9 ear a oy sup Ov YEU 0 OHI PED 2 EN 3m 250 LE SION, eins 29 uo is won oy Bus feu 0g -eze-qns agp Jo wud 9g pinom stuowayo wo juo wom “not ‘oh sed of ueM 9 pu “Cee ayy ur syuawsye Q| te 20 www pay 4 Sszppe am sod usp a up WOW oa ai 2jdutxa so saquod Sexe ue ospe 1 Kue-gts® 0 Jarod y eNe-gnsv se HMO ‘oar ayo wed e sed ose ued 94, uoRauy vo Kast ajo a4 sed 01 AeSSS004 OU S14, ‘smo se 29 prnoys wontsejoop ay rourred se Asae ur sdaoae ey "wonomny a 1 pureed sexpoue se exe ayo 225 ay SSbd os] uaa NOR, 8p suowssaxo aay Busn Xq Aue 2tp Jo siuowoqo 249 fe ss9908 Ue of geEA 20 ‘Keuw ue sv yu pure ajgeues e 0 2quod e se poraoyu 9 eure ue se 2apeoy Uonoany ut ase22p s sroursed outa} wot, "wonoUry oxy uy genes Jayuod [e20j a 03 potdoo st feat ‘Jo wowye yoaae an so ssouppe au “uoouy # 0} Seu ue Jo OUT atp Sed am U4 st A, ‘worry poe ayo Kee ‘auuo any sessed yong opoo ay sorensny 27'¢aundig “eur ojo ourey amp ssed Aus ue 2 “uo} ry # of Seu ayn UE ssed 0 2 am Lous “aQ}RI9U WoTHD} 2H JO One XP a pur sre Seu agp Sus we Aeur oyu sowie Surmewar 2p 30 Supp 2UI. “Avou ayy wy UL ay Jo 2449 81g 24 01 sHafas sue Kau 2 2 WH IN possROIP a4Py aM, unoy ay 30 ssuppe ay sed 0} sua: | Hmpaoatd q uautaya Keu jenprapuy wv jo passed st anjea deni ue 10 y 01 passed st a]geten ofa iu B JaMay SIOYIOG A|psey oTIOUT yea 801 a ero [¢ Jue ‘2104] ‘oIssaidxs xoput SSK, wong payfeo atp OF passed st Aeaie ay) Jo ywautaya ati Kjuo “oj dusexa ax0qe aq) up vogoun eo sivas hese enpu oussey teizemy 4 BRP amo Aun jo sgeues ssed am se souueu ues vovequmuwes woKpun a0} Seu euoKELID SUD Ores ‘sessarppe Busse ‘serjen ep Ouse fare aus annua ou Burst renpinpur Gussea | i | Sear UORBUAT| "5140 sfaue Q) ry.opn ak a 8 ‘ens ann aq 50 0 oon we au 0 0 J gS AT oun ove 3 una Aus nok ‘suppers atuos uf uorriny v 0} Kuze we sso oste Uea am SNOLLONN OL SAVERY SNISS¥d 9°E 2A amos 1°99 13, Write program to read an array ofm numbers and then find the smallest number. ineate cto.» veld reedarrayCint arr], Ant ine fr sall(int ret], it ine win nt ua clr brintf(in Enter the site of the array ©"): Scone, eae sray(ou, fale fd snald(r, 9); print¢("\n The anallect rer Sn the array Ls = ny enaests 1 sealtest) etenc ) Xotd read araytint arr{20}, Ant 9) ‘ *) prinef(*\n are) = Srant(oe, arr d > ot fod_seatSnt are{20], Int 9) 4 int i 0, small = aero}; forcietitensins) ‘ stores} ¢ stl) ‘nall = 3e(3)5 ) > Output Enter the size of the array £5 treba) 24 ereta) = 5 ‘he analLest unter Sn the array 4s = 1 14, Write a program to interchange the largest andthe smallest number in an aay inctude cetio.t> ‘include cone.» Wold reaeorray(ise ay. arreytD> $889 Vetd display atrayCint nyrray(], #83: Se fd snailest pos Canty array ” fine sea clrser( \n Eater the size of the array eeten(s etuen 0 > Vote read aray(int my array}, Ant 9) t for(ieostensivn) c peintf(* aerttal = Scant xa", tay arrays ) > oid display aray(int ay array[1], Ant 9) ‘ For(is0;5en0) Brinef("\n are(ta) = 48", ay array ) oid interchange(int ny array[10], Sot 9) t Int teap,big.g0s, seal pos: bg.pos = fa_biggest_pos(y_ arrays ms sebll pos = Sd_snallest pony 3t?39.n): temp > ny_aray[bie poe) iyrarray(Big pos] = 6 2rraysnall pos]; rysarray(srol pos) = ts d nt fod biggst_pos(int wy_array(10}, int 9) ‘ Ane 4 ange = my array[0}, pos-0; for(istziomie t 4F (ny aryl] > Large) ‘ urge = ay. array ) Pe > fnd_snalet. poe (int oy array at 9) Small = wy.arrayiol, poss; a0) 4 (oy. aevay(3} « salt) ‘ soll = ny arrayli) andyng, i Pk apaTs8 DO y 6. 18 fouan Heise, Cures 9h ‘Seu we oy saujod« But Sear ur so suoy409 9 saysPoU Yay 9Po2 Bayo} a ‘ane aes og sn ie 298m squid pur seu ‘oxojoioq “0 nO snjutod ese ‘wwaunap sry su Jo ssxppe an 012 ‘ureu Keare ue ‘osoasouy “pajoapuaeg su ous 15 9) (oles = ns 17 yduexo x04 sayuod vse aure eu yo Suny “au fe i an 0 08 1 woyeamnbo sj [y]3e ax woyssaudxa ue Sioytod Burs gay, “yo ssasppe amo} 269 | Iu pe wot pjnow sens esses [enparp Ue arOHS 0) posn Ua9q 2x now Aaowow a ur a3kq Asana “Kee JaoeIeUD © 29 SIH PEEL ‘aye pou 2g) ‘SCE By UF UMOMS SST oy od oy 9 aout Hs way elas fee (ewe jue ue 6001 2001 £00 005 S00 00: £00 2001100 0004 2s 288 alo (fa) so0rts a uaaldwunouae ay a Sa ++ Aan omy Suisn soutod v Buqusuixout “end of woqe sod eu a wo Aeae we Buoy mp ‘saute ¥ gud yy said e sani + Spe wow “2 aye ae Lay 05 o|geues Lastod 16 slouy you parerajeaq uo swuauae aatsooons fossa yuo ty J S230 SP nd swous pz'g amity “e xoput puny a4 09 10d 01238 09 “(0 ay eu em yaya dino a4 ax1osqo pur oq amowg ear 9 Jo wow sig 24 0 ufod 01 9peu S38 “94 ‘ame we oa 9 4 adzouos uaa se ageuea syd v rag wep Aue a4) 2}geues nut ‘fen 9 Jo wou pm 2402 Sunttod elusey 8 ae 0 60% = fesse 40 ssasppy Uy aud no 01099420409 18 2po0 a -moyeq wowores au n/sn 9] MON “fol2e Jo seuppe ayy 40 Kes 24 “se parmop fexo 104 °¢2'¢ B14 Hpisu0; oIMIOd ‘01 prog yoru A $1 Kee Jo 1d30u09 94 ‘SAVMUY ONY SUBINIOG Le 0b 9001 oor zo0L ooo (owe [ele fewe te 45 + Kease ag go orgs 003 0303 nding ‘ 20m e106 os tres Using © {in ¢we can ad or subtract an integer from a pointer to get anew pointe, pointing somewhere ther than the original positon. c also permits addition and subtraction of two pointer variables, For example, look at the cov Ant main) ‘ ant ‘pte, pte2 = arreas Seint#('N6, peea-pteays ) Output In the code, otra and ptr are pointers pointing to the elements ofthe same aay. We may subtract two pointers as long as they point othe same array. Her, the outpt 2 beceuse there sare two elements between pra and ptr in the artay arr. Both the pointers must po! aray of one p Moreover, the pointer points to some element nearer tothe beginning ofthe thother variables relational eperators (>, <, >=, et.) ean also be applied to pointer variables, ‘ite piogrin to display anaray of given nimbers. Finelude étaso. ty int naing) { 18. peed = orto); vhste(ptraceptry c ined, ptt} Fetura 0; ? ‘Output —_—_— ees 3.8 ARRAYS OF POINTERS An array of pointers can be declared os int tptel30} shove statement declares vatable. For example, look at mension int tel Can you tell what willbe the output ofthe following statement? print¢("\n a", “pte reste address of integer variables and “tr(3] will therefore is 4 Now look at another code in which we store the address individual arrays inthe array of pointers: “at maint) ‘ , ‘Output Surprised with this output? Try to understand the address of srt (0, tr the case with see) and sea) ‘TWO-DIMENSIONAL ARRAYS Till now, we have only discussed one-dimensional arays. One-dimensional strays are organized linearly in only one direction. But at ies, we need to store data in the form of grid or fable. Here, the concept of single-dimension arrays is extended to incorporate two- ayy yey uD a4by A aoe 2 asp sumionas oC | 9% Data Sverre Using © The individual elements ofa two-dimen ‘operator as shown bere ized using the assigame sarks[4](2) = meks(4)(3) + 3.9.3 Accessing the Elements of Two-dimensional Arrays ‘Theelements of 2D array ae stored incoaiguous memory locations. arrays, we used a single for lop to vary the index 3 in every pass, so ‘be scanned, Since the two-dimensiaeal aray contains two subscripts, we will use two for loops to scan the elements. The fist fr oop will scar each row inthe 2D array and the second fo loop I scan individual columns for every row in the array, Look at the programs which use two for Joop to acoess the elements of a 2D array 16, Writea program to pr include conto. 1 elements of 82D array. innind) t ne avaqial = (2, 6, 56,235 Fordioriassm t pein Recassaie) Serescxaw", sets , 6; ) Output no 17, Write a program to generate Pascal’s triangle. nclute ctsiours ol = etl idle(row co?) arr) [cal] = ara: + aretram al feo($en; £07 444) rats for i I arrays 97 prite\e A, arr} werent , Output 18, Ina small company there are five salesmen. Each salesman is supposed to sell three products, Write program using a 2D array to pin (i the total sles by each salesman and (i) total sales of each item. include exto.to fined econo. Int nain() ‘ ne sates[){3]> , 3s total sales-o; ype pines PER THe DATAy Prineeyy teseetesne 0; 1S; ine) printf" Enter the sles of 3 Stone sold by soesman td: *, 1s) Forts 8s Jo) facet sean, Ssales( 1}: ) 1) PN TOTAL SALES BY EACH SALESHON 165 164) total sales = 331 4) fel sales 4+ ele pits ("Wn Total Sales By Soesnan Md = 84, Sot, total. sales orm, ses 11 for enc Sten Se) for 3c salesran ‘ales © sleet} rane) Tota sales of Stan 34 =a", 1, total sales) ) Output Enter the sales of 2 Sane sold by slesnan 1: 29 22 45 Enter the sales of 3 Stns sold by salesman 2: 34 45 6) eer the sales of 3 Stone sold by salesman 4: 39 5235 HG ages aa 42 saan ay 29 029 ¥ XIE Ux w “voja;IE "xu pudoas ap UI Sikod JO Jaquams apo} fenbe say 4p uf sutyoo go saqumu ap 1 29H! YP pM paHAW aq UD Sane OM, JIMA aay ways. sue pay 243 oF ypsou 9 Sus ‘prsengns 94 PD Jao Yea LA: omy, suas ‘Bum Aa poppe aq wo saounew ows Jo SOUS 4 SUEIIOD pu s§oE Jo saga ous a ancy Ag oy 2}quednoo 9g 0 prs axe soureu OAK) LNB PI a UE aynsa tp Sano ‘aypa801 pappe aq ued Jay Yeo Yj 2}qHeOD re HY SEALNEUL ON, stoi ‘e ue exe we wots tv uNOM Ux UR Jo asodsuEy, asodsundr uo suonead Sumo oy 49 nop wes a “hear ouosstOUNP paduese‘sioqumu yo pu vs} xpreu »‘sommtxgt ‘uy seounew jo ndaouoo yeonowoyieu ayy owojéim 0 pasn aq wed sAaLsefeuoISUSLaIp-OMy, SAVHUY TWNOISNAWIC-OML NO SNOLLVHIEO OF 100 Data Sracares Using C ) return 05 > Output Enter the elevate of Se wate ‘ne ents of the mtrin are 125 456 ras 24 Witea pgm wtanspese #33 mati floneats of the transposed astrie are bes 2a" transposed ast ADLII05 ' i f 22, Write program to input two n x matrices and then calculate the sum of their ‘corresponding elements and sore it in a third w x matrix. umber of rows in the frst eatrix *), ‘nuibee Wf ealamns sn the fst mitede % ‘oto pope 2410} passed aq uso Kein jeuotsundup-ows & Jo mor offus © moy sxensntE Yon Ze BE 4007 equ or oyp yu au Kee 24 Burxopu Ka possed aq ue Seu fwISUBLP-O99 BJO MOL WY ‘may @ butsseq ogee uorsun soy Seu g2_ yee eng ama me a emuooubses] [80/884 | | nppeSanses es Songer UoRDUTy | sou. Aye de j i | i Se 3) 0 eT ae anf ap Sous 1¢"¢ AmsLy “uoNOUTY ay O} exse fEuORSUATUNp-ooy D2KUD 2xp sod UD oan “PILL, i Seabed es enaa nena eemee ne eee 21y Bupssed oy woqeamnbe sisi :keuerouorsuaUMp-ony 2x9 Jo sor arse ssed ued am ‘puOIaS. “ o fe een ee oe iu of sein. iva cane Do eee ‘am euotsustp-240 jo owojo we Bussed se auras ayy Axo 8 sy. Kear aM J0 USNS Trnpuapusseduzo.o sug -uonoury ey dete fevrsuactp-ong e Busse sen cong am a104, ‘SNOLLINN O1 SAVUBV TWNOISNIWIG-OML ONISS¥d LIE yanen 3849 63 UE sttnyo> Jo Jog o¥y 803 Tsang HG, | xtunen 264 19 UE sau go Joquny 0103 fue wpunew qweagnsay ou 40 530m xyunen poses ain go sumoys ot eo seuy usp sonomns om 204 104 Data Sects Using © Called function Figure 3.82. Passing a row of 220 ayo Passing the Entire 20 Array fall m4. tea program to fil a square matrix with value zero on the diagon right triangle, and -1 on the lower lft triangle the upper sd. matrx(int it Arras > Output Enter the ruber of ras ae eolums of the matrix: 2 3.12 POINTERS AND TWO-DIMENSIONAL ARRAYS Consider a two-dimensional aray declared as To declare pointer toa two-dimensional array, you may write trchangeat sed using either ouloods st éeaejouorsuotp- se fsioau0.) Ke usooypuru ancy am fem aus oq ut Aout yeooysuu <0 © UL X9pu UO aR 2M SY Shes Jo KEE StS SAVHHY TWNOISNWIC-IINW €L°e Fes i yas pe sou om pues 9 LE Sod Bod agro eUayN, 10/01 ood wy wap seve gz a, 0 ame eb epee rey noo Cues oh bp eas yn psn fe eo ave xteu iy go suiawnts out Secesvert ape ay Jo suustore ay do anding, 4 ue Xe agp Jo-stmeots aL Oued 2 } (aims) aurnaerssp- pron ¢ we ees [OEE Ela Soy } >aforn)op Ge Hokie bay 49 siowora ms Sea “yort> opntaine eporoas apmpina ul €¢e Weds pe peas or eidoud ous, “st iaudp sf Aiouiat moq 20s | 1 a | pane ur stra yrauteus 24 9 349 stn 00 3052 jue smo J0 Joquinu ay swsaud 321s N95) 2 Abus stor 3 25: Jo sequin ay siuasou Ia2ts] oun fesse) 9867 ea “Busn Aer ue oy quod vampsop 26 S[azrs}aeu™hesse, adk-eaep | urn sed ofa we asg59 9 | ppd ou nding t ‘ CCE Hse8).) *.pe ata Festa. ey (ey eT t0 = De Here) ele] (ehove a5 } omen ut cxorps> aprTouTE 1 0184 UaA!8 9p09 aH {or s30909 4 sosayiasad 994) 50 uted #18 991 Mad) a0 18 paznoap s Cor ouoisusuap-on © yeas oy ssaupod yo deur we se aus 4p ou st Ae eUoIsMaUUP-Omt '9pHoUO9 Cx) on swtod + + x (o}-sea po “ve [o}eo}lo}ver‘azous OL LOK SBIPPE SI» Le LL auojaau, (321 591647 30 YoROSwuouDe s) 821449 atojduO> dys 11'91 pk “Cy}ueg Fue “upuayyue JoIOd 0 Suipaoooy sug ann “aoor ssaippe ste ‘sa 8 § Jo mos aaqua ue sds spony 9q two r+. Jo souppe ay ‘ozs mesa ancy soquOd 820M “ee uF aK Sey ae ge SU samoaus 2090 108 Dasa Sicves Using C colton of x0, x8 8, rif by using n subscripts as jimensional array can contain as many indices as needed and as the requirement of ‘memory increases with the nuuber of indices used, However, inpratie, we hardly use more than three indies in any program. Figure 3.33 shows a thee-dimensonalaray. The array has ‘1 $ Vv w x Page 3 e F 6 Poge? H Page 1 Third dimension Figue3.33- 1 simensiona aay HET a cticsinnsionst aay are anna te sae way we are ania ono and ays, “Example 3.6 Consider a three-dimensional array defined as how the memory repression OF the ae consists of pages. Each page in tu, coris rows and 9 C1 ee ee [peze) zal] : 7 (0.09) (00.1) (02) (41 {© (0.10) (00.4) (0.1.1) (00.2) (0.12) (1.0 (Column major der The tree-dimensional anay will contain 2 x 2 x 3° 12 demens Arrays 26, Write program to read and display a2x2x2 ara, include cetaio.r> arti) 8.344 SOLE YY PE ‘syous SBuins se ons srraanas Rp yo suDuo{ dt OL pas Ose ame Ke» splosss ae stouisa asogm Ke Ju sasegerep UU sojqe se Buepas 40 spury Jato pue sooueut‘sio}994 anew ‘an sunyoy easy swore ajo jog psn Xpuanbay are shessy SAVUUY 40 SNOUVONTddY 91¢ LR OTC TTP E TUS TY 99 8 Cw ewe Jo uqa09 amp ai9}1—Burddow ost MOY (8) ‘hem Bao} 24340040 Au u auop 99 Hed CeLeYeuorsHa\Np-2uo« E xENEU[EUOSUR-OAY idea oy) "satay osbe-uow Suo seis tap Ase YoSuaNNp-suo ean ED *SsowaurayyuSjuaroujo xan feueSeip-ts v9s05 of xe eIOSEEP-a e sMoyS OF ay squou2 "Po TF 30) suowseo122-uoU suE}ueD oUO Ep Uap axOGe. (3) “juau9 ‘up refe 0j saya o222-uoU suequo> 1 euoHep ua 80,99 (Q) i alo Te UF 30} shuoutaj oxz-uoU surAUOD I euoREIpUrEUN Xp) 0 wasead axe swou> jt EU 1599 ao oq any sau 9) Iouoflerpan © ups « 16 ~ +1 azoqa‘o="y sane fouodepin ea 20U0pt ew "asow ouodep-uepaeo ose st xuTeM oad sng jawFerp ow mojaq IOI, SEC AmB 4 anoge Ateipumu 30 uodip ayq vo foo seed uo ones aloz-vou ie tps sue yorum ur uy asd Jo yewonsowoue sary eis suo rues ue snows ony See Sd zie | 28 4007 Nor qu 49 uF OMAP C1z-uOU BHO asLHayN pe OY PODS 9 bes 1 sjuauape oss2-uow T nod uy ayy ot swuauo|9olo2-uow v sey xuNeU | | sepueupsoddn oxo uy Ecrazayn o* a ew sentueu-idén sereamby fi 2 6 sem RurwoyoyaJo a0 Au hoe op squr>feuseuossuomp-auoepue xsi euoisuaup-oaseusomiog |p yg ‘Buddew oy syuouojs o1se-von Auo sans yy feu jauoisuap-o00e Sa ‘sn ues am Yeowou a un puotaugs uteu seUELY mote 2208 OL ‘Nueu sejeBueu-rawoy v sways Hoe yee BW 007] mor yw ay a seus oxz-uoU w astaoys pe s403 puooas a Ut oo otz2-4oH on 01 uy a UE UOWOP auRz-UOW 340 eq ¥ EEL eusn-roMo] uxU Uy “C>5 aiayy Oy “REM sees 190] F Up Wud xp mojaq ade anya oxz-u0U 8 pn siuaun. om 8299 xe fouoBOuT (Hw) v pote Ose st xueus Is0ds $0946 UL ‘onjen o1oz » anny feUOdep mew oq aaoge swuaMaa [e “sen asses jo ac yu xp uy ssouEW aes Jo Sad ony a axD4. Tm stouy sn arty ose nea nok wauey 1 peau Os ¢oe(v058 a0 TISeyETT aw MN TXT AE a RA SLggreetmueenenee paiaoye ap ate ding, qi om) tat fo a) ) (of > Ff uo b (ardor = nor sue fest 2x x Za 4 SORTS UL WSWEIE ¢ ‘ 8 * pe )ue35 (eet te>4 10 a)oy ) (oe 22> fo uo ) (ors 2 > 5 f0 = 0 Ho shease 2% 2 2 jo fume 9 1H3 WWE "Does use) ‘ear jnorsuaunp-22n sojutode yo 36m ayy sores ory uresBoud © ay “Le c {q Seuejeuotsuoump-samy © Jon ase) Dede = (NCL De can j 3 Rana 4 The elements ofan ary are sored in consoatve ‘emory locations end ae referenced bya index (ats known as the subse. “The ndex species an oe from the beginning of the aay tothe element being efereced (4) How many elemenss woud be moved ithe é Andro bao be aed ini Programming Exercises 4. Consitan aay wines (2015) which es the ‘marks obtained by 20 studens in subject. Now ined in each ©) find the average marks obtained by every stadent Sind the numb of students who have sored ads an aray of 100 of elements whose 3. Wrteaprogram iairchinge the second clement ‘with he second lat lament 4. Wate program thar ileus the sua. squares ofthe elements 5. Wht program o compute th sum and mean of 9. Woes program tat comps te pod ements hat are stcredon the dismal above the arays—ane that rsa! odd lonens of he ‘vo-dimensionsl aay and the oter that sores alleen clement of te aay. 12, Wrtea program read two Boating pintauaber rays. Merge the wo arraye and digpay the | resltant aay in revere order, 13, Witea program using pointes interchange the second bigest an he second soles nunber in the ara. 14 Wiitea mem driven program to red and di 1 pxexr max, Also, id the sum, rans and produc ofthe two pxaxr maces, 18, Write program hat reads a mati and displays the sum of is dagonal elements 16, Wht progr that reads a mati tod pegs the sum ofthe elements above th man diagonal. (Win Cateadte sun of elements ere soe ue oy saemens yi uosoidp uy “g “WOU UE MUBLOTS wep YE ss Aus OY “y ~ “ur iy dus ws evs y ~g _¥7 JO SRW oy ss006 oF Poss OOTY “E _— ‘ajo vs psn qu owen ae Uy *Z ea us 29 aA soon aon yan yas pons ean “T seq tions sovou feu Suueped *s = se so Kane ip 3 URN sadusqns uyeiuo> suoup-u ey -g UDNEURE MT TT pos a feu we Jo ue LE Bsn possoave st you Keo ‘squeta ou, i em go sans wy oN N29 AST pst ana e> sBuuys spp 20 open st po} wore wo wees up UP Sod oF 9 “eae poses gy yo sq 4 Pats ae a 30 susque seo fee PRP 9 v WaLdvHO M6. Dan Snares Using C | onan seg fosore te charactor and sero ste ‘onal character. ‘doesnot alow an emply character. Figet- Deane betean cha ne and ting storage ts (also known a index) to access the element to access the elements of ast the characters of ive memory locations. Figure 4.2 shows how stored inthe memory. Ths, a sequence of characters. In Fig. 4.2, 1000, 1001, 1002, et, are the memory addresses of individual characters Fr the figure shows tha ix stored at memory the ASCIL code of a character is stored in 1g ae Insuch cases, the compiler ereatesan array of sie 10; stores "WEL." int and finally terminates the string with a nll character. Rest ofthe elements inthe array are automat NULL. [Now consider the following statements: cannot be separated from declaration, 4.14 Reading Strings If we declare a string by writing 00} can be tead by the ser in three ways: wellknown and easy to use, th rain of finds a blank seace. For example, This is because the moment a function. You may also specify ante ead. Remember that extra the inpt buffer. values, s format does not requir the armpetsand before pe wha tin i a ‘The next method of readix ‘able inthe scant state ‘eres an er. character Th (das st gene tre pasianen uaag aney sixoe af UG patdoo ‘seo Jodd ut Apaaie stage 211m ‘q 280 sod ons poraauon sy wy ‘9569 Zo tts} sper yoeo ase 2815 Jo Nop 3p st x Bug 0122 0p st) wisis4an 0 pape Rey) © ua W'94%> w pouyep ave aye ()sO%Te9 pu Csadinon sume ht 2809 10d eyo sien ases sano] amy su2Auo9 Ue Smoys fp aang a>jseIyD ayy Jo a se dn 21101 Z¢ Pe 01 pa2U aie ‘He9 19m] ee ‘seo sadn ue pag 0) aney 3 apa is dng ‘J anyea oS am woy ze taengns oy ou in ‘iol = [nIsuswedan Las aang (oor 40 03) {an aseoFoddn opt sy98sEY9 3649 J2MO] © HOALOD 7a aan 2m 3'0$ "Ee 01 4g toy SBE 2-8 Joy 3F09 i wael OSV aH pur 16 0% $y woxy souea 2-¥ 30) 2p0> tastier ot TIosWaUL tne xan jo pena pace Soe sve TOSV Atotuou a ey possnosp Apeae ane om sc rls 41: dns ‘today “tone ose or bs Gurwtint) 16s Jamo pain om finns @ osiapeseyg Gupenutg oF 8 Gareuine) — _____ Fras ag wea ‘Om = meas oka vet : nding, t Owies (Bsr (rt oy Bue an Jo UBT AU wags samen urea 5 venues spate ror abuts 2m pay onwestond yy Baus jo igtus a Sings 930795 Wa tig (15.81.95 vo "Jo onyea a au pz St boy am ue doo 4" 2p 30 No Sul anton ap eID Tm a stunoaU 3m 9500, on Baus Sr OSepeRP YaNEDO LULOON FP endl, ® ings eyo bua ge had ey a | ‘soreness aoe | sien 385 | gp souonbos e quid oy Aipoweadas uonaury (4eypans ap Sad Aq uantin 9 ose wea SBuLg fo sypequesp a) suoalo4o Tew uoHauny ads est (as)nind Td 2 my 4 posjdsp 0g weo Suen y -uosouny ()s9 Busn Aq st Sus @ Funes 40 pompous x ssa uo pup Soar a ane cds paid tonsaneay Gasan puta anveg sa supm eH UNA TET aqua 9 “aida 104 uals ‘poynsnf yor Zauisaxp ayo) ypu paesoe ap ut pays WBLL9g Pj sseIeTEYD as 081 ‘so}oen 244 Jo AY PHOT PU Sa.geNp a. sy aH UO Ad Pow Wows ‘jduroxa 10g “porous 13 xu ap Soytoodsuows2014 24 pus ayau y ‘popped yu 30 pepped yo ses.) nutid ja vas sou 98 so ‘padeydip 99 01 siovnseyo 3o saquune e}9p 9 ue Ne Zoe oys sped ya] 1 990d x9 "Hogs ses ng appl play ado wouMun a Soyioads iw a5 ose Seu ayy 2]geUEN Bus 9 sengereyp 3, US! 314) 8H AatED 34I9SG0 Bute wydno oy sxsOy!rads YUL 2509, Perret ouny (saved ujsn ‘sess aan Bono ap Busn usos a wo pacedsip 29 ued sé suns Sunum 21-8 ‘pctude estdo.to fines ceontet> Sat ring) 4 * |. wpe. ste[300}5 print#("\n Enter the string :°)5 ets(str) vhtle(ste) 1+ 0") c fiGstelsyee! a8 sted} pert} = ste[8) = 325 11. Write a program to convert the lower case characters ofa string into uppercase. oper see} = stot toss } > aper_ste} © "(0's pranef("\n the etring converted Arto upper case 1s 5"); puts(uppe sts, , Output Enter the string : Nello | Thecstring converted 4ato per cose is = WELL | Ampending a String to Another Sting 12 one string to another string involves copying ination string, For example, ifs and s2 are rwo stings, t rans we have to ad the 110 2. So, sts the source string and s2 i the destination sting, The appending operation would leave the source string s1 unchanged and the destination sting s2 » £2 + 51 Figure 4.5 shows an algorithm that appends two stings. ‘Te iar function seat (st, 2) which i eed in string. concatenate sting 21 =. [ig INITIALIZE) SET 1-9 and 2-0 {0 oF cor) stg: Rvs Spe 7 ote se sr) I= mak Step sa (100 oF 100 end, thai, each 3c source string ate thet Soings 124 copied into the destination sting starting from that position, Finally, anu characteris added 19 terminate the destination string. ‘Waite a program to appeod a string t6 another string Hinelute <éetio.t» include scot. fa main t char vest. stato, sures. stisa}; 5 gelott a Eater a sire sting ©) opeetseurestns : Ager" Enter the destination sting = °)s Eestoese se) fo Bose sera 05) es shitesoare sts} le “0? t vest str] = Source t3]5 ‘ ce ) dest Setts o's rnG#C"\n after pending, the desthoation sing is + fastoesestedy 2 eet return 9; ) i , Output : Enter the soucce String’: How are you? ‘Ener the destination string * Helle, ‘After apoencing, the destination string Js : Hello, Hoy are you? Comparing Two Strings ngs, hen comparing the wo sings (@) stand s2 are equal (6) stos2, when in ditionary order, st will come after 2 tionary onde, s1 precedes 52 ‘sco strings, each and every charater is compared from both the: the charactersare the same, then the Wo strings ae si that compares ro strings. MEDS tery tncton streets) which ties in strig.n compares sting st wh 2 In this algorithm, we first check whether the two strings are there iso point in moving bead, a However, ifthe 1wo ans + om Bie ES MIA AAs Jo IB}ezE 4D Wt 2 des a "p dang uy passao0e ae Sums 9 Jo soneI 2 cong ult Suns ayy yo ypu] ayy or pecs st c pus a2 01 poz 9 ea se 80.35 opens Ct) Suns» soszar ey un y si wo os pus satoeueyo se puosss aan YI 1IEYD puodds say eA ANIM 1519 ag dens 0} paou nf om ‘Sus v 2831 Of “Hi Tenby se eer aus Srngs 18 Stefi) = stelss Batebies 4 fru stew: sbstets)» ser: my i ca So Printf(*\n The reversed string is puts(str): exten 1 ; Output Enter the string: i there The reversed string 15: erent eoeereetistrine sector Extracting a Substring fom a String Toenract a substring from a given string, we need the folowing three parameters: 1. the main string, 2 the position ofthe fist character ofthe substring in the given string, and 3. the maximum number of charaters/length ofthe substring For example, if we have a string str] = "Welcone to the world oF programing’; Then, i suesrana(ste, 38 (ariatrze) Set 1-9, 2-0 and 0 Repeat steps 3 to. Repeat ubile Str(K] {0 oF ack oor) : N07 F- 5primee (phe sinstring 48 2 5 buss(onorte) ea return 6; Inserting a String inthe Main Sting The insertion operation inserts a stcing s in the main text + The general syntax of TASERT(text, postion, stein). For example, tows an algorithm to inser a ile TEXT t= sue seu sel} = Serie) fut ané 0 |] Figure 48 shows en slgoidumthatextactssubstng al? sgt sos) «St ftom te middle of sing. ev ste(3} = eT] suing ina given extat the specified postion Sesc3ed in this algoritim, we meron “This algo ii Srnsn lt that is the poston fom w stop 4: Sete Beh ino the string to er, F 0 a copied. Steps 3 to 6 are repeated w {eno oF out ‘contents of wey sTR are i 4 ineverychaacer copied, we decreren |_| step 5: Se nen sr qual to the position a which te substring been copied s the value of». The characters of the string are: eek Agosthm toertract a subsing from another string called the suas, Atthe end a the midi of sting is appended to suesra to terminate the string, 6. . Write program io extract a substring from the middle ofa given string. 7 include estate.» Flneloce ceonte.h> rt main() ‘ rinef(\n Enter the main string © ")s bets(ste)s Enter the position from hich to start the substring: “)s Brint4("\n Enter the Length of the substrings) Scant", a) hile(ste(s] I= "or aa 0) ear ‘as tobe inserted, then the inner lop copies the contents of the substring into nex. sr Otherwise the contents ofthe text ae copisd it ‘Write program to insert string in the main tet, {include cxtsio,hy ineluse ceoio. > ne in) ‘ har tert(10], str{20), ins texc{2c0} nt 1-0, J, £0090 clrser( Prant¢("\ Enter the main text: *}s bets(text) DrintF(*\n Enter the string to be inserted : *); aets(ste)s Drintf("\n Enter the position at anich the string has to be insersed:")s Seont("2d, poss vitectexti] = "10" xa) uasi8 eu sss op ag sm ‘usrevo9 1x01 Jo sa}ezey9 om {Ty Bomo} wuONIsod Woy JulAMSPay|ap 99 0) ano ey sus;erey> jo saquim otp $1» 0 x9pur 99 wD “eH0p 94 ory way uogsod yo ee aun vs din 1 ofp 0} unquodje ue smoys sursenennat 128 Data Seracires > Output Enter the main text Hell Enter the string to be deleted The new ring ist Helo Pho are you? res et ‘Replacing a Pattern with Another Patter in a String “The replacement operation is used o replace the pater , writing rPLacectext, pattern, pattern). For example, ne) = saawcec by another pattern», Thisis done by | Inthe second example, there is nochange as does not appear i text, Figure 4.12 shows an algorithm to replace a patter, with another 92. -Write a program to replace a patter with another pattem inthe text. incloge conto. taint) c char ste{200), pat(20], noe, ste 20 clrser() printf(*\n Enter the string eets(str); ("Wn Enter the pattern to be repli ” tar te replacing pattern re_pat ep_aners 0); the length of every individual nar nef the aay be done? Here, we needa sing o Here the frst indes will specify how many strings are needed andthe second index ing. S ‘name can be a maximum 30 characters long Let us se the memory repres Shings 129 rng that stores the names rings or an aray of strings al stings. An array of strings is declared as speci ere, we wil allocate space for 20 names n of an aray of strings. If we have an array declared as ri", "Gop" stored as shown in Fig. 4.13, Figure 4.13 Menory presen oa 20 character aay cows ipa putas jap os wha “Cost soot 3s ae aus ap owe ) Ourew sh ‘arora pntaun eyroreas apaute Jou Jo aunspued vs uns &stpeq pu 0} wesBoid ayy 62 sf datbeln yo dumo> pean og u 1 ay onium Jo os 18 at ‘ois Jo od ast Me NL {mes ion pe HE spon go ares Teed a sy pind se> ‘ames pie (oon (erase. = blasay eas" a wor P68 sor SRR pad 1 Oistos “y= Sus on oor uF ‘Hoots se ter sua / “vrorpat> apmaene ‘spe Jo s5qU De RueS ysueuen eAGIpy | AVE wipe yeoTeReNETE HY SUIDMS Bf nding, ‘ rsa Gers yfoer)a0y fe vapuo qeoqamqeyete Ur siuppms ayn 40 Foe WA. JaNUIUE Me ‘ ‘ Hon “traf}soueuyterns H(wvF}seueu ‘soueuycasays F]seeu “auss) casas , rsf}soueu *(C]soueansursss ay > oheoe , (ersswrfoeriny t cirsaveuyenaa C065 1. pe su0pms go aueu ays Janu) weed , Gsrtwstostany (9 9) 30025 suapmas go ssqanu ain Jones oad ‘oop STortéway “Cor]s}saes ee ca “yroru> opens ores opener tepmis Jo sour a4 oso} wesBard ey, ow ‘bosssaouds Suns enpratpat yea “¢daig uy ‘passave ae Aue a4; ur sus om je yum pamoax9 51 doo] ate FZ , ssa feveue epg ssoo x untiy py amy dang sz og quu xoput om seen 4“ dng up stuns yo see Cunt One eguee oad = meses cae em 0 aot 1 aig paisen st paroo Kowoul ajo eq noge_f (zIsaem oa ssous dey” 2¢ ss ey 298 an sn s044g £2 81 potdnooe AoW yenoe ap Cee oman time Ing sag 9s amaoqe am Sau Ae 2 Bue}209 Ag aflstrea] = seen c ca 2 se 2 rea y 1 des) pripee(r\n eaLTOROWE); slot Wa PLONE), eto f et > ; ee Output i Tn the Seth win ane 4.4 POINTERS AND STRINGS In, strings are treated as arays of characters that are terminated with binary zero character (writen as *\o"). Consider, for example, cor stel20)5 CC provides two atemate ways of declaring and initializing o ting, Fits tar stel20} = CH, 188, °1, N04 But this also takes more typing than is convenient, So, € permits char ste{i0] = "HI"; ‘When the double quotes are used, runt character ("\0") is automat of the string sppended tothe end izes its first four characters a8 ¥i\0 prints a text prirté(*\n The seeing $8 5 "5 thsle(tpete '= 10") prante(ters “ste pate ) ) 7 ‘Output The string is: Hetlo ses aside a contiguous block ofthe memory, | point the pointer pete to tc, Then, we prin Instead of using the write loop, we could straightaway use the function pi pots(pst) The function prototype for pute) isa fl Ant puts(const char *8); ere the const modifier is used to assure thatthe function dose not modi the contents pointe 0 by the source pointer. The addres of the string is passed tothe fonction as an argument. ‘The parameter pased to puts() is pointer which is nothing but the adaess to which it po to of simply an address. Thus, wtiting pets(ste) means passing the address of =tr(0) ‘when we write puts(pstr; we ae passing the same address, because we have written pstr= sr Consider another program that reads a tring and then sans each characte to count the ame of upper and lower case characters entered. using the sate loop, ly uppers s\n Total munker of wpper cate characters = Xe", upper) Total ober oF Loner case characters = 84°, lovers Output Totel nomen of upper case Characters = 1 Total numer of lower cave characters © 8 13, Wit a program to copy a sting into another string. include estio.t9 sot moin() 4 har ste(300}, copy_st(300}; Reopy_str = copy.strs osmperew 1 saedinoa| sosiaierg Buymwesborg | eis |e pt kaze spesiye © caansg aes (01 pas stonoury mip finder preparys ay way peat su 5 M2 WORRIED 20, sn Huns 70 2ueN + |e poosep ant 9 se om sues 2 ad |e “345.2 fg 299 9 PND 2% suomoy 9s Jo Kory, suns Jo smn) aAHNNSUTPAIOSae Sa EONS APH + | skorts Sousqadime ay sug ce mo sms ep ses | Pou2idj0raqmnae sods dig pampoms) «um poser 9q uo seams jon EN ‘Aypredas wore) seoan ‘ear pein prema u es Ns # set Buus a 6. White a program to count the mumber of digits, 2, White a program to rewrite the string “sod per case characters, lower case characters and spect characters ina given sting. ps AT 52 =SHELLOY 9 BYE". Hlow exh 492 Wh ngs intialied during its declaration, ontaenate the thee sings? “the ering musbe explicily terminated with anal aoe); will rerum & ‘peraor ean be ured to copy the ‘auints f one string into note 29, Nea program insect anew name in thes assuming tha names are wore ‘untion aviomatialy sppends 816, ition computes the end ofthe string read from ing 17. Besides printf, function can be ‘sed to print a line of text onthe screen the keyboard. 12. Sting variables canbe present either on the lft ‘orn the righ side of he assignment operator, 18, Weteaprogamto convitthe pve sing “hello 3n1193780 ONINUVIT ‘win parpop oueu agouen yoo ody sip pougap | auioeq Sey aandans aN) NON 4 suoluy) pue seunjoniys svoun pure sana vogesecop aye unos #909 98.9 0400 sue sen sa e309 oo) ©) MRLaVHO (61 S901 pu sams alterate names given toa known datatype. The general syntax of using the typedet keyword is sivenas: ede statement doesnot occupy any memory; i the new name of datatype in. To declare variables ing the new datatype name, precede the variable name withthe data ‘ype name (new). Therefor, to define an integer variable, we may now write When we precede struct name wi pendant sateen def keyword, student becomes ofthis new datatype variable of you may write [ote that we have not written 1, Siruetures and Un etant2, constant 3,035 ie a student structure by writing, 5.1.4 Accessing the Members of a Structure Each member ke a norms scoessed using a a strutute or a member of structure can be given as: tv. nanber rane The dot operator is used to select a particular member ofthe structure. For example, to assign values to the individual data members of he structure variable stud, we may write Once the variables example, We can use the jgnment operator (-) 10 as to: dogo Tos on Jot, nding oon toms SPL son pun sumonas 1s parodunes 24 ‘uo Jo siaquiaw fenptaiplr u942M0K so\pouE th 2jgeues aston 240 jo uosurdwo9 Huadu so0p. S14 U UMOYS Se UDA 2g Songs aif MOU aI0j8194, un gy 2m our Hooosy ‘v2 rans ajo fy ane am J apdurexa 204 ‘ody aus ay) Jo amisrusYotpoue 0 amos BWSBIEH2 Nh saumanug Sueduog pue Gulden $$ ) se pedo ca ‘aa Sumo wo ope aL Avo ub ae pe) sto ae M4 Data Soucares Using © eq" sum-c.real, sur_citme)s break gib_coreal = chips) = e2sreals 3g = ching ~ €2.3nag! The difference between two complex unbers hein); betes paitateption te Bech: return 2 Display ne comles aers “3: hal the comer ners LAS Sitsce the eo] rowers 3 on Feeer yaar open 1 © pte Igcresh 8 Satan pets of he frst compen nbn +2 3 ie heen and Snglary parts of Ue second Crp rmber | 45 me aC lee abirs Tie feat cole nabs 48 Sin stems ine neers fe Riempom as bye conaneren sahtnbers aun, gael 8 5.2 NESTED STRUCTURES ‘A structure can be placed within another structure, i. a structure may contain another struct its member. A structure that contains another stricture as its member is Let us now see how we declare nested structures. Although itis poss structure wth one declaration its nt recommended. The easier and clearer way is to declare the structures separately and then group them in the higher level structure. When lake care to check that nesting must be done frm inside out (from lowest level to the mest inclusive level), ie, declare the innermost structure then the next evel structure, work ter (most inclusive) structure. har Lastname oe poate, typedet serve e ME mane; mar coursel20);, ote oo; ture student contains tWo oer structs, MME and pre. Bu The structure nae has thre fields: frst il nan rane, The stractre osTe also bas tree felts: 4, en, and yy, which specify the day, tnd year ofthe date. Now, to assign values tothe siuctre fel, we will Stud nan Stud sme I3et Stu 008.m = 03; Incase of nested structures, we use the dot operator in conjunction withthe stuctre to access the members ofthe innermost as well asthe outermost structures, The use resis ilustrated ithe next program. Ls 3. Writea program to read and display the information ofa student using a nested structure. ‘include «stato.» ‘nelude cconfo in mind t sere 008 ‘ Sint dys » ‘ » SeaniCad", still ro no) rint#("\ enter the Scant("S", stud -na Seanf("#, stud fees); scanf('d N8 38", Atul. date-day, Sstw0s.date-eouth, Ast date.year); 1 855 19 soy od avg “p4.) 4005 G+ devine 9g ox se pastes Stoum sgunu auapans wy omnes Uebsaufod t eto E> ‘on Vi 8s) A INBOAS 40 STIVLIOasoseeng Why) WHA ) (esseutos ooh ‘ eo) “oo0es +408,“ uekay, ‘sv atti ua 2 ‘wonesesop yo ou aun sojquues armors jo Kear agp iat tang pang "01 esr 9 (Fons 284 a oat neu" [Ipras) 3, Pee i Goriisroryaos ose 1S A 2718 siento sBluy NOTE pest ous mia “any 15 18 WE Hosloms suepnis sans ‘ % ojo see 00) iE ‘loslawe _woneuusoyat are xp Axydsrpox paz wopmys i aun Jo syreap acy pe sep B48 uephas oqh [eso wooo sin eqdsy pus pester meron! e yp fy 98809 ame ‘Hoves-ingine 9680389 “se uo aq ue soomanus yo Kze ue Busefop 4 xe eo 4 saKoydua amas jo dea we “a Kojdia ay ye 30} wonquyop aumgnuis uown v 9x84 ue 92104 ‘0g UOHnos ae14 © sto0fojdute 1242 Jo} aunanins aeandote Suuyap ‘ag ‘stays Jo aqua 8 Sey utleziue=i0 Uy ‘uoseauedio ue Jo ase US} ajqusap st saunouas so Cen ue a1ayM ajduexe soqouy dep urna #0 fee ue arjoap an se Kom aus 29 ut parpsap s sanjonas yo ease uy “saunas jo AeuE Ue 2 2 ua aid 9g pyvos STU SWANS OF ay 0} pas 29 ueD amIonas ox Jo voRTEP ‘uss 9499S s1u9pMIS Oko] 9q UL BLO Ng wOpTUS 240 nf net JU Op am SSE} HL ns Jo ABP pad pow aN aIDYN sKfuUe Sy ‘eu us soy Snap [1 98 ‘HON “IOqUUSU! IL sa) ‘asodind sp 204 "paresop #1 sass, "ap su 1 Sonje wBISse pur aumonns v aze}9p 01 wf ues aNey an SafduIExa dnoge ay SaUMLONULS 40 SAVHRY 8°S oorenase = 5334 Tey : suey on asta 0 :oqins (ou 9 3b nding, ‘ fowwa oeteonep" tes “gucw 2p Tes “Aep"2eD TONS SPR ~ PL P= ona.) (500) Tamas “ay = S34 W\)sneTud HCouee-Toms “Lox = 3am WD snuTad cor tps "px = on TOW U\wod + SUVIGG S.1NOSeeveeee W)S30F >is 148 Date Srcures Using Srrctres and Unions 199 Passing individual mombers essing the entre stuctre Passing the address of stucture Figure 8.4. Diteren ways of passing seucures to ancons 5.4.1 Passing Individual Members ‘Topass any individual member ofa stucture toa function, we must use the direct selection ordinary ‘ variable ora structured member. Look atthe code given below which illustrates this concep. Output Enter the unter of students 2 Drintf(* The cordinates of the point are: Ed a", a, 6); > Output ‘The coordinates of the point are: 23 5.4.2 Passing the ie Structure {st ike anyother variable, we can pass an entire structure as function arg san argument, itis passed using the call by ¥ | | The general syntax for passing a structure ” struct struct_nane fune_nae(st ‘The above syntax can vay as want g fanetion fo receive a strut code given below passes a struc tops them to functions and return inthtee ways as shown in Fig. 5.4 / essere ‘anes course 9 PE - Sorvep a mn en? on 2 oy eg at a ea € ae JO1OU"TPR “SUITPR APR PE_)IUEIS eens 1 sun em os ao tote + sas «ss 5 trans ieee wopseyenie y {(voradow ‘px, sues (o> semeent 1, 4 write tanta ego ts c G10 *$ UTS seme eS erm H,seounsye ous 2885 “9 sameetes sees nae ee (Ceaseae ah oe “ews + 1 saoveastp aut fe[dsta *z u\,)sauTad “ ; fc ers oh en t ic 14 ONBH NIV vevveses Uin)43UTUC ‘ener ~ sew « sane Coane , ssonaeap nae eats o 1 ‘one (oorte mabe) supe a ‘te sta i ) | 8 wt (eo pst op sive iesns Saste ‘ap “9 "9 “op smasta : t 1 Fe ced ey cereal oa tis wins | ‘(Sawiasd “saat some oe amt i | ‘sos sont x sme cata | ee , | ; oot =< anima} inn i nun tne oa oeAZP + SUED > SUEk‘wmns: i ‘eqroquon> apnt>urs_ sneer ane osbme rors omtutt , sto po su fsa (em aes “ip peste ve hmsia Poyep aqisney 29mm] ssoumsTp om aengns pu ‘ppeKeydyp ‘Pras or ume CAHN, “S tow + verter ' : s (hd 6 ‘pe PR S8UR quTOD oy 30 SexeUTpLODD ayL,.)4IUTIE “Coonow-p fa yp “shou px sa ! Fe 5 sown om wwatog sumssp aL Uda (es Sc "poet sana soe 7 sma. se ayes into sias-ep ‘sexe ‘ene , Px S04 EF ST seaRSTP On Jo AMF ML U,)J2UIAd Sep "WUE He = Ove ae Cantos) p20 182 Data Sectures Using C Enter your option + 1 Enter the fest distance dn kas and miters: § 300 Enter the Second distance in kms aod meters? 3400 Enter your option + 3 The sum of too distances 45: © tas 700 waters Enter your option : 5 Let us summarize some points that must be considered while passing a structure to the called + inthe e 2 is returning a copy af the entire structure then it must be declared as, strvet followed by te srocure name. ‘© The structure variable used as parameter inthe function declaration must be the same as that ofthe actual arg thecalled function (and that shouldbe the ame ofthe struct typ). + When a function returns a structure, then in he calling function the returned structure must be assigned w a structure variable ofthe same type. 5.4.3 Passing Structures through Pointers Passing age structures to functions using the call by value is preferred fo pass structures through pointers. user-defined types. tisextremely common to create poi but merely a variable that address ofa structure, The syntax to declare a pointer toa structure can be given as, (4a03_type meer pane}; votes * garuct struct_aane “pte; For our student structure, we can declare ap To access the members ofa structure, we can write get the sructure, the elect 4 menber / (Got, stag) roll not Since parentheses have « higher precedenc istatementis not easy same task. This operator i kno used as En fe roll.no in the structure pr stad points to +/ 6. Writea program o initia the membersofa sete by using pointerto the srr. cle eat fret art ‘ tn tare Sar ews Se tes b Jie sin) ‘ struct saan sta tr sts aise dered» tetas Sent" teeth detlls ofthe student £5 feloe(en tte the tlt Heder Tamra perro prints eter esc set» Senha tote te Case = econ s0n"> curse) Snip tater the ret = Santi" ape sat > fe HL MBER mt post “> 0) An ees pts nan), Output Enter the details of the student: Ener the fol! hinber 02 Encer the Mane » Adstys Ener the Course = HER ine = aya Write a program, using an array of pointers to structure, o read and display the data of students. ‘include Bineluge Output srrpmsie fewer pe epnoso0 25 9939 Buna an nada anon tpg sasjuan Sywuestong yon 24 ues soon stopeoydde you 4mm seinonns nog sidux oe i 1 s3pHdea promkoy ao, ‘ofetenao9 -scoindsnur po sins wo sou "etn pean i Pe i soins oss ‘sinus oe ‘8 quou 50 pose |e nis sopra soot posses ua | towne po armoanseusaviig soup Apo su) -« sequen yates, 3 24 29 fb sung jo a 9 oa oped loMCoy min pops saraaaRaAs ety : ‘mona 26.) Sam Ramee a oA aon m5 pO Soni dip dee s9r] sum gaat fo SePiag hope ‘amon emeaRjSr ore sMop¥SA pon Kouou 3H nop Hamas 24a 30 mp 0s 2 my s09 amp 01 Kanu yi amt ©5948 nf apes seiosoumming 20 Keo 8 aye] 100 9p. woneajap sanonas our. + 3 & 3 i 8 5 i i i 5 PRGU & pqs sr amonuw ® gong oquom 3 $8 tom otto 9 panto) | mbes fepous weaioo fom amoms vst eu ‘asm pao om Sus pompop s amoae y # trouser ay | Toon Be Gale mp oman | Fosse ed reams gma areas y+ apis ad tp pnapnd ee seg © Se {afeaetod “Fp pu Pe ave Lpattog 40 ssi 610017 pur sans 160 Date Display the ame of the stidents wh ave secured ‘The function mus recive one parameter which less than 40% ofthe aggregate. {za souctue that contains the ype of igure and the size ofthe components needed io caleult ea must bea part of uion. Not th eautes just one component, rectangle re ‘wo components and ingle requis the of thee components to caleulte the area Multiple-choice Questions 1, Aaa soucture that can store related information fons 99 884 pow aU op Ound aves 29 aby ‘sSouppe OU 24798 Om “Le am oo ‘wong pou you 240 of 01 eau Surpuodsai0> a4) 205 29. . “ueSy-3s1y ssenppe tay pauterqo atwoj> pep puosas ayy [oF rims ‘oxy pou oH ® AL WSE DRI 5 avis dune rz zo] i © t t are SuLR|>9p IA SU aqmnaosuon ut pasos ep Jo wo}2oqo9 soun YS Seus uP Te paipMs ane 94, NOWINGOMLN! 1's Peay ‘apo ya aio sS29pe fas pba zed eo 500 an 8 uanewo Jo vou pve "doe uo, Sens Soi 9989 wood sue wep fae! CuLOS yo Ken woe UE Eph sk ORT vou, apou aon eep aut i udu W029‘ UL ‘poo Soop a4 Bun st pa cqy "7m = 2901s S9poujourEYD Pu 1 2p0u Suppaeoos sto ssuppe ays J SSa:ppe ap SUIEUOD YPTYN. sus 2 Ut 9poU 94130 ssappe aly suors eH LIAS ayqaLEA ‘ad oyop onuacaeuos © pay 20) 2pou yxau ay of yutodw suryu09 apou ayy jo ued Sis ayy, “emIonys eo “ete ue ‘2d ep ajdutsw apnjour deus ep sureru0> Yong 2p0u a, 19) pox aeuis WEeERKEEKED REE KE LE KETE SIS] payuly ‘pou x9u 24101 JoUJod & pur splay mEp 2:0W 20 uo sure apOU {oes yy ur sapon yo aouenhas v0 wien #8 poatsozodaq ue9 1 POU V SuoULEA say ue Quniewo ‘sonenb ‘syns se ypns Somnus Hp 1uDwA;du 0} ya0(q SupNG #8 se ‘SM soaMDNAS : e918 poner 164 Data Sructres Using C Linked Lite 168 ‘would denote the end ofthe linked list, When we traverse a7A and nex in this manner, we finally ene noe are == : ‘word HELLO. - ‘S02 ‘Shyan Cy 1 Oe eee nae eer a : See ee 1 : eres peer = 2 See eer Lery igen orem ree a : ‘pointer, which gives the address of the first node “4 sua 2 2 Paes 7 Next *5 are reached by looking at the value stored sant 1” 3 ‘in the wext. 2 . 38] wv ‘Siz ‘worica 7S ‘Distinction = eo tee | (conser Science) Figure 6.8 Sten ket Ist Computer Science ee $02, $04, $05, SO, and Ths inked roid an ficient way of storie elated data performing basic si, such at inseton, deletion, and upon of informton athe cost of ex spice required Weave already sith hana pat node Storing headdress of next nodes See 6.1.8 Memory Allocation and De-allcation fora Linked List example ose how a atelistatcsond | 8/8) 8) wwe delete node from occupied 10 avai hw the operating sy we can say thatthe comy an srry and linked ist ean be cee canbe done at any point in the Another advantage of linked lstavern array a store a maximum of 20 datsele all fee memory cells. Thi ist of availabe space is called the fre pool ‘ane a suretn09 2 2pou 240 Sapp aN suas mq 308e ip osaxd str ou apou san yo ed worresoyr ogy usar stone aa 8 eam Spay sua Bunysea5 05 wed +94 9 pue ed uonewoyus a sed ot om Peppy ar yom spon o ass “pessosipAPEST SYST Pa spjoqued puy 1 sueau sy pou» argo 1811 poyur e ut anren e 10) Suryaieeg 2°2°9 31 poyut# ur sopou yo Joquumu og yuad oy uuuo8ye om swous 69 any paseydsip 24 sooo ajo anyen jeu own possaxen usOg 3308 poy a Jo pou HSN yoear am 2040 * Ay sono ay wow “pou ronpiaspuy Ato Bursionen 9149. you &gapou nou a 01 2A! unos ory me an yoppy 9) ssovond ayn Aide 2m “24g UL TH SBLUNOOUD HUN st mN“epow se a yeadarst yuu pana st doo} reve dats ut wo, 81 paMUl 2410 9p0U super -usipoao sauna ay pd UO 69 amy 09 9 E}UOBIE SH Up 9°30 eoquaMDy wo4 UO 1s 249 Jo sopou tp Suse suvau i poxUY ezUISAeAT, 1877 payurTe Buyssaneu, 4-2°9 ssupenuy Ag 9 embig twerBoud Jayne aos Aq posnos 24 05 ood 2945 a4 01 oq ET KEREKER “1 pore oyu Aus 204M ‘241012100 #sureu09 9pou Hp 15 © smoyS [9 amily Kea uo Ut Kuo Ep so Tesz048m SH ‘a apou rua 0 ssemppe des yada ep ues any apou rx ay 01 B1YOd e seus 2pou ayy ep ueaté 9m “pow OH pur ep ows suteoo apou ioe youys ur po jo a aps ay SSH Pay ABUISY ‘SLSITG3¥NIT ATONIS 29 nose a2 oH a 2 Gs op JO SA la a ‘wo1yajjoo 3008 pa st ssvos! nu sniea Jaqz0 Kq past aq us sj aso HOF Yood 204 ap 1 saIppR Ay) 1919217 poqwry 7 fc Tote aH atte pms n o every node's pata with vat for which the search is being made. IF the search i suecesfil that is, VAL has been found, then the address of that node is stored in os and the contol jumps tothe last statement ofthe algorithm. However, ifthe which indicates can be explained a sh TH Linked Lies 169 THY TEPER ELE ELE EE Allocate menry for the new node and Snitialine sts DATA pat to 9 209 the new node as the Fest node of the L4st by making the NEXT part oF the neu rode contain the adcrese oF START ° TET ELE EEE s]x} teow mak START to point to te First rade ofthe Hist T+ GT +O PELE 7a AG igor 6.12 tnseing an eeme athe bepnig oa inked at Figure 6.13 shows the cL ere PIR->OATA« 7, Since PIR -> DATA t= 4 we wove 40 the xt node ThE BEEELPE Ge fore PIR > OATA = 2 sce FIR-> OTA GE+R E+E EFEESH ELH ELF GE Here BTR > DATA = 4, Sint the adbress oF the nade th Figure 6.11, Searching ainied ist 6.2.8 Inserting a New Node in a Linked List Inths section, we will se how a new node is aed ito an already existing linked list. We will free memery cells present inthe system. When appropriate messape. Inserting a Node atthe Beginning ofa Linked List Consider the linked lst shown in Fig. 6.12 Suppose we want t9 add a new node with data 9 and add itas the ist node ‘Thon the following changes wil be done int ‘coneition occurs, the program must give an st the beginning ofa linked list In Step 1, we first check whether memory is available forthe new node, Figure 6.18 Algorithm to insert anew nade at ‘he begining following wo steps: Step 2: SE MEM NO0E = AVAL Step 3: Ser avare = “These steps allocate memory forthe new node. InC, there are functions likes Seruct node tereate_(steuet node tstart) c prince("\n enter -2 t0 ent") rewnoe = (stroct nodet)atloc(stzof (struct ode)); Geert t new nace» ext = Wt; tare = senate Linked Lots 177 ptresterts trste(ptr-anexe rot) Perper ono per-onext = nena) ew pede-rnareaN > rante("\n Biter the data 2 *)5 Seont xd", bn) > return starts d Struct node *eisplay(struct nade “start) ‘ viitegpte T= mut) 4 princécnve pers ptr ptr datas eo Petuen starts > Struct node insert og(struct nade *start) « struct nade tn od int mow Branté(*\n Enter the data Seanad", tun): nes rode ='(struct node *)aalloc(siseof(etruct nade))s ewsnode-> data = nan evcnade nett = starts Sart = new ode, y : Struct mode Pinsert_end(strict nade *start) « struct node site, tee nodes Enter the date ="); Sta (struct node *)naitoc(stzeor(struct ode)); revcnade-> dats = rons fevctode next = MeL; per= start; etae(per next f= LL) ern Btn ests ptr->eit = nen ades > Struct nade tinsert before(struct made tstert) ‘ struct rode tot ode, sper, toreptr: printf (\n Enter the asta Feane("is, fra); Brintf("\n Enter the value before which the gata has to be inserted"); Seane('ta", B02); ew rode » (Struct node *nalloc(sieeof(ctruct codes nevonage->date = nun pire starts hine(pte > eta 1 vel) free nd = nad ( freuen = tad faint, “ind, opou bo rues i ‘ uease 9pou pa sues wumos : wont (orm mon fae aoaut dS uydaad ) (ten a} exepcandporny one et 977 poy a snaw = oe frevcad = ne ta 2 vdead ) Caars, aon sonns)toaan, eo ns fad = pane spore ape roves oy daod ‘ tract «ne ‘peu p08 PS ) (seas, 9pou ganns)aanse"ao8ut, epou a3NIas Lo ( hagd © gate operand ‘pois 2 pau aatoad 1 fraud = ad ‘and > aad ) 9 Bugy ssoninaas 29g Lt 180 Doto Sirctres Using C The only downside ofa circu jing. Figure 626 shows act =a gue 6.26, ‘pages visited, Trav backward direction helps Tn this section, take bo cases Case 1: The new node Case 2: The new node Inserting a Node atthe Beginning of a Cicutar Linked List ‘Consider the ink ‘he fist node ofthe list. Then the following changes willbe done inthe linked lis. Now, look at Fig. 628. Two different linked ists are simultaneously maintained in the memory. There is 20 ambiguity io taversing through the list because each ng at the figure, we can conclude that the roll, numbers ofthe students who have opted fr Biology are 501, 503, 506,50, 51 and si Similar ofthe students who chose Computer Science are s2, sos 505, 07, and on. ed ss stored in fe memery ting a New Node ina Circular Linked List how a new node is added int neady existing linked list, We will ist shown in Fi. 629. Suppose we want to add an TPG ‘enary for the wale +60) ‘he neu ode Im betwen PTR and START aT EOHe Fire 6.29. Icerting new ode heb ing of ace irked st spou si aa aap OL MMROEY PEG BMO 11 oyu 249 ur aUap 99 a. ssunyo Suueojoy a uo 84 poy ayy wosy 219 ap 01 WEA am osoddng nclude cao b> ‘ int datas ui struct node *create_ell(struct node Struct ode “eleplay (struct no ‘Sruct node Hinearteg(strset node Struct node tdetete begstruct rode struct node téeleteend(struct node *} Struct node sdelete_sfter(stract race *); Struct node tdeete_iist{steuet node *)3 int ming) € Li option; airseros ¢ eines n\n e¥¥eenain MoM #90") Feinee(-\n ds create 9 lit") rinte("\n 2: Display the List"); feines(-\n 3: 0449 node at the begsening’); rintf(*\n 4: a Rode at the end"): Brintf(*\n 5: Delete a nde fron the beginning” Delete & nose fron the end") ‘-Delate & nde ter a giver ade” aete the entire 1st"); pat"); Scant, option): sutten(ontion)| ‘ case 2: start = creote-clU (star) feint¢(*\n CIRGLAR LINEED L357 CREATED"); case 3) start = Snsert_ beg stat); breaks cate A: start = Snsert_end(tart) Breaks “ete Se Het stein oar case 6: start » deleteend( sta cate 7: Hat Slee ttaratart; case 8; start = delete List( start); princ¢(*\n CIRCULAR LIMED LIST DELETED"); ntle(option 1-9) ) 1: Struct noe reste elI(struct node start) struct nae *noyode, tpt; Drinef("\n Enter -1 to end); prinef(o\ enter the date Teane(*Ki>, aan) nev.rade » (struct node!)nalloe(sizeof(struct nose); ieGetart = muy ‘ 2 reve an sowa T seve 903 2303 poo 03 t= vows ‘sayws3aq aun 38 9900 © pov ie ert om ferasrg 22 ast e o3e0)9 3 nding 1 ve}onos Hansypusreatep = eas Cues ny gue and)oiT0n tend, B00 ns ) (Ges apou sonsas)asrT-enaTape spew S3NANS ¢ Gav = ap feu cand tj aed “a t Haines na fad sued } (res +) ep & sadeue)orrue fads avenue unas 2 ad cee raion (+ pmnatop on sey apou a RI sage anren oun au Uy jpavEad fadeady ‘andy apou Sonate > (ores monn unata, ses nis eye wins Hadas, Mu hcscaee fuavead + yous dead ae 4 4 frvend » nd and + sadhad ) Guns} sore nannye Ennead, ‘oe apo oeaas oe ws wines fue = wns (seasons fev caes = paue ad peewee yd Ques 2) Sere anders a1 907 pager, fuss «ad ford ajou Bes ) anise spon ianseyoeroseTep, spy ones fae = pote aps a ‘apovnay = wea ad sous ne Ges) pave anaare ‘Sune sd ne = exep apoi-nos (p00 aonsasyjooess)oorteue spou 390038) = apou7oU Hawg “pau fC eagp awn santa ah bse “ ‘tow 3 1 2p0u"haus nse opou I>NE ) (ues, opou aanans)pua sas 3p0u a9ne . ( ‘apournou = 3388 fueas = awe opens ‘pov sau = rab hd fpavernd = nd Guns 2) sere andar ‘aves sad “(pou 320s3s)Joazpe)20rten(. apov aanaae) = 2900"A) Hanoy *pX,)s005 vep oxy soa Iapwtad ‘ano 304 1 “opounauy BpOU INE ) (seas. 9p0u ronnsyBoe"uasuys au pons c Hep and pe n.)neud eeu snd Heep and op a.) (ues ah pane, pas nas » (aus, apou sannasyeeresoy sp00 wns ( t (ee 30025 + exep ayniones Shabsured ‘ squeas = yav<- apm “apou"nau = au o3d fuoveays aid Gans 3) aus axaarsyn fuses} od a 2 Su semanas m8 188. Dato Sructres Using C Enter the sata: 4 fnter the data: 2 CIRCULAR LINKED LIST CREATED Enter your optisn #3 Enter Your option : 5 Enter jour option © 2 Encer your option: 9 6.4 DOUBLY LINKED LISTS parton a poe tote next node and a poi tthe previous ods shown in Fi 6397 Lenoec Figure 8.1 Doubly inka ist In, te structure ofa doubly linkod list can be given a, eel eC s[x “The Pre field ofthe first node andthe nox fed of the last node will eo fic is used to store the address of the preceding node, which enables us to wav backward direction. ‘Thus, wesee thats doubly linked sm. The Prev it makes searching twice as efficient, Let us view node, ithasno previous node and hence in the pev field. We wil traverse outlines et Case 1: The new node is inserted atthe beginning. tions (forward and backward). The main} Linked Lies 199 Inserting a Node a Conse the dub shown in Fig 639. Suppose we want to a anew node wth ta 9 asthe ist node of te ist. Then the following changes wil be done in he inked list Ret POA POSER) inory For the new node and initéalize 48s OATA part £0 9 and PREY Field to Wt node before the START node. Nw the new nade becones the Ft rade of eet rode Ce Dece Sta Figure 6.38. nserinya now node at te begining fa doubly inked st Figure 6.40 show the beginning of ad ‘whether memory is and the nex pat is node of list, Whi 5 OMIA port to 9 as Sos “Tete bel EL ec ‘2889 seo 2009 SI wonotop oy 296 uotp PuES9580 380} 2H I 2A, 38 pay KIgnop Funsexa Apeauye ue wid} PoreEp St apOU Y way 95 EH AM UORADS Sp {S17 payury Aignog e wou epon e Sunejag 2'4°9 PU SPOU ANE Eaiojsg pou neue BuEsu) gpg uly Lele PiiEtecie De] GE] rt 2 Up Waa oa xe ket pehesah 99 oh rents ou te 28 or 7H “casey BJ fou BIT) aE EF Seo 600 aed viva say azytesater = ‘pou pots 21) alojoq parser 1 9pou nou oy my Kew ons HF Spjoy Ave pub Lava 2BUEYD 2x4 pO" STA YoPAL aM 9940 "vis Wa Hf azyeMIU pue ve 2}gEIEA ‘246 a's days uy “opoUu mau ayy 40 aetEEA Sf ALOIAN I4oAN AAHD SIH 9m “| ONS ‘S¥9 rg 1 unoys yg aye yoO| say 1 Ys payuy 9). AUOP aq THM A SHUR ‘a Zurssnop aso} ¢BuywEIWo9 apou ap 210}2q, 0} ue 98 a80dde§ Atgnop 4 apisu0 157] pay ‘Avqnog &uapoy wang e axojog opoy @ Bunresyy p00 van ‘natn =8ueyp 2m ‘apou sy yoval 98 20U)“9pOU su 29ye peuDsut 2g TE apou mau ayy 2sne99q pou si oes 01 pou 244 "ww o ona anyea i EIU pu aa quod w aye 9% dang {y payuyAjgnop e ut 9pou uaald Baye apout Mou vHasu 0 uMUORe xp mous Ep'9 m8 6 5577 pour 101g apou nave Last cL OO. gy mB "51pm fanap ew 9p vad e aye spou wave CuESL) HPQ amby 6 01 aued viva soe oxtterntur ue ap0u ma 43 40} Kowa (ae eob Perret poyurt og waco: ‘gm 2pou au © ppe or wea am asoddng “+y'9 iy 4817 payury Aygnog ou uae e eye apou neue ue A MMUEOIY EF gM ‘uy waoys 8H psu Slamop 24) s2pSU 2. u 9poy wenlg € sayy apon © Buresuy usaaye ®pou aL LESH ULOEY” 2p ay nowy assoaen 90 doo ats agp uy avis quO a 22 Aaag uy 0 poy Atqnop e jo pus agp ve ap0u OU 8 ase 192 Data Srucaves Usiag C - Linked Lists 198 (Case I: The first node is delete. (Case 2: The last node is deleted, (Case 3: The node afer a given node is deleted. (Case 4: The node before a given node is deleted, Deleting the First Node from a Doubly Linked List Consider the doubly linked list shown in Fig. 647. When we want to delete a node from the beginning of the list, then the following changes wil be don in the linked list Figure 6.50 shows the a last node afa daubly Step 12 TF START = ULL we ean also access the second lst node by taking its address fom tf node. To delete the last node, Chet PORTE eT et eee set the next field of second stant eee that it now becomes the (ae Free the morory occupied by the First node oF the 1st and nae the Second nade of the linked lst‘The memory ofthe previous last nods Ast a5 the START node is fved ond returned w the fee pool Gere bole sT et Tx ‘Deleting the Node After a Given Node in a Doubly Linked List ‘Consider the doubly inked ist shown in Fig. 6.51. Suppase we want to delete the node that sce ‘he node which contains data value 4. Then the following changes willbe donc in the linked Figure 6.47 Deleting the frst ode rom a dub Figure 6.48 shows the algorithm to delete the fist node of 5 etree eH Tote polnter variable TR ard me i point tothe first ode oF the aD Sel et te R further so thet Les data part is equal to the value after wich the rode hos DT eB eee *LeCrery) Figure 6.48 Aloritnto cette fst nace Deleting the Last Node from a Doubly Linked List a doubly linked list shown in Fig, 6.49. Suppose we want to delete the lst node from CLR TE . PLD SCrTy ingchanges wl be don nthe linked lst. sant Tl EE Figure 6.1. Deleting te node ater guen nae na cout inked ist Figure 6.52 shows the algoritum to delete a node first node of = Tel] the Last node of the List through the linked ‘Once we teach the node co ale pointed by PIR and store WULL in NEXT Field oF Selb oecrre field ofthe suecceding retumed 1 the fice pool. Figure 6.49. Deleting te last noe tom a doubly liked ist {eas} uonse"satap = 24838 cor 3509 ‘ue s)pua" ays ee 'B ase> Sawen ast azwty srenog v\.unad sGansytrewen = es (0-5 vorade wah sania wd) Rue Hating 2 3 Agent supa 9 pou vonsl'e soise 2900 © shet09 “OF S000 UantB © aicyaq opou 8 a33t30 "6 UAC}swrad yg, SoD Mv ahou @ oyatea 78 U2) sud (_Supus}8eq 24805 ape a3stad of wAC}sannad H0u dons e venje ap0u © py °9 WA.)g3inid fu UanTB © sanjoy apo © py 33 WA.)SautOd Cpu 3 ye anos © Fer op Whe) sauFE S0jUsTBeg a 38 p54 © Bor fChert a fetésia <2 we) subd GASH 8 ale) aA.) SCoseeee M34 NOMsene WO) UTE , soe 2 nope a : Fy (urea set + 2900 298135) \8" eRe Tee ap NSN pou yonsas)sease atone apou nae ‘spo aonans)asojaq ietape apou yt ope aonsas)puevelaps apo BRAS Sp0u 3onsis)Boq aa{ops spou nse pod tonne) s8ije-jaseFy pou Yonsye spou yonans)avosoq"iosut, apou nie (6 apou inuns)puer sur, spew nate (apn jonss)feqasipy apo Yoniae Spou aonsas)ET sven pou anae ‘m= aueysy apou Sons soa ES eye wy ‘vou, spou sons ) pau aonss ser 997 Surpasaid pou ‘140 poy rays ayn But 28 3900) 9POU Passap ‘Bnonp sosvanen doo Tra au 430 2pou 8 op 01 sutod mou wie qs “> apnp>ute su wuoyzod pu sy paxul Aiqnop e aea19 01 wesBoxd 2 aIAA,“E IEE Noo won wn sj vivo 1 somouns ore yo 196 Data Soretres ring © starts prev = ne. n09; ) rewcnode->dsts = nan, 2 J Ssppe aK softs Aa wow 9 aEoy ‘vorysod vyoros om jun ammpaooid sig wodax oy 3s ¢ sauppe ‘toy paseigo uotoy> ep puesas aj} “2poU sty aM jo sseuppe JPY orNaTd oy aN! EP HOU aN YOIG 1 ¢ 3 9p, pou Ha Jo sssppe ap soso psn a sets args 328 yn ut 9° ap AE so pours pH gnp OND xno aK ST ‘wayoqya sv 20)m3 won ‘soyeur ae sty pay onsen 2p og Sepyoud i pont Agnopsejna19& o.amoysuonRiado aseq ansuodxo 210 pul apo od ‘o0ds aru 203 se ‘auruona su sued aan se}U0D 1 $5°9 BL uumous ss pay Atgnop seyMoHD Y”apoU | a 50 saIppe ath SOHN pg IY ‘Jo py sosord a Amat “wes “9 Ht a Jo-apou 81g ax Jo SSDP amp $8105 pot 18e| a4. Jo poy au ah 24 J play n2u 919 pur pou nota ‘2 UF Mi UE Yu SBOp 8 pox AIgnop ZENOH ais oy oyuut Arbus w uaoaaog sistx9 yy se aus 51 Poy Agmop zeMaHS w ue poy Kghop v ustag ‘2x5 24 a soMonbos ay apou snomand ty sf se Kou a4 oF ytd #surIUeD YH st pour 30 od xo} arou vst 81 pou Kes-omy span 30 8H Px Igmop RAN YY ASI O3¥NIT ATANOG HVTNOUID $9 G61 8577 poquey & (2385, spo0 node is freed and returned fo the fee poo. doubly linked ls and perform insertions and deletions cda3)oa.y taesnude-qieye seas = dun, frveans * saved fave aes ad Goras =) poe oxdyannyn ‘Sune sd fad, dpb vane ) (Gavi pau jms) atte, poe aoe aes {oyorne «aid cases Runes yale oportoe £(2pau sons) sosays)otteu( of0d anne) © apne Hexen aa Sons I poupes {Spa hte ‘sty oon tons > Guess, pou soasipersciy, pou 3nsty t -_tepounae = yore fapou"nad food Surat ‘pos caeyotsan Sune snd £(9p0u s2nsys)4oszrs) o1Tea(4 opos aonsns) » Spo nou : ‘ew "px sons (op agony gad eo id, “aparnay, apo tnant (2ttsy pou toss) Bor sass opow nat ues, 7 Nonwae t = ane ep vad" pe a) > pou naar fuer ad sad, a8 vane Gans ) (teas, apou ansns)sersstpe apoy aonase iG $02 9977 poyury ‘ ony (4002 HG. 5 saep aun uonea ihejsaueid ‘epeu"nau = youond DRd = paul apeu Rad , on ( fapou"nau = sess ene = exepc-aposraon yn + oud ape {((opou ypnsneyscoets)20rteu(.ap0u s3nins) = aP0u"RaY ) nm a= easier y (=f etre nu‘ 0%,) 98098 (5 evep aaa ries OU sauR Epo ov 1 sons wy pun ‘anu ye fe ‘pour nau, ape 3303s , (auras, apou aonaas)qaieay apou sons { joie jousn3a 1511 obMur AvaNOG wrIDATD W\,)4RUF sGaes)ssttsI9T3p = Hess 2B 9509 eeua Hansqapesrayetep = Less 2 9609 Haumsipus"anetep = ue3s:9 3509 Hues opera « ess 5 9809 sea queysjps"unsuy = eae op 8882 (avens)Roe"BsUy « 38 9529 sea Haus)terdstp «ules 2 S00 ease (omen 1st aaws1 ayeroa weMNID 0); FQueis tT yeas = eye or one : (oop doypaens Huoradog "op3,)4008 98s dome 206 Data Sowerives Using C > Exvuct nage *daete_end( struct rate *start) c struct node totes Jeeuct noe sete eetstract re stat) ‘ struct node tpt: = detete beg(stort); ” Linked tise 207 66 eo LinkeD sts CO-OP 0-6 CS-E Tt 6 FE) esate nde in sequence Cone Fig 666 7 Nae thar strstr te eso the header nde The 5 stato dette ender code, Teer el Few 55 Menoy apron ta fener st next and not wrt fs because srast header linked Figne 648 Agpthn'o ows aca heafer insist ee nhc Sa ane aueaeo 1st oan BOR Te omep ay us F fetep om aug 1: varie in sau srt oun Kereseg *t SH e e809 HE ining : ‘ ‘ fyaucnd «ng Hewpeand Nan suid rnonejaneparrge fie 9pou aaa (avis poy sue) 50s 2} ‘ ‘ win “x os sep oan pow ioe txevecndee Che avennsernon (2000 apnans)sasere)2or ((op00 29013) 09215) >0rte( Hagerty fatasta 220 TGisHt eieo.9 :T at eeeee MK MMieneee HWSO ) one > 6, apou anins)detesrps afou vans «Spon toene)tte sara, apou aM Fram = wes, ofou dons # ) spay ns ‘seems pmtaute orgy apna “ss payut sopean e womafdn of weiBoud ea “5 1 Kg possonne 2g 4 9pou ay 9 y4pnd90x9 UES 24 KIERO 99 A SU ye wood 0} suxpucdyp ou 1 J9peou (Aigrop) en-on9 s]naud w pu sy J9pEDY (KIanOP) Seaom @ aney osie am st Jopeoy Jeno. © pue any am o4p stugIUORYE axp pu SunUOBYE aso4T UDOMNq aOURIBYIp [WS uO isn A4orUDE 1 aioy] “Groreundxoyos axe sue asm rpg © akey 29 a4F7 Yale passnasip Sussnosip yy spony pea 15 pox peng ena eu}apou wane visu ol utgBOBY 6 a oT ue sone 2B : ones Mas waad BSE das ‘eae Lis = id 135 9 is ig as ati» pue t sdons seadoy 4035 MeLWS = SLI 135 °F ORS Sanh = sive at = 6235 | 20 Data Stctues Using C 67 MULTH Peed Usts “unted Lies 204 we can abo have a caresponing inverse inked lst representation ofa sparse matrix, HEISE. vey anor ante suse tis stant cores node ht mutes ‘list must be deleted. " 5 exactly two pointers. One pointer points tothe previous node and the next node. But a node inthe mult-linked list can have any number of Go Coe wu [ULL joes ame and marks oie by sadn las, hn 90 ways cording othe nie) cof marks so thatthe information of student | = co-ordinate ee Figure 671 shows a | 7 rementioned ways | eae! wa [a ra | = | Nein china Noe | @ tm =} —[noit [Roe Fue 6.78 Maisto npc of sre mtistows Fg 672 Fie 8.71, Mutiied stat sores anes abate a ls snug dresing the differen op reepresented in th ‘A new node can be inserted in a muli-linked list in the same way asi is done for a doubly linked lis sts, we can have laverses of ech poi as in a oul kad Us. 6.8.4 Polynomial Representation a single nde. Letusseehow a polynomial is epresened inthe memony using Mc en ni em i parse matrices, Such matrices have very few non-20¥ ofthe entries are zero, Sparse matrices ae very com If we use normal aray to store such matrices of space, Therefore, a beter solution is torepresent | Figure 6.74 Linked enesentatan oa polyoma [Now that we know how polynomials are represented using nodes of a linked is | rogram to perform operations on polynamias Figresz2. Spas wat (owen heysyp « yaseas so 2502 fay “tind, apou dons ease (quis ‘Zuers “Taueas) hres = pumas 2 2509 (exeras, opou apnans ‘eases, apou rons “Tess, spOU aansas)AtO FER BPCU 338 e0i9 ener bro herdesp = quiet 9 980 ‘ H(euies “runs “turis)kiorppe = quest =5 o> dove = 6 Desig om cand nvcand are tat Hewersyiaorrheydsrp « ghee +» 2522 (raw) serra Heuiesyheorayeei> = rhs 9802 fue syd | aig {ide pou aors38 SCevsens hr heragp « tuese 2 2889 } Feosg (2s. apau aonsas) Arad heresy, pau Dns eceuieas)htofansein = Thiet or se c | ) faves wma (opsoyoayrs ‘ uopdon !apa,)gue>8 auras + wosndo anol su wt) UE svar soy saata hepaured Guna “6 v\y)sauTad Carnes on fejestg “8 Uy) sUTIE tensoutfod aun yoesgns °Z wh) saute ‘1 Stress nia Aetseg °9 Ws)sawtad {5 soqun ay seus 8. Ogaunad tewwoutfod 93 ppv “5 wy)sauTad e t eruoutted puss ous Aeqest0 “P U\s)SIUTIE “tov = ban 3 sTeqwoukted pues oxg aban “fuse Tt = 20 appa ‘Cyetwouttod Ssay ayn Aevesa “2 w\,)aavTad 2 1 Hem mins HGtepmourtedaeuy aa sun wADaenid (ope 35) 400018) ctu spew nite) = pO ) Chm sh wave aor suo Sues sg sore st 3 ) a urn ut Rie ( peu ans Sy au apo oe pou aonsas *, apou dans“, apou aonsas)ALOO ppey spa Janne ie soos < aperape 1G aptu tonaas)Atod eTdsiPy 9p Jone er a ' enuelapourae ‘ Spo sons) APOE sees >y OPO NS “{(enod toms)sorrsjottees spou anus) © Spr Phan + EseTy ope DNS Orman) EMiw = Bess opou aon ) faim = rues apou Jone G- 1 yeti Sims Bets pou joes Hi MG. 1 awopoyjos say asa Raawtad ‘x0u, spay nas (9 “yp) Hes re sam 9 ita (ossue ‘on et gory > 4 Sp0U'mauy SpoH DN peu sans ) cysortee stuns (ess, opou aomas)étod 92404 opau senate . urofes> opasuTe ‘0 umes yore worado) att eo C5877 popury ‘aot epnute 1ousjod oma uo uonoengns poyuny Buisn yenuousjod & xoys 0 weal any c ov 2M Date Srvctures Using © ptrt = starts, ptr2 = stare; Chide(pted T= MILL Rh pera fe LL) « AMlotrh > coeff pte > cost) ‘ sun.num = pert-> nu 4 ptr2—>nun; Styred = a0) pode(star, Sun_num, ptet-> coef ptr = ptrt-> et ira © ptr2-> net? > flee Se(ptra > cost > ptr2->cooFf) ‘ Starts » add node(start3, pted—> un, ptr coat); Pert = pert nests > ase sF{ptet > cet t « ptr2—sconFf) c start = a0d.node(starts, pte2-—> um, pte2> coeff); plea = ptra> ext 5 mit) viie(ptee = LL) ‘ Startd » ald node(start3, pte2—>rim, ptr2-> coef); pera = per2->nexts > > secptrz =» wit c sue(oten f= mvt) ‘ starts = odd pode(starts, pert nun, ptrt-> coeff) piri = ptra nett; ) ) ) Eeruct node sub poly(atruct rade *start, struct node tstart2, struct node *stirts) ‘ struct nage tote, *ptr2; pera = start, pied = starta; fo ‘ ieiptrt-> coeff == ptr2-> coeff) ‘ sub.pon = tetsu ~ pte2—> nn; torte « ede pode(starca, sub hum ptr > coef"); pert = pert > nest irz = perz-> next » dae st(ptra-> coett > ptr2—>contf) ‘ starts = ad_pode(starts, ptr aun, ptr certs tra = pera , Use ittptra > cooff pea» cost) Linked Liste 218 ‘ stactd » add node(stares, ptr2->num, ptr2-> coer); pera = ptra-Srexts ) Dbstecptra be WAL |] ptr2 t= mM: sfipten == nu) ‘ vidde(per2 be mL) 4 starts « add nodestarts, ptr2->um, ptr2-> coeff); pied s ptrd saxty » > {¢¢per2 == way « nte(ptra t= mit) ‘ starté = add ode(starts, ptri->nun, ptrl-> coeff); ptra = pera Sex > b ; 7 fret ree ad anestac mde tr 9, So struct node *ptry tnew nee; iv(erare == 0.0) rew.node « (stouct node *)malbec(szeot {struct node); rewcrode sun = 5, row node > cost spacnede > next start = ncn ney Mide(ptr—> next naw node” (struct nl rewcnode > coeft = cs ewsnode > ext = ML; percent = mente » ; 3 Ouipat 1. Enter the feet polynontal 2 teplay the st polyrenial Enter your option : 2 Enter the mumter : 6 Enter your option © 2 Enter your option : 9 Enter sts coefficient : 2 Enter £8 coefhesert oe Bung Samo et ure apam ciudad eda | aon yeqouoppe nomeuedene rere ee das | sap es ‘att om ve eee nb wont 3 om peg yo Moet widens poss bed POON cedure pe | po np vent ep on | er pievinemnromoacalvean ax i Panam ong | casos guns sameselunon i por ym pion ey one 92 permet mana coe oy 2900 4 2g jo ones 29 aun of wand a4 “gt | “sayes 25a Stes yep pay © sony ens -reu poe uuu sud ey esol ny “BL Lat srr payer © u patos snyon sy po ont a8ous o wes IN “L vo 20 (pro Bapunos poo 8 pam ani om gay sila sp wRsfoadw oS ay sate e- 000 yoga yuo BOHN F ans pea ‘sesquerg Gujuuredoud oyu om Jo stay09 ox pu soueu a noe uy S90) pow a9 08 play om30 1s] 2 fo pray HU gh oMNeY “>pou ‘epou0nst 2pe! paaod eeu suoy natn Blanks is used to store the address of the ist Tice memory leation inset node atthe beginning ihe begining ofthe doubly linked list ace o modify Inserting nod inthe midi noe to modi Jaseting anode atthe end ofthe crelar inked needs to modify _ pointer. tng anode a tie Beginning of the circular doubly Tinked list needs to modify _ poin 1 Deing rma ening iesndy ads o modify °. Scan from the ide fe ou senty CHAPTER, if Stacks LEARNING OBJECTIVE Fowe 71 peyuousnep soe dig “a 1 paso tou pod yoes a4 uoREDO 3 30 ane 248 uy worupaos yovsiow 249 09 yaa 81H 98] Age DES 2 Wy now ue aj oy uose a SHOWS O23 vonnep ye BES gL aun NB PL Bi BL PES ety asad yh e op 2g so {6 “tq ur uous se saurosoq yous parepdn 2yp ‘sn aod 6g poqutd anjen agp HaUr8s99p ‘946 U4 25] St oNapuoD axp HL "THmeou J YPOUD ISH 3m oKHD|SASONUdO,a4NEp OL Yas grainy 1 ayn apes © woy anges v22]9p 0 ape ‘de yes 2p seoMN | way 5H 949 SIE oypONp Sy WL 9 “anYBR ap BUNA} AI} ‘4 wo maweyesoudoy2¢p aap 0 pasn 81 woyeradg dog z'e°, “ua pomodwpes| 9 e 3p a paMSsNBA.99 dG ‘5 Kea oyu woneao}axou 24 oy sud 3 EN Os poyuDNzoUN st ‘a "woRUpuod nosso aun 3 3904> 1H 9 | dog Up soy ganoues 08 ‘ut pas fqwanboug ase Sous ‘Os0Fx04 —_ pm'd Papers vind Usomece yore ants ayy fea coun Jo pp amp araye “suonung Jo J3puo uownaexa Jadoxd v saunsuo 30 WaIsKs cud Jo) porowe/ 9 _, Feary iim 'panon sug uum ‘974, Bg ut amos se sowos09 yon pawn 9) 2 KU a tos poe JoJo nye ap yaDsOu F994 184g amg anyen yas MOUoyO UE HASH Of peg gay Poor es en re Dos rete $¢ Biy ur vans? yous My { ‘piston ‘paytid s essam wovsaro ue ny ApuauE St eA YoHS YUL Anew SUT 0} apeU s tone we 3 -suop 2q eo suorosuy 2x0w ou pues st D418 a Ut ‘ase ayy ta 250909 “tervexj! 9go 819 9K one op Bum.osut 30799 YaK=MOFL DEAS aL J0 uoNsOd SOLO} ‘1 poppe st atm|2 ou ay >>HS af Ow! iuaWoqS Ue NDsUL OY posts| Lorjeade Ysnd 94) owerada ysnd 1'e"L mpan9—%@ ger 3 von} Fausoma) — s) wm owen Guo eee oe fawn] oa uaa pas Wests oa) ‘twvopavende'y a2 2 U8uM = uoioana Voom “yom xp jo tuawap sound an yo anyen ayy suri urna 99d Sossars] ulm oan ue oe mt 4, ous ap Jo dos ay wou wot9|9 a Saxon wontado dd tp pu pes ep Jo dv 2k oF “ta ooo 220 sro etre ue sppe uonezdo wind a 900 prod ‘und suotsodo o1s0q san suoddes oes i can ee me NOVAS WHO SNOLLVRdO EL | sawepmpnesg’osgueun [| __ svopetnads'y'sayey eu oe falas 2 in sa m Step 2: TF TOP © MULL | PRINT "STACK 1S EHPT 0 step 3 f step 2: ReTURN STAC TOP] Step 2: 610 1 Figure 7.11 Ag moe Pek option clement of the stack algor thou deeting far peok operation i gives Towever, he Pek operation first checks the stack is empry, f'o® = wt then an appropriate message is prin "the value is returned. Consider the stack given in Fig 7.12, e712 Sack Herter eatin wil ret 5,5 itisthe vu o the tpmst element fhe tc, ‘Write a program to perform Pus Hinde conto. socio W439. nt maint) ‘ int val, options prante(r\n pranee(ovn 2. "8 Enter Your option option) 3h, Pop, and Peek operations ona stack. sutten(option| Q orintf(“\a Enter the nur to be pushed on st30k = "i feanf(X8, val); puan(st, valde breaks val = poo(st)s Sevan! = 3) rint#("\n The value deleted fro stack 6", vals ‘val = peak(st eva ren The value stored a top oF sack wa ? Bihite(option f= 5); etch » ‘oid pusn(int st}, Ant vaz) c sF(t0p == matt) ‘ prtnt€(*\n STHex VERELOW"); 2 se ‘ ston] = val; 3 pe nt pootine st(1) € (top == -2) ‘ Print f(*\n STACK LNDERFLOA"); ) 3 val = st 3 2 ‘ote display(int StL) t nes Seep == -1) DBrinte(r\n STACK 15 eV"); ae ‘ For(ietopsto-032—-) Brine ke s3)5 ) ) nt pookint «4f)) 4 sF(t0p == -2) c arint fun Stace 16 TDS » ose return (st te > Output cera ene 1 apou 1x5u a4) 01 pew e04°¢ aig ut 201 01 uompu0> wos) UD] UP ay2}9p 0 2p smous FL aundig _uewat Souder a 0 vongep ye BE OTHER REED REE RE RET od yey) wi senutod asm ax°z dig uj I 04 Joy 4094 ISIy am “| dang Uy YEH © orca 41g w unoys se seunooag 46 paepdn ayy ‘mL >UIS POH Puoses ay 010d oot yeu pu a>: Ka payed 9pou 24 22] 420 epOIposnstuonedo dog, wonevadg dog 2's" ose 30 pou sy 243, nf 2104 $1 apoc. 9 81 apou mou vw u2gp ‘an nos sous SuP;oayD &qazap 81 ayo ed yaw ypu pase wires sr 24) 35 set spUg mou 944 Joy Kono exezofty or eas 12 poppe st wauyp ou sd pu ods wonevadg ysnd 1S" ‘Ley suonesado yous oa ay fe stodds yous poy, OWLS G3NNITV NO SNOLWYRdO SZ used ag 03 equ 343 Uo pouend 99 03 2 Ts worse sak 26 Data Soucres Using C printf("\n tena mene PrintfC*\n 2. USK"); Printe("\n 2. pop") a Seanf ("Rd option); suiten(option « ‘printf "\n Seane("8s, ‘op = push reat ‘ep =:pon(ton)s aes val = peek(top): iF (val Srin(\n The value at the top of stacks Printf(“\n S180 15 OY"); ‘sop = d3splay(top); 2 duiteCoption 1 5) 2) Eervct stack tush (sruct stack top, nt val) ‘ i Struct stack tte ptr = (struct stacktpraloc(stzeot(struct stact)); pir-oeata = vals teen 22 mL) ( perpen = Wlt; kop = ates ) ‘ ptr-onext = op: top pent 2 return tops ) ‘truck stack “aisplay(struct stack top) « struct stack tr; es ‘(top = mL) Drinee("\n STACK 15 ERY"); cise ‘ he nunber to be pushed, on stack :°); a, va); shite(pte te mutt) ‘ Dprint#("\ntd", pte» dita); ptr = pte >not ) » return tops : firut stack poeta stack top struct stack pts per = top (cop = RAL) Dranef("\n STACK UNOeRE LW"); cue ‘ 2p = top-> next) printf("\n The value being deleted is : 1d", ptn->data)s free(etr): ) cura ti ) fot peste stack to) s¢(topenttt) return 15 cle return topsdata; 5. pat Enter your option + 2 Stack theron Enter your option : § 7.6 MULTIPLE STACKS While ng. stack using an array, we had seen that the sizeof the array mse advance. located less space, then frequent oesFiax conditions willbe en Tel vi hispoblem te oe wil have be odie Lelloate oe pes othe Incase we al senor, Ths. thr es trade-off between the fequency of overions andthe space ‘So, bette solution to deal with his problem i o eve mul Figure7.20, array Stace is used oye (12M p= vas wus pode anren au. uate (em i )gue75 (£89985 vo Wind ox anton agy aye) he ]saURAd 2 8509 (eng, Su 5 wpe wo wand on snes ayy sBa49 ULsJauRd =r 3589 > (opadojoasnt Coord pk gues (205042 snk sows Delgo *Giuie "2 w\-}aavnud 8 yous Avigs10 “9 WN. )paeEad Oe ous AvSI6 “$ w\,)sauRd SUOMS Woks os 7 A)yuEIE YY ADHS HOH Os“ WA) suTad “Beis RE ind “e w)aaond SOUS ME WSnd“F w\ydatwlae renteeveee WATS ) an ‘oopie aut ) come et ‘ ; ‘ pore 3 Cash ny ) “ fate 6 4 ons atid Comainye Beal) omoeirmése nh er ) ot i Haounae SS covers ) ‘ Ten = (doa) u ) ort sens. Homage w\nwesd ' (vee Gen auyausnd pon easton 2\-)purad rios)or ypees"kerasre véod aut t G Hen + (yderdpens frig ovata v\)pwTd (etdorden)ar iors pasate yuo eA“ be > Ene Thine ZL Fy UL onoys st i> oR (ss pue [re soups Sq papunog 20eds o woes a4ny a8 5 FE tie es w Sfes af ‘uy aus 9 1 9 uo 08 i v 9362S Buu au ajo 1 WELD {J faqs u yas a past 2405 1 (Scr he ue oped fon stack 9 cease 5: printF("\n The contents of Stack A are s\n"): cage 6: URE Te contents OF Sack # ae = Ws Soro ' : ehizetoton 7; a } Output 1. Pa IN STAGE A 5. Por FROM STACK 1 poe Fon STAOL 8 Eneer your hotes #2 Encer the value to push on Stack 8: 10 Enter the value #0 push on Stack A: 15 Enter your eholee = 5 Enter your choice + ie Enter your ofee’: 7 7.7 APPLICATIONS OF STACKS In this section we will discuss typical problems where stacks can be eas and efficient so wil be discussed i this ' Reversing a «Parentheses chocker * Conversion of an infix expression into a postix expression n ofa postfix expression version ofan infix expression into a prefix expression + Evaluation ofa prefix expression + Recursion + Tower of Hanoi T.TA Reversing a List A list of numbers can be reversed by re 4. Write program to reverse ist of given numbers fineluge nt sth) c Enter the nnber oF elements Sn the array 2°) Seant('aa", ta); eintt(\ Enter the eletents of the array + For(in0;4en;4+8) seant(Xe, aaref8))5 sorttco;sensiey) peshrets)s for(tenjsens3) t sal-~ pony; derfsds va, > PrSnef(*\n The neversed array is for(is0;4eas4), printé("\ xa, ane Ds y ola pushCine val) t y fat cond } Output Enter the mune of elenents in the array 2 $ The teversed erry $9 5.83.21 7.7.2 Implementing Parentheses Checker Stacks can be used to eheck the igebraic expression is sie(setop] = van; Fetuea(ste(top—-) 3 ‘but an expression (A, gebraic expression to 5, Writea program to check nesting of parentheses using a stack, finetese cxtdio.to Pinelude Ceonto.t> ‘inelude estringsh> ‘deine hak 10 on pus yay 3+ v ten wosssandya ous frouvaaryns J 2jdureva 104 sesoquated yo asm Surge poSumyo 9q, vo stood 3859 Jo uonenon, ‘Smoqos se 'aas8 9 ueo suoreodo aka fo aouopasaad ayy ‘sions ‘tuo asn fiom way) UO8|e ax JO Ausyéums odo ‘sesoquuoed wrewuos Avw 1 ~suorssodo xyaid out uta cosa ores ue 24112] Suwa ap oanog 71 atderg uoqssaitag Asad e ow uojsseudey Ayu we jo uoysse8uog 22pi0 age ouuro sayoeng tons pu aamroosse pu aatopadad sojsado Jost tou op ose surssondxo xyaud xyisod ay" aoysado 21 jo at op ‘18 yxy spursado out 01 pada aze stoeiodo soudvo Bupuodsatio> 4! auexo 204 spunado ayy a1ojoq pod ‘soja oi ‘uonerou xyaid vot et st uogetou xgoad pu wonmou xyiod ewsauiay ouR:ap S099 a oF yp soy paenesoosy st wns xyald¥eEnoKRTY uoynyos ‘suotsaidyo xysod on suas yet Buysonog ay wonuoD 4 oydurerg eee ae oneiow xypsod yp feiou xpsodv uaa “ajdurexa 20, spueredo ain uo sty poyeiodo 8 UoHEN|EAD Jo saplo 2 Yona ayBts 01 yo wou sKeaye sr uossaxdyo xypsod eo lt say se wonton 39 ura uo}saxdxo aures ayy “uoreio xyut UL ary Se Uae “eidaueo 104 spuerado ou oye paoeid st sreiodo omy ‘S97 auzew oy) Se “UON EON psd "Nd 20 voRBION yst[og asIDAay se UsoUYJnIng st IY uONEIOU xIsOd pu (uoLRNO noo 100 xyaud20y-s:soynionnd vdojanap 01 sea wre iuoa ‘og ‘sos 2pus>40 yaa sayOHA9 PU joss pt asp20aid sojaado mnoge papa 5 woneuuoyuy uoisandx9 om yen 14 Jo Yo spaou sand axn se ogmed 0, smnowup pry ssyndwoo ‘wom eOu gu SuIsmsuoissaudK> 3 Bnowry's poe Spurred om oui uoaiaeg paced st soreiodo se ‘tay ‘sev ‘jdazexo 04 “spuniedo ay ‘som ut poor tse ay “uontsioN yu! Buisnuojsauda ane we Hunton alae eee spe 24 Date ts Using © ‘The algorithm given below transforms an infix expression ito postfix expression, as shown Tho algorithm uses a stack to temporatily hold operators, The postfix expression is obtained fo lef-tosight using the operands from the infix expression and the operators which are removed fom the stack. The fist step in this algorithm isto push a left parenthesis onthe stack and t add «corresponding right parenthesis atthe end of th infix expression. The algorithm is repeated nti the stack is empty. othe postelx expression antid a the "(fron stack and do not 3 Conver the following infix fix expression using the fea program to convert an infix its equivalem postfix hae); ) char test) Stacks 26 (Gee BIEN as } arian ‘Sngen "edo "p80 460) | } }o0 sepyananpasogesentend 0p t orssoudeo sod fue Joaes oor} se > urea aut {({} seo aren soenentns 0) Sevan ee) | ‘gen aeop AY cyan yon | ‘cao ey cor te oui ‘anos memere Sonos. dts aver spool stormed nywod v rmexo oy imrdoid #9 % aunpocoud 2p smo HOM TL 3g, 38 YO9T ~ F496 ye eso umm oq ues / (2 + (+ ©) - 6uoisaidyD xg ‘orssaidao oy arenfeag “> / (8 + (F €)) - 6 UDAIS Uworsaudxa xyuy 9 JapsuoD nguo8p sur so asn soyE Ye oyduzExD we aye ou si sod Bus uasovda mjs0d eNO ONO 2" pers on 40 ‘iowa ssoudoy un 69 tenbe smnsaH 13s Gre aa) 1 ans vornentene go anaes a4 te "ymofae suns nt of a pie aasote yroudon on sry sunim "y 0g sentend ipue y seg fue y se sei a eos) saunas on sy dod “e | 228 aR uo 35 aNd prsnwunonua st.(. Tu p pue € Sdoae cans ‘eadbs poe Worestude Kised opszo sod uoHaMINS Lage), ‘948 46 usizeseys Asana veg 2 das dofssoudea xd 2 40 pun aun ae s(. 8 py <4 aS ust spo norseno vos oporssateea ME aNava12 >2mON oyssaudxg mpsog eyo woyenjen3 wofesasdee guy Aue 0403 nding, ‘ > (C8 ses)aot sed t ‘ fos)ae do oe wa (even ) (en sup “LIne seppyuend prot ‘ (6 sey karorsayed aut i 0. Fyn, t et (38) = (688003 } [doa}as) a (1-n1663)portue ( ‘ sane Dyan , Jose puhtant st), fost vst) t Dush(st, (oat) (expl4]-"0"))5 62 = pons value = ot + 092; breaks ‘value = 092 - op2: breaks ease" ‘value = opt / opt ‘value = opt * opts value = (int)opt ® (Eatp2i ) eshtst, value); > eturn(p0n( st); s(copett-3) rAnt#(*\e STACK OVERFLOW"); (Vn ack DERE LOW) d uivalemt prefix expression 1 is shown in Fig. 7.25 Siacks 28 ‘The corresponding prefix express ‘obiained in the operand stack 91 Sen ee date In tn RP Se ety eee For examp FO GIRL step 2 Pash the operator nto the ooertar ack, ven an infix expression (x ~ ‘operand into We operand sack, ond Sgrore all Ue left parentheses until a'riprt porentnesis 1s encountered step 3: Pop sperané P fran operand stack ‘Step 4: op operand 1 From operand stack Step: Pop operator fron operstor stock Step 7: Concatanate result with operand 2, Step 8: Push result Inte the operand sack Step 9: 0 se te infix string. Note that the siring sou must intercha and right parentheses, won ere Step 2: Obtain the corresponding pos! expression ofthe infix exprestion obtained as expression intoprofy @ Yel of Sep 1 1 expression is: (L=K/8) "(68-4 Fique7.24- North to convertan Therefore, = (e4/1* [C68 = idle reversing the string you ust lnterchange Teft and right parenteses stop 2: Obtain the postfix expression of the nfie expression obtained in step 1 step 3: Reverse the postfix expression to get ‘he prefix expression ar} + fe] Leas - casas Step 3 Reverse the posfs express pref express Therefore, the prefix express are Figure 7.25 Algorithm to convert an ins exoresson ito prefix expression Cosma 8 White a program to convert an infix expression toa prefix expression. incluge cetése.h> include econto.h> nelode eetring hs Bnelode eaype.to old InsetoPortx(char soucet nt petPrdorityCenr) har Sn6s(300), postnc{200}, texpl200]; nt maine) ‘ char targets etre Strepy(posten, ~ InGxtorostBx(tenp, post pranef(nin The eseespon ts(posthe sept, reverses ‘9 L Hg wt uo 81 voissaudha youd Jo wonengesayo dea so}duus ty uossaidva xyard eBuenyona oy sonia yo aqum e839 oqssand ayaid & 0 vojenjeng AGorssaara Nt wana Dawo%nt ie Hpeanos aaa « tet He) = (euaesien unos) AaFOTIe28 We 5018 (femn]3ep6asuor4sia) wp (.), =a fdoa]95) we (e-=idos) arn sae ee Eran [24 (9800005 | (tsTosanosdeu sasmynenued san 280007 H(arsssua Dano 8. sony f((p)p>snos “380 ‘oer aut , (Cy3e81e3 sew “{u005 sewa)esascaovegit pron t 242 Dat Sractues Using © Step 2: Accept the prix expression Step 2: Repeat unit all the characters snl pet expression hve (2) scan the prefix expression from riprt, one character at 2 (0) TF the scam chara Berend, push tt on Sporond stack (c) TF the scanned character $5 an bperater, then (3) bop tee values from the (43) Hpply the operator on ‘he popped operands (Lt) Pusn'the result on the operand stack prefix expression + ~ 9 ‘us now apply the algor evaluat tis expression, 9. Writea program to evaluate aprefix expression, Aineaude «stato.» relode {nt-pon03. sid pas) {ne min) ‘ Brinef("\n Enter the prefix expression: “); eets(prefie): en = FerLen(prefe); for(seten ‘ sebteh(get_type(orefxltD) ‘ Sak profs] "0's eae: pe2 = port); Stitch breses)) ‘ res = apr + opr; break res = pet + opts casey rer ope / op d pushores): » Ant pop() ¢ > fine get_typachar€) ‘ roturn(stk(ton~ seme > Output mesuur = 14 7.7.4 Recursion is made which does not require a eal to itself, Since a recursive funti makes use ofthe system stack o temporarily store the retum address and local variables ofthe calling function. Every recursive solution has two major cases. They re se case, in which the problem is simple enough tobe solved directly frther calls othe same 's obtained by combining the solutions of simpler sub-parts. ‘Therefore, recursion is defining large and complex problems in terms of smaller and more easily solvable problems. In recursive functions, complex problem is defined in terms of simpler problems and te simplest problem is given explicitly. ‘Tocalculate n}, we multiply the number with factorial ofthe number th Tn other words, nl = 9 (0 Let us say we need t9 value of This canbe writen as, Therefore, iy, we ean also write, oaten sourzon s Sead zea! psea 32x11 | Figure 727 Recursive factor urction peters @ aaroe abe te T= (0 2) (a "2poA a @ = Ct H7nas ee (partie 2 (2 brs 2 se 20rd pes dees 2m ty "238s" Oea Suppo, sn soquin ¥ Jo sued pu ose ur ay, swouodey Guypu nding, ¢ (90s (O09) wna } (6 us 9 at 7 ‘ (900 (eonu en “P= pe DUE P40 029 wy) Tad (fans "aru)ai9 = #30 fC aanqun ony 343 38909 oh ‘sou (zane anu > ures a fur guyana ‘Sbrigun anrsriser Bust aqua om: Jo G25 oi swenogeo oy uriondw IEA, “LL ‘snoge N18 wna} agp a SHE spay ‘S989 a (S198 ejosdas nding, | Hcranpes 0) wumsa | ft wmas | , (wpe at ‘ und pu =v 3 teense wh dw | stan) tee ug "op 3008 H(, eanana agg sons Ag A en “ana ut voxener0 worLoens J "(aut aDe5 5 Aoquume uoAsd Jo jeuo}se, 4p arenope9 oF wesBOLd vA, “Op roquuna pase swesSoad Sutwofos 2184007 una vou 8 "yo peuoroey axa saeynoye9 | (28) Tenowes ou + (orepoes 8 UAH aq ues ofa stp 40 fe 3 yon ang yi e918 uoRaURy jouj 24) Jo ase augsansay + 81 oq jo wnsas oT = 4g sea9g "T= UoUN 81288 284 oso aatsanaas w pu ase af8g ¥ 240 1 exp ree(2, 4) 12, Write a program toca ‘ > nt exp_rec(int xy int y) ‘ stro) return (x * exp_reclt, 9 } Output The Flbonacct Series The Fibonacci series can be given as sum oft ms, and soon, Now we the nen tenn ofthe Fibonacci series, The general form ‘As per the formula e every problem second terms, Similarly, fourth tem design a recursive solution to find todo so canbe given as Tris (n'-'2) + ex0(e ~ 2), otherwise AMPLE 13, Write a progrem to print inctuse estate.» Fihonacei series using recursion, printt("enter the number of Teant (ean) Fabongect.seres\e fortis; bens tse) ns\e"hs wr prinee(rnave? res); > Int FabonaceS(Sit 9) ‘ weCn 0) cite s¢ (nt ae return ( Fibonaeci(a-) + FSbonaccS(0-2) 5 d Output Enter the nana oF terms Fibonacch series Types of Recursion Recursion i a technique that breaks problem it ‘the original problem, Any rocursive func ine Fone (in 0) iF (n= 0) return (Fune (9-15 section, we will read Direct Recursion Figure 7.28 Dire recursion nis said 10 be direc reeusiveit it Funcl (ane) (a= 9) evar Fonz Fanci #) below These 40 return rusted) cach oer Fig, 728. omen Fal Recursion Fqure 7.29 lndieterrson Ine FaeeGnt 9) t en stack is independent of In Fig 7.30, the factor return (n* Fat aes ouipou pue uayiam 24 uss 9p00 aa ‘uo tnajgoad xp yn 2s HK asap" o7a008!,9% 02 94 0 aHoM U5 (eds se 9599 Je “20.005 se Ha aque aye you s30p He Sapa Jo sean 9 Supuod ap 4 20 won ‘wojgoud 1000, 4J0 940] 24) Jo wojmos xp suowe| dat 9po> Burwoypy a, vojsinany aay pu sau rods st y Busn 3 01 g Woy Su T— vaso « yey ‘ads Busn 9 0} U0 yy ‘popodu ae ioiaureed Ase xm 141108) 918-94 sb aagsanaoy ands se Bu 9ny woy fou. se vou ag uo ands se Sus 3.0 WOH, sS01 uSuyou Jo woygid to 0 woos ait Sema OL ‘EL ig unos SUL (0) a08 woneNSop 5 (gated adap ny sBs utp shou ons as euy ou, 9 HED a owns eo isms a uu vau ayy fod way porous wang ay BU EM NON, fant 4 paysuion ane a, se dats oy waior wo pouuogzod EL Bid ut unogs se 01 ¥ aod Woy sus ont sy 9 00 ‘uasgo Anryaie ood stds aq pun od toneunsep oy 5 sty "2889.10 uy “ajo axeds © Fuss sip Bap 9q im ay “ysip 2] ayy aAoge uaa sane ont sp 9] ap yxy st ns ure ay, Japuo sees op BurteyrEUs ays. jou 01 90d woy sr 5049 8 anoU ot way goad ayy “Y 2]0d wo pojunout sfuu omy SmOUS YOIUM EEL Big 1 YOO] ort sens (irthore are two ngs, then st move ole ana then move ting 2 rom sour led the to. Hence, a Intbecompul sing either linked i ions Vhat do you understand by stack ovrfow and underfow? 2. Differentiate ber 3. How does a anaray and a ‘5 Why areparent expressions? 6. Explain how stacks ae wed linear data structure in which elements fe added nd removed only fom one end, which ck called @ LIFO a, Fiss-Out) data structure as the element placed before the operands. Postix notations ae evalstod limite. 3988 9m ‘wons08 1 OY “I poy ep 2501) Jo Yeo Busn pawuosoydu are sonanb x04 181g paoeyd sem yoyo eq ay 0 98OUNo}aU0 IS 2439 1 euruts Jo mop Bu NoWsNGOULNI Fe ‘aNUL93P80 ONINUYT sanano 9 ualdvi ° 1099 worsIng 24h 4 01 vowniado Zupuad v st 5194 syuosssudaawysod 20 wont oa. ot pe ype a uo aU We soe NON OH “E el 8, worsendea a owns oy wnsBoas SAE “0 9, worsaudio oy nonuo> 2 weed 8a "a 1 Buss yoos © youoydam oy awsdoadw 908,“ sesiuoxg Suwuesbo.g sed soos a eg 91 psd & aynjen2 01 mesioud « 2108 of eno uy pu worst pod aNpeods09 Sdes00¥@) -a.9+8Y 2 5u9 som isms TE neues canbe eat vanables tit EISELE aa Fir 8.1 Oe CECE Ee Pa Fi 8.2 ova errr aS Figwe8.3 one aero dove ofthe queve, The que afer. Here Fon = d= 6 ‘ ‘heck for overtow conditions. An overtou ‘we ty ta insert an element ‘When Rea = nex = step 2 0 have an over ow cont tooo step 3: Ser tutte) «mm edit us now look at Figs 8.4 and ich show the algorithms ty insert and delete an elem Figure 8.4 Algor inane aque 1. Wiite a progisa to implement linear cucu, Quenes 158 ‘efi nix 10 nt que); veld insart (ois); nt delete-elenen (vod); nt poek(wis) vad aisplay 0 5. Eat); " Enter your option I, topeions saatencoption ‘ case Inserts ren Val = delete eLenent()s iF alt ei) Printf("\n the ranbur deteted i + M6", val)s breaks Va = eek: Ye atten a agit the Rt valve in fate 15 £34", wd; ‘isplay(); tren ) Dahide(optson t= 5); Been) ; feta snsertcy Enter the nuber £0 be inserted dn the qusue “); tran) Finn onthe; suse aft 2 tary ceemicent doe atte mae ‘ 2F(Front «= -4 1] frontorear) 4 FE ananon(0pOU wes 249 pe nous 2 O5Te 51 yong) 2p0u ay fo wed sx xp tn patoys st ous spo 8 pou pou sig 2g St apou aU 2M Jt oy dog uy 9pou ayp ut poxrs 29 6 nye xpi ® p00 nou unosu ye onan pa wg aniiy 99 ua ta 2pou mou ayy. ‘ued 1x pur wed ava su uy any ay ators “pou sou B 18 iy ut wags ananb poyuy ayn s9pisuog “anon ap 30 ousap9 se] ‘ur pappe st awoye au a “nanb v UL oi9[9 Ue Mosul posn s uoqeiado esto opesedg 9501 ‘nanb 24 Jo usta ‘say a 30 anges oxy stumiar Youn a¢ uoneuodo JoMoue 81 ato ‘sy wawy Hed “anon ap 40 HRs 20 uo ap wow wowoye ue soxomar wontsedo siete ay pu ‘ananb ath jo puD ay 7 au we sppe woueiado wesuF ayy e799 put wesut‘suoTeIAdo oIseg omy sey onan Y ‘senang paxuy] uo suonesadg 978 31g 1 unoqs 51 aonb jo uonewaseidos poy 2, “xo st aan gg sowerpa NU aM Jo sa}uId rae a uaa ou OM JO SAPO at ‘ors yy s2ynoue pus rep a 301s ey 2 ‘sd om sy uate £AD49 onan pyle ‘0st suonezado Jo} wounynb aur [Rad isaudau pour fo uotmaunbox 98208 24 2 pu (o)0 st swam » yas anon & 50 osm s woperuaseudos pyar ay) “21 ‘oanewye 2490 agp ‘SoueAPE UL PoUIRAR}op 29 jouaea aa Soa 931 ng “uoEDaMa|dun Woqgo Ue sone ann aa JO won| dun ‘eae aq) ua ‘soueape ur usouy st 218 tanurxeu 30 Uo [ous {ine ws nb ap a8 Uy “Uh 0 10] Buramsuoo pe roitouo Joo] eBupeasa Agora ‘Suop 29 taney a suogeaoy-9J0 3 © tox 98s pu 9m, “Senor dn pussy; yup ananb 830} suoneoo| Kowa $55 aFEOqT ax ae Ul PY "Pesen 3 Ast song $4N3ND JO NOLIWANaSuaaH OSINN &'s nanbp poy nena ny we Duan jo siond au pve ‘enonbus pape | aonb ay u Nowa we OuLAsu Jo Sseo0 ay, (seseauess || enwos)E 4 #11 > (end suf « SSG oma quevet message i printed. Consider the qvee sho in Fig. 8.10, (pias aSoSEM To delete an element, we Figure 8.1. itt ewue ater deen ofa ment fac aecarsesseanainerae Teste _— wall now point tothe second elemest of the stop HF R= nt inked queue. Ths, the updsted queve be onder Floe ig. 8 points to Fron. In Step 3, raat is made topo node in sequence. In Step given back tothe free pool 41. Witea program to implement linked queue. ‘inuoe conten ge cede ct nose mck unre vinset(strct gueee nt): it gusue *eeletecelewent( struct queue *); ect gunue esisplay (struct qove *); peeu(struce queue fat Sing nt val, opt trserOs peinee("\n sees weaureese) rinte("\n 1. 6SER0" Petnee(\n 2: OLETe" Js the ease, then the queue is empty and no more deletions can be done. If an atempt is made to delete value is already empty, an under 1s a shown in Figure 8.12 shows the algorithm to delete an element from a linked queue. In Step 1, we first check forthe undertow condition. Ifthe condition i tre, then an appropriate message a is displayed, otherwise in Stop 2, we use a pointer TR that the memery aecupied by PR ie etete lent) teens val = peak(g)s Seva rin("\n The value at front of queue 35 : Xe", val); a= displaye@); reat > Jhate(option f= ‘old create qucve(struct queue 2) c 2 Struct queve *insert(struet queue *qyint val) ‘ seract node ates per = (Struct nodeaaltoc(sizeof(struct nose); 4(q-> front == MLL) ‘ 5 Snowe = nL: ‘ a-prear-> next « ptr; eo rear = pers ) ¢ struct nade te per = a> front Se{peennn nu primer" QUEUE IS enone"); se a lstroct quae) printer “svonypue san 20) pou 96 une UD! UF aaop O25 KN Ppatuoped as suon2jap moy ssnosip Now st 3 i “Sadao st nan 249 998) 8 3909 ‘on ayer a7 dg u won 2m dag onan sens v augu0de ayp sis yoru 61 swayeoy ween yun aang) 4'9 amis ermine cect mmnon “ ne {Pap oranny mesa wong ONO, , orsip pus donsosu suzojod ays apoot MEE SS ke uy st anon eons voy fe pu o> mvs Ua U0 998 ana ano ayy MAHER. HBA 1s sooo xp sy ‘ayy uy ‘ananb semana w as 0} st uoxdo puooes au, wy Speedo Buqumsuoo-ou £299 29 ue> sm spo ps t= eau wormpuds oxy asnea9g ssa [fs UoMYpuos eoysoNe 3 ‘ai yo uosg “p('gBly UF UMS anon 3x Uy Heoa]o wou B UASUL O08 ‘= wae pu = $91 ur unos se uae 34 wap cn oy a ese.935 pts. “paz 34 Azada st anon a asne309 391800 930% 19z_ song sro poets ananb ou 400 nani ad feyepc-quodse-d wansas one t Gata SL anand UY, 908 (ies) (oy aonb sonunayaged 9 Second “on 51 pone aus sen ou og Teve yoy b = abot (5 anon nase) 262 Date Swuctres Using C CSET + book ig 820 SO aS eT Frenoetem er = eas Ey queue owt =, then thre Tieateea ps Sete siee sae caemittoa) |: | We dees boronic cat ROR. 9 andrea aresetto-1. Th Delt is lamentand st REAR = FRONT = 2 2-1 Queue wa single amon Figure 8.22. Guave where rat = sx beta dleton tosee ifthe queue has become and send to see rrohas reached ofthe queue, The value of racer 25 Ror toolete a element roma cela aueve ‘ Owens 263 print#(*\n The nunber deleted is + 44", vals The Rest value fn queue fs = 44", val); ” ‘ate [Pear ema; ‘oate Pear oman; se¢tronteatnier) rants i uoraco)arru eae someésee ‘peas Lomareeen aCe pen (uotré0). 2 ; dendaierrs (tone Me er ee ne oe fen? A ‘coed Sires ee ) wore auf ) (onbap"snduy on toume | : ¢ fes9 Oonbapr nina sabe aet (vorntonyoarnt (von toy px oe (wo wo anak aaa pu enbop poaatsaas weiner? Usa ontop poaprases gnc y W\yaaunad aneco MU HDs UD SS "sons ‘uop 8H urs ites wh “oimettaty pin nut sat on (Groner nse fis ap tant oe Goyer Fe org tfin on {ern ny yon sGidseet ot soe “sep pornos ndino pe dy yuna oy wesBaud 8 aM p LHL | $90 sono ' pus pus sot 2401 sod yoy "ore pure 1437p sonbag 7¥@ | war anak her Auaea st and + vorido so oat se: Sr pnatep Joqun au, 2 doris ae so¥ek st £ enor ous uy posuosuy ag an aoqune a o3¥e} TS wore anak sen rand an Kersta "> dt ususys ve ated *t Howe ve yout *T an (sana ) ae 4 (sana (7 ae suoajer) Joy > (een wou)st ) (AL@A SI 308 WA.) gaeTad en Wa tees 308) 91 TCaoaiad messy oot fl fyuosp]aand umes ‘seanf("Rd" option) ; » Eatehortion) : case 1: Tost. tents case 8 delete left()s Saele70: ‘ Jwhtdecoptton ) fold ansertright() ‘ sot vals Dprint#(*e Enter the value to be aéded:"); feanrCas", al); GFCClsre =e O's edgne <= naca) I (left = sgn) ‘ printe("\n OVERFLOW”); ) de cat» ‘ 2) /* $6 queue $5 snitsatty empty */ rete Fieke = 05 sf(rtent == moa) /*right Ss at Last position of queue */ fees ae hantens | egueteieht) © val : 2 foie Snsert_teFt() ¢ Fretaaee od Oka raphe == meen) || (ler == rigneiny? « prante("\n OvERFLO” 1 if (left oo -1y/*1F que As initially emty+/ qi lee =o Nace a t rate = 0) Tete; a defen , doque(aere) = vols oid delete 10F¢() $F (Lert a) ‘ prinee(o\n wenrtow eturn > feiateC"n The deleted ene te; 2", cqvelleFeld: {ede = rlt) tite fv only one sean *7 dete = Hoes, a t suet = pater Tet 3 one ete = eee; ) ‘oid detete_right() ‘eet = 9 ‘ reste mr; p ia ae at he tele FS RE ee i a ¢ sett righ se¢oighe use d Vote atspiay() Lek fro = ere ear «eight ¢ etn @HUE 18 eT"; ) : Brint#(°\n the elenons oF the queue ane *) pou mau |0uonesu aye aonb Sous 2@ ably “yuawge mou ay jo ey ue Anon Jato qn auowoye ap ua» = oasruA2p082 pues eta wot HSU} DAD gp een vous 92-¥anbig ‘978 ig ut umoys aman Ayuoudl 2 p09 “2idurexe tog uous rey oye pasos | yuo. ou Avo as 4 sy ey ua ue sD ao JF ‘ydisud $404 uo possanoud ue pafuene oe swuswoys ayy Aasoud oures omy axey susumao ony uo 288399 0 a20}9q anon ax 1m pauosur sex 43 aya 40 3 a1ojoq paras sem JoNagA INO a “anonb ap tony siuouio xs Busby ananb Aloud pouos ws sZ'g Bey wt anon ‘uy s220joq passocoad 29 iv ug '¢Joquuru Kyoya © Sey & pur | Joquin Kou w Sey ¥ AYN “spur vstuawoyo om aue aio ojdutex Jog GH0ud say suvaul ZoqumuAitoud famo7 enon uous 2-9 and S78 iy ul umoqs anonb Au0ud ay sopisu0-) Jo pou Asana ups pay e Busn pauowojdas st ananb Kod e 1 sea usm powuosoudat0q ues ann iuoud Axo yndeu09 ap Ut ‘aneng Ao & 0 uoneqwasaxtoy poxury sso 20 atm (v Bor)o Anon soy Saxons oms 28019 Jo punig»Algenso pueyus!7Hfou are sonbayon ay) "811 941 wor} INoW> we 22)9p 0} auH (u}o pu uae LE LDS) ua ‘enue a UO ou uy pexours ag oy sey Uo we wt Sune ave Suossasu 14 08 39) poyoaeas 9g oa fou ‘nang Awoud @ jo wonewewsjoiuy 1s1y pernooxs 9q ya pu oruodua 20w st Borjo0qauyuo oxy Ssn0¥.go uo ‘seapyoONs Jo Bund ym puoses a PUN or Bd rouse uo passsoaid ote outa ue s30joq passaoaid st 210 Duta Sructares Using C However, if we have anew element wi be inserted after, as both these elements ave tl FCFS bass as shown in Fig. 828. sta # and price sty runbec=2, then the element ill same priority but the insertions are done on ESE EE iseron ofa Fiore 6.28 Per que a ote Deletion Deletion isa very simple process inthis case. The frst node ofthe ist. and the data ofthat node wil be processed fis. ‘Array Representation of a Priority Queue ‘When arrays are used to implementa priority gu separate queue for each priority number ismaintsned, Each of these queues willbe implemented using circular arrays or circular queues Every individual queue will have is own #Aovt and nea pointers ‘We use a two-dimensional aray for his purpose where each queue willbe allocated the same amount of space. Look atthe two-dimensional representation of a priority queue given below. Given the FHoxT and REAR Valves of eae the two-dimensional matrix ean be formed as shown in Fig, 8.29, our and texk(t) contain the font and rear values of row «, where «is the priority number. [Note that here we are assuming that the ow and columa indices stat from 1, not 0. Obviously, ‘while programming, we wi in the priority queue, add the element at the rear end of row H, where isthe row number as well a the priority number of that element For example, if we roto insert an element with priority number 3, then the priority queue willbe given as shown in Fig 530 Deletion To deletean clement, we ind the fstnon empty queue and then process the f the ist non-empty queue. In our pri 5, Write program to implementa priority queue inclage cstto.m> ‘Bruck note treet struct nade *startnutt; Struct node Sinsere(strict node * Struct node *dolece(struct nde yoid.display(struct node Wind) t int on et 2 c etre ever ene frintrwn i cen prime cn ft yous option + Sean a tonto selecneotion c Eerrimere(try; fart» ettastorys me tsptaycsartys , ; asteoptont); ey ode *insert(: aa ct rote start) Struct node +p, 9: pte = (struct node *)palloc(sSzeof (struc. node Print¢(*\n encer'the value and ite priority #2) Seonf( "2d Xe", Bal, tor percodate = vals Ptroopetority = Tecstarteot Pr < start-oprkoity 9 a emu ponte wy ptr-onext = ponent; , s , : dec oa “este note start : ) re sen = [oue0s-jaand ten » (gsees} ‘wet = gs ) ‘res ™ eatous We eM o> CHRIST (res wp eases pron anand px 3\.)sauTae (Caphnuedestyaunages)a0g > Ovenan8-etdesp pron ‘ ‘ (oesscr0) 35 voup]anand = to 2 . ‘ SCoragan w,) utd a seyyu0us)49 ) were yt t en » fyuebueelanand t en = fa, F wie wT weet rove mone Geis oe : (ex wryvaasus prot Se = HON) Seated “T-oyauos 5-—pieas fanan oat crop bontate Somos) 2pntaate Soran apd you dy oy wreifoud e ay, va ep aj 2aueape FC Kaoqadend ‘enepeonad ‘ foxeho0r (a = Aaporidis (t= Gnueratjor ‘anand autores 2 dorado snot aout Tor : Aapiora sa pus anpen oy 203 TE! Aapiogad SIF pue enter a saat 1 Pdothdo ano seat nding t ‘ tyoveadnnd pan. Daur ¢ > Ww =| sary $C. 2 st ana ALlWotMa W500 ) 5 Abaha SE anand ‘Sr == aes ues ae fad p00 NaS ) (yp sou pony sere prot c Seavey enepcoad (5 at penoTag wl whe aeons senamniys 24 Daa Smee Ung a cose 5: pint Te contents of Gin hare do atte Eapty ees sp wou cise 6: pin Fille amo A ean striae}, fear didetortionion: » men? wis i va = leer Genta) Ben eenarXs return vol HHesrontBenme) 445 APPLICATIONS OF QUEUES + Queues are widely used as waiting sts ora single shared resource ike printer, disk, CPU + Queues are used to transfer data asynchronously (data not neces ne rae 2 sent) beeen tvo proceses (10 ble), pipes fi + Queues are used as bufers on MPS players and portable CD playes, Pod LL Llaleleely] | 9 Wo suoneiedo SuymoHog ap ALO}Od MON CLT TET summon orumtonteonig 1 ADEISHNOYR NtoGLON sesjo1073 SuesBo1g pv @) ‘ranb 1 suogeiedo Bu na aonb 2 iano pV even mou eur 050 : jsoonb ay no an aa eyo ea a ee 0 sydo Boon 9p wioiad NON sword sy ai ncn Aud A | orang ney | aus nou 9p Jossppe a) pe Saas ag sospqumu fond a) (9) ssedeang ane yenisjon,ocpouserouap | EUs ae pies non Gunga wea 6 pssoarl 9 yum sumo po 39 8 auop age) siono=t 31 ‘pao ouo ae Av0 avop 29 wo suonatep | bese pee | enon) 49 vonensnda poy o auaunbas a0 24 + pep Se oq Buen pontuoqay 99 089 fanenb “Aromow szeinduoo aunt] + "Nos pp pa om ng noes WH 1p feu mone 9 2uyo Su ‘xno punauo we poppearesronbe ure OGL + ‘nbep © “Gouiu &ndio 2 no Dye) ag 0 2u0 319 2 =) Pe mp 205 PREP 20 PPE 9 uD eM OU BIBNO} NEURO YY AMINES CATA ESLaRENDY © Lut soning 6 a4) ut $208 uon eur ay, 1 ssanoud auras ay Sa. t "uy omy stp uonsod y uostod typ o> Oe» CHAPTER 9 Trees LEARNING OBJECTIVE INTRODUCTION sfiqis am ty poe 11 sapou pur g pue s sapou ‘) pue g sapou is pue y sapot pu 's sossagons fy se 4 UF apou Kuv Stuy) auounge ‘Abojoursey ston Ado neyo pes snap pu srosssa0ns ou 294 ZT pUE* “s sop0u'e' Bug | ap waa Zang “¢ s9p0u Jo ss1sUo9 pou 1001 2p Jo 290-98 82 "6 PUE'G "6" SepoU aM Jo IssU0D apoU os 3M Jo 3BH-GNS Yo} OM 1 SION, 2085000Ns 8119) jst wawayo wsoudor ‘sag uy sapou paqes sotsja jo uor!o][09 ese pouyop se aumonss ep #51300 AzEUIg soa Kiewg €°2'6 "224 Jo pou 001 a4 uA {a wor» oa son pu vss we om Mung YSUOONSH PH Zl an Hupuodsonoo a smcys (3) Big PUR aIY Ga) © sous (0) 6 Bia “fra 104 2912493 9p 043 5 spou aiuseSuppe Ayaan eo sax siamoumDm® CO O@® & OO “yds 99 uno 9 pu as ao © @® w 2 10 038250 5 Paap yep 29 Os we Isa Y ter sdf g Burnoyoy 2124, 29 50 a0852p 24, ‘sy 9pou e ey! uoxprys Jo soquinu po} yenbas12pou BJo saHHaq 29490 qn ja] 18 are apou Joos 2p 50: fem eypos ut 2queny joy» paises wep uansap ap He pul °C“9°> Sopou |g Fj wL UDA yappUaOS9p {uP SARK Jou OP SopOL 227 2pOU Js} o:9poU 34D "ung yred ue wo apou sossagans Au apou wOpUD2Sap Y apou mpUDDSIE S3UL40 SAL 26 1 Surava spo o saquin ays! apou 8 yo2asHapIm0 2dopIMQ irae sp Jo seq 24st apou e jo 20s83p-0] eaypoyy 282 Daa Srctres Using C root Tee” eo) @®O Of @ Q © o Figure 95 Leaf node A node that has no children i called a leaf node ora termina node. The leaf nodes in Similar binary trees Two bine tees and these trees have the same struture. Figure 9.5 shows two id to be copies corresponding nodes. Figure ine connecting node to any ofits successors. A binary tee lyn - + edges because every node exept the rot nade is parent via an edge Path A sequence of consecutive edges. For example, in Fig 9.4 the path from the toot aode othe node 8 is givens: 2 4 and 8 Depth The depth of 4 node wis given ste length ofthe path from the ot ‘10 the node n. The depth ofthe root node is 220, Height of tree \tsthe total numberof nodes onthe path from the o9t node tothe deepest node inthe tee. Ate with ony root node has a height of 1 nodes. Ths is because every f every level has two noes ‘sony on element and at most n TeeT Tree” ® @ @®Q @Q © OO Figue 8.6 Tisacony oT A binary tree of height has at least» nodes and at most lve wil ve et oe noe and oan ave tet 2 noe Inddegreclout-degree ofa node It's the aumber of edges arriving at a node, The root node is the only node that hasan in-degree equal to 2er0, Similarly, oudegree ofa node is the number of edges leaving that nade inary tees are commonly usedto implement binary search trees, expression tees toumameat ‘trees, and binary heaps. +2 nodes, level 2 has 2°=4 nodes, level 3 has 6 nodes which is less than the maximumt of 2 + nodes. ly 13 nodes. They have been purposely ee Figure 9.7 Conse bina vee He Log, (o 43) | ‘This means, fare has 100,000 nodes, Extonded Biaary Trees ‘A binary tre + is said to be an extended binary Wee tree) iPeach node in the tee has either no child or ex ‘wo chilren. Figure 9.8 shows how an ondinary binary ‘converted into an extended binary tee al Tnanextended binary tee, nodes having 60 cil ‘internal nodes and nodes having no children ae called ex Figure 8.8 (0 Snare and ()eAENEOE pds. In Fig 98, theinteral nodes are represented sing: binary tree and the extemal nodes are represented using squares. ‘To convert a binary tre into an extended tee, every empty sub-tee is replaced by a new node. The original nodes inthe tee are the internal nodes, and the new nodes added ae called the external nodes, ‘Representation of Binary Trees in the Memory {at compt'memory tay een emai hry inked represe inked cepresentation of a binary toe, cv left node, and a pointer tothe righ 1 4 x] s[x x[e[x] [x]e[x] [xf Figure 9.9 Links presentation of ana ee

You might also like