0% found this document useful (0 votes)
7 views

Introduction DS and Structures

The document provides an overview of data structures, defining them as ways to organize data items and their relationships, and categorizing them into primitive and non-primitive types. It discusses various data structures such as arrays, lists, stacks, queues, trees, and graphs, along with their operations and implementations. Additionally, it covers storage classes in C, including automatic, external, static, and register variables, explaining their scope and longevity within a program.

Uploaded by

tempoabhi1234
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Introduction DS and Structures

The document provides an overview of data structures, defining them as ways to organize data items and their relationships, and categorizing them into primitive and non-primitive types. It discusses various data structures such as arrays, lists, stacks, queues, trees, and graphs, along with their operations and implementations. Additionally, it covers storage classes in C, including automatic, external, static, and register variables, explaining their scope and longevity within a program.

Uploaded by

tempoabhi1234
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

Introduction

to
Data Structures
Definition

 Data structure is representation of the logical


relationship existing between individual
elements of data.
 In other words, a data structure is a way of
organizing all data items that considers not
only the elements stored but also their
relationship to each other.
Introduction
 Data structure affects the design of both structural &
functional aspects of a program.
Program=algorithm + Data Structure
 an algorithm is a step by step procedure to solve a particular
function.
 algorithm is a set of instruction written to carry out certain
tasks & the data structure is the way of organizing the data
with their logical relationship retained.
 To develop a program of an algorithm, we should select an
appropriate data structure for that algorithm.
 Therefore algorithm and its associated data structures form a
program.
Classification of Data Structure
 Data structure are normally divided into two broad
categories:
• Primitive Data Structure
• Non-Primitive Data Structure
 A primitive data structure is generally a basic structure
that is usually built into the language, such as an
integer, a float.
 A non-primitive data structure is built out of primitive
data structures linked together in meaningful ways,
such as a or a linked-list, binary search tree, AVL Tree,
graph etc.
Classification of Data Structure

Data structure

Primitive DS Non-Primitive DS

Integer Float Character Pointer


Classification of Data Structure

Non-Primitive DS

Linear List Non-Linear List

Array Queue Graph Trees

Link List Stack


Primitive Data Structure

 They are basic structures and directly operated


upon by the machine instructions.
 In general, there are different representation on
different computers.
 Integer, Floating-point number, Character
constants, string constants, pointers etc, fall in
this category.
Non-Primitive Data Structure

 These are more sophisticated data structures.


 These are derived from the primitive data structures.
 The non-primitive data structures emphasize on
structuring of a group of homogeneous (same type)
or heterogeneous (different type) data items.
 Lists, Stack, Queue, Tree, Graph are example of non-
primitive data structures.
 The design of an efficient data structure must take
operations to be performed on the data structure.
Non-Primitive Data Structure

 The most commonly used operation on data


structure are broadly categorized into
following types:
• Create
• Selection
• Updating
• Searching
• Sorting
• Merging
• Destroy or Delete
Description of various
Data Structures : Arrays
 An array is defined as a set of finite number of
homogeneous elements or same data items.
 It means an array can contain one type of data
only, either all integer, all float-point number
or all character.
Lists
 A lists (Linear linked list) can be defined as a
collection of variable number of data items.
 Lists are the most commonly used non-
primitive data structures.
 An element of list must contain at least two
fields, one for storing data or information and
other for storing address of next element.
 As you know for storing address we have a
special data structure of list the address must
be pointer type.
Lists
 Technically each such element is referred to as
a node, therefore a list can be defined as a
collection of nodes as show bellow:

[Linear Liked List]

Head
AAA BBB CCC
Information field Pointer field
Lists

 Types of linked lists:


• Single linked list
• Doubly linked list
• Single circular linked list
• Doubly circular linked list
Stack

 A stack is also an ordered collection of


elements like arrays, but it has a special
feature that deletion and insertion of elements
can be done only from one end called the top
of the stack (TOP)
 Due to this property it is also called as last in
first out type of data structure (LIFO).
Stack

 It could be through of just like a stack of plates


placed on table in a party, a guest always takes
off a fresh plate from the top and the new plates
are placed on to the stack at the top.
 It is a non-primitive data structure.
 When an element is inserted into a stack or
removed from the stack, its base remains fixed
where the top of stack changes.
Stack

 Insertion of element into stack is called PUSH


and deletion of element from stack is called
POP.
 The bellow show figure how the operations
take place on a stack:

PUSH POP

[STACK]
Stack

 The stack can be implemented into two ways:


• Using arrays (Static implementation)
• Using pointer (Dynamic implementation)
Queue

 Queue are first in first out type of data


structure (i.e. FIFO)
 In a queue new elements are added to the
queue from one end called REAR end and
the element are always removed from other
end called the FRONT end.
 The people standing in a railway reservation
row are an example of queue.
Queue

 Each new person comes and stands at the


end of the row and person getting their
reservation confirmed get out of the row
from the front end.
 The bellow show figure how the
operations take place on a stack:
10 20 30 40 50

front rear
Queue

 The queue can be implemented into two ways:


• Using arrays (Static implementation)
• Using pointer (Dynamic implementation)
Trees

 A tree can be defined as finite set of data items


(nodes).
 Tree is non-linear type of data structure in
which data items are arranged or stored in a
sorted sequence.
 Tree represent the hierarchical relationship
between various elements.
Trees
 In trees:
 There is a special data item at the top of
hierarchy called the Root of the tree.
 The remaining data items are partitioned into
number of mutually exclusive subset, each of
which is itself, a tree which is called the sub
tree.
 The tree always grows in length towards
bottom in data structures, unlike natural trees
which grows upwards.
Trees

 The tree structure organizes the data into


branches, which related the information.

A root

B C

D E F G
Graph

 Graph is a mathematical non-linear data


structure capable of representing many kind of
physical structures.
 It has found application in Geography,
Chemistry and Engineering sciences.
 Definition: A graph G(V,E) is a set of vertices
V and a set of edges E.
Graph

 An edge connects a pair of vertices and many


have weight such as length, cost and another
measuring instrument for according the graph.
 Vertices on the graph are shown as point or
circles and edges are drawn as arcs or line
segment.
Graph

 Example of graph:
6
v2 v5
v1 v3
10

v1 8 11
15
9 v2
v3 v4 v4

[a] Directed & [b] Undirected Graph


Weighted Graph
Graph

 Types of Graphs:
• Directed graph
• Undirected graph
• Simple graph
• Weighted graph
• Connected graph
• Non-connected graph
Storage class in C

Topics
 Automatic variables
 External variables
 Static variables
 Register variables
 Scopes and longevity of above types of
variables.

28
Few terms
1. Scope: the scope of a variable determines over
what part(s) of the program a variable is actually
available for use(active).
2. Longevity: it refers to the period during which a
variables retains a given value during execution
of a program(alive)
3. Local(internal) variables: are those which are
declared within a particular function.
4. Global(external) variables: are those which are
declared outside any function.

29
Automatic variables
 Are declared inside a function in which they are to be
utilized and declared using a keyword auto.
eg. auto int number;
 Are created when the function is called and destroyed
automatically when the function is exited.

 These variables are therefore private(local) to the


function in which they are declared.

 Variables declared inside a function without storage class


specification is, by default, an automatic variable.

30
Example program
int main()
{ int m=1000;
function2();
printf(“%d\n”,m);
}
function1()
{
int m = 10;
printf(“%d\n”,m);
}
function2() Output
{ int m = 100; 10
function1(); 100
printf(“%d\n”,m); 1000
}
31
Few observation about auto variables

 Any variable local to main will normally live throughout


the whole program, although it is active only in main.

 During recursion, the nested variables are unique auto


variables.

 Automatic variables can also be defined within blocks. In


that case they are meaningful only inside the blocks
where they are declared.

 If automatic variables are not initialized they will contain


garbage.
32
External Variables
 These variables are declared outside any function.

 These variables are active and alive throughout the entire


program.

 Also known as global variables and default value is zero.

 Unlike local variables they are accessed by any function in the


program.

 In case local variable and global variable have the same


name, the local variable will have precedence over the global
one.

 Sometimes the keyword extern used to declare these


variable.

 It is visible
33
only from the point of declaration to the end of the
program.
External variable (examples)
int number; int count;
float length=7.5; main()
main() {count=10;
{ . . . . . .
. . . . . .
} }
funtion1() funtion()
{. . . {int count=0;
. . . . . .
} . . .
funtion1() count=count+1;
{. . . }
. . .
} When the function
The variables number references the variable
and length are available count, it will be referencing
for use34in all three only its local variable, not
the global one.
Global variable example
int x; int fun3()
{
int main() x=x+10;
{ return(x);
x=10; }
printf(“x=%d\n”,x); Once a variable has been
printf(“x=%d\n”,fun1());
printf(“x=%d\n”,fun2());
declared global any function
printf(“x=%d\n”,fun3()); can use it and change its
} value. The subsequent
int fun1() functions can then reference
{ x=x+10;
return(x);
only that new value.
} Output
int fun2() x=10
{ int x
x=1; x=20
return(x);
}
x=1
35
x=30
External declaration
int main()
{ • As far as main is concerned, y is
not defined. So compiler will issue
y=5;
. . . an error message.
. . . • There are two way out at this point
}
int y; 1. Define y before main.
2. Declare y with the storage class
func1() extern in main before using it.
{
y=y+1
}

36
External declaration(examples)
int main()
{
extern int y;
. . .
. . .
Note that extern declaration
}
func1() does not allocate storage
{ space for variables
extern int y;
. . .
. . .
}
int y;

37
Multifile Programs and extern variables

file1.c file2.c

int main() int m;


{ function2()
extern int m; {
int i int i
. . . . . .
. . . . . .
} }
function1() function3()
{ {
int j; int count;
. . . . . .
. . . . . .
} }
38
Multifile Programs and extern variables

file1.c file2.c

int m; extern int m;


int main() function2()
{ {
int i; int i
. . . . . .
. . . . . .
} }
function1() function3()
{ {
int j; int count;
. . . . . .
. . . . . .
} }
39
Static Variables

 The value of static variables persists until the end of the


program.

 It is declared using the keyword static like


static int x;
static float y;

 It may be of external or internal type depending on the


place of there declaration.

 Static variables are initialized only once, when the


program is compiled.
40
Internal static variable

 Are those which are declared inside a function.

 Scope of Internal static variables extend upto the end of


the program in which they are defined.

 Internal static variables are almost same as auto


variable except they remain in existence (alive)
throughout the remainder of the program.

 Internal static variables can be used to retain values


between function calls.

41
Examples (internal static)

 Internal static variable can be used to count the number of calls


made to function. eg.

int main()
{
int I;
for(i =1; i<=3; i++)
stat();
}
void stat() Output
{
x=1
static int x=0;
x = x+1; x=2
printf(“x = %d\n”,x);
x=3
}

42
External static variables

 An external static variable is declared outside of all


functions and is available to all the functions in the
program.

 An external static variable seems similar simple external


variable but their difference is that static external
variable is available only within the file where it is
defined while simple external variable can be accessed
by other files.

43
Static function

 Static declaration can also be used to control the scope


of a function.
 If you want a particular function to be accessible only to
the functions in the file in which it is defined and not to
any function in other files, declare the function to be
static. eg.

static int power(int x inty)


{
. . .
. . .
}
44
Register Variable

 These variables are stored in one of the machine’s register


and are declared using register keyword.
eg. register int count;
 Since register access are much faster than a memory access
keeping frequently accessed variables in the register lead to
faster execution of program.

 Since only few variable can be placed in the register, it is


important to carefully select the variables for this purpose.
However, C will automatically convert register variables into
nonregister variables once the limit is reached.

 Don’t try to declare a global variable as register. Because the


register will be occupied during the lifetime of the program.
45
46

C structures and
unions
47
C structures: aggregate, yet
scalar
 aggregate in that they hold multiple data items at
one time
 named members hold data items of various types
 like the notion of class/field in C or C++
– but without the data hiding features
 scalar in that C treats each structure as a unit
 as opposed to the “array” approach: a pointer to a
collection of members in memory
 entire structures (not just pointers to structures) may be
passed as function arguments, assigned to variables,
etc.
 Interestingly, they cannot be compared using ==
(rationale: too inefficient)
48

Structure declarations
 Combined variable and type declaration
struct tag {member-list} variable-list;
 Any one of the three portions can be omitted

struct {int a, b; char *p;} x, y; /* omit tag


*/
• variables x, y declared with members as described:
int members a, b and char pointer p.
• x and y have same type, but differ from all others –
even if there is another declaration:
struct {int a, b; char *p;} z;
/* z has different type from x, y */
49

Structure declarations
struct S {int a, b; char *p;}; /* omit
variables */
 No variables are declared, but there is now a type struct
S that can be referred to later

struct S z; /* omit members */


• Given an earlier declaration of struct S, this declares
a variable of that type

typedef struct {int a, b; char *p;} S;


/* omit both tag and variables */
• This creates a simple type name S
(more convenient than struct S)
50

Recursively defined structures


 Obviously, you can’t have a structure that
contains an instance of itself as a member
– such a data item would be infinitely large
 But within a structure you can refer to
structures of the same type, via pointers
struct TREENODE {
char *label;
struct TREENODE *leftchild, *rightchild;
}
51

Recursively defined structures


 When two structures refer to each other,
one must be declared in incomplete
(prototype) fashion
struct HUMAN;
struct PET {
char name[NAME_LIMIT];
char species[NAME_LIMIT];
struct HUMAN *owner;
} fido = {″Fido″, ″Canis lupus familiaris″};
struct HUMAN {
char name[NAME_LIMIT]; We can’t initialize the owner
struct PET pets[PET_LIMIT]; member at this point,
} sam = {″Sam″, {fido}}; since it hasn’t been declared yet
52

Member access
 Direct access operator s.m
• subscript and dot operators have same precedence
and associate left-to-right, so we don’t need
parentheses for sam.pets[0].species
 Indirect access s->m: equivalent to (*s).m
• Dereference a pointer to a structure, then return a
member of that structure
• Dot operator has higher precedence than indirection
operator , so parentheses are needed in (*s).m
(*fido.owner).name or
fido.owner->name . and -> have equal
. evaluated first: access owner precedence and associate
member
* evaluated next: dereference pointer to
left-to-right
53

Memory layout
struct COST { int amount;
char currency_type[2]; }
struct PART { char id[2];
struct COST cost;
int num_avail; }
layout of struct PART:
currency_type

id amount num_avail

cost

Here, the system uses 4-byte alignment of integers,


so amount and num_avail must be aligned
Four bytes wasted for each structure!
54

Memory layout
A better alternative (from a space perspective):
struct COST { int amount;
char currency_type; }
struct PART { struct COST cost;
char id[2];
int num_avail;
}
currency_type

amount id num_avail
cost
55
Bit fields
Bit field members must be
ints
 If space is a serious concern, you can select the number
of bits used for each member Note: This won’t work
on machines with 16-bit
struct CHAR { unsigned ch: 7; ints
unsigned font: 6;
unsigned size: 19; };
Layout possibilities (machine-dependent):

ch font size

size font ch
56

Bit fields
 Portability is an issue:
• Do any bit field sizes exceed the machine’s int size?
• Is there any pointer manipulation in your code that
assumes a particular layout?
 Bit fields are “syntactic sugar” for more complex
shifting/masking
• e.g. to get font value, mask off the ch and size
bits, then shift right by 19
• This is what actually happens in the object code –
bit fields just make it look simpler at the source level
57
Structures as function
arguments
 Structures are scalars, so they can be returned and
passed as arguments – just like ints, chars
struct BIG changestruct(struct BIG s);
• Call by value: temporary copy of structure is created
• Caution: passing large structures is inefficient
– involves a lot of copying
 avoid by passing a pointer to the structure instead:
void changestruct(struct BIG *s);
 What if the struct argument is read-only?
• Safe approach: use const
void changestruct(struct BIG const *s);
58

Unions
 Like structures, but every member
occupies the same region of memory!
• Structures: members are “and”ed together:
“name and species and owner”
• Unions: members are “xor”ed together

union VALUE {
float f;
int i;
char *s;
};
/* either a float xor an int xor a string */
59

Unions
 Up to programmer to determine how to
interpret a union (i.e. which member to
access)
 Often used in conjunction with a “type”
variable that indicates how to interpret the
union value
Access type to
determine how
enum TYPE { INT, FLOAT, STRING };
to interpret
struct VARIABLE {
value
enum TYPE type;
union VALUE value;
};
60

Unions
 Storage
• size of union is the size of its largest member
• avoid unions with widely varying member
sizes;
for the larger data types, consider using
pointers instead
 Initialization
• Union may only be initialized to a value
appropriate for the type of its first member
61

Examples Structures and Unions


struct candidate {
int roll_no;
char grade;
float marks[4]; // Array within the structure
};
struct candidate ar_can[10]; // Array of Sructures
Accessing : ar_can[1].roll_no;
62
Nested Structures and Self
Referential Structures
struct college Self Referential Structures
{
int clg_id; struct node {
char clg_name[50]; int data1;
}; char data2;
struct student_detail struct node* link;
{ };
int id;
char name[20];
float percentage;
struct college clg_data;
}stu_data;
Passing Structures to a Function
struct std
{ void func(struct std record)
int id; {
char name[20]; printf(" Id is: %d \n", record.id);
float percentage; printf(" Name is: %s \n",
}; record.name);
printf(" Percentage is: %f \n",
void func(struct std record); record.percentage);
}
int main()
{
struct std record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
func(record);
return 0;
}

You might also like