Dsu CH-1
Dsu CH-1
Introduction to
Data Str.u ctures .l\
11.0 I INTRODUCTION
• The data plays an important role in computer, as all.operations ar~ carried out on data. The data is
just a value or a collection of values (data is raw, unorganized facts that need to be processed
however after processing, it becomes information).
• To perform any operation on data, it should be first available in· main memory so that processor can
perform operations on data.
• In order to represent data in main memory some model is needed so that the data can be processes
efficiently. This model is called. as data structure.
• A data structure· is a programmatic and systematic way of storing and organizing data (how data is
organized, how it can be manipulated and how it can be utilized) in a computer system so that it can
be accessed and processed efficiently. .
• The C programming language includes data structures like an array~ stack, queue, linked list, tree,
graph etc. , J. ,
• In today's competitive
and challenging world,
organizations and keeping data is one of the mos
this data organized and t powerful tools availab
• As computer applicatio easily accessi le to
ns are becoming more co ble is become very impo
rtant.
day, which may cause pr m plex an d the amount of data is
oblems with processing increasing day by
etc . speed, searching data, ha
ndling multiple requests
• Data structur e provide
s a way of organizing, m
plays an im portant role anaging, and storing da
in enhancing the perform ta efficiently. Data structu:
function of th e program is ance of a program/appl e
to store and retrieve the ication because the mam
• Following ar e the point user's data as fast as possi
s which specify the need ble .
l. Ease of Retrieval: of organization of data:
With help of data struc
program can easily access ture data can be stored
it. in such a manner that th
2· Operati e
ons Allowed: Various
operations (insertion, de
can be performed easily as letion , traversing, searc
3· Increa da ta is well organized and ac hing, sorting etc.)
ses Efficiency of Algo cessible with help of data
rithms: Effective use structure.
efficiency of algorithms to of principles of data str
4· Su solve problems like search uc tures increases
itable Representation: ing, sorting and so on.
,,__ _it....represents the va W ith help of data
rious components of the structures data can be stored in such a manner th
problem . ' at
1.1.3 Definition of Data Stru
cture
• A dat~ structure
effectively created,isacacetec hnique to syste
ssed and managed.matically store data so that the data can be
easily and
Data Structure Using c Introduction to D1t• Structure,
1.3
• Data s~ructure is a way of collecting 11nd orgnnlzlng rlllla In such o way that we can perform
operations on these data In an effective and efficient way.
• The logical or mathematlcol model of a particular organization of data In main memory I~ called as
data structure.
• The term data structure is defined as, "the study of how data Is org:rnlzed In the computer's memory
and how it maintains logical relationship between individual elements/item s (a single unit of value-;
like RolLNo, Name, Address etc.) of data and also how efficiently the data can be retrieved and
manipulated ." OR AData Structure (DS) Is defined as, a set of domains D. a designed domain e D, a set
of functions F and a set of axioms A. The Triple (D, F, A) denotes the data structure where,
1. Domain (D): Denotes the data objects (represents an object having a data).
2. Function (F): Denotes the set of operations that can be carried out on the data objects.
3. Axioms (A): Denotes the properties and rules of the operations.
• Above definition is also called as Abstract Data Type (ADT). Implementation details of an ADT are
hidden, that's why it is called abstract.
• A data structure is a systematic way of storing and managing data in a computer so that it can be
retrieved and used efficiently.
Advantages of Data Structures:
1. Data structures improved data organization and storage efficiency.
2. Data structures provides faster data retrieval and manipulation.
3. Data structures facilitates the design of algorithms for solving complex problems.
4. Using the right data structure technique, one can manipulate huge amounts of data easily.
5. Data structures can reduce the amount of time a computer user/programmer spends storing,
retrieving, and processing data.
6. A data structure helps us to analyze the data, store it and organize in a logical manner.
Disadvantages of Data Structures:
l. The data structures increased computational and memory overhead.
2. Difficulty in designing and implementing complex data structures.
3. The data structures have limited scalability and flexibility.
4. Difficulty in modifying/updating existing data structures.
I 1.1.4 I Abstract Data Type [S-22, W-22, S-24)
• Each programming language provides a set of built-in data types like char, int, float and so on. But
sometimes situation occurs that built-in data types are not enough to handle the complex data.
• So, its programmer's responsibility to create their own data type (user-defined data types) where
he/she will define everything about data type such as how data values are stored, possible operations
that can be carried out with on that data. Such custom data types are called Abstract Data Type (ADT).
• The ADT is special kind of datatype, whose behavior is defined by a set of values and set of
operations.
• The keyword "abstract" is used as we can use these data types, we can perform different operations.
But how those operations are working that is totally hidden from the user.
• The ADT is made of with primitive data types, but operation logics are hidden. An ADT is defined as, a
collection of values/objects (data types) and a set of operations on those values/objects, that is
accessed only through an interface (defines its supported operations).
Dn t• Structure U,l ni, £_- - - - --~------ 1 .4 '
~------
- lntrnctu,tton 10
f'l show s un AI H wh lrh l'o · • .. _ 0 ~•~Str!lctu,..
• g. .
d;i lil
12
t C llll d 01wr •1tlon s
struc ur •
n s lst s of'
··
On ly 1111•
1111 11hstr1H:t'
«>tll'l'lltluns lll' l'
Ah11tr111:t Duin Typ,, (All
I')
-~- ......
,
v1ewa 11~
J e
•f)•,..111 tlH' 0111 sl,lc cmd cl1
11
, tlu• l11t,•rf11 cl' .
•fi1 ll'
• •r·
An obs, ~i i.:•t cl •·••''•1 1y1w• Is II ln~ lrn l tic- scr ipt 1011
• of how Abl'ltrn, .t Duin Stru,:tur•
we view the dn ta nn d tht
' 11111'rntlnn
s tha t 11rt .i 111low1•1I
without reg:ird ho w th1•y will he lmplt'nH
10
'11tt•1I. Punntlon!l/Op11rntlona
• This mc nn s 111 :-11 we nr<'
conct.•rnPd only with whnt lntorfnce
dJ ta ts rcpn• st'ntln~ nncl the
not' with how It will
eventu all y b e constru ctt.·d .
l'lg. 1.2: l'lctorlnl ll<1prc
ex am ple of AD T in 'C' t1cntatlon of Ao·r
l.nngua~c:
• In 'C', we defin e da
ta type na me d 1'11.1:, wh
opera tio ns on fil e such ns, ich ts an obstruct mode
fopcn() to op en o fil e, fcl l of a file. We can perf
fil e, fp ut cO to wr ite a chara<.: , os d) to close file, fgctc()
tcr to 11
1 c f I 1e. to rend character r°rrn
• De fi nition of nu: Is in rorn
stdio.h, the file in pu t-o ut pu
the file as a str eam of bytes t ro ut in es In 'C' ~untlme lib ra ry en
an d to pe rfo rm va rio us op able us to view
routines. So , flL C de finition erlltlons on this str ea m by
togel'her with functions op calling input-output
• We do not kn ow 'C' str uc crn tcs on It becomes o ne
tur e internally, in ste ad we w da ta type.
inn er detai ls of f'ILC. This rely on functions an d ma
is called hiding. cro s that essentially hide
Ad va nt ag es of ADT:
1. The ADT is re usab
le an d en su re s ro bu st datu
2. The AD T en su res th at str uc tu re .
the en ca ps ula tio n da ta ca
3. The ADT reduces co nn ot be co rru pt ed .
ding efforts:
I 1. 2 I TYPES OF D A TA STRU
CTURES
• We de fin ed a data str uc tu
1. A se t of data ele me
re as a wa y of or ga niz ing
nt i.e. a da ta object, an d
da ta th at specifies: l
2. A set of op era tio ns
which ar e ap pli ed to this
• AlJ available da ta str uc tu re s ca da ta object.
n be cla ssified in following
1. Pr im iti ve an d Non-pr categories:
im iti ve Da ta St ru ctu re s:
0 JJrj mitiv e data !>lr uc tu res (S- 22, S-23, W -23 1
ar e ba sic da ta str uc tu re
in i-.;tr uctions e.g. lnt cger, ch an d ar e directly op er ate
ar a cter etc . d on machine
0 Non-p rimiti ve da ta !itruc lu
res ar e deriv ed fro m th e
Ji~l ere. pr im iti ve dato str uc tu re s
e.g . array, linked
2. Li ne ar an d Non-l in ea r
Va ta St ru ct ur es :
0 • Lin
ei.lr cfoUJ str uctu res main (S -22 , S- 23, W -23 )
lai n a lin ea r (se qu en tia l)
e.g. urrny. re lat io ns hi p be tw ee n th eir
da ta elements
0 No n-l inear data str uctu
res do no t m ai nt ai n an y
data elem en ts e.g . tre e. re lat io ns hi p (li ke hi er ar ch
y) between their
3. Static and Uy na m ic Da
ta St ru ct ur es :
0 In 1>tut ic da ta str uc tu re s
m em or y is ali oc atc d at th
~tructu re ls colJcction of e tim e of.compilation e.g .
da ta ele m en ts in me mo ry ar ra y. A static datu
du rin g 'r un tim e. wh ich ls fix ed in siz e an d ca nn ot changed
o Jn uy na ml c da ta str ·
uc tu re s m em or y ls all oc
e.g . Jin ke d li st. Jn dy na m ate d at ru nt im e us in g ma
ic da ta str uc tu re s th e siz lloc(), callocO function
t h f! t X(•cut Inn ()f th
e of da ta ele me nt s In me mory vnrtes
e pr og ru rn . du rln~
-
Data Structure Using C
1.5 Introduction to Data Structures
----, 0
In heterogeneous data structures all data elements are of different type. e.g. structure.
1.2.1 Primitive and Non-Primitive Data Structures
• Primitive data structures are the most )Jasic and fundamental types of data provided by C
programming language.
• Primitive data structures store the data of only one type i.e., built-in data types like integer, float,
character etc. ·
• Normally, primitive data structures have differe.nt representation on different computers. Aprimitive
data type defines how the data :will be internally represented in, stored and retrieved from the
memory.
Characteristics of Primitive Data Structures: I .
1. Single Valu~: Primitive data structures are designed to store a single value at a time. For
example, an integer variable holds one integer value.
2. Built-in: They are built into the programming language and readily available for use without the
need for additional definitions or libraries.
3. Fixed Size: Primitive data structures have a fixed size, which is known at compile time. This fixed
.size contributes to their memory efficiency.
4. Efficiency: Due to their si;mplicity and fixed size, primitive data structures are highly efficient in
terms of memory usage and performance.
• Primitive data structures of any programming language are the data types that are predefined in that
programming language. The type and size of those data types are defined already. ·
• Following table shows the primitive data types of Clanguage with their size, range and format string:
Sr.No. Format String
1. char 1 byte -128 to 127 %c
2. unsigned char • 1 byte Oto 255 %c
3. signed char 1 byte - 128 to 127 %c
4. int 2 or 4 bytes - 32,768 to 32,767 %d
5. unsigned int 2 or 4 bytes Oto 65,535 %u
6. short 2 bytes - 32,768 to 32,767 %d
7. unsigned short 2 bytes Oto 65,535 %u
8. long 4 bytes · - 2,147,483,648 to 2,147,483,647 %Id
9. unsigned long 4 bytes Oto 4,294,967,295 %lu
10. float 4 byte -3.4E - 38 to 3.4E + 38 %f
11. double 8 byte 1.7E - 308 to 1. 7E + 308 %lf
12. long double 10 byte 3.4E - 4932 to 1.1E + 4932 %lf
• The non-primitive data structures are derived from the primitive data structures and can store the
data of more than one type i.e. derived data types like arrays, structures etc.
• The non-primitive data structures are highly developed complex data structures. Non-primitive data
structures are derived from the primitive data structures. ·
1.6
, uu~·
D ta Structure__: s1 n!!_! lg~C :_._- --- Introduction to Data Str u~
~ . 'tive Data structures: ~
• · ofNon-Pnmi
characteristics .· 'tive data structures are inherently more
1 complexity: Non-pnm1 complex due to their hill
· Uections of data . a ty to
manage co. l'k primitive data structures with fixed sizes, non-
mic primitive data structu
2. Dyna . sized' : Un i e h h 1 . .
dynamically a ius t their size based on the data t ey o d. This dynamic sizing makes themres can
versatile. tnore
. .
3 User-Defme d·. While primitive data stru ctures are provided by programming language
· . . . d t structures can be user-de f'me d
Pnnuuve aa . d . Programmers have the flexi.bilit.. s, non.
y to create cu
th .
. •u· e data structures tailore to eir speci'fiic
non-prum v . needs. stom
. . Non- prim itive data . .
4. Efficiency. . structur . es may be less memory-efflClent compared to pn""':ti
data structures due_ to their dynamic nature, but they offer greater flexibility in uuu ve
complex data scenarios . managing
• The non-primitive data structures emp~asize
on structuring of a group of homogeneous (sam
or heterogeneous (different types) data items. e type)
• An array is a collection of homogen
eous (variables of similar type) data elements
nam e. under a single
• That means an array can store one type of
data only all integers, all floating-point numbers
characters. All the elements in an array are or all
stored contiguously and stored in linear fashi
memory. on in
For examples:
i nt a[10] ;
// integer array declaration
char b[ 10];
// character array declaration
int ar r1[5] = {10, 20,3 0,40 ,50} ;
// integer array with .ini tial izat ion
double arr2[5] = {100 0.0, 2.0, 3.4, 7.0,
50.0 }; // double array with init iali
• Structure is the collection of heterogeneous (var zati on
iables of different types) data elements under a
nam e. single
• In following example address is a structur
e variable which is collection of different varia
name, street, city, state and pin. bles like
stru ct address
{
char name[30];
char stre et[5 0];
char city [30 ];
char stat e[lS ];
int pin;
};
Difference between Primitive and Non-primiti
ve Data Structures:
Sr. .
No. Primitive Data Structures •,
3. Primitive data structures are basic data Non-primitive data structures are derived
structure ( re-defined b the Ian a e itself). from the rimitive data strucrures.
4. The size of the primitive data structures is The size of the non-primitive data structure is
fixed and predefined by the language. dynamic and can vary (not fixed) during
runtime.
5. Primitive data structures are more efficient in Non-primitive data structures are less efficient
terms of memory and performance. efficient in terms of memory and performance
due to additional memo and overhead.
6. Primitive data structure always contains some In the non-primitive data structures the NULL
value i.e. these data structures do not allow to value can stored.
store NULL values.
7. Used . for representing simple values and Used for organising and managing data in
erformin basic o erations. more com lex wa s.
• Data structures are divided into two types, Linear data structures and Non-linear data structures as
shown in Fig. 1.3.
fff? oata structures :}1}§
· Non-linear
•
that an array can store one type of data only all integers, all floating-point
numbers or all characters .
All the elements in an array are stored contiguously. The elements of array are
2
--...
stored in linear fashion in memory as shown in Fig. 1.4.
In simple words, an array is a linear data structure that stores the elements of
•
•
similar data types at a contiguous memory location.
An array is declared by following way in Clanguage,
n
---
Array
Fig. 1.4
int a[10];
. c
Data Structure Using l.S · Introduction t 0
o ata Structii
. d laring the array we must know the upper limit on the number of. element ~
1 s in
• Whihe e;ords we can say that the size of array is fixed. Generally, the allocated memory
In ot er , . . . advance,
the upper limit irrespective of the usage, and m pract1ca 1uses, upper limit is rarely reached.ls equal to
• He1.e, a is the name of array. which can holds. ten data elements of . .integer type only. The elements ,
array always stored from mdex O up to (S1Ze of ar~ay-1) . Ind1v~d ual element of an array can Ill
assessed by specifying name of. array, followed by mdex/subscnpt. Its means that array
random access of data. For example, a[2] will represent the data element stored at inde:xed
be
2. supports
• An array is always read and write through loop. There is requirement of one loop
to re d
!-dimensional array and another loop for writing the 1-dimenstional array as shown below:
a one
Reading 1-dimensiorial Array 1n C. . ··, Writing 1-dimen·sional Array in c _._
for(i=0;i<=9;i++) for(i=0;i<=9;i++)
{ {
scanf("%d",&a[i]); printf( "%d",a [i]);
} }
• Whereas, to read and write 2-dimensional array there is need of nested loop to represen
t indiViduaI
row and column as shown below:
.
Reading 2~di#ieii~l8~~l'~tl\'St,,. :':,'.l{ti~g~;~~;;,~n~iArray
inc
for(i=0;i<=9;i++) for(i=0;i<=9;i++)
{ {
for(j=0;j<=9;j++) for(j=0;j<=9;j++)
{ {
scanf("%d",&a[i][j]); printf( "%d",a [i][j]);
} }
} }
(ii) List/Linked List:
• Linked list is alternative approach of arrays. A linked list is a linear data structure in
which, data can
be placed anywhere in memory and these data ate linked with each other using pointer
field. This
pointer field stores the address of next element in the list.
• In other words, linked list is collection of
nodes where each node consists of two HEAD/START
parts i.e. data and pointer to next node.
• The first node in linked list is called NULL
data element in list and the last node Fig. 1.5: Linked List
contains null pointer :is shewn in Fig. 1.5.
(iii) Stack:
• Astack is a · :,ear data tructure in which all the insertion and deletion
mil PUSH t POP
L....;-4+ --TOP
are perfo·. 1ed at one .1d which is known as TOP of the stack.
• The im ·tion op,:,r don ·in stack is known .as PUSH and deletion
operat~ . in stac' .; known as POP as shown in Fig. 1.6.
L'
1
• Stack ' 1lows Lll . (Last In First Out) principle (means the last element
:~:.,; n actac! ,ill beremoved first). The real-Ii!e examples of stacks
pl, es ,n ,.ay and stack of coins etc Fig. 1.6: Stack
Data Structure Using C 1.9 Introduction to Data Structures
(iv) Queue:
• A ~eue is a linear data structure in which insertion and deletion are
Rear
performed at rear and front respectively as shown in Fig. 1. 7. Front
• Queue follows FIFO (First In First Out) principle (means the first ! i·
•
element stored in a queue will be removed first).
The real-life examples of queues are People waiting in the Bus stop for -U 1 I11-
ticket. . . Fig. 1.7: Queue
• The operations that can be performed on a ·queue are Insertion (add an
el ement in the front end of a queue) and Deletion (Deleting an element
fr om the rear end of a queue).
2. Non-Linear Data Structures: '4f}#ffj1
• In non-linear data structures, data elements are not organized in a sequential fashion means the data
elements are randomly arranged. .
• Each element in non-linear data structure is not constrained to have a unique predecessor and ~
unique successor. · ·
• Tree and Graph are the two non-linear data- structures are explained below:
(i) Tree: lmlJI
• Tree maintains a hierarchical structure on collection of data items/elements.
• A tree is collection of one or more nodes such that there is a specially node called root and remaining
nodes can be partitioned into n (n>=0) disjoint subsets. Each disjoint set is a tree as shown in Fig. 1.8.
(ii) Graph: · · · lmlJI
• Graph is collection of vertices (nodes) and edges (arcs) where each edge in it is specified by a pair of _
. . vertices.
The graph can be directed graph or undirected ~raph as shown i~ Fig. 1.9.
[ 1 _3 f OPERATIONS ON DATA
STRUCTURES . . cs·-2 3, w-2 3. s.
The data plays an nnp • orta nt role in pro gra mm ing, as all 241
• perform any ope1·at1·0 11 on dat a it ope
. rati.ons are ear ned out on data· To
~ • sho uld be first ava ilab le m ma m mem ory so
perform operation on data. tha t processor can
.
• ,re ma k e a,·a1·1able thi·s dat a in mai n mem ory wit .
h hel p of dat a stru ctu
. re. As now dat
data struc CUre, no'
• ,, one can per form sev era l ope rati ons on it as sho . a 1s stored in
• The operations associat ed wit h a wn m Fig. 1.10 .
given dat a stru ctu re dep end on how
represented in mem ory and how the . the dat a structure is
y are bei ng manip_ulated by ~ par
defining a data sn-ucture, ,,ve also nee d ticu lar language. While
to def ine the se asso ciat ed operat10ns .
• Creation ..,.
, ;~ · . Des troy ·
. ns,:
Operations on) '
data structurei ~
f'
,,, Traversal
Fig. 1.10: Ope rati ons on Dat a Stru
ctur
es
• The following ope rati ons are mo st freq
uen tly per for me d on any dat a stru ctu
1. Pri mit ive Dat a Str uct ure Op era re:
tion s:
(i) Creation: To cre ate a new dat a stru ctu
re, gen era lly one wri tes an ope rati on
"cre ate". The who le pur pos e of this ope and nam ed it as
tim e for dat a . rati on is to allo cate me mo ry at com pile tim e or run
(ii) Des tro y: To dele te dat a stru ctu re or
to des troy a dat a stru ctu re, gen era lly
ope rati on and nam ed it as "de stro y". one wri tes an
The who le pur pos e of this ope rati on
me mo ry whi ch is alre ady allo cate d wit is to deallocate
h hel p of malloc() or calloc() fun ctio n.
(iii) Sel ecti on: As per app lica
tion or req uire men t, one wa nts to wo
rk on som e specific dat a and
oth er wan ts to wo rk on ent ire dat a
ava ilab le in dat a stru ctu re. So it is
ope rati on of selection as per req uire nec ess ary to write
me nt of ind ivid uals. Selection is use
to access the dat a wit hin dat a stru d by pro gra mm ers
ctu res.
(iv) Update: This ope rati on is use d
to edi t or cha nge the dat a wit hin the
ope rati on upd ates or alte rs or cha nge dat a stru ctu re. This
l
s the dat a .
Data Struct"re Using C
1.11 Introduction to Data Structures
2. Non-Primiti ve Data Structure Operations:
Ci) Insertion: Insert operation on any data structure is performed to insert/add one or more
data element in the existing/alre ady created data structure at a particular position.
(ii) Deletion: Delete operation on any data structure is performed to delete/remov e one or
more data element from the existing/already created data structure at a particular position.
Deletion should be performed in such a way that remaining elements should not be in
inconsistent state.
Traversing: Traverse operation is generally performed to access each and every element of
(iii)
data structure exactly one's. Most of the time, in programs display O/show () operation is
used by programmer to display each and every element of data structure which implicitly
traverse each data element of data structure.
(iv) Searching: Search operation is performed on any data structure to find out the location of
particular data element in data structure.
(v) Sorting: Sort operation is performed on any data structure to arrange all the data ·of data
srructure in a specific order either ascending or descending order.
(vi) Merging: Merge operation is performed to combine two data structure into a single one.
• In addition to primitive and non-primitiv e data structure operations, two extra operations are:
1. Copying: Copy operation performed for copying the contents of one data structure to another.
2. Concatenati on: This operation performed for combining the data from two or more data
structure.
Practice Question s
l. What is data structure?
2. List types of data structures in C language.
3. List operations on data structures.
4. What is linear data structure? Explain two of them.
5. Define non-linear data structure. List them.
6. Compare linear and non-linear data structures, (any four points).
7. What is ADT? What are the advantages of ADT?
8. Define data structure.
9. List objectives of data structures.
10. List any four operations performed on data structures.
11. State the need of data structure. Explain in detail.
MSBTE Question s with Answers
I Summer 2022 I
1. Define linear data structure and non-linear data structure. [1111)
Ans. Refer to Section 1.2.
2. Define Abstract Data Type. [1111)
Ans. Refer to Section 1.1.4.
I Winter 2022 I
1. Define abstract data type. la1I]
Ans. Refer to Section 1.1.4.
2. Differentiate between linear and non-linear data structure, (any four points). 11111)
~ s. Refer to Section 1.2.2.
Data Stn, ctur e Uslnp C
1.12
I Su mm er 202 3 J
--
Introduction to D•ta ltr
Wr
ine
ite
the terms: Lin ear dat a stru ctu re and
Refer to Section 1.2.
any fou r ope rati ons tha t can
non -lin ear dat a stru ctu re.