You are on page 1of 48

R L JALAPPA INSTITUTE OF TECHNOLOGY

Dept.. of Computer Science & Engg.

Module 1

Iliyaz Pasha M
Assistant Professor

De
1 partment of Computer Science, RLJIT
Outline
 Introduction:
 Data Structures, Classifications (Primitive & Non Primitive).Data structure
Operations
 Review of Arrays
 Structures, Self-Referential Structures, and Unions
 Pointers
 Dynamic Memory Allocation Functions
 Representation of Linear Arrays in Memory
 Dynamically allocated arrays
 Array Operations:
 Traversing, Inserting, Deleting, Searching and Sorting
 Multidimensional Arrays
 Polynomials
 Sparse Matrices
 Strings:
 Basic Terminology
 Storing
 Operations
 Pattern Matching algorithms
Department of Computer Science, RLJIT 2
Data Structures
 Data structure is a Specific way to store and organize data in a
computer's memory so that these data can be used efficiently later.

 Data may be arranged in many different ways such as the logical


or mathematical model, for a particular organization data is
termed as a data structure.

Department of Computer Science, RLJIT 3


Classification of Data Structure
 Data structure are classified into Primitive and Non-Primitive
data structure.

Department of Computer Science, RLJIT 4


Classification of Data Structure
Primitive Data Structures
Data structures that normally manipulated by machine-level
instructions are known as primitive data structures.

Examples: Integer, float, character and pointers

These data types are available in most programming languages as


built in data types.

Department of Computer Science, RLJIT 5


Classification of Data Structure
Non Primitive Data Structures
Data structures that are not manipulated by machine-level instructions
are known as non primitive data structures.

Non Primitive Data Structures is classified into:


Linear Data Structure: Elements of data structure are stored in a
linear or sequential order.
Examples: Arrays, Linked Lists, Stacks, Queues

Non-linear Data Structure: If the elements of a Data Structure are


not stored in a sequential order, then it is a Non-Linear Data Structure.
Examples: Trees, Graphs
Department of Computer Science, RLJIT 6
Classification of Data Structure
Linear Data Structure Non-Linear Data Structure

Every item is related to its previous and Every item is attached with many other
next item. items

Data is arranged in linear sequence. Data is not arranged in sequence

Data items can be traversed in a single run. Data cannot be traversed in a single run.

Examples: Array, Stack, Queue, Linked Examples: Tree, Graph.


List.

Implementation is Easy. Implementation is Difficult


Department of Computer Science, RLJIT 7
Data structure Operations
Some specific operations applied to data available in the data
structures.
The different data structure operations are listed below:
• Traversing : Accessing each record(element) exactly once so that
certain items may be processed.
• Searching : Finding the location of the record with a given key
value.
• Insertion : Adding a new record into the data structure.
• Deletion : Removing a record from the structure.
• Sorting : Arranging the record in ascending or descending order.
• Merging : Combing two data structures.

Department of Computer Science, RLJIT 8


Review of Arrays
• An array is collection of similar data items.
• The elements of an array are of same type and each element can
be accessed using same name, but with different index value.
• An array is defined as collection/set of variables of the same type
under single variable name, and array is linear data structure
that can store fixed number of values.

• Arrays are of 2 types:


• Single/One dimensional array
• Multi dimensional array

Department of Computer Science, RLJIT 9


Review of Arrays
• Formally, an array is defined as a set of pairs <index, value>,
where index is position and value is data stored in position index.

Example: Array of marks[5];

Department of Computer Science, RLJIT 10


Review of Arrays
ADT(Abstract Data Type) for Array:
An ADT of array provides details of array implementation and
various operations that can be performed on an array.
Structure Array is
Object : A set of pairs <index, value> where value is data stored at index position
in an array, for one dimensional, array index values are {0, 1, 2, 3, ……. n-1}for
two dimensional, array index values are { (0, 0), (0, 1), (0, 2), (1,0), (1, 1), (1, 2),
(2, 0), (2, 1), (2, 2)}
Functions: A € Array, i € index, x € item, n € integer
Array Create (n, A) ::= return array A of size n.

item Retrieve (A, i) ::= if i € index then return item stored in array A at
index position i.
else return error
Array Store(A, i ,x) ::= If i € index then return array A , by storing x at
index position i in A
else return
Department error
of Computer Science, RLJIT 11
end Array
Review of Arrays
SINGLE OR ONE DIMENSIONAL ARRAY
• A single or one dimensional array is a linear list consisting of
related elements of same type.
• In memory, all the elements are stored in continuous memory-
location one after the other.
Syntax :
data_type array_name [size];
Example:
int a[3];
char carr[20] ;
float b[3] ;
Initialization of Array :
int a[5] = { 4, 5, 7, Department
3, 9}; of Computer Science, RLJIT
12
Review of Arrays
Multi-Dimensional Array
(Array of Array) Array having more than one subscript is called Multi-
Dimensional array.
Multi Dimensional Array is also called as Matrix.
Ex: Two dimensional array, Three dimensional array, four dimensional array
etc.
2D array
The Two Dimensional array is used for representing the elements of the array in
the form of the rows and columns and these are used for representing the matrix.
Two Dimensional Array uses the two subscripts for declaring the elements of the
Array
Syntax :
data_type array_name[num_of_rows][num_of_column];
Example:
int a[2][2];
Array initialization syntax: Different ways to initialize two dimensional array
int arr_name[2][2] = {{0,0},{0,1},{1,0},{1,1}};
Department of Computer Science, RLJIT 13
Structures
A structure is a user-defined data type.
It is defined as a group of dissimilar or heterogeneous data items, where items can
be of a different data type.
Structure declaration:
Syntax :
struct structure_name
Example:
{ struct student
type1 var1; {
type2 var2; int rno;
int age;
..............................
char name[30];
typeN varN; };
};
Where
struct is a keyword(for structure)
type1, type2, ….typeN are standard data types like int, float, char, double
var1, var2,…varN are member of the structures.
Department of Computer Science, RLJIT 14
structure_name or tagname is any identifier
Structures
Example to define structure for employee in c.

struct employee
{
int id;
char name[50];
float salary;
};

Here, struct is the keyword, employee is the tag name of structure;


id, name and salary are the members or fields of the structure.

Department of Computer Science, RLJIT 15


Structures
Declaring structure variable
• User can declare variable for the structure, so that member of
structure can be access easily.
• To allocate the memory for the structure, we have to declare the
variable as shown.
struct structure_name structure_variable_names;
Example:
struct student cse, ise;
Once structure variables are declared, compiler allocated memory
for the structure variables.

Department of Computer Science, RLJIT 16


Structures
Two ways to declare variables:
Method 1
Method 2
struct student
struct student
{
{
int rlno;
int rlno;
int marks;
int marks;
char name[20];
char name[20];
};
} cse, ise;
struct student cse, ise;

Memory Representation of Structure: cse and ise is as follows.


24 bytes of memory is allocated each for the structure variable cse
and ise.
Department of Computer Science, RLJIT 17
Structures
Structure intialization:
Assigining values to the structre
variable.
Method 1 Method 2
struct student
{ struct student
int rlno; {
int marks; int rlno;
char name[20]; int marks;
}; char name[20];
struct student cse = { 01, 99, } cse= { 01, 99, “Kumar”};
“Kumar”};

Department of Computer Science, RLJIT 18


Structures
Structure intialization:
Assigining values to the structre
variable.
Method 1 Method 2
struct student
{ struct student
int rlno; {
int marks; int rlno;
char name[20]; int marks;
}; char name[20];
struct student cse = { 01, 99, } cse= { 01, 99, “Kumar”};
“Kumar”};

Department of Computer Science, RLJIT 19


Structures
Accessing members of structure
• There are two ways to access structure members:

–By . (member or dot operator)

–By -> (structure pointer operator)

• The code to access the id member of p1 variable by .


(member) operator.
p1.id
cse.marks
Department of Computer Science, RLJIT 20
Structures
#include<stdio.h>
#include<conio.h> printf (“Name=%s”,cse.name);
struct student printf (“rlno=%d”,cse.rlno);
{ printf (“Marks= %d”,cse.Marks);
char name[20]; }
int rlno; OUTPUT:
int marks; Enter the Name of cse Student
}; Geetha
Enter the rlno of cse Student
void main( ) 35
{ Enter the Marks of cse Student
78
struct student cse;
Name=Geetha
printf(“Enter the Name of cse Student \n”); rlno=35
scanf(“%s”, cse.name); Marks=78

printf(“Enter the rlno of cse Student \n”);


scanf(“%d”, &cse.rlno);

printf(“Enter the Marks of cse StudentDepartment


\n”); of Computer Science, RLJIT
21
scanf(“%d”, &cse.Marks);
Structures
Array of Structures:
struct student ∙ In this example we have declare a structure variable
{ (i.e s).
char name[20]; ∙ Using this structure variable (i.e s) we can store the
int usn; information of only one student.
int marks; ∙ If we want to store information of more number of
}s; students then we declare structure variable as an
Array.

∙ struct student ∙
∙ { ∙ In this example we have declare a structure
∙ char name[20]; variable as an Array i.e s[10].
∙ int usn; ∙ Using this s[10] we can store the information of
∙ int marks; 10 students.
∙ }s[10]; ∙

Department of Computer Science, RLJIT 22


Structures
Nested Structure
• Nested structure is a structure that contains another structure as its
member.
• There are two ways of creating nested structure.
– Declaring a structure inside another structure.
– Structure variable as data member inside the structure.

Department of Computer Science, RLJIT 23


Structures
Declaring a structure inside another structure Structure variable as data member inside the
Nested Structure structure
struct student struct DOB
{ {
char name[20]; int dd;
int usn; int mm;
int marks; int yy;
};
struct DOB
{ struct student
int dd; {
int mm; char name[20];
int yy; int usn;
}date; int marks;
}s; struct DOB date;
}s;

Accessing the members of Structure DOB


Accessing the members of Structure DOB
s.date.dd;
s.date.dd;
s.date.mm;
s.date.mm;
s.date.yy;
s.date.yy; Department of Computer Science, RLJIT 24
Structures
Type defined Structure:
The structure definition associated with keyword typedef is called type-defined structure.
This is the most powerful way of defining the structure. This can be done using two methods:
Method 2
Method 1
struct structre_name
typedef struct
{
{
type1 member1;
type1 member1;
type2 member2;
type2 member2;
.
.
.
.
};
}typedef_name;
typedef struct structre_name typedef_name;
Example:
Example:
typedef struct
struct student
{
{
char name[20];
char name[20];
int age;
int age;
int rlno;
int rlno;
}student;
};
Create variables:
Create variables:
typedef_name variables;
typedef struct structure_name st;
Example Department of Computer Science, RLJIT
Example st cse, ise; 25
student cse, ise;
Self-Referential Structures
Self Referential Structure is the data structure in which the pointer
refers to the same type of structure, as their member.
struct tag Example:
{
struct node
member 1;
member 2; {
………… ………… int data;
struct tag *name; struct node *ptr;
};
};
• The structure of type tag contains a member, “name‟ which is a
pointer to structure of type tag .
• Thus tag is a self referential structure.
Department of Computer Science, RLJIT 26
Self-Referential Structures
Types of Self Referential Structures
1. Self Referential Structure with Single Link
2. Self Referential Structure with Multiple Links

Applications: Self referential structures are very useful in creation of


other complex data structures like:

– Linked Lists
– Stacks
– Queues
– Trees
– Graphs etc

Department of Computer Science, RLJIT 27


Self-Referential Structures
Advantages:
1. Unlike static data structures, self referential structure can
dynamically be expanded. Thus, require dynamic memory
allocation functions (malloc, free) to explicitly obtain and release
memory.
2. Useful in applications that involve data structures like linked list
and trees.

Department of Computer Science, RLJIT 28


Unions
Union is a user-defined data type in C, which is used to store collection of dissimilar
data items (just like a structure).
Union and Structures are same except allocating memory for their members.
Structure allocates storage space for all its members separately, whereas unions
allocates one common storage space for all its members.
Structure declaration: Example:
Syntax : union student
union tagname {
{ char name[20];
int age;
type1 var1;
int rlno;
type2 var2; };
..............................
typeN varN; Note: here, union allocates only 20 bytes of memory,
}; since the name field or mrmber
Requires the maximum space compared to age and rlno.
Declaration of union variables:
union tagname var1, var2, ……,var N;
Example:
union student s1,s2,s3; Department of Computer Science, RLJIT 29
Unions

Department of Computer Science, RLJIT 30


Pointers
Pointer is a variable that stores/points the address of another variable.
Pointer Declaration:
Syntax :
data_type *var_name;
Example:
int *p; // p is pointer which can hold the address of integer variable.
char *q; // q is pointer which can hold the address of character
variable.

To assign address of variable to pointer we need follow the 4 steps


Step 1: Declare a data variable. int a=10;
Step 2: Declare a pointer variable. int *p;
Step 3: Assign address of data variable to pointer p=&a
Step 4: Access the pointer printf(“value of a is %d”, *p)

Department of Computer Science, RLJIT 31


Pointers
Advantages of Pointers:
• Pointers provide direct access to memory
• Pointers provide a way to return more than one value to the functions
• Reduces the storage space and complexity of the program
• Reduces the execution time of the program
• Provides an alternate way to access array elements
• Pointers can be used to pass information back and forth between the
calling function and called function.
• Pointers allow us to perform dynamic memory allocation and
deallocation.
• Pointers helps us to build complex data structures like linked list,
stack, queues, trees, graphs etc.

Department of Computer Science, RLJIT 32


Pointers
Disadvantages of Pointers:
• Uninitialized pointers might cause segmentation fault.

• Dynamically allocated block needs to be freed


explicitly. Otherwise, it would lead to memory leak.

• Pointers are slower than normal variables.

• If pointers are updated with incorrect values, it might lead to


memory corruption.

Department of Computer Science, RLJIT 33


Dynamic memory allocation
Memory management is important task in computer programming.
There are two types of memory management.
1. Static memory management: The allocation and deallocation of
memory is done during compilation time of the program.
Example: int a[10];
2. Dynamic memory management: The process of allocating
memory during program execution(run time) is called
dynamic memory allocation.

C language offers 4 dynamic memory allocation functions. They


are,
malloc() calloc() realloc() and free()

Department of Computer Science, RLJIT 34


Dynamic memory allocation
Static memory allocation Dynamic memory allocation
Memory allocation is performed Memory allocation is performed
at compile time. at run time.

Prior to allocation, fixed size of No need to know the size of


memory has to be decided. memory prior to allocation.
Wastage or shortage of memory Memory is allocated as per
occurs. requirement.
Example: arrays Example: linked list

Department of Computer Science, RLJIT 35


Dynamic memory allocation
malloc ( ) function:
It allocates block of memory during run time.
The size of the block is the number of bytes specified in the
parameter (i.e. size).
Syntax:
ptr= (data type *) malloc(size);

It allocates a block of memory which is specified in parameter size.


This function returns the staring address of allocated memory on
successful allocation.
This function returns NULL on unsuccessful allocation.( if specified
memory is not available)
Example:
ptr= (int *) malloc(10);
In above example, malloc function allocates 10 bytes of memory and
returns the starting address toDepartment
the pointer ptr. RLJIT
of Computer Science, 36
Dynamic memory allocation
calloc () function:
It allocates multiple block of memory during run time.
calloc means contiguous allocation of memory.
Syntax:
ptr= (data type *) calloc(n, size);
Where, n is number of blocks to be allocated. size is size of each
block.
Totally it allocates ( n * size) bytes of memory
This function returns the staring address of allocated memory on
successful allocation.
This function returns NULL on unsuccessful allocation.( if specified
memory is not available)
Example:
ptr= (int *) calloc(10 , sizeof(int));
In above example, calloc function allocates 20 bytes of memory and
returns the starting address toDepartment
the pointer ptr. RLJIT
of Computer Science, 37
Dynamic memory allocation
Difference between malloc() and calloc() functions in C

Department of Computer Science, RLJIT 38


Dynamic memory allocation
realloc () function:
realloc means reallocation of memory.
Process of allocating or deallocating a memory for already allocated
memory during run time is called reallocation of memory.
Syntax:
ptr= (data type *) realloc(ptr, newsize);
The realloc() function accepts two arguments,
The first argument ptr is a pointer to the first byte of memory that
was previously allocated using malloc() or calloc() function.
The second argument newsize parameter specifies the new size of
the block in bytes.
Example
ptr= (int *) malloc(50); This first line allocated 50 bytes of memory and return
starting address to the pointer ptr.
ptr= (int *) realloc(ptr,100);This line reallocated the memory from 50 bytes to
100 bytes and return starting address to the pointer ptr.
Department of Computer Science, RLJIT 39
Dynamic memory allocation
free () function:
This function is used to deallocate (or free) the allocated memory.
Syntax:
free(ptr);
This function free deallocates the memory which is pointed by the
pointer ptr.
Example
ptr= (int *) malloc(50); This line allocated 50 bytes of memory
and return starting address to the
pointer ptr.

free(ptr); deallocate the memory which is


ptr=NULL; allocated for pointer ptr, and finally
assign NULL to pointer ptr.
Department of Computer Science, RLJIT 40
Representation of Linear Arrays in Memory
Representation of 1-D Array:
In C language, array index always starts from 0 (zero).
Below figure shows, the representation of 1-D array ( Assuming the
starting address 200).

Formula to find the location a[index];


Loc A[index] = BaseAddress[A]+ w*(index-LB)
Where, w is word length(size of each element)
LB is Lower Bound of array.
Formula to find the Number of Elements in an 1D Array:
Number of elements = UB – LB + 1
Where, UB is Upper Bound and LBofisComputer
Department Lower Bound
Science, RLJIT 41
Representation of Linear Arrays in Memory
Problem:
Consider linear array AAA(5:50) and BBB(-5:10)
a) Find the number of elements.
Solution: AAA(5:50)
Number of elements = UB – LB + 1
Number of elements = 50-5+ 1=46

BBB(-5:10)
Number of elements = UB – LB + 1
Number of elements = 10-(-5)+ 1=10+5+1=16

b) Suppose Base (AAA) is 300 and w=2. Find AAA[15] .


Solution:
Loc AAA[index] = BaseAddress[AAA]+ w*(index-LB)
Loc AAA[15] = 300+ 2*(15-0)=330
Department of Computer Science, RLJIT 42
Dynamically allocated arrays
The array can be dynamically allocated using malloc( ), calloc( ) or
realloc( ) function.
Similarly allocated memory can be freed.

Advantage: Memory for array of any desired size can be allocated.


No need of fixed sized array.

Department of Computer Science, RLJIT 43


Dynamically allocated arrays
C Program using Dynamic array to add n array elements.
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,sum=0;
int *a;
printf(“enter the number of elements\n”);
scanf(“%d”, &n);
a=(int *) malloc (n*sizeof(int));
if(a==NULL)
printf(“ No Memory Allocation\n”);
printf(“ Enter the Array Elements\n”);
for(i=0; i<n; ++i)
{
scanf(“%d”, a+i);
sum=sum+(*(a+i));
}
printf(“ Sum = %d\n”, sum);
free(a);
getch(); Department of Computer Science, RLJIT 44
}
Array Operations
Traversing:
Traversal of a data structure means processing all the data elements
present in it i.e. process every element of data structure is visited once
and only once, such type of operation is called as traversing.

For example to display all the elements of an array, every element is


visited only once, so it is called as traversing operation.
Function to display n elements of array (Traversing an array) as shown below.

void display(int a[ ], int n )


{
int i;
printf("The array elements are:\n");
for(i=0; i<n; i++)
printf("%d\t", a[i]);
} Department of Computer Science, RLJIT 45
Array Operations
Insertion:
Insertion means addition of a new data element in a data structure.

When an element of the same type is added to an existing data


structure, the operation is called as Insertion operation.
Function to inserting an item into an array based on position as shown below.
int insert(int a[ ], int n, int pos, int item)
{
int i;
if(pos>n || pos<0)
printf(“ Invalid Position\n”);
return n;

for(i=n-1; i>=pos; i--)


{
a[i+1] = a[i];
}
a[pos] = item;
return n+1;
} Department of Computer Science, RLJIT 46
Array Operations
Deletion:
Deletion means removal of a data element from a data structure if it is
found. When an element is removed from the data structure, the
operation is called as Deletion operation.
Function to delete an item into an array based on position as shown below.
void del(int a[ ],int n, int pos )
{
int i;
if(pos>n || pos<0)
printf(“ Invalid Position\n”);
return n;

printf(“item deleted = %d\n”, a[pos]);


for(i=pos; i<n-1; i++)
{
a[i] = a[i+1];
}

return n-1;
} Department of Computer Science, RLJIT 47
Questions???
1. Define Data structure. Give its classification. What are the basic operations
that can be performed on data structure?
2. Define array and its types & explain how array is declared & accessed with
an example.
3. What is structure? How is it different from array? Explain different types of
structure declaration with example and give the difference between
structure and union.
4. Brief about Self Referential Structure.
5. Define Pointers. How to declare and initialize pointers, Explain with
example and give advantage and disadvantages of pointer.
6. Explain dynamic memory allocation functions in detail.
7. List the difference between Static memory allocation and Dynamic memory
allocation.
8. Briefly explain dynamically allocated arrays with example.
9. In brief explain array operations of data structures.

Department of Computer Science, RLJIT 48

You might also like