Contents C Book by Dr. Patanjali Kashyap

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

Data Structures

Using C
Also Covers Topics Like

SOFTWARE PROCESSES AND PROGRAMMING PARADIGMS


DEBUGGING STRATEGIES AND TACTICS
BASICS OF C PROGRAMMING LANGUAGE
C INTERVIEW QUESTIONS (GENERAL AND TECHNICAL)
HOW TO BECOME HIGHLY PAID PROFESSIONAL
LEARNING MAP AND REMEMBERING TECHNIQUES
COMPANY ETIQUETTE
WAYS TO DEVELOP CREATIVE THINKING
HOW TO MAKE PROFESSIONAL RESUME
TESTING CONCEPTS

By

Dr. Patanjali Kashyap


Ph.D ( Physics ),Ph.D (Computer Science,Persuing)
M.Phil ( Computer Science ) , M.Sc ( Physics ) ,
M.Sc.( Bio- Informatics), MCA, PGDCA , B. Sc. ( Physics )
M.Sc.(Pschology , Persuing),

ii
Arctech Publishers Pvt. Limited.
A Unit of Arctech Microelectronics Pvt. Limited.
Offices
Delhi, Kolkata, Mumbai, Patna
E-Mail : info@amesesystems.net

Distributed By
Arctech Publishers Limited.

Office Address
Arctech Publishers Pvt. Limited, Delhi.

Arctech Publishers Pvt. Limited, 2009.


First Published, 2009.
ISBN : 10 81-8333-257-9
ISBN : 13 978-81-8333-257-6
Cover and book design.

Arctech Publishers Pvt. Limited, 2009.


Printed at
Arctech Publishers Pvt. Limited, Delhi.
Published by
Arctech Publishers Pvt. Limited, Delhi.
LIMITS OF LIBILITY AND DISCLAAIMER OF WARRANTY
The Author and publisher of this book have tried their best to ensure that the
programmes, procedures and functions described in this book are correct. However, the
author and the publishers make no warrant of any kind, expressed or implied, with regard
to these programmes or the documentation contained in the book. The author and
publisher shall not be libel in any event of any damages, incidental or consequential, in
connection with or arising out of the furnishing, performance or use of these programmes,
procedures or functions. Product name mentioned are used for the identification
purposes only and may be the trademark of their respective companies.
All trademarks referred to in the book are acknowledged as the properties of their
respective owners.

iii

To the memory of my father and a great critic of my


intellectual works,
Who did not live to realize his greatest ambition-That of witnessing his son will get a job at least.

iv

Special Thanks to
Mr. N R Narayana Murthy and Mr Nandan M Nilekani, CoChairman, of INFOSYS TECHNOLOGIES LTD, Whose
vision help me to plan and write this book.

AND
My mamajee Dr. Hulas Narayana Singh for his unconditional
support during my problematic days while finalizing the
manuscript for the book.

FROM THE SAME AUTHOR


1. Data Structures Using C++
2. The Spiritual Universe: A Journey from Black Hole to Time Machine.
3. My Struggle: An Untold Story of Every Indian.
4. The Cheater Society: My Last One Year Experience with the Society, In Special
Reference To Developing And Developed Countries (A SocioPschological
Synthesis)
5. Srimad Bhagavad Gita : A Book of Pschology and Management.
6. Vadic Revaluation : Few Steps Away.
7. Indology: A Review of Vades, Upnishad, Purana and Astaawarkra Mahagita in
Modern Perspective.
8. Software Engineering : A Text Book
Science and Philosophy of Sports Series
1. Science and Philosophy of Sports : A Inside Story of Football
Upcoming titles
1. The Restless Corporation: A Synthesis of Brain and Medical Science,
Psychology, Sociology, Management Theories with the flavor of Newtonian and
Quantum Physics.
2. A Test Book of C #
3. Beyond Physics : Journey from Spirituality to Nanotechnology with the Backdrop
of Bio-technology , Bioinformatics, Psychology and Vedant
4. Physics
Trilogy On Information Technology And New Science
1. Change : A technical history of Computer From Abacus To Nano-Quantum
Computer
2. The Future Perfect : Evolution of DNA and Pantaflop compution.
3. Here We Are : Birth of Spinelectronics And Deth of Silicon

vi

About The Author


Patanjali Kashyap has compleated his Ph.D thesis in Electronics, Radio,
Quantum and Atomic computation, and is doing his Ph.D in Computer Science and
Applications on Big data, DWH, Devops, CG and BI integration. His academic
achievements include huge list of degrees, certificates and diplomas, some of them are
MCA, M.Phil (Data Mining, Knowledge Management, and SOA), M.Sc (Electronics and
Radio Physics), M.Sc.(Bio-Informatics) and PGDCA in computer applications. His various
research papers (around 25 in numbers) are published in national and international
journals of repute on topics like Indology, Nanotechnology, Quantum Computer, Optical
Computer, Photonic Crystal, and DNA (Bio) chips, Organizational Structure, Human
Behavior, Evolution and Psychology. He conducted several workshops and delivered
lectures on new generation motivation techniques of emotional, spiritual and social
intelligence. He developed a unique Mind Mapping Techniques with association of
ancient Tao, kundalini and Vadic methodology, which proves to be very effective for the
increasing / maintaining memory and effectiveness of the organization.
Patanjali write extensively for the news papers, magazines, web-sites and for the
blogs, he is also associated with the career and psychological counseling. Apart from all
these boring stuffs he dance well (specialist in Salsa, bollywood dance), plays cricket,
badminton and table tennis. He is a good bathroom singer and thought some time he
will get best playback singer award for his performance (!!!!..... Tooo Optimistic !!!)
Patanjali also has extensive experience in software industry. Presently, he is
working as a Project Manager in INFOSYS TECHNOLOGIES LTD, Bangalore, and has,
in past led and manage projects in banking, travel, financial sector and of Mortgage, in
his spare times he loves to play with the latest technologies from Microsoft Corporation
specially technologies revolves around .NET, now a days he also make his hands dirty
with Unix and other open source products. He enjoys writings research papers for journal
and presenting them in the conferences.

vii

Acknowledgements
First and foremost, I thank my maa and maa-see-maa, for their unfaltering
support and confidence in all my endeavors even the sensible ones. I thank also my
sisters and brother in law Dr. S.K. Chaudahary for giving me unconditional support in my
difficult time. I thank also to my colleagues Srjeeth Janardanan, Vijayant Jha and Kaku
for their emotional support and confident hand , which gives me feeling that I am not
alone. I want to thank INFOSYS TECHNOLOGIES LTD in totality for their policies to
stand behind their employee, when they need their support at most. I want to thank
Dr. H. C. Rai for his support. During preparation of this acknowledgement memory of
Dr. R Panday become refresh in my soul , he was my mentor and guide for intellectual
life, giving me valuable insight about cosmology, physics and religion. He was the one
who gave me the real test of writing, and thinking big in interdisplineary way. I also want
to thank Shaunak for her suggestions while giving final touch to manuscript, getting
feedback from her was unbelievable for me because she provide all this in the age of 10
only. I also want to thank my brother and best friend Sumukh for standing always with
me, unaffected to the situation he always tries to bring smile on my face by any cost.
I want to give special thanks to my mamajee Dr. Bhuthi Narayan Singh for his sober
communication.
While writing this book, I lead almost a hermit life, totally out of touch of the
society and so called friends and relatives, no access to refrigerator, even restricted
access to TV. My mother, sisters, brother and musa called me at times for making sure
that I am leaving a normal life, some times my frustration come in words, I told them what
I am not supposed to tell, I really feel sorry for all those moments. I love and enjoy eating
fast food and having a can of coke with that,but due to health reasons, I make it sure that
I always away from all types of junck foods during last seven months. I lived almost alone
while writing this book by lot of reasons. I was very productive during those period, I
planned for six book and a trilogy on computers, completed four of them ( almost 2500
pages, apart form the time involved in research). I need healthy diet during the times for
getting extra energy to fulfill my commitment to my self, I thank Raju for preparing food
for me without oil and spice, also for taking care of my minute details. I want to thanks Dr.
S.N.Tewari, HOD of my time from department of Physics, Bihar University, Muzaffarpur
who make me realize about nuts and bolts of physics, especially new physics.I want to
give special thanks to my musa Sri. Nagaswar Pd. Sharma for his emotional support.
I want to give special thanks to Dr. Prasana for all of his empathy and
cooperation towards me, he actually goes beyond from the role of doctor for supporting
me. I am also thankful to the Dr.sandeep, Dr. Ready, Dr. Deeraj and the support staff of
hospitals where I was treated.Finally my thanks goes to Golu for his encouraging words
on telephone while writing the book.

Patanjali Kashyap
Muzaffarpur, Bihar
Mothers Day, 10-05-2009

viii

Preface
C is a flexible, powerful programming language with hundreds of thousands of
applications. However, the knowledge of how to take advantage of its full potential comes
only with time and experience. Thats where this book comes in. Think of it as a
cookbook for solving your programming problems, much as The Joy of Cooking is a
guide to solving your dinner dilemmas. Data structure using c is a book for the beginningto-advanced C programmer who needs immediate answers to the problems that crop up
in the professional software-development world. I assume that you have prior
programming experience, as well as experience specifically with the C programming
language. Fluff like discussions of looping structures or defining variables, or the
basics of compiling applications is kept to a minimum here. Instead, I offer quick, stepby-step instructions for solving specific problems in C.
Each technique includes example code which you are welcome to use in your own
applications, or modify as you see fit. This is literally a case of steal this code, please. C
is a language that lends itself well to component-based design and implementation. This
means that you can take a piece from here and a piece from there to implement the
solution that you have in mind.Data Structure using C is not an operating-system specific
(or even compiler-specific) book. The techniques and code that you find here should work
on all compilers that support the standard C language, and on all operating systems for
which a standard compiler exists. This book is intended to be as useful to the UNIX
programmer as to the Microsoft Windows programmer and just as useful for
programming with X-windows as it is for .Net.
I included some utility and general purpose chapters in this book which will be beneficial
for the user of the book , these chapters covers minute details and important aspect of
professional and academic life , topic like How to become highly paid professional ,
Learning Maps and Memory techniques solves difficulties of real life. Chapter on
Interview C interview question ( General and Technical) gives a glimpse of the
important interview questions asked in the interviews , my personal experience says , if
you prepared with sample question before going to face interview it will gives you
confidence.One chepter on software process and on debugging techniques are also
included.
My goal in writing this book is to empower you with some of the stronger features of C
and using them in data structure, as well as some great tips and methods to solve
everyday problems, without the headaches and lost time that go with trying to figure out
how to use those tools. C provides simple, fast, powerful solutions to meet the demands
of day-to-day programming my goal is to save you time while making the tools clear and
easy to use and finding solutions as a when required.

Patanjali Kashyap
Muzaffarpur, Bihar
Mothers Day, 10-05-2009

ix
A Note on Creative Thinking and their practical use
Writing good computer programme and developing efficient algorithms are all about
creative thinking, so just before stating our journey to Data Structures, I try to present
some rules and tips for developing Creative Thinking. These rules are totally based
on my personal experience and research. I provide a formula for achieving greater
creativity for managing your time and apply that to solve your problems.
Here We Go >>>>>>>>> BIRBAL >>>> Says
B: Begin by short-listing the problem you want to solve, out of many that may confronting
you.
I: Investigate the cause, circumstances and all available facts, listing these out on a sheet
of paper. These are the various components of your problem.
R: Relate these components of your problems to the available resources, it may be in the
form of books, case studies, previous experience.
B: Balance and weigh the various options available to you. Here are some optiongenerators you can use to come up with possible solutions:
1. Can you make one of the components of your problem bigger than others? What
does the problem look like now?
2. Can you make another component smaller and check the result?
3. Can you combine two or more of them into a single component? Will that change
the nature of your problem?
Just list out the possible solutions, however outlandish they may appear first. Dont be
critical at this stage. Look for unexpected angles.When you have done this, list the
solutions you think are most likely to succeed. If necessary, modify them to suit your
needs. Select the solution that appear most appealing to you. May be you combine two of
your activities to reduce expenditure of time.Do your planning or some other work in the
train or bus on your way to work. Instead of allocating an hour to jogging, walk bristly at
least part of the way to office. What would happen if dropped some of your activities or
delegated them to someone else in thee family or workplace?
A: Apply the solution to your problem and check the results Does it have any
unfavorable side effects? Until you apply it, you will not know. (Perhaps some activity is
not being accomplished adequately. You may have to either delegate it to someone else
or drop some other activity.
L: Link the other short-listed solutions as well to your problem. Do any of them fit it better
than the one you selected first? Usually the first solution is not the best solution. Select
your final solution. Perhaps you did end up saving a lot of time . That doesnt mean you
cant save even more time. Try other options at different times till you feel you can no
longer improve the outcome.
Above exercise should enable you to refine and fine tune the best solution. This process
makes you more creative and intelligent problem solver.

CONTENTS
About The Author
Acknowledgement
Preface
A Note on Creative Thinking and their practical use

1.

2.

vi
vii
viii
ix

Software Processes and Programming paradigms


1.1
Introduction
1.1.1 Functional decomposition
1.1.2 Programming paradigms
1.1.2.1 Gear-Oriented Programming
1.1.2.2 Switch-Oriented Programming
1.1.2.3 Procedure-Oriented Programming
1.1.2.4 Object-Oriented Programming
1.1.2.5 Aspect-Oriented Programming
1.1.2.6 Component-Oriented Programming
1.2
Software engineering and development : A tight bond
1.2.1 Characteristics of software development strategies
1.3
The waterfall model
1.4
V-shape development model
1.4a Incremental and Iterative models
1.5
Risk reduction models
1.6
The prototyping model
1.7
The spiral model
1.8
The Cleanroom model
1.9
Capability maturity mdoel (CMM)
1.10 Extreme Programming (XP)
1.11 Software project life cycle for XP

01
01
03
03
03
03
03
04
04
04
06
06
07
08
08
09
09
10
11
12
12

Debugging strategies and tactics


2.1
Introduction
2.2
Evaluation Mechanism
2.3
Binary search strategy
2.3.1 Binary search assumptions
2.3.2 Binary search control structure
2.4
Greedy search strategy
2.4.1 Greedy search assumptions
2.4.2 Greedy search control structure
2.5
Breadth-first search strategy
2.5.1 Breadth-first search assumptions
2.5.2 Breadth-first search control structure
2.6
Depth-first search strategy
2.6.1 Depth-first search assumptions
2.6.1 Depth-first search control structure
2.7
Program slice strategy
2.7.1 Program slice assumptions
2.7.2 Program slice control structure

13
13
13
13
14
14
14
14
15
15
15
16
16
17
17
17
18

xi
2.8

Deductive-analysis strategy
2.8.1 Deductive-analysis assumptions
2.8.2 Deductive-analysis control structure
Inductive-analysis strategy
2.9.1 Inductive-analysis assumptions
2.9.2 Inductive-analysis control structure
Choosing a strategy
Debugging Tactics
2.11a Introduction
2.11.1 Read the source code
2.11.2 Write a unit test
2.11.3 Display variable values
2.11.4 Display execution messages
2.11.5 Questions answered
2.11.6 Display procedure arguments
2.11.7 Generate a flow trace
2.11.8 Generate a variables snapshot
2.11.9 Generate memory dump
2.11.10 Choosing tactics
2.11.11 Force variable value
2.11.12 Check data structures
2.11.13 Display data structures
2.11.14 Execute on a different platform
2.11.15 Use runtime subscipt checking
2.11.16 Use runtime stack checking
2.11.17 Use runtime heap checking
2.11.18 Initialize local variables
2.11.19 Change storage class
2.11.20 Use a different compiler
2.11.21 Compile to assembly code
Important points

18
18
18
19
19
19
19
21
22
22
24
24
26
27
28
30
31
32
33
33
33
34
36
36
36
36
36
36
36
36
36

Basics of C programming language


3.1
The built-in data types in C
3.2
Various data types in C
3.3
The Control Statement (if statement)
3.4
The iteration loop (for Loop)
3.5
The do.... while loop
3.6
The switch statement
3.7
Preprocessor
3.8
Function
3.9
Address
3.9.1 Accessing a value through a pointer
3.9.2 Using pointer
3.9.3 Testing for NULL pointer
3.9.4 Pointers to Constants
3.9.5 Constant Pointers
3.10 Parameter Passing
3.10.1 Introduction
3.10.2 Call by reference

37
38
39
40
41
42
44
45
46
49
51
54
54
55
56
56
56

2.9

2.10
2.11

2.12
3.

xii

3.11
3.12

3.13

4.

5.

3.10.3 The concept of Global variables


3.10.4 Calling functions
Recursion
3.11.1 Writing a recursive function
Arrays
3.12.1 Address of each element in an array
3.12.2 Arrays and Pointers
3.12.3 Accessing an array using pointers
3.12.4 Manipulating arrays using pointers
3.12.5 Two-dimentional array
3.12.5 Three-dimentional array
3.12.6 Pointer array
Dynamic memory allocations
3.13.1 Using memory
3.13.2 Dynamic memory allocation : the malloc() function
3.13.3 Memory allocation with the calloc() function
3.13.4 Releasing dynamically allocated memory
3.13.5 Reallocating memory

58
59
60
61
63
64
65
67
68
70
71
73
74
75
75
76
77
78

Storage of variables
4.1
Storage
4.2
External references
4.3
Register variables
4.4
Scope of variables
4.5
Further scope of variables

80
81
82
83
84

Performance analysis and design of algorithm


5.1
Intoduction
5.2
Some important point about algorithm
5.3
Standard ways of manipulation
5.3.1 Manipulation, the amerian way
5.4
Definition of algorithm
5.5
Definition of design
5.6
Model of computation
5.7
Algorithm's performance
5.8
Notations
5.8.1 -Notation (Same order)
5.8.2 O-Notation (Upper bound)
5.8.3 -Notation (Lower bound)
5.9
Algorithm analysis
5.10 Worst-case complexity
5.11 Average-case complexity
5.12 Optimality
5.13 Reduction
5.14 Algorithm performance analysis
5.15 Most algorithms fall into one of the following types
5.16 Important points
5.16.1 O-Notation
5.16.2 -Notation

85
86
87
87
88
88
88
88
88
88
89
89
90
90
90
90
91
91
92
92
92
93

xiii

5.17
5.18
6.

7.

8.

5.16.3 -Notation
5.16.4 O-Notation (example)
5.16.5 -Notation
Time complexity of an algorithm
Time complexity of a problem

93
93
93
94
94

Arrays, Searching, and Sorting


6.1
Arrays
6.2
Memory representation
6.3
Representation of Two-dimensional Array
6.4
Application of arrays
6.4.1 Implementation of a static contiguous list
6.4.2 Manipulations of the list implemented using an array
6.4.3 Alternative method
6.4.4 Inverse of the list
6.4.5 Merging of two sorted lists
6.4.6 Transpose of a matrix
6.4.7 Alternative version of the program
6.5
Implementation of the heaps
6.6
Sorting and Searching
6.7
Quick sort
6.7.1 Choice of the key
6.8
Merge sort
6.9
Heap sort
6.10 Searching techniques : linear or sequential search
6.10.1 Binary search
6.11 Hashing
6.11.1 Hashing functions

95
95
96
97
97
99
101
103
106
109
112
114
114
117
117
122
126
129
132
134
138

Stacks and Queues


7.1
Stacks
7.1.1 Array implementation of a stack
7.1.2 Implementation of a stack using linked representation
7.2
Applications of stacks
7.3
Queues
7.3.1 Implementation of queues
7.3.2 Array implementation of a queues
7.4
Circular queues
7.4.1 Implementation of a queue using linked representation
7.5
Applications of queues

143
143
146
149
154
154
155
158
161
165

Linked Lists
8.1
Linked list
8.2
Inserting a node by using recursive programs
8.3
Sorting and reversing a linked list
8.4
Deleting the specified node in a singly linked list
8.5
Inserting a node after the specified node in a singly linked list
8.6
Counting the number of nodes of a linked list
8.7
Counting the number of nodes of a linked list

170
173
175
180
184
191
193

xiv
8.8
8.9
8.10
8.11
8.12
8.13
8.14
8.15
8.16
8.17
8.18
9.

10.

11.

Merging of two sorted lists


Erasing a linked list
Polynomial representation
Circular linked lists
Splitting a list with 2n nodes into two separate and equal lists
Merging of two circular lists
Reversing the direction of links in a singly linked circular list
Doubly linked lists
Insertion of a node in a doubly linked list
Deleting a node from a doubly linked list
Application of doubly linked lists to memory management

Trees
9.1
Introduction
9.1.1 Definition of a tree
9.1.2 Degree of node of a tree
9.1.3 Degree of a tree
9.1.4 Level of a node
9.2
Binary tree and its representation
9.3
Graphical representation of a binary tree
9.3.1 Representation of a binary tree
9.4
Binary tree traversal
9.5
Binary search tree
9.6
Constructing a binary tree using the preorder and inorder
traversals
9.7
Counting the number of nodes in a binary search tree
9.8
Swapping of left and right subtrees of a given binary tree
9.9
Searching for a target key in a binary search tree
9.10 Deletion of a node rom binary search tree
9.11 Applications of binary search trees
9.12 General comments on binary trees
Graphs
10.1
Basic definitions and terminology
10.2
Representations of a graph
10.3
Link list representation
10.4
Computing indegree and outdegree of a node of a graph using
adjacency matric representation
10.5
Depth-first traversal
10.6
Breadth-first traversal
10.7
Connected component of a graph
10.8
Depth-first spanning tree and breadth-first spanning tree
10.8.1 MST property
10.9
Prim's Algorithm
10.10 Directed acyclic graph (DAG)
10.10.1 Topological sort of directed graph
C Interview questions (General and Technical)
11.1
Introduction
11.2
General questions

195
200
203
208
211
214
217
221
225
228
231

234
234
235
235
235
235
236
237
240
243
248
249
251
254
258
266
267

275
278
279
280
283
285
289
295
299
299
303
304

312
312

xv
11.3
11.4
12.

13.

14.

Conventional questions
Technical questions on C programming language

How to become highly paid professional


12.1
Introduction
12.2
Establish an intelligent routine
12.2.1 Prioritize your projects
12.2.2 Critique your performance everyday
12.2.3 Check in with every member of your team or group
everyday
12.2.4 Keep your project paper work in order and upto date
and
your office sportless
12.2.5 Ask to work and major corporate businesses
12.2.6 Reach for the business function that makes you most
valuable
12.2.7 Note that good things come in big packages
12.3
Packages worth working on (best first)
12.4
What your boss really wants from you
12.4.1 Fair warning about problems
12.4.2 Confidence
12.4.3 Positive feedback about you
12.4.4 Accuracy
12.4.5 Putting your work ahead of your ego
12.4.6 The prudent "I don't know"
12.4.7 Respect
Learning map and remembering techniques
13.1
What is learning map
13.1.1 Getting started
13.2
Too much and no system
13.3
Keywords
13.3.1 In a nutshell
13.3.2 The right word
13.4
The human brain
13.4.1 Learning maps
13.5
The use of keywords
13.6
On a memory hunt
13.7
The natural way
13.8
Your own writing and speech
13.9
Rules
13.10 Learning maps applications
13.10.1 Study planning
13.10.2 Personal planning
13.10.3 Meetings
13.10.4 Budgets
Company etiquette
14.1
Let's star with the some typical characteristics of successful
people
14.2
Etiquette in writing

313
317

333
333
333
333
334
334
334
334
335
336
336
337
337
338
338
338
338
338

340
342
344
344
344
345
346
347
349
350
350
352
353
353
355
355
355

357
357

xvi
14.3

Cross cultural differences - writing skills


14.3.1 Be concise
14.3.2 Phrases to avoid
14.3.3 Local words to be avoided in all our communication
14.3.4 Americal v/s english spelling
14.4
Tips on Telephone Etiquette
Appendix - 1 Self evaluation sheet (sample)
Appendix - 2 The elements of C and C++ coding style
Appendix - 3 Software testing concepts
A3.1
Introduction
A3.2
Role of software testing
A3.3
Software testing concepts
A3.4
Software testing types
A3.5
Software testig test cases
A3.6
Software quality assurance (SQA) & testing
A3.7
Software testing softwares
Appendix - 4 How to make professional resume and cover letter
A4.1
Introduction
A4.2
Structure of the resume
A4.2.1 Overall format
A4.2.2 Your profile
A4.2.3 Achievements, Education & Qualifications
A4.2.4 IT and other skills
A4.2.5 Personal details and hobbies
A4.2.6 The language you use
A4.2.7 Double check it
A4.3
Cover letter
Appendix - 5 Intellectual work of author published in journals /
abstract / books / Magazines
References & Bibliography
Index

358
358
358
358
359
359
361
365
370
370
370
371
372
374
375
376
378
378
378
379
379
380
380
380
380
381
382
389
390

You might also like