C and Data Structures: A Snap Shot Oriented Treatise Treatise with Live Engineering Examples
With more than 1000 Solved Programs Plus More than 500 questions with answers.
N.B.Venkateswarlu E.V. Prasad
S. CHAND & COMPANY LTD. (AN ISO 9001:2000 COMPANY) RAM NAGAR, NEW DELHI - 110055
C and Data Structures: A Snap Shot Oriented Treatise Treatise with Live Engineering Examples
by N.B. Venkateswarlu, Ph.D (BITS, Pilani), PDF (Leeds, UK) Senior Proessor in CSE, AITAM, Tekkali, A.P, India & E.V. Prasad, Ph.D (IIT-Roorkee) Principal,, JNTU College o Engineering Principal JNT University, Kakinada, AP, India
S. CHAND & COMPANY LTD. (AN ISO 9001:2000 COMPANY) RAM NAGAR, NEW DELHI - 110055
S. CHAND & COMPANY LTD. (An ISO 9001:2000 Compan Company) y) Head Oce: 7361, RAM NAGAR, NEW DELHI – 110 055 Phones: 23672080-81-82, 9899107446, 991131088; Fax: 91-11-23677446 Shop at: schandgroup schandgroup.com; .com; E-mail:
[email protected] & in
[email protected] in
[email protected] Branches: • 1stFloor,Heritage,n 1stFloor,Heritage,nearGujarat earGujaratvidhyapeeth,Ashr vidhyapeeth,AshramRoad, amRoad,Ahmedabad-380 Ahmedabad-380 014, Ph. 27541965, 27542369,
[email protected] • No.6,AhujaCha No.6,AhujaChambers,1stCr mbers,1stCross,Kumara oss,KumaraKrupaRoad, KrupaRoad,Bangalore-560 Bangalore-560 001. Ph:22268048, 22354008,
[email protected] • 238-AM.P 238-AM.P.Nagar .Nagar,Zone1, ,Zone1,Bhopal-462011. Bhopal-462011. Ph: 4274723.
[email protected] [email protected] • 152,A 152,AnaSa naSalai, lai,Chennai-600 Chennai-600 002. Ph: 28460026,
[email protected] [email protected] • S.C.O.2419-20,F S.C.O.2419-20,FirstFloor irstFloor,Sector-22-C(Near ,Sector-22-C(NearAromaHot AromaHotel), el),Chandigarh-160022, Chandigarh-160022, Ph-2725443, 2725446,
[email protected] • 1stFloor 1stFloor,BhartiaT ,BhartiaTower ower,Badambadi, ,Badambadi,Cuttack-753009, Cuttack-753009, Ph-2332580; 2332581, cuttack@schandg
[email protected] roup.com • 1stFloor 1stFloor,52-A,RajpurRoad, ,52-A,RajpurRoad,Dehradun-248 Dehradun-248 001. Ph: 2740889,2740861,
[email protected] [email protected] • Pan PanBazar Bazar,,Guwahati-781 Guwahati-781 001. Ph: 2738811, guwahati@schandg
[email protected] roup.com • Sulta SultanBaz nBazar ar,,Hyderabad-500 Hyderabad-500 195. Ph: 24651135, 24744815, hyderabad@ hyderabad@schandgroup schandgroup.com .com • MaiHi MaiHiran ranGate Gate,,Jalandhar Jalandhar-144008.Ph:2401630,5000630,
[email protected] -144008.Ph:2401630,5000630,
[email protected] • A-14JantaStor A-14JantaStoreShoppingC eShoppingComplex,Unive omplex,UniversityMarg,BapuNa rsityMarg,BapuNagar, gar,Jaipur Jaipur-302015,Phone:2719126,jaipur@ -302015,Phone:2719126,jaipur@ schandgroup.com • 613-7, 613-7,M.G. M.G.Road Road,Ern ,Ernakulam akulam,,Kochi-682 Kochi-682 035. Ph: 2378207, cochin@schandgr
[email protected] oup.com • 285/J,BipinBihariGang 285/J,BipinBihariGanguliStreet, uliStreet,Kolkata-700 Kolkata-700 012. Ph: 22367459, 22373914, kolk ata@schandgr
[email protected] oup.com • MahabeerMarket MahabeerMarket,25Gwynne ,25GwynneRoad,Aminaba Road,Aminabad, d,Lucknow-226 Lucknow-226 018. Ph: 2626801, 2284815,
[email protected] [email protected] • BlackieHouse,103/5, BlackieHouse,103/5,WalchandHir WalchandHirachandMarg,O achandMarg,Opp.G.P pp.G.P.O., .O.,Mumbai-400 Mumbai-400 001. Ph: 22690881, 22610885,
[email protected] • KarnalBag,ModelMillCho KarnalBag,ModelMillChowk,UmrerRo wk,UmrerRoad, ad,Nagapur-440 Nagapur-440 032 Ph : 2723901, 2777666
[email protected] [email protected] • 104,Citicentre 104,CiticentreAshok,GovindMitra Ashok,GovindMitraRoad, Road,Patna-800 Patna-800 004. Ph : 2300489, 2302100,
[email protected] • 291/1,GaneshGayatri 291/1,GaneshGayatriComplex,1stF Complex,1stFloor loor,Somwarpeth, ,Somwarpeth,NearJainMandir NearJainMandir,,Pune-411011. Pune-411011. Ph : 64017298,
[email protected] • FlatNo.104, FlatNo.104,SriDraupadiSm SriDraupadiSmritiApatment, ritiApatment,EastofjaipalSingh EastofjaipalSinghStadium,NeelRat Stadium,NeelRatanStreet,U anStreet,UpperBazar pperBazar,, Ranchi-834001 Ph : 2208761, ranchi@schandgr
[email protected] oup.com • KailashResidency,Plot KailashResidency,PlotNo.4BBottle No.4BBottleHouseRoad,Shan HouseRoad,ShankarNagar, karNagar,Raipur. Raipur. Ph. 09981200834, raipur@schandg raipur@schandgroup. roup. com Copyright © 2009, by Authors Allrightsreserved.Nopartofthebookistobeprinted/publishedwithoutthewrittenpermissionofthePublisher/Author. However,, some parts o the book have been reproduced However reproduced with acknowledgement rom the public sources available in the Internet, and the rights to them are governed by the licensing rules that originally applied to them. S. CHAND’S Seal o Trust Inourendeavourtoprotectyouagainstcounterfeit/fakebookswehaveputaHologramStickeronthe cover o some o our ast moving titles. The hologram displays a unique 3D multi-level, multi-colour eect o our logo rom dierent angles when tilted or properly illuminated under a single source o light. Background artwork seems to be “under” “under” or “behind”the logo, giving the illusion o depth. A ake hologram does not give any illusion o depth. First Edition 2009 ISBN: Code: PRINTED IN INDIA
ByRajendraRavindraPrinters(Pvt.)Ltd., ByRajendraRavindraPrinters( Pvt.)Ltd.,7361,Ramnagar 7361,Ramnagar,NewDelhi-110055 ,NewDelhi-110055 and published by S. Chand & Company Ltd., 7361, Ram Nagar Nagar,, New Delhi-110 055.
Dedicated to Our beloved Students or their consistent Inquisitiveness and Inspiration
FOREWORD School of Computing University of Leeds Leeds LS2 9JT T +44 (0) 113 343 5430 F +44 (0) 113 343 5468 E ofce @comp.leeds.ac.uk W http://www http://www.comp.leeds.ac.uk .comp.leeds.ac.uk
UNIVERSITY OF LEEDS
Roger D Boyle Tel: +14 113 3435487
[email protected] http://www.comp.leeds.ac.uk/roger July 2, 2009
Computer programming programming is an essential in many i not most branches o science and engineering: not justfortheobviousskillofbeingableto justfortheobviousskillof beingabletomakethecomputerdo makethecomputerdoeciently ecientlywhat whatisneeded,butfor isneeded,butforthe the discipline o ecient logical thought it brings. But computer programming has proved over many decades to be very dicult to teach. That combination o logic, clarity and pedantry that makes or success is hard to communicate and can be souldestroying to practice. Venkateswarlu and Prasad bring a text that will assist. The C language has a reputation or being streamlined and compact. It has stood the test o time and remains a avourite among many scientists and engineers. The text is presented with many apposite examples and exercises that will assist the learner in the undamentals and more advanced aspects o the language, and programming in general. Further,, the text is introduced by a useul section letting the reader understand properly what is going Further on under the bonnet – what the programming language is actually talking to. The authors are very well qualifed to present this text: they both present many decades o ront-line experience in computing applications o science and engineering and also have deep experience o classroomteaching.Knowingthesubjectandthepitfallsinvolvedinteaching,theyhaveproduceda book that gives what is needed in a clear and direct way and I am delighted to recommend it.
Roger D Boyle Head o School
vii
FOREWORD
This book has been conceived and produced by two popular teachers who taught the course or many long years. There are many aspects o this book that are worth n oting in this context. These two authors with their experience o dealing with thousands o students or the last two decades have designed and delivered the content very well. The presentation and examples dealt in the book, named “snap shot oriented treatise” is no doubt likely to make even a below average student to understand the logical approach. I am very much impressed with the contents o the book and the orientation given by the authors. The book has succeeded in introducing Data Structures concepts to a computer science student in the best possible manner. Pro. Allam Appa Rao, PhD (Engg) FIE, FIETE, FIIBE, FIV, FISIBM, Sr MIEEE, SDPS Fellow Vice Chancellor Jawaharlal Nehru Technological Technological University: Kakinada Kakinada 533 003, AP, India www.allamapparao.org Contact: + 91 884 2300 888 (Work), 2360 999 (Home), Fax: 2300 800
ix
LISTOFENGINEERING/ MATHEMATICAL PROBLEMS SOLVED 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37.
Quadratic Equation Solution. Newton Raphson Method. Application of Newton Raphson Method to a generalized equation. Conversion o angle rom radians to degrees, minutes and seconds. Conversion o angle in degrees, minutes, and seconds to radians. Conversion o temperature value rom one scale to another. Simpson rule to calculate the area under a curve. Trapezoidal rule to calculate the area under the curve. Calculating a unctions value value and derivative in a given given domain with a given given step value. Calculating sum o the two vectors. Calculating scalar product o two vectors. Checking or uniqueness o a matrix. Calculating transpose o a matrix. Traversing Trav ersing a matrix in row-wise raster ashion. Checking a matrix or magic matrix properties. Calculating Determinant o a matrix. Inverse o a matrix calculation. Solving simultaneous equations. Calculating the product o two matrices. Adding two matrices. Calculating quadratic term value between a vector and matrix. Traversing a odd sized square matrix in a spiral fashion. Towers Tow ers o Honoi problem. Eight queens problem. Checking a number or its primality. Calculating actorial value o an integer integer.. Calculating NCR value eciently eciently.. Euclid’ss algorithm or fnding GCF o two integers. Euclid’ Solving exponential unction. Solving sinh(x) unction Generating Fibnocc Fibnoccii series Use o random numbers in testing IQ o a child. Use o random numbers in estimating coin tossing the probability probability.. Use o random numbers in simulating a noisy channel. Mean fltering a 1-D signal. Filtering a 1-D signal. Calculating the histogram o a population o students marks.
xi
87 208 284 41 40 97 232 231 284 284 285 335 332 337 402 504 506 507 348 346 347 358 443 445 380 377 422 378 149 150 146 237 236 239 286 287 272
xii
C and Data Structures: A Snap Shot Oriented Treati Treatise se with Live Engineering Engineering Examples Examples
38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52. 53. 54. 55. 56. 57. 58. 59. 60. 61. 62. 63. 64. 65. 66. 67. 68. 69. 70. 71. 72. 73. 74. 75. 76.
Best ftting line using Least squares. Correlation coecient calculating between two series. Program to print Pascal triangle. Program to calculate LCM between two integers. Program to calculate GCF between two integers. Calculating outliers. Calculating median o a population. Calculating mode o a population. Calculating a polynomial value in a given domain. Normalizing a set of data. Standardizing a set of data. Calculating relative percentile o a set o students marks. Scaling a data. Calculating covariance matrix o a data set. Examples to demonstrate the computational errors. Adding two algebraic polynomials. Subtracting two algebraic polynomials. Multiplying two algebraic polynomials. Horner’s method o calculating polynomial value. Calculating Ackermann unction. Calculating Bezier coecients for line drawing. Calculating parity o an integer or error detection. Calculating Cyclic redundancy checking (CRC) checksums. Program to calculate Internet checksum. Program to calculate longitudinal and vertical redundancy check. Program to calculate Hamming bits. Human coding Minimum distance problem solution using Dijkstra’s Algorithm. Calculating transitive closure o a graph. Complex number manipulations. Program to clip a point against a rectangular window window.. Flood flling algorithm or graphic applications. Pattern matching algorithms. Adding two big integers Adding sparse matrices. Calculating transpose o a sparse matrix. Converting infx expressions to postfx. Evaluating RPN (Reverse Polish Notation) expressions. Calculating mean and standard deviation o a population.
244 404 381 382 383 271 274 279 283 295 294 297 296 356 245 855 855 859 427 433 435 430 616 617 620 621 950 971 966 542 625 434 737 846 734 734 793 792 114
PREFACE Our purpose o writing this book is to let the young and new entrants to programming to enrich their logical abilities. Tracing Tracing or mimicking or copying is the means through which a human being learns since their birth. Here, also we believe the benefts o such a type o learning learn ing process and explain our contents in similar lines which we reer as snap shot oriented learning. Prominent characteristic o our book is to take live Engineering examples or explanation and implementation. Each chapter includes programming assignments or which solutions will be provided at author’s home site www.ritchcenter.com/cbookexamples.Moreover,eachchapterissupplementedwithconceptorientedobjective questions with answers and explanations. First chapter introduces the undamentals o computers, programming, algorithms, programming languages, compilers, and development environments. environments. Second chapter explores the elements o C programming such as variable declarations, arithmetic, logical, Boolean and conditional operators. Here, itsel we will let students to think logically. How logics involving simple operators operators can be used is demonstrated with live examples. In addition, student will be introduced to character variables which include escape characters. A chapter on control structures such as goto, i, i-else, and switch introduces the student about how to think program development in a systematic way. Some practical lie problems rom Education, business are included. Chapter on loops is used to urther strengthen the student’s abilities to attempt practical problems. problems. Loops such as while, do-while and or are used to implement many mathematical and scientifc problems. The examples are explained by tracing the programs (program snap-shot) such that the readers will be having better mental pictures about how a piece o code works. That is, the loops will be traced (simulated) with some dummy data so as to make the reader understands the unctioning o a piece o code in a better way. This chapter is the one which contains large number o programming examples with many problems as exercises exercises.. A chapter on strings introduces the user to string variables. The users will be exposed to use standard library unctions such as strlen(), strcmp(), strcpy(), atoi(), atoi(), ato(), itoa(), toa(), etc.,. Needforanarrayin Needfor anarrayinatypicalprogrammin atypicalprogramming glangua languageis geisemphasizedin emphasize dinchapteronarrays. chapteronarrays. Somelive examplesareusedtoshowthatthe examplesareusedto showthattheuseofarraysreducesI/O useofarraysreducesI/Orequireme requirementsofa ntsofaprogram.Practica program.Practicallife llife examples are solved by writing suitable programs. Also, use o 2D character, integer and other type o arrays is demonstrated with live examples. Examples Examples includes sorting a set o numbers, strings in addition to some matrix operations such as matrix transposition, multiplication, etc.,. Chapter on Function introduces the student to the program development approaches such as top down or bottom up. Function declaration, defnition, call is dierentiated with live examples. How to send normal variables, arrays to unctions is explained with practical examples. Also, passing by value style o arguments passing is explained in detail with simple concept oriented example. Moreover, storage classes and global variables are explained with simple examples. Variables scope and lie is explained with each o the storage classes to name automatic, static, register, register, and external.
xiii
xiv
C and Data Structures: A Snap Shot Shot Oriented Treat Treatise ise with Live Engineering Engineering Examples Examples
A separate chapter is included or recursive unctions. The examples are explained with snap shots. Some Mathematical problems are implemented both iteratively and recursively. recursively. Also, a chapchap ter is included on pre-processor directives. The term Pointer, Pointer, which makes most o the resh students to run away rom C language, is dealt in a separate chapter in an illustrative manner. manner. Simple, lucid examples are employed to explain the concepts. Also, some examples are used to explain“passing by address”style o argument passing to unctions.Inaddition,needf tions.Inaddi tion,needfordynamic ordynamicarraysaree arraysareemphasizedwi mphasizedwithpractical thpracticalexamples. examples.Useofst Useofstandard andard library unctions such as malloc(), calloc() and ree() is included in this chapter. A chapter on user defned variables makes the readers about structures, unions and enumerators. Needforuserdenedvariablesisemphasizedwithexplanationtodataabstraction.Liveexamplesfrom general lie make the examples o this chapter more attractive. Use and need o data fles is explained in general and their use in C in practice is dealt in detail in Chapter on Data Files. Practical examples are included to let the reader to perceive the concept clearly. Achapteroncommandlinearguments a rgumentsintroducestheusertocommandlineinput.Moreover,aseparatechapteronbitwiseoperatorsisincludedfortheuse.Someexamplesfromcommunication/control makeECE/CSE/INSTstudentstounderstandthereal makeECE/CSE/INSTst udentstounderstandtherealpowerofbit powerofbit-wiseoperators -wiseoperators.. Chapter on Sorting and searching introduces the readers to the practical applications o these problems. This chapter frst starts with introduction to data structures, algorithm analysis, time complexity, complexity, etc. The selected sorting algorithms to name bubble, selection, radix, insertion, merge, heap, and quick sorting are explained by preparing the snap shots o the programs with a selected data set. Also, their relative perormance is compared in terms o memory requirements and CPU time requirements. A chapter on stacks and queues introduces the student to their practical applications. Live examples examples are discussed to make the student to have real eeling on the concepts. Use o stack or expression parsing, infx to prefx conversion, is discussed with a ready to use program code. In addition, queue isalsorealizedthrougharrays.Also, isalso realizedthrougharrays.Also,examplesare examplesareincluded included toexplain toexplaintheneed theneedforpriorityqueuesand forpriorityqueuesand de-queue’s. The concept o linked list is explained by employing sel-reerencing structures. Simple examples are used to build the reader a simple linked list on their own. Also, circular linked lists, double lists, areexplainedwithreadytous areexplainedw ithreadytouseprograms.P eprograms.Practicalapplicati racticalapplicationsoflinkedlists onsoflinkedlistsareemphasized areemphasizedwith with fullimplementation. Inaddition,examplesare Inaddition,examplesareincluded included inwhich inwhichstacksandqueues stacksandqueuesarerealized arerealizedusing using linked lists. Chapter on trees introduces the reader to trees with special emphasis on computer sciences. The chapter starts with defnitions and ends practical implementation o a binary search tree in C language. Concepts such as binary search, tree rotation or balancing, etc., are explained with illustrative examples. A chapter on Graphs is used to introduce the reader to graphs and graph theory. Need or minimum distance,pathmatrix,isexplainedwithliveexamples.Also distance,pathmatrix,isexplaine dwithliveexamples.Also,useofDijkstra’ ,useofDijkstra’salgorithmtondmini salgorithmtondmini-mum distance is explained with a live practical example. Prim’ Prim’s and Kruskal’s algorithms are used to fnd minimum spanning tree o a given graph. In addition, tree traversals such as breadth frst traversal and depth frst traversal are explained with simple graphs. N.B. Venkateswarlu E.V. Prasad
ACKNOWLEDGMENTS There are many people, to whom the authors are prooundly indebted while bringing out this book; especially, those thousands o C language students who had undergone training under the frst author, Pro. Venkateswarlu, Venkateswarlu, at RITCH center, center, Visakhapatnam. The authors, Pro. N.B. Venkateswarlu and Pro. E.V. Prasad do express their, sincere thanks to the students o AITAM, to whom the frst author has taught frst level courses on C and Data Structures. The students’ silly mistakes and the authors’ advises during the laboratory sessions is the basis or this book. Dr. Venkateswarlu would like to thank his wie Dr. Sarada and the little Appu, or bearing with him, while preparing this manuscript and sacrifcing the time reserved or them other wise. Pro.. Prasad wants to convey his thanks to his wie Mrs. Lakshmi and his three daughters, Srividya, Pro Srivani and Srivalli or allowing him to spend week ends on bringing out this book. The authors would like to express their sincere thanks to their constant source o inspiration, Pro.. BR Gandhi, ormer proessor o BHU, Varanasi, Pro. KVGK Gokhale, ormer Proessor, Pro Proessor, IIT-Kanpur, Pro.. Roger D Boyle, University o Leeds, UK. Pro. Venkateswarlu Pro Venkateswarlu wants to convey his thanks to many o his teachers and colleagues or their constant inspiration. Pro. Pro. Venkateswarlu owes a lot to them; especially espec ially,toProf ,toProf..Raju,Prof Raju,Prof..Mahesw Maheswari,Prof ari,Prof.VS .VS Rao,Prof Rao,Prof..JVRamana,Prof.Ve JVRamana,Prof.Venkatesw nkateswaran,Prof aran,Prof.. Misra, Pro PN Rao o BITS, Pilani. Also, he is indebtul to Pro. C Venkataramaiah, Pro. Pro. Kotaiah, Pro. Jagannadha Rao o SVUCE. The authors express , that it might be a grave mistake , i they orget to mention about the moral encouragement given by Pro. Allam Appa Rao, Hon’ble Vice Chancellor o JNT University, Kakinada. The authors believe that this book may be that their snail’s response or the call to extend co-operation to make the JNT University, Kakinada as a world grade ors University, by the Vice Chancellor. The authors do express their gratitude to Chairman o AITAM, Dr. Someswara Rao, Secretary, Mr. LL Naidu, Director, Pro. Pro. VVN Rao or their support while writing this book. The authors express their thanks to Pro Pro.. JVR Murthy, Mur thy, Pro. Pro. Satya Prasad, Pro. Pro. Srinivasa Kumar, Mr. Mr. MHM Krishna K rishna Prasad, JNTU, Kakinada or their support and encouragement. The authors do owe their sincere thanks to Pro. Seetharamanath, Pro PVGD Prasada Reddy o AU, Pro N Patel, BIT Ranchi, Dr. MN Reddy, NAARM,Hyderabad,Prof. NAARM,Hyderabad,Pr of.TrimurthuluofA TrimurthuluofAcharyaNagarjunaUniv.fortheirc charyaNagarjunaUniv.fortheirconsistentandconstant onsistentandconstant encouragement.Mr.VishnuRaju,Prof.DRRaju,Director,ofSVECW,Bhimavaramareremembered or their help and encouragement. Also Al so,, th they ey ex expr pres ess s th thei eir r th thank anks s to Mr Mr.. Dh Dharm armaje ajee, e, Mr Mr.. Ch Ram Rames esh, h, Mr Mr.. Na Nage gesw swar ara a Rao Rao,, Mr Mr.. Prasanna,Mr.Sahu,andotherstamembers Pras anna,Mr.Sahu,andotherstamembers ofCSE/ITofAIT ofCSE/ITofAITAMColleg AMCollege.Also,theyshallexpre e.Also,theyshallexpress ss their sincere thanks to scholars Mr. Naga Tirumal Rao, Mr. BG Reddy, Mr. Bharat, M r Ramu, Mr. M r. Ravi, Mr.Nagendra,Mr.Giridhar,Mr.Rajkishore,Mrs.Sunitha,Mr.Ramesh,Mr.Satpathy,Mr.BTirumal Rao, Mr. RVV Muralikrishna, Mr. Subramanyam, Mr. Chandrasekhar (RVRJC), Mr. Hidayatullah. They dothankDr.SuryaRao,Mdm.JayaRao,Mr dothankDr .SuryaRao,Mdm.JayaRao,Mr.Achari,Dr .Achari,Dr.SambhuPrasadofRIT .SambhuPrasadofRIT,Mr.Govindarajulu ,Mr.Govindarajulu,Mr. ,Mr. Bhaskar, Berhampur, or their encouragement. Also, the authors would like to express their gratitude to Pro Ananda Rao, JNTU-Ananthapur, Pro.. Narasimham, Pro Srinivasulu, Pro. Govardhan, o JNTU-Hyderabad, Mr. GSM Rao, Pro. Kantha Pro
xv
xvi
C and Data Structures: A Snap Shot Shot Oriented Treat Treatise ise with Live Engineering Engineering Examples Examples
Rao,Prof.P.S.Rao,Prof.P.S.RajuofGVPCOE,Mr.VenkatRao,VignanUniversity,Prof..RajasekharofKL University,Prof.Raju,PrincipalofMVGR,Prof.GuptaofVITS,Prof.VenuGopal,Mrs.SabithaofVITS, Dr.VVRPrasad,Prof.MM.NaiduofSVUCE,Dr.ArjunRao,Mr.Nanaji,Mrs.Sailaja,Mr.JaganofJITM, Mr.Vidhyadhar Mr. Vidhyadhar,Dr.SriMuraliofVEC,Kavali,Dr ,Dr.SriMuraliofVEC,Kavali,Dr.VijaykumarofGIET .VijaykumarofGIET,Dr.SPPanda,Dr ,Dr.SPPanda,Dr.Panda.Mr.Rao .Panda.Mr.Rao o GIET, Gunupur, Dr. Dr. Ravindra Babu o RVRJC, Dr AK Rath o Bhubneswar. Lastly, The authors would like to express their thanks to Smt. Nirmala Gupta (CMD), Shri Amit Gupta (CEO), Shri Navin Joshi (Vice President-publishing), Shri B. Kaushik (GM-Sales & Marketing) and Shri N. S. Bisht (Regional Manager), and other publications sta o S Chand group or bringing out this book.
CONTENTS Foreword
vii
List of Engineering/Mathematical Problems Solved
ix
Preace
xi
Acknowledgments
xiii
1. Brie Introduction to Computers 1.1 Some Novice HW Concepts 1.2 Some Novice SW Concepts 1.3 Conclusions
1 2 6 13
2. Basics o C Language and Program Development 2.1 C Programming under Turbo C 2.2 Programmi Programming ng under Dev-C++ IDE 2.3 Working Under Unix/Linux 2.4 Introduction to C Compiling under Unix/Linux 2.5 Compilation Steps under DOS/Windows 2.6 Introduction to anatomy o a Simple C Program 2.7 Conclusions
15 15 18 20 23 25 26 30
3. C Operators 3.1 Arithmetic Operators 3.2 Relational Operators 3.3 Logical Operators 3.4 Unary Operators 3.5 C Language Operator Precedenc Precedence e Chart 3.6 Declaration o Storage Class 3.7 Conclusions
31 31 47 59 61 64 65 67
4. Character Variables 4.1 ESCAPE Characters (OR) Special Characters 4.2 Ready made unctions to manipulate Symbolic Inormation 4.3 Conclusions
69 77 78 81
5. Control Structures 5.1 The i condition 5.2 Labels 5.3 The goto statement 5.4 Switch Construct 5.5 Conclusions
83 83 90 90 92 100
6. While Loop: The Dawn o Logic 6.1 The while loop 6.2 The break statement
105 105 142 xvii
xviii
C and Data Structures: A Snap Shot Shot Oriented Treat Treatise ise with Live Engineering Engineering Examples Examples
6.3 6.4 6.5
Continue Statement Nested While Loops Conclusions
153 161 163
7. String Variables 7.1 Input/Output string variables using scanf function 7.2 Manipulating Strings As a whole 7.3 Manipulating Strings Character by Character 7.4 Processing Line Full o Text 7.5 Conclusions
165 167 168 178 192 202
8. The do-while Loop 8.1 Conclusions
205 209
9. For Loop 9.1 Random Numbers: A Real Engineer Must Know 9.2 Best Fitting (Least Squares Fitting) Line 9.3 Conclusions
211 235 242 246
10. One Dimensional Arrays: Excluding Strings 10.1 Why do we need Arrays? 10.2 Conclusions
249 249 302
11. 2-D Character Arrays 11.1 Introduction 11.2 Conclusions
305 305 321
12. Multidimensional Arrays 12.1 Conclusions
323 360
13. Functions 13.1 Introduction 13.2 Birds View o Execution o a Program with Functions 13.3 Passing 1-D Arrays 13.4 Passing 2-D arrays to unctions 13.5 Conclusions
363 363 367 387 400 411
14. Recursive Functions 14.1 Background 14.2 Mutual Recursion 14.3 Tail Recursio Recursion n 14.4 Conclusions
413 413 436 436 447
15. Macros and Preproc Preprocessor essor Directives 15.1 Introduction 15.2 Conclusions
449 449 458
16. Pointers 16.1 Introduction 16.2 Passing Pointers to Functions 16.3 Dynamic Memory Allocation 16.4 Precedenc Precedence e o Operators on pointers and Arithmetics o pointers 16.5 Conclusions
459 459 467 477 498 510
Contents
xix
17. User-defned variables: Structures, Unions, Enumerators 17.1 Structures 17.2 Unions 17.3 Enumerations 17.4 Typede 17.5 Conclusions
511 512 530 531 542 547
18. Redirection Operators and Command Line Arguments 18.1 Redirection Operators 18.2 Introduction to Command Line arguments 18.3 Environment Variables 18.4 Conclusions
549 549 552 564 567
19. Data Files 19.1 Introduction 19.2 Conclusions
569 569 606
20. Bit-wise Operators 20.1 Introduction 20.2 Conclusions
607 607 627
21. Functions with Variable Number o Arguments 21.1 Introduction 21.2 Combining C and C++ programs 21.3 Conclusions
629 629 632 638
22. How Main Executes? 22.1 Introduction 22.2 How main() is executed on Linux 22.3 Conclusions
639 639 647 655
23. Make 23.1 Introduction 23.2 Conclusions
657 657 665
24. Introduction to Graphic Programm Programming ing using C 24.1 Graphic Programming using Turbo C 24.2 Introduction to X Windows System 24.2.1 GTK Programming 24.2.2 Qt Programming 24.3 Graphic Programming Under Blood Shed Compiler 24.4 Conclusions
667 667 668 674 681 684 684
25. Introduction to Function Pointers 25.1 Introduction 25.2 Conclusions
689 689 696
26. Mixing C and Assembly 26.1 Introduction 26.2 Conclusions
697 697 702
xx
C and Data Structures: A Snap Shot Shot Oriented Treat Treatise ise with Live Engineering Engineering Examples Examples
27. Common Programmi Programming ng Errors 27.1 Introduction 27.2 Conclusions
703 703 716
28. Introduction to Data Structures 28.1 Introduction 28.2 Time Complexity analysis o algorithms 28.3 Reducing Space Complexity 28.4 Conclusions
717 717 721 729 735
29. Pattern Matching 29.1 Introduction 29.2 Conclusions
737 737 746
30. Sorting and Searching Algorithms 30.1 Searching 30.2 Sorting 30.2.1 Counting and Bucket Sort 30.2.2 Bubble Sorting 30.2.3 Insertion Sorting 30.2.4 Selection Sort 30.2.5 Radix Sort 30.2.6 Address Calculation Sort 30.2.7 Merge Sort 30.2.8 Quicksort 30.2.9 Heap Sort 30.2.10 Shell Sorting 30.3 Sorting Algorithms Compared 30.4 A Note on External Sorting Techniques 30.5 Conclusions
747 747 754 754 756 758 760 763 765 766 768 771 775 778 779 779
31. Stack and Queues 31.1 Stacks 31.1.1 Realization of Stacks Using Arrays 31.1.2 An application o stack or checking expression validity 31.1.3 Infx, Postfx and Prefx Expressions 31.2 Queues 31.3 Conclusions
781 781 782 786 790 797 809
32. Linked Lists 32.1 Single Linked Lists 32.1.1 A Practical Application: Radix Sorting 32.1.2 A practical Application: Manipulating Large Integers 32.1.3 Another Practical Application: Representing Polynomials as linked lists 32.2 Single Circular Lists 32.3 Double Linked Lists 32.4 Designing A Simple Line Editor 32.5 Conclusions
811 812 841 843 849 862 872 889 895
Contents xxi
33. Trees 33.1 Introduction 33.1.1 Binary Search Tree Treess 33.1.2 Max Heap & Min Heaps 33.1.3 Tree Traversals 33.1.4 Creating Binary Search Tree 33.1.5 Deleting a node rom BST 33.1.6 Traversing Tree Using Stacks 33.1.7 Height Balan Balanced ced Trees or AVL Trees 33.1.8 Sequential Representation o the Tree 33.1.9 Human Encoding 33.2 Conclusions
897 897 902 903 904 906 913 915 940 945 949 951
34. Graphs 34.1 Introduction 34.2 Graph Representations 34.3 Transit Transitive ive Closure and Path Matrix 34.4 Graph Trav Traversals ersals 34.5 Minimum Distance Problems 34.6 Minimum Spanning Tree 34.7 Topological Sorting 34.8 Conclusions
953 953 959 965 966 969 973 976 980
35. Collection o Sample Questions
981
Reerences
1011
Appendix A: Some Useul Functions
1013
Appendix B: ASCII Table
1017
Appendix C: Style Guide
1019
Index
1039