22
C and Data Structures: A Snap Shot Oriented 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 Using Live Engineering Examples

Embed Size (px)

DESCRIPTION

about c

Citation preview

  • C and Data Structures:A Snap Shot Oriented Treatise with Live Engineering Examples

    With more than 1000 Solved ProgramsPlus More than 500 questions with answers.

    N.B.VenkateswarluE.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 with Live Engineering Examples

    by

    N.B. Venkateswarlu, Ph.D (BITS, Pilani), PDF (Leeds, UK)Senior Professor in CSE, AITAM, Tekkali, A.P, India

    &E.V. Prasad, Ph.D (IIT-Roorkee)

    Principal, JNTU College of EngineeringJNT 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 Company)Head Office: 7361, RAM NAGAR, NEW DELHI 110 055Phones: 23672080-81-82, 9899107446, 991131088; Fax: 91-11-23677446Shop at: schandgroup.com; E-mail: [email protected] & [email protected]

    Branches:

    1stFloor,Heritage,nearGujaratvidhyapeeth,AshramRoad,Ahmedabad-380 014, Ph. 27541965, 27542369, [email protected]

    No.6,AhujaChambers,1stCross,KumaraKrupaRoad,Bangalore-560 001. Ph:22268048, 22354008, [email protected]

    238-AM.P.Nagar,Zone1,Bhopal-462011. Ph: 4274723. [email protected] 152,AnaSalai,Chennai-600 002. Ph: 28460026, [email protected] S.C.O.2419-20,FirstFloor,Sector-22-C(NearAromaHotel),Chandigarh-160022, Ph-2725443, 2725446,

    [email protected] 1stFloor,BhartiaTower,Badambadi,Cuttack-753009, Ph-2332580; 2332581, [email protected] 1stFloor,52-A,RajpurRoad,Dehradun-248 001. Ph: 2740889,2740861, [email protected] PanBazar,Guwahati-781 001. Ph: 2738811, [email protected] SultanBazar,Hyderabad-500 195. Ph: 24651135, 24744815, [email protected] MaiHiranGate,Jalandhar-144008.Ph:2401630,5000630,[email protected] A-14JantaStoreShoppingComplex,UniversityMarg,BapuNagar,Jaipur-302015,Phone:2719126,jaipur@

    schandgroup.com 613-7,M.G.Road,Ernakulam,Kochi-682 035. Ph: 2378207, [email protected] 285/J,BipinBihariGanguliStreet,Kolkata-700 012. Ph: 22367459, 22373914, [email protected] MahabeerMarket,25GwynneRoad,Aminabad,Lucknow-226 018. Ph: 2626801, 2284815, [email protected] BlackieHouse,103/5,WalchandHirachandMarg,Opp.G.P.O.,Mumbai-400 001. Ph: 22690881, 22610885,

    [email protected] KarnalBag,ModelMillChowk,UmrerRoad,Nagapur-440 032 Ph : 2723901, 2777666 [email protected] 104,CiticentreAshok,GovindMitraRoad,Patna-800 004. Ph : 2300489, 2302100, [email protected] 291/1,GaneshGayatriComplex,1stFloor,Somwarpeth,NearJainMandir,Pune-411011. Ph : 64017298,

    [email protected] FlatNo.104,SriDraupadiSmritiApatment,EastofjaipalSinghStadium,NeelRatanStreet,UpperBazar,

    Ranchi-834001 Ph : 2208761, [email protected] KailashResidency,PlotNo.4BBottleHouseRoad,ShankarNagar,Raipur. Ph. 09981200834, raipur@schandgroup.

    com

    Copyright 2009, by Authors

    Allrightsreserved.Nopartofthebookistobeprinted/publishedwithoutthewrittenpermissionofthePublisher/Author.However, some parts of the book have been reproduced with acknowledgement from the public sources available in the Internet, and the rights to them are governed by the licensing rules that originally applied to them.

    S. CHANDS Seal of Trust

    Inourendeavourtoprotectyouagainstcounterfeit/fakebookswehaveputaHologramStickeronthecover of some of our fast moving titles. The hologram displays a unique 3D multi-level, multi-colour effect of our logo from different angles when tilted or properly illuminated under a single source of light. Background artwork seems to be under or behind the logo, giving the illusion of depth. A fake hologram does not give any illusion of depth.

    First Edition 2009

    ISBN:Code:

    PRINTED IN INDIAByRajendraRavindraPrinters(Pvt.)Ltd.,7361,Ramnagar,NewDelhi-110055and published by S. Chand & Company Ltd., 7361, Ram Nagar, New Delhi-110 055.

  • Dedicated to

    Our beloved Students for their consistent Inquisitiveness and Inspiration

  • vii

    FOREWORD

    School of Computing

    University of LeedsLeeds LS2 9JT

    T +44 (0) 113 343 5430F +44 (0) 113 343 5468E office @comp.leeds.ac.ukW http://www.comp.leeds.ac.uk

    Roger D BoyleTel: +14 113 [email protected]://www.comp.leeds.ac.uk/roger

    July 2, 2009

    Computer programming is an essential in many if not most branches of science and engineering: not justfortheobviousskillofbeingabletomakethecomputerdoefficientlywhatisneeded,butforthediscipline of efficient logical thought it brings.

    But computer programming has proved over many decades to be very difficult to teach. That com-bination of logic, clarity and pedantry that makes for success is hard to communicate and can be soul-destroying to practice.

    Venkateswarlu and Prasad bring a text that will assist. The C language has a reputation for being streamlined and compact. It has stood the test of time and remains a favourite among many scientists and engineers. The text is presented with many apposite examples and exercises that will assist the learner in the fundamentals and more advanced aspects of the language, and programming in general. Further, the text is introduced by a useful section letting the reader understand properly what is going on under the bonnet what the programming language is actually talking to.

    The authors are very well qualified to present this text: they both present many decades of front-line experience in computing applications of science and engineering and also have deep experience of classroomteaching.Knowingthesubjectandthepitfallsinvolvedinteaching,theyhaveproducedabook that gives what is needed in a clear and direct way and I am delighted to recommend it.

    Roger D BoyleHead of School

    UNIVERSITY OF LEEDS

  • ix

    This book has been conceived and produced by two popular teachers who taught the course for many long years. There are many aspects of this book that are worth noting in this context.

    These two authors with their experience of dealing with thousands of students for 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 of 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.

    Prof. Allam Appa Rao, PhD (Engg) FIE, FIETE, FIIBE, FIV, FISIBM, Sr MIEEE, SDPS FellowVice ChancellorJawaharlal Nehru Technological University: KakinadaKakinada 533 003, AP, Indiawww.allamapparao.org Contact: + 91 884 2300 888 (Work), 2360 999 (Home), Fax: 2300 800

    FOREWORD

  • xi

    LISTOFENGINEERING/ MATHEMATICAL PROBLEMS SOLVED

    1. Quadratic Equation Solution. 87 2. Newton Raphson Method. 208 3. ApplicationofNewtonRaphsonMethodtoageneralizedequation. 284 4. Conversion of angle from radians to degrees, minutes and seconds. 41 5. Conversion of angle in degrees, minutes, and seconds to radians. 40 6. Conversion of temperature value from one scale to another. 97 7. Simpson rule to calculate the area under a curve. 232 8. Trapezoidalruletocalculatetheareaunderthecurve. 231 9. Calculating a functions value and derivative in a given domain with a given

    step value. 284 10. Calculating sum of the two vectors. 284 11. Calculating scalar product of two vectors. 285 12. Checking for uniqueness of a matrix. 335 13. Calculating transpose of a matrix. 332 14. Traversing a matrix in row-wise raster fashion. 337 15. Checking a matrix for magic matrix properties. 402 16. Calculating Determinant of a matrix. 504 17. Inverse of a matrix calculation. 506 18. Solving simultaneous equations. 507 19. Calculating the product of two matrices. 348 20. Adding two matrices. 346 21. Calculating quadratic term value between a vector and matrix. 347 22. Traversingaoddsizedsquarematrixinaspiralfashion. 358 23. Towers of Honoi problem. 443 24. Eight queens problem. 445 25. Checking a number for its primality. 380 26. Calculating factorial value of an integer. 377 27. Calculating NCR value efficiently. 422 28. Euclids algorithm for finding GCF of two integers. 378 29. Solving exponential function. 149 30. Solving sinh(x) function 150 31. Generating Fibnocci series 146 32. Use of random numbers in testing IQ of a child. 237 33. Use of random numbers in estimating coin tossing the probability. 236 34. Use of random numbers in simulating a noisy channel. 239 35. Mean filtering a 1-D signal. 286 36. Filtering a 1-D signal. 287 37. Calculating the histogram of a population of students marks. 272

  • xii C and Data Structures: A Snap Shot Oriented Treatise with Live Engineering Examples

    38. Best fitting line using Least squares. 244 39. Correlation coefficient calculating between two series. 404 40. Program to print Pascal triangle. 381 41. Program to calculate LCM between two integers. 382 42. Program to calculate GCF between two integers. 383 43. Calculating outliers. 271 44. Calculating median of a population. 274 45. Calculating mode of a population. 279 46. Calculating a polynomial value in a given domain. 283 47. Normalizingasetofdata. 295 48. Standardizingasetofdata. 294 49. Calculating relative percentile of a set of students marks. 297 50. Scaling a data. 296 51. Calculating covariance matrix of a data set. 356 52. Examples to demonstrate the computational errors. 245 53. Adding two algebraic polynomials. 855 54. Subtracting two algebraic polynomials. 855 55. Multiplying two algebraic polynomials. 859 56. Horners method of calculating polynomial value. 427 57. Calculating Ackermann function. 433 58. CalculatingBeziercoefficientsforlinedrawing. 435 59. Calculating parity of an integer for error detection. 430 60. Calculating Cyclic redundancy checking (CRC) checksums. 616 61. Program to calculate Internet checksum. 617 62. Program to calculate longitudinal and vertical redundancy check. 620 63. Program to calculate Hamming bits. 621 64. Huffman coding 950 65. MinimumdistanceproblemsolutionusingDijkstrasAlgorithm. 971 66. Calculating transitive closure of a graph. 966 67. Complex number manipulations. 542 68. Program to clip a point against a rectangular window. 625 69. Flood filling algorithm for graphic applications. 434 70. Pattern matching algorithms. 737 71. Adding two big integers 846 72. Adding sparse matrices. 734 73. Calculating transpose of a sparse matrix. 734 74. Converting infix expressions to postfix. 793 75. Evaluating RPN (Reverse Polish Notation) expressions. 792 76. Calculating mean and standard deviation of a population. 114

  • xiii

    PREFACE

    Our purpose of writing this book is to let the young and new entrants to programming to enrich their logical abilities. Tracing or mimicking or copying is the means through which a human being learns since their birth. Here, also we believe the benefits of such a type of learning process and explain our contents in similar lines which we refer as snap shot oriented learning. Prominent characteristic of our book is to take live Engineering examples for explanation and implementation. Each chapter includes programming assignments for which solutions will be provided at authors home site www.ritchcen-ter.com/cbookexamples.Moreover,eachchapterissupplementedwithconceptorientedobjectivequestions with answers and explanations.

    First chapter introduces the fundamentals of computers, programming, algorithms, programming languages, compilers, and development environments. Second chapter explores the elements of C programming such as variable declarations, arithmetic, logical, Boolean and conditional operators. Here, itself we will let students to think logically. How logics involving simple 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, if, if-else, and switch introduces the student about how to think program development in a systematic way. Some practical life problems from Education, busi-ness are included.

    Chapter on loops is used to further strengthen the students abilities to attempt practical problems. Loops such as while, do-while and for are used to implement many mathematical and scientific prob-lems. 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 of code works. That is, the loops will be traced (simulated) with some dummy data so as to make the reader understands the functioning of a piece of code in a better way. This chapter is the one which contains large number of programming examples with many problems as exercises.

    A chapter on strings introduces the user to string variables. The users will be exposed to use standard library functions such as strlen(), strcmp(), strcpy(), atoi(), atof(), itoa(), ftoa(), etc.,.

    Needforanarrayinatypicalprogramminglanguageisemphasizedinchapteronarrays.SomeliveexamplesareusedtoshowthattheuseofarraysreducesI/Orequirementsofaprogram.Practicallifeexamples are solved by writing suitable programs. Also, use of 2D character, integer and other type of arrays is demonstrated with live examples. Examples includes sorting a set of numbers, strings in addi-tion 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, definition, call is differentiated with live examples. How to send normal variables, arrays to functions is explained with practical examples. Also, pass-ing by value style of arguments passing is explained in detail with simple concept oriented exam-ple. Moreover, storage classes and global variables are explained with simple examples. Variables scope and life is explained with each of the storage classes to name automatic, static, register, and external.

  • xiv C and Data Structures: A Snap Shot Oriented Treatise with Live Engineering Examples

    A separate chapter is included for recursive functions. The examples are explained with snap shots. Some Mathematical problems are implemented both iteratively and recursively. Also, a chap-ter is included on pre-processor directives.

    The term Pointer, which makes most of the fresh students to run away from C language, is dealt in a separate chapter in an illustrative manner. Simple, lucid examples are employed to explain the con-cepts. Also, some examples are used to explain passing by address style of argument passing to func-tions.Inaddition,needfordynamicarraysareemphasizedwithpracticalexamples.Useofstandardlibrary functions such as malloc(), calloc() and free() is included in this chapter.

    A chapter on user defined variables makes the readers about structures, unions and enumerators. Needforuserdefinedvariablesisemphasizedwithexplanationtodataabstraction.Liveexamplesfromgeneral life make the examples of this chapter more attractive.

    Use and need of data files 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.

    A chapter on command line arguments introduces the user to command line input. Moreover, a sepa-ratechapteronbitwiseoperatorsisincludedfortheuse.Someexamplesfromcommunication/controlmakeECE/CSE/INSTstudentstounderstandtherealpowerofbit-wiseoperators.

    Chapter on Sorting and searching introduces the readers to the practical applications of these prob-lems. This chapter first starts with introduction to data structures, algorithm analysis, time complexity, etc. The selected sorting algorithms to name bubble, selection, radix, insertion, merge, heap, and quick sorting are explained by preparing the snap shots of the programs with a selected data set. Also, their relative performance is compared in terms of memory requirements and CPU time requirements.

    A chapter on stacks and queues introduces the student to their practical applications. Live examples are discussed to make the student to have real feeling on the concepts. Use of stack for expression parsing, infix to prefix conversion, is discussed with a ready to use program code. In addition, queue isalsorealizedthrougharrays.Also,examplesareincludedtoexplaintheneedforpriorityqueuesandde-queues.

    The concept of linked list is explained by employing self-referencing structures. Simple examples are used to build the reader a simple linked list on their own. Also, circular linked lists, double lists, areexplainedwithreadytouseprograms.Practicalapplicationsoflinkedlistsareemphasizedwithfullimplementation.Inaddition,examplesareincludedinwhichstacksandqueuesarerealizedusinglinked lists.

    Chapter on trees introduces the reader to trees with special emphasis on computer sciences. The chapter starts with definitions and ends practical implementation of a binary search tree in C lan-guage. Concepts such as binary search, tree rotation for balancing, etc., are explained with illustrative examples.

    A chapter on Graphs is used to introduce the reader to graphs and graph theory. Need for minimum distance,pathmatrix,isexplainedwithliveexamples.Also,useofDijkstrasalgorithmtofindmini-mum distance is explained with a live practical example. Prims and Kruskals algorithms are used to find minimum spanning tree of a given graph. In addition, tree traversals such as breadth first traversal and depth first traversal are explained with simple graphs.

    N.B. VenkateswarluE.V. Prasad

  • xv

    ACKNOWLEDGMENTS

    There are many people, to whom the authors are profoundly indebted while bringing out this book; especially, those thousands of C language students who had undergone training under the first author, Prof. Venkateswarlu, at RITCH center, Visakhapatnam. The authors, Prof. N.B. Venkateswarlu and Prof. E.V. Prasad do express their, sincere thanks to the students of AITAM, to whom the first author has taught first level courses on C and Data Structures. The students silly mistakes and the authors advises during the laboratory sessions is the basis for this book.

    Dr. Venkateswarlu would like to thank his wife Dr. Sarada and the little Appu, for bearing with him, while preparing this manuscript and sacrificing the time reserved for them otherwise.

    Prof. Prasad wants to convey his thanks to his wife Mrs. Lakshmi and his three daughters, Srividya, Srivani and Srivalli for allowing him to spend week ends on bringing out this book.

    The authors would like to express their sincere thanks to their constant source of inspiration, Prof. BR Gandhi, former professor of BHU, Varanasi, Prof. KVGK Gokhale, former Professor, IIT-Kanpur, Prof. Roger D Boyle, University of Leeds, UK. Prof. Venkateswarlu wants to convey his thanks to many of his teachers and colleagues for their constant inspiration. Prof. Venkateswarlu owes a lot to them; especially,toProf.Raju,Prof.Maheswari,Prof.VSRao,Prof. JVRamana,Prof.Venkateswaran,Prof.Misra, Prof PN Rao of BITS, Pilani. Also, he is indebtful to Prof. C Venkataramaiah, Prof. Kotaiah, Prof. Jagannadha Rao of SVUCE.

    The authors express , that it might be a grave mistake , if they forget to mention about the moral encouragement given by Prof. Allam Appa Rao, Honble Vice Chancellor of JNT University, Kakinada. The authors believe that this book may be that their snails response for 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 of AITAM, Dr. Someswara Rao, Secretary, Mr. LL Naidu, Director, Prof. VVN Rao for their support while writing this book. The authors express their thanks to Prof. JVR Murthy, Prof. Satya Prasad, Prof. Srinivasa Kumar, Mr. MHM Krishna Prasad, JNTU, Kakinada for their support and encouragement. The authors do owe their sincere thanks to Prof. Seetharamanath, Prof PVGD Prasada Reddy of AU, Prof N Patel, BIT Ranchi, Dr. MN Reddy, NAARM,Hyderabad,Prof.TrimurthuluofAcharyaNagarjunaUniv.fortheirconsistentandconstantencouragement.Mr.VishnuRaju,Prof.DRRaju,Director,ofSVECW,Bhimavaramarerememberedfor their help and encouragement.

    Also, they express their thanks to Mr. Dharmajee, Mr. Ch Ramesh, Mr. Nageswara Rao, Mr.Prasanna,Mr.Sahu,andotherstaffmembersofCSE/ITofAITAMCollege.Also,theyshallexpresstheir sincere thanks to scholars Mr. Naga Tirumal Rao, Mr. BG Reddy, Mr. Bharat, Mr Ramu, Mr. Ravi, Mr.Nagendra,Mr.Giridhar,Mr.Rajkishore,Mrs.Sunitha,Mr.Ramesh,Mr.Satpathy,Mr.BTirumalRao, Mr. RVV Muralikrishna, Mr. Subramanyam, Mr. Chandrasekhar (RVRJC), Mr. Hidayatullah. They dothankDr.SuryaRao,Mdm.JayaRao,Mr.Achari,Dr.SambhuPrasadofRIT,Mr.Govindarajulu,Mr.Bhaskar, Berhampur, for their encouragement.

    Also, the authors would like to express their gratitude to Prof Ananda Rao, JNTU-Ananthapur, Prof. Narasimham, Prof Srinivasulu, Prof. Govardhan, of JNTU-Hyderabad, Mr. GSM Rao, Prof. Kantha

  • xvi C and Data Structures: A Snap Shot Oriented Treatise with Live Engineering Examples

    Rao,Prof.P.S.Rao,Prof.P.S.RajuofGVPCOE,Mr.VenkatRao,VignanUniversity,Prof..RajasekharofKLUniversity,Prof.Raju,PrincipalofMVGR,Prof.GuptaofVITS,Prof.VenuGopal,Mrs.SabithaofVITS,Dr.VVRPrasad,Prof.MM.NaiduofSVUCE,Dr.ArjunRao,Mr.Nanaji,Mrs.Sailaja,Mr.JaganofJITM,Mr.Vidhyadhar,Dr.SriMuraliofVEC,Kavali,Dr.VijaykumarofGIET,Dr.SPPanda,Dr.Panda.Mr.Raoof GIET, Gunupur, Dr. Ravindra Babu of RVRJC, Dr AK Rath of 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 staff of S Chand group for bringing out this book.

  • xvii

    CONTENTS

    Foreword vii ListofEngineering/MathematicalProblemsSolved ix

    Preface xi Acknowledgments xiii

    1. Brief Introduction to Computers 1 1.1 Some Novice HW Concepts 2 1.2 Some Novice SW Concepts 6 1.3 Conclusions 13

    2. Basics of C Language and Program Development 15 2.1 C Programming under Turbo C 15 2.2 Programming under Dev-C++ IDE 18 2.3 WorkingUnderUnix/Linux 20 2.4 IntroductiontoCCompilingunderUnix/Linux 23 2.5 CompilationStepsunderDOS/Windows 25 2.6 Introduction to anatomy of a Simple C Program 26 2.7 Conclusions 30

    3. C Operators 31 3.1 Arithmetic Operators 31 3.2 Relational Operators 47 3.3 Logical Operators 59 3.4 Unary Operators 61 3.5 C Language Operator Precedence Chart 64 3.6 Declaration of Storage Class 65 3.7 Conclusions 67

    4. Character Variables 69 4.1 ESCAPE Characters (OR) Special Characters 77 4.2 Ready made functions to manipulate Symbolic Information 78 4.3 Conclusions 81

    5. Control Structures 83 5.1 The if condition 83 5.2 Labels 90 5.3 The goto statement 90 5.4 Switch Construct 92 5.5 Conclusions 100

    6. While Loop: The Dawn of Logic 105 6.1 The while loop 105 6.2 The break statement 142

  • xviii C and Data Structures: A Snap Shot Oriented Treatise with Live Engineering Examples

    6.3 Continue Statement 153 6.4 Nested While Loops 161 6.5 Conclusions 163

    7. String Variables 165 7.1 Input/Outputstringvariablesusingscanffunction 167 7.2 Manipulating Strings As a whole 168 7.3 Manipulating Strings Character by Character 178 7.4 Processing Line Full of Text 192 7.5 Conclusions 202

    8. The do-while Loop 205 8.1 Conclusions 209

    9. For Loop 211 9.1 Random Numbers: A Real Engineer Must Know 235 9.2 Best Fitting (Least Squares Fitting) Line 242 9.3 Conclusions 246

    10. One Dimensional Arrays: Excluding Strings 249 10.1 Why do we need Arrays? 249 10.2 Conclusions 302

    11. 2-D Character Arrays 305 11.1 Introduction 305 11.2 Conclusions 321

    12. Multidimensional Arrays 323 12.1 Conclusions 360

    13. Functions 363 13.1 Introduction 363 13.2 Birds View of Execution of a Program with Functions 367 13.3 Passing 1-D Arrays 387 13.4 Passing 2-D arrays to functions 400 13.5 Conclusions 411

    14. Recursive Functions 413 14.1 Background 413 14.2 Mutual Recursion 436 14.3 Tail Recursion 436 14.4 Conclusions 447

    15. Macros and Preprocessor Directives 449 15.1 Introduction 449 15.2 Conclusions 458

    16. Pointers 459 16.1 Introduction 459 16.2 Passing Pointers to Functions 467 16.3 Dynamic Memory Allocation 477 16.4 Precedence of Operators on pointers and Arithmetics of pointers 498 16.5 Conclusions 510

  • Contents xix

    17. User-defined variables: Structures, Unions, Enumerators 511 17.1 Structures 512 17.2 Unions 530 17.3 Enumerations 531 17.4 Typedef 542 17.5 Conclusions 547

    18. Redirection Operators and Command Line Arguments 549 18.1 Redirection Operators 549 18.2 Introduction to Command Line arguments 552 18.3 Environment Variables 564 18.4 Conclusions 567

    19. Data Files 569 19.1 Introduction 569 19.2 Conclusions 606

    20. Bit-wise Operators 607 20.1 Introduction 607 20.2 Conclusions 627

    21. Functions with Variable Number of Arguments 629 21.1 Introduction 629 21.2 Combining C and C++ programs 632 21.3 Conclusions 638

    22. How Main Executes? 639 22.1 Introduction 639 22.2 How main() is executed on Linux 647 22.3 Conclusions 655

    23. Make 657 23.1 Introduction 657 23.2 Conclusions 665

    24. Introduction to Graphic Programming using C 667 24.1 Graphic Programming using Turbo C 667 24.2 Introduction to X Windows System 668 24.2.1 GTK Programming 674 24.2.2 Qt Programming 681 24.3 Graphic Programming Under Blood Shed Compiler 684 24.4 Conclusions 684

    25. Introduction to Function Pointers 689 25.1 Introduction 689 25.2 Conclusions 696

    26. Mixing C and Assembly 697 26.1 Introduction 697 26.2 Conclusions 702

  • xx C and Data Structures: A Snap Shot Oriented Treatise with Live Engineering Examples

    27. Common Programming Errors 703 27.1 Introduction 703 27.2 Conclusions 716

    28. Introduction to Data Structures 717 28.1 Introduction 717 28.2 Time Complexity analysis of algorithms 721 28.3 Reducing Space Complexity 729 28.4 Conclusions 735

    29. Pattern Matching 737 29.1 Introduction 737 29.2 Conclusions 746

    30. Sorting and Searching Algorithms 747 30.1 Searching 747 30.2 Sorting 754 30.2.1 Counting and Bucket Sort 754 30.2.2 Bubble Sorting 756 30.2.3 Insertion Sorting 758 30.2.4 Selection Sort 760 30.2.5 Radix Sort 763 30.2.6 Address Calculation Sort 765 30.2.7 Merge Sort 766 30.2.8 Quicksort 768 30.2.9 Heap Sort 771 30.2.10 Shell Sorting 775 30.3 Sorting Algorithms Compared 778 30.4 A Note on External Sorting Techniques 779 30.5 Conclusions 779

    31. Stack and Queues 781 31.1 Stacks 781 31.1.1 RealizationofStacksUsingArrays 782 31.1.2 An application of stack for checking expression validity 786 31.1.3 Infix, Postfix and Prefix Expressions 790 31.2 Queues 797 31.3 Conclusions 809

    32. Linked Lists 811 32.1 Single Linked Lists 812 32.1.1 A Practical Application: Radix Sorting 841 32.1.2 A practical Application: Manipulating Large Integers 843 32.1.3 Another Practical Application: Representing Polynomials as linked lists 849 32.2 Single Circular Lists 862 32.3 Double Linked Lists 872 32.4 Designing A Simple Line Editor 889 32.5 Conclusions 895

  • Contents xxi

    33. Trees 897 33.1 Introduction 897 33.1.1 Binary Search Trees 902 33.1.2 Max Heap & Min Heaps 903 33.1.3 Tree Traversals 904 33.1.4 Creating Binary Search Tree 906 33.1.5 Deleting a node from BST 913 33.1.6 Traversing Tree Using Stacks 915 33.1.7 Height Balanced Trees or AVL Trees 940 33.1.8 Sequential Representation of the Tree 945 33.1.9 Huffman Encoding 949 33.2 Conclusions 951

    34. Graphs 953 34.1 Introduction 953 34.2 Graph Representations 959 34.3 Transitive Closure and Path Matrix 965 34.4 Graph Traversals 966 34.5 Minimum Distance Problems 969 34.6 Minimum Spanning Tree 973 34.7 Topological Sorting 976 34.8 Conclusions 980

    35. Collection of Sample Questions 981

    References 1011 Appendix A: Some Useful Functions 1013 Appendix B: ASCII Table 1017 Appendix C: Style Guide 1019 Index 1039