Module1 DS
Module1 DS
Module 1- Introduction
Introduction: Data Structures,
Classifications (Primitive & Non-
Primitive), Data structure operations
Module 1 Syllabus (Traversing, inserting, deleting, searching,
and sorting). Review of Arrays. Structures:
Array of structures Self-Referential
Structures. Dynamic Memory Allocation
Functions. Representation of Linear Arrays
in Memory, dynamically allocated arrays
and Multidimensional Arrays.
Demonstration of representation of
Polynomials and Sparse Matrices with
arrays.
Primitive Data Structures: Primitive data structures are the basic data structures that
directly operate upon the machine [Link] are the fundamental data types which
are supported by a programming language. Some basic data types are integer, real,
character, and Boolean. The terms ‘data type’, ‘basic data type’, and ‘primitive data type’
are often used interchangeably.
Non-Primitive Data Structures: Non-primitive data structures are those data structures
which are created using primitive data structures. Examples of such data structures
include linked lists, stacks, trees, and graphs.
Based on the structure and arrangement of data, non-primitive data structures is further
classified into
Linear Data Structure
Non-linear Data Structure
Linear data Structures : If the elements of a data structure are stored in a linear or
sequential order, then it is a linear data [Link] data structures can be represented
in memory in two different ways.
One way is to have to a linear relationship between elements by means of
sequential memory locations.
The other way is to have a linear relationship between elements by means of links.
Examples include arrays, linked lists, stacks, and queues.
1. Array: Simplest type of data structure is linear array. It is the list of finite
numbers n of similar data elements referenced respectively by a set of n
consecutive numbers. Ex: array of students consisting of six students shown in
fig.
2. A linked list is a very flexible, dynamic data structure in which elements (called
nodes) form a sequential list. A linked list, every node contains the following two
types of data:
The value of the node or any other data that corresponds to that node
A pointer or link to the next node in the list
The last node in the list contains a NULL pointer to indicate that it is the end or tail of
the list. Since the memory for a node is dynamically allocated when it is added to the
list, the total number of nodes that may be added to a list is limited only by the
amount of memory available. Figure shows a linked list of four nodes shown in fig.
3. A stack is a linear data structure in which insertion and deletion of elements are
done at only one end, which is known as the top of the stack. Stack is called a
last-in, first-out (LIFO) structure because the last element which is added to the
stack is the first element which is deleted from the stack.
4. A queue is a first-in, first-out (FIFO) data structure in which the element that is
inserted first is the first one to be taken out. The elements in a queue are added at
one end called the rear and removed from the other end called the front.
Non-linear data Structures If the elements of a data structure are not stored in a
sequential order, then it is a non-linear data structure.
4. Inserting- It is used to add a new data item in the given collection of data items.
5. Deleting- It is used to delete an existing data item from the given collection of data
items.
6. Sorting- It is used to arrange the data items in some order i.e. in ascending or
descending order in case of numerical data and in dictionary order in case of
alphanumeric data.
7. Merging- It is used to combine the data items of two sorted files into single file in the
sorted form.
Data_type Name[Size];
The type can be either int, float, double, char, or any other valid data type.
The number within brackets indicates the size of the array, i.e., the maximum
number of elements that can be stored in the array.
For example, if we write, int marks[10]; The above statement declares an array
marks that contains 10 elements. In C, the array index starts from zero. This
means that the array marks will contain 10 elements in all. The first element will
be stored in marks[0], second element in marks[1], so on and so forth.
Therefore, the last element, that is the 10th element, will be stored in
marks[9].
1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th
eleme eleme eleme eleme eleme eleme eleme eleme eleme eleme
nt nt nt nt nt nt nt nt nt nt
Mark Mark Mark Mark Mark Mark Mark Mark Mark Mark
s[0] s[1] s[2] s[3] s[4] s[5] s[6] s[7] s[8] s[9]
Here, A is the array, k is the index of the element of which we have to calculate
the address, BA is the base address of the array A, and w is the size of one
element in memory, for example, size of int is 4 .Ex: Given an array int marks[] =
{99,67,78,56,88,90,34,85}, calculate the address of marks[4] if the base address =
1000.
99 67 78 56 88 90 34 85
Marks[0 Marks[1 Marks[2 Marks[3 Marks[4 Marks[5 Marks[6 Marks[7
] ] ] ] ] ] ] ]
#include <stdio.h>
int main(){
int marks[10],i,n,sum=0;
{
printf("Enter a[%d][%d]: ",i,j);
scanf("%d",&arr[i][j]);
}
}
printf("\n printing the elements ....\n");
for(i=0;i<3;i++)
{
printf("\n");
for (j=0;j<3;j++)
{
printf("%d\t",arr[i][j]);
}
}
}
1.5 Structures
Structure is a user defined data type that can hold data items of different data
types.
The major difference between a structure and an array is that an array can
store only information of same data type.
Syntax
struct{
member1;
member2;
…..
member n;
}; structurename
Example
struct {
char name[10];
int age;
float salary;
} person;
The above example creates a structure and variable name is Person and that has
three fields:
name = a name that is a character array
age = an integer value representing the age of the person
salary = a float value representing the salary of the individual
Assign values to fields :to assign values to the fields, use. (dot) as the structure
member operator. This operator is used to select a particular member of the
structure
Ex: strcpy([Link],“james”);
[Link] = 10;
[Link] = 35000;
1.5.1 Structure Declaration
Structure definition with a tag name-Tagged Structure
Syntax:
Struct structure_name
{ member1;
member2;
…
member n;
};
Example:
struct person
{
char name[10];
int age;
float salary;
};
Example1: Program that uses a simple structure to store the student
marks details
#include <stdio.h>
#include <string.h>
struct student
{
char name[20], subject[20];
float percentage;
}s1;
int main()
{
strcpy([Link], "aditi");
strcpy([Link], "Maths");
[Link] = 91.25;
printf(" Name : %s \n", [Link]);
printf(" Subject : %s \n", [Link]);
printf(" Percentage : %f \n", [Link]);
return 0;
}
Type Defined Structure: We can create our own structure data type by using
typedef statement as:
typedef struct
{
data_type member 1;
Prepared by Saritha Suvarna, Dept of CSE, CEC Page 11
DATA STRUCTURES AND APPLICATIONS (21CS32)
data_type member 2;
………………………
………………………
data_type member n;
} TypeName;
typedef is the keyword used at the beginning of the definition and by using
typedef user defined data type can be obtained.
struct is the keyword which tells structure is defined to the complier
The members are declared with their data_type
Type_name is not a variable; it is user defined data_type
Method-1:
typedef struct person{
char name[10];
int age;
float salary;
};
person person1, person2;
Method-2:
typedef struct {
char name[10];
int age;
float salary
} person;
person person1, person2;
In above example, person is the name of the type and it is a user defined data
type. Declarations of structure variables: person person1, person2;
This statement declares the variable person1 and person2 are of type person.
Example2:Program that uses a simple structure to store the student marks
details using typedef structure
#include <stdio.h>
#include <string.h>
typedef struct stud
{
{
students s1;
strcpy([Link], "aditi");
strcpy([Link], "Maths");
[Link] = 91.25;
printf(" Name : %s \n", [Link]);
printf(" Subject : %s \n", [Link]);
printf(" Percentage : %f \n", [Link]);
return 0;
}
for(i=0;i<num;i++)
{
printf("\n enter the details of student %d",i+1);
printf("\n name:");
scanf("%s",std[i].name);
printf("\n Rollno:");
scanf("%d",&std[i].rollno);
printf("\n totalmarks:");
scanf("%d",&std[i].t_marks);
}
printf("\n the student details are:");
for(i=0;i<num;i++)
printf("\n student %d \n name %s \n Rollno %d\n Total marks
%d\n",i+1,std[i].name,std[i].rollno,std[i].t_marks);
}
1.6 Unions
Union is a derived data type, like structure, i.e. collection of elements of different data
types which are grouped together. Each element in a union is called member. Union
allocates one common storage space for all its members, or memory space is shared
between its members. So only one field of union is active at any given time
Syntax:
Method-1:
union tagname
{
Type1 member1;
Type2 member2;
….
};
Method-2:
typedef union
{
Type1 member1;
Type2 member2;
….
};
Similar to structures, a union is a collection of variables of different data types.
The only difference between a structure and a union is that in case of unions, you
can only store information in one field at any one time.
To better understand a union, think of it as a chunk of memory that is used to
store variables of different types. When a new value is assigned to a field, the
existing data is replaced with the new data.
Thus, unions are used to save memory. They are useful for applications that
involve multiple members, where values need not be assigned to all the members
at any one time. Table below shows the difference between structures and unions.
Basis of
Structure Union
comparison
The separate memory location is allotted All members of the 'union'
Basic to each member of the 'structure'. share the same memory
location.
struct struct_name{ union u_name{
Declaration type element1; type element1;
type element2; type element2;
…. ….
} variable1, variable2, ...; } variable1, variable2, ...;
Keyword 'struct' 'union'
Size of Structure= sum of size of all the Size of Union=size of the
Size
data members. largest members.
Stores distinct values for all the members. Stores same value for all the
Store Value
members.
A 'structure' stores multiple values, of the A 'union' stores a single value
At a Time
different members, of the 'structure'. at a time for all members.
Way of Provide single way to view each memory Provide multiple way to view
Viewing location. same memory location.
Example
#include <stdio.h>
#include <string.h>
union student
{
char name[20], subject[20];
float percentage;
}s1;
int main()
{
strcpy([Link], "aditi");
strcpy([Link], "Maths");
[Link] = 91.25;
printf(" Name : %s \n", [Link]);
printf(" Subject : %s \n", [Link]);
printf(" Percentage : %f \n", [Link]);
return 0;
}
Self-referential structures are those structures that contain a reference to the data
of its same type. That is, a self-referential structure, in addition to other data,
contains a pointer to a data that is of the same type as that of the structure.
For example, consider the structure node given below. Here, the structure node
will contain two types of data: a character data and a pointer link. The value of
link is either the address in the memory of an instance of a list or the null pointer.
Consider these statements which create 3 structures and assign values to their
respective fields:
1.8 Pointers
In computer science, a pointer is a programming language data type whose value
refers directly to (or "points to") another value stored elsewhere in the computer
memory using its address.
This is a memory-location which holds the address of another memory-location.
The 2 most important operators used w.r.t pointer are:
& (address operator)
* (dereferencing/indirection operator)
Example
#include <stdio.h>
int main ()
{
int var = 20;
int *p;
p = &var;
printf("Address of var variable: %u\n", &var );
printf("Address stored in p variable: %u\n", p );
printf("Value of *p variable: %d\n", *p );
return 0;
}
Example: Program to calculate the sum of n numbers entered by the user by using
malloc()
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, i, *list, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
list = (int*) malloc(n * sizeof(int));
// if memory cannot be allocated
if(list == NULL) {
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements: ");
for(i = 0; i < n; ++i) {
scanf("%d", list + i);
sum += *(list + i);
}
printf("Sum = %d", sum);
// deallocating the memory
free(list);
printf("\n Array Contents after deallocation...\n");
for(i=0;i<n;i++)
printf("%d\t\t",*(list+i));
return 0;
}
[Link]()
“realloc” or “re-allocation” method in C is used to dynamically change the memory
allocation of a previously allocated memory. In other words, if the memory previously
allocated with the help of malloc or calloc is insufficient, realloc can be used
to dynamically re-allocate memory. re-allocation of memory maintains the already
present value and new blocks will be initialized with the default garbage value.
Syntax: ptr = realloc(ptr, newSize);
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *list, i , n1, n2;
[Link](): free() method in C is used to dynamically de-allocate the memory. The memory
allocated using functions malloc() and calloc() is not de-allocated on their own. Hence the free()
method is used, whenever the dynamic memory allocation takes place. It helps to reduce wastage
of memory by freeing it.
Syntax: free(ptr);
Malloc Calloc
The name malloc stands for memory allocation. The name calloc stands for contiguous allocation.
malloc () doesn‟t initializes the allocated calloc () initializes the allocated memory to zero
memory. It contains garbage values
Since no initialization, time efficiency is More expensive because of zero fillings. But
greater than calloc() convenient than malloc
Syntax Syntax
variable_name=(datatype*)malloc(sizeof(datat variable_name=(datatype*)calloc(n,size);
ype));
Required no. of bytes to be allocated is Takes 2 arguments: nno. of blocks to be
specified as arguments. i.e., size in bytes allocated, sizeno. of bytes in each block
space, or if we make it small, sometimes our data may not fit in that. A good solution for
this is to do run time allocation of array.
Example:
int *list, n;
printf(“enter the no. of elements to generate”);
scanf(“%d”,&n);
if(n<1)
{ printf(“improper value of n”);
exit(0);
}
list=(int*)malloc(n*sizeof(int));
Now if n<1, it will come out of the program, else, it will create n*4bytes during run time.i.e,
if n=3, we need to generate 3 memory location for integer no’s (12 bytes
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int row = 2, col = 3;
int *arr = (int *)malloc(row * col * sizeof(int));
int i, j;
for (i = 0; i < row; i++)
for (j = 0; j < col; j++)
*(arr + i*col + j) = i + j;
printf("The matrix elements are:\n");
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++)
{
printf("%d ", *(arr + i*col + j));
}
printf("\n");
}
free(arr);
return 0;
}
1.11 Polynomials
A polynomial is a sum of terms, where each term has a form axe ,Where x=variable,
a=coefficient and e=exponent.
For ex, A(x)=3x20+2x5+4 and B(x)=x4+10x3+3x2+[Link] largest (or leading) exponent of a
polynomial is called its degree.
Assume that we have 2 polynomials, A(x)= ∑ai x i & B(x)= ∑bi xi ,then A(x)+B(x)= ∑ (ai +
bi) xi i.e the above sum would be S(x)=3x20+2x5+ x4+10x3+3x2 +5
A polynomial thus may be represented using arrays or linked [Link] any term is not present,
then we assign 0’s in the corresponding coefficient.
A structure may be defined such that it contains two parts- one is the coefficient and second is
the corresponding degree. Given below is the polynomial representation using structure.
#define max_degree 100
typedef struct
{
float coef[max_degree];
int degree;
}polynomial;
Array of Structure: Instead of using one array for each polynomial, we use one array to store
all polynomials, which saves space
Polynomial Addition: Suppose a is one polynomial and b is another polynomial then c=a+b,
where c is the addition of polynomial a and b. inorder to add 2 polynomials, there are
different cases to be verified:
Case 1: Power of Polynomial a is Equal to Power of Polynomial b
Ex: a = 25x6+10x5+7x2+9 b = 15x6+5x4+4x3
lead exponent(a)=6 lead exponent(b)=6
so, lead exponent(a)=lead exponent(b)
sum is,
25x6+10x5+7x2+9
15x6+5x4+4x3
c=40 x6+………
Case 2:Power of Polynomial a is Greater than Power of Polynomial b
Remaining polynomial is: a =10x5+7x2+9 lead exponent(a)=5
b = 5x4+4x3 lead exponent(b)=4
so, lead exponent(a)>lead exponent(b). so copy lead exponent(a) directly to c
sum is,
10x5+7x2+9
5x4+4x3
c=10 x5+………
Case 3: Power of Polynomial a is Less than Power of Polynomial b
Remaining polynomial is: a =7x2+9 lead exponent(a)=2
b = 5x4+4x3 lead exponent(b)=4
so, lead exponent(a)< lead exponent(b). so copy lead exponent(b) directly to c
sum is,
7x2+9
5x4+4x3
c=5x4+………
so final polynomial is: 40x6+10x5+5x4+4x3 +7x2+9
Coding:
/* d =a + b, where a, b, and d are polynomials */
d = Zero( )
while (! IsZero(a) && ! IsZero(b)) do {
switch COMPARE (Lead_Exp(a), Lead_Exp(b)) {
case -1: d = Attach(d, Coef (b, Lead_Exp(b)), Lead_Exp(b));
b = Remove(b, Lead_Exp(b));
break;
case 0: sum = Coef (a, Lead_Exp (a)) + Coef ( b, Lead_Exp(b));
if (sum) {
Attach (d, sum, Lead_Exp(a));
a = Remove(a , Lead_Exp(a));
b = Remove(b , Lead_Exp(b));
}
break;
case 1: d = Attach(d, Coef (a, Lead_Exp(a)), Lead_Exp(a));
a = Remove(a, Lead_Exp(a));
}
}
insert any remaining terms of a or b into d
Triplet Representation
#define max 101
typedefstruct
{
int col, row,val;
}term;
term a[max];
In this representation, we consider only non-zero values along with their row and column
index values. Each non zero value is a triplet of the form <R,C,Value> where R represents
the row in which the value appears, C represents the column in which the value appears and
Value represents the nonzero value itself. In this representation, the 0th row stores total
rows, total columns and total non-zero values in the matrix. For example, consider a matrix
of size 5 X 6 containing 6 number of non-zero values. This matrix can be represented as
shown in the fig.
In above example matrix, there are only 6 non-zero elements (those are 9, 8, 4, 2, 5 & 2) and
matrix size is 5 X 6. We represent this matrix as shown in the above image. Here the first
row in the right side table is filled with values 5, 6 & 6 which indicate that it is a sparse
matrix with 5 rows, 6 columns & 6 non-zero values. Second row is filled with 0, 4, & 9
which indicates the value in the matrix at 0th row, 4th column is 9. In the same way the
remaining non-zero values also follows the similar pattern.
To transpose a matrix we just interchange the rows and columns. This means that each
element a[i][j] in the original matrix becomes b[j][i] in the transpose matrix (Fig 2.11).
The product of 2 sparse matrixes may no longer be sparse. For example see the Fi
In linked representation, we use linked list data structure to represent a sparse matrix. In
this linked list, we use two different nodes namely header node and element node. Header
node consists of three fields and element node consists of five fields as shown in the fig.
Question Bank
1. Define data structures
2. Explain classifications of data structures
3. Explain the different operations of data structures
4. Define structures. Explain different types of structure declaration and initialization
5. Write the difference between structures and union
24. Consider two polynomials A(x)=2x1000+1 and B(x)=x4+10x3+3x2+1 with a diagram show how
these two polynomials are stored using 1D array and also give its C representation.