0% found this document useful (0 votes)
101 views33 pages

21CS32 DSA Module1 Notes

Uploaded by

adithik2002
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
101 views33 pages

21CS32 DSA Module1 Notes

Uploaded by

adithik2002
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Vivekananda

College of Engineering & Technology


Nehru nagar post, Puttur, D.K. 5742013

Lecture Notes on
21CS32
DATA STRUCTURES AND APPLICATIONS

Prepared by
Ms. Thapaswini P S
Dept. of Computer Science and Engineering,
VCET Puttur

SEPTEMBER 2022

Module-1 : INTRODUCTION

Contents
Lecture Notes | 21CS32-Data Structures and Applications| Module 1

1.1 Data Structures:

Definition:
Data structure is a mathematical or logical model of storing and organizing the data in a
particular way in a computer required for designing and implementing efficient algorithms
and program development.
OR
Data Structure is a way of collecting and organizing data in such a way that we can perform
operations on these data in an effective way.

Need for data structures:


The computers are electronic data processing machines. In order to solve a particular
problem, we need to know:
i) How to represent data in computer?
ii) How to access them?
iii) What are the steps to be performed to get the needed output?
These tasks can be achieved with the knowledge of structures and algorithms.

1.2 Classifications (Primitive & Non Primitive)

Prepared by Thapaswini P S, Assistant Prof, Dept.of CSE Page 2


Lecture Notes | 21CS32-Data Structures and Applications| Module 1

1.3) Data structure Operations


The data appearing in our data structure are processed by means of data structures are
processed by means of certain operations:
Four major operations are as follows:

OR Combining two data structures is called as merging.

1.4) Review of Arrays


An array is a collection of similar data elements. These data elements have the same data
type. The elements of the array are stored in consecutive memory locations and are
referenced by an index (also known as the subscript).
Declaration of an array:
In C, arrays are declared using the following syntax: datatype name[size];
For example, 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.

Prepared by Thapaswini P S, Assistant Prof, Dept.of CSE Page 3


Lecture Notes | 21CS32-Data Structures and Applications| Module 1

Therefore, the last element, that is the 10th element, will be stored in marks[9]. In the
memory, the array will be stored as shown in below Figure.

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

Initialization of an array:

Calculating the Length of an Array:


The length of an array is given by the number of elements stored in it.
The general formula to calculate the length of an array is:
Length = upper_bound – lower_bound + 1

Prepared by Thapaswini P S, Assistant Prof, Dept.of CSE Page 4


Lecture Notes | 21CS32-Data Structures and Applications| Module 1

Calculating the Address of Array Elements:


Address of an array index can be calculated as base address+ total elements present till that
index*sizeof each block.
Addresses of an element of an array say “A [I]” is calculated using the following formula:
Address of A[I] = B + ( I – LB )*W
Where,
B = Base address
W = Storage Size of one element stored in the array (in byte)
I = Subscript of element whose address is to be found
LB = Lower limit / Lower Bound of subscript, if not specified assume 0 (zero)

Example:
Given the base address of an array M [1300…..1900] as 1020 and size of each element is 2
bytes in the memory. Find the address of M [1700].
Solution:
The given values are: B = 1020, LB = 1300, W = 2, I = 1700
Address of A [ I ] = B + W * ( I – LB )
= 1020 + 2 * (1700 – 1300)
= 1020 + 2 * 400
= 1020 + 800
= 1820

Abstract data type (ADT) of arrays:

Prepared by Thapaswini P S, Assistant Prof, Dept.of CSE Page 5


Lecture Notes | 21CS32-Data Structures and Applications| Module 1

An ADT of an array provides details of various operations that can be performed on an array.

1.5 Structure:

Definition:
Structure is basically a user-defined data type.
It is defined as a group of similar/dissimilar data items where each item can be of a same or
different data type stored under a single name.
The major difference between a structure and an array is that an array can store only
information of same data type.

Prepared by Thapaswini P S, Assistant Prof, Dept.of CSE Page 6


Lecture Notes | 21CS32-Data Structures and Applications| Module 1

Structure Declaration:
struct struct–name
{
data_type var–name;
data_type var–name;
...............
};
Example:

Like any other data type, memory is allocated for the structure when we declare a variable of
the structure.
Two ways to declare structure variables:
1.
struct student
{
int r_no;
char name[20];
char course[20];
float fees;
};
struct student stud1;

2.

Memory allocation for a structure variable:


struct student
{
char name[20];
int age;
int r_no;
};
struct student cse,ise;

Prepared by Thapaswini P S, Assistant Prof, Dept.of CSE Page 7


Lecture Notes | 21CS32-Data Structures and Applications| Module 1

Initialization of Structures:
A structure can be initialized in the same way as other data types are initialized. Initializing a
structure means assigning some constants to the members of the structure. When the user
does not explicitly initialize the structure, then C automatically does it. For int and float
members, the values are initialized to zero, and char and string members are initialized to '\0'
by default. The initializers are enclosed in braces and are separated by commas. However,
care must be taken to ensure that the initializers match their corresponding types in the
structure definition.
The general syntax to initialize a structure variable is as follows:

For example, we can initialize a student structure by writing,


struct student
{
int r_no;
char name[20];
char course[20];
float fees;
}stud1 = {01, "Rahul", "BCA", 45000};
Or, by writing,
struct student stud1 = {01, "Rahul", "BCA", 45000};

Prepared by Thapaswini P S, Assistant Prof, Dept.of CSE Page 8


Lecture Notes | 21CS32-Data Structures and Applications| Module 1

Below Figure illustrates how the values will be assigned to individual fields of the structure.

When all the members of a structure are not initialized, it is called partial initialization. In
case of partial initialization, first few members of the structure are initialized and those that
are uninitialized are assigned default values.

Accessing the Members of a Structure:


Each member of a structure can be used just like a normal variable, but its name will be a bit
longer. A structure member variable is generally accessed using a '.' (dot) operator. The
syntax of accessing a structure or a member of a structure can be given as:
struct_var.member_name
The dot operator is used to select a particular member of the structure.
For example, to assign values to the individual data members of the structure variable studl,
we may write
stud1.r_no = 01;
stud1.name = "Rahul";
stud1.course = "BCA";
stud1.fees = 45000;

To input values for data members of the structure variable stud1, we may write
scanf("%d", &stud1.r_no);
scanf("%s", stud1.name);

Similarly, to print the values of structure variable stud1, we may write


printf("%s", stud1.course);
printf("%f", stud1.fees);
Memory is allocated only when we declare the variables of the structure. In other words, the
memory is allocated only when we instantiate the structure. In the absence of any variable,
structure definition is just a template that will be used to reserve memory when a variable of
type struct is declared.
Once the variables of a structure are defined, we can perform a few operations on them. For
example, we can use the assignment operator (=) to assign the values of one variable to
another.

Prepared by Thapaswini P S, Assistant Prof, Dept.of CSE Page 9


Lecture Notes | 21CS32-Data Structures and Applications| Module 1

Typedef structures:
The typedef (derived from type definition) keyword enables the programmer to create a new
data type name by using an existing data type.

Prepared by Thapaswini P S, Assistant Prof, Dept.of CSE Page 10


Lecture Notes | 21CS32-Data Structures and Applications| Module 1

1.6 Arrays of Structures

Nested Structures:
A structure can be placed within another structure, i.e., a structure may contain another
structure as its member. A structure that contains another structure as its member is called a
nested structure.

Prepared by Thapaswini P S, Assistant Prof, Dept.of CSE Page 11


Lecture Notes | 21CS32-Data Structures and Applications| Module 1

1.7 Self-Referential Structures


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.
struct node
{
int val;
struct node *next;
};
Here, the structure node will contain two types of data: an integer val and a pointer next.
It is used in linked list.

1.8 Dynamic memory allocation functions

Memory management is important task in computer programming.


There are two types of memory management
 Static memory management
 Dynamic memory management
1. Static memory management- the allocation and deallocation of memory is performed
during compilation time of a program.
Example: int a[10]- allocates 10 bytes of memory for array.

Prepared by Thapaswini P S, Assistant Prof, Dept.of CSE Page 12


Lecture Notes | 21CS32-Data Structures and Applications| Module 1

2. Dynamic memory management - the allocation and deallocation of memory is performed


during run time of a program. This when program is getting executed at that time the memory
is managed. This is the efficient method as compared to static memory management.

Differences between static and dynamic memory allocation:

Static Memory Allocation Dynamic Memory Allocation

Memory allocation is performed Memory allocation is performed at run time.


at compile time.

Prior to execution, fixed size of No need to know size of memory prior to execution.
memory has to be decided.
Wastage/shortage of memory Memory is allocated as per requirement.
occurs.

Example: Array Example: Linked List

There are four functions used in Dynamic Memory Allocation functions:


1. malloc():
It allocates a block of memory. It is used to allocate memory space as per requirement. This
function allocates memory and return a pointer of type void* to the start of that memory
block. If function fails, it returns NULL. Therefore is necessary to verify pointer returned is
not NULL.
This function does not initialize the memory allocated during execution. It carries garbage
value.

Prepared by Thapaswini P S, Assistant Prof, Dept.of CSE Page 13


Lecture Notes | 21CS32-Data Structures and Applications| Module 1

Prepared by Thapaswini P S, Assistant Prof, Dept.of CSE Page 14


Lecture Notes | 21CS32-Data Structures and Applications| Module 1

1.9 Dynamically Allocated Arrays


The array can be dynamically allocated using malloc(), calloc() or realloc() functions.
Similarly allocated memory can be freed using free() function.
Advantage: Memory for array of any desired size can be allocated. No need of fixed sixed
array.
One Dimensional Array:
C program for 1D dynamic arrays:
#include <stdio.h>
#include<stdlib.h>
int main()
{
int n, i, sum=0;
int *a;
printf("Enter no.of elements\n");
scanf("%d",&n);
a=(int*)malloc(n*sizeof(int));
if(a==NULL)
printf("No memory allocated\n");
printf("Enter array elements\n");
for(i=0;i<n;i++)
{

Prepared by Thapaswini P S, Assistant Prof, Dept.of CSE Page 15


Lecture Notes | 21CS32-Data Structures and Applications| Module 1

scanf("%d",a+i);
sum=sum+*(a+i);
}
printf("sum=%d\n",sum);
free(a);
return 0;
}

Two-Dimensional Arrays:
C program for 2D dynamic arrays:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int r = 3, c = 4;
int *arr = (int *)malloc(r * c * sizeof(int));
int i, j, count = 0;
for (i = 0; i < r; i++)
{
for (j = 0; j < c; j++)
{
*(arr + i*c + j) = ++count;
}
for (i = 0; i < r; i++)
{
for (j = 0; j < c; j++)
{
printf("%d \t", *(arr + i*c + j));
}
printf("\n");
}
return 0;
}
Output:

Prepared by Thapaswini P S, Assistant Prof, Dept.of CSE Page 16


Lecture Notes | 21CS32-Data Structures and Applications| Module 1

1.10 Representation of Linear Arrays in memory


Array elements are stored consecutively in memory and memory locations are continuous.
Each location has an address. The computer keeps track of only first element address which is
called as base address.
Now let us use the notation:
Loc (DATA[k]) =Address of element DATA[k] of array DATA

Example: From the given array memory representation the


LOC(DATA[1])=1002. DATA[0]
1000
1001
Using base address, computer calculates other location addresses.
1002 DATA[1]
Loc (DATA[k]) =Base ( DATA)+w(k-lowerBound)
1003
Where w is no.of words per memory cell for array DATA.
........
Refer 1.4) Review of Arrays section for more details on address .........
calculation.

1.11 Multidimensional arrays


A two-dimensional m x n array A is a collection of m.n data elements such that each element
is specified by a pair of integers (such as J, K), called subscripts, with the property that 1 ≤ J
≤ m and 1 ≤ K ≤ n.
The element of A with first subscript j and second subscript k will be denoted by AJ,K or
A[J, K].
Two-dimensional arrays are called matrices in mathematics and tables in business
applications.
The below figure shows the 2D array representation.

Representation of Two-Dimensional Arrays in Memory:

While storing the elements of a 2-D array in memory, the elements are allocated contiguous
memory locations. Therefore, a 2-D array must be linearized so as to enable their storage.
There are two alternatives to achieve linearization: Row-Major order and Column-Major
order.

Prepared by Thapaswini P S, Assistant Prof, Dept.of CSE Page 17


Lecture Notes | 21CS32-Data Structures and Applications| Module 1

Consider the following example:

The row and column major order representation is as follows:

Address calculation in row major order:


Suppose A is a 2D array of an order m*n, the address of an location A[i][j] is calculated
using the formula:
A[i][j]=BaseAddress+((i*n)+j)*size where initial index value of row i=0 and column j=0.
OR
A[i][j]=BaseAddress+(((i-1)*n)+(j-1))*size where initial index value of row i=1 and
column j=1.

Example 1:

A 0 1 2 3

0 1 -1 5 15

1 0 12 5 2

2 9 7 5 6

Prepared by Thapaswini P S, Assistant Prof, Dept.of CSE Page 18


Lecture Notes | 21CS32-Data Structures and Applications| Module 1

Row major order representation is as follows:


1 -1 5 15 0 12 5 2 9 7 5 6

Find the location of A [2,2].


Solution:
Given i=2,j=2,m=3,n=4
A[i][j]=BaseAddress+((i*n)+j)*size
A [2,2]= 100 + (2*4+2)*4
= 100+10*4
= 140

Example 2:
A 1 2 3 4

1 1 -1 5 15

2 0 12 5 2

3 9 7 5 6

Row major order representation is as follows:


1 -1 5 15 0 12 5 2 9 7 5 6

Find the location of A [2,2].


Solution:
Given i=2,j=2,m=3,n=4
A[i][j]=BaseAddress+(((i-1)*n)+(j-1))*size
A [2,2]= 100 + ((2-1)*4+(2-1))*4
=100+(4+1)*4
=100+20
= 120

Address calculation in column major order:


Suppose A is a 2D array of an order m*n, the address of an location A[i][j] is calculated
using the formula:
A[i][j]=BaseAddress+((j*m)+i)*size where initial index value of row i=0 and column
j=0.
OR
A[i][j]=BaseAddress+(((j-1)*m)+(i-1))*size where initial index value of row i=1 and
column j=1.

Prepared by Thapaswini P S, Assistant Prof, Dept.of CSE Page 19


Lecture Notes | 21CS32-Data Structures and Applications| Module 1

Example1:
A 1 2 3 4

1 1 -1 5 15

2 0 12 5 2

3 9 7 5 6

Column major order representation is as follows:


1 0 9 -1 12 7 5 5 5 15 2 6

Find the location of A [2,2].


Solution:
Given i=2,j=2,m=3,n=4
A[i][j]=BaseAddress+(((j-1)*m)+(i-1))*size A [2,2]= 100 + ((2-1)*3+(2-1))*4
=100+ (3+1)*4
=100+16
= 116

VTU QP Problem:
Suppose each student in a class of 25 students is given 4 tests, assume the students are
numbered from I to 25, and the test scores are assigned in the 25 x 4 matrix called SCORE.
Suppose base (SCORE): 200, w : 4 and the programming language uses row-major order. To
store this 2D array, then find the address of 3rd test of 12th student i.e SCORE (12, 3).
(Appeared in June/July 2018)
Solution:
Given i=12,j=3,m=25,n=4
A[i][j]=BaseAddress+(((i-1)*n)+(j-1))*size
A[12][3]=200+(((12-1)*4)+(3-1))*4
=200+(44+2)*4
=200+ 184=384

1.12 Demonstration of representation of Polynomials

What is a polynomial? What is the degree of the polynomial? Write a function to add
two polynomials. (Appeared in JUNE/JULY 2017)

Prepared by Thapaswini P S, Assistant Prof, Dept.of CSE Page 20


Lecture Notes | 21CS32-Data Structures and Applications| Module 1

Polynomial Definition:
“A polynomial is a sum of terms, where each term has a form axe, where x is the variable, a
is the coefficient and e is the exponent.”

Two example polynomials are:


A(x) =3x20 + 2x5 + 4
B(x) =x4 + 10x3 + 3x2 +1

The largest (or leading) exponent of a polynomial is called its degree. Coefficients that are
zero are not displayed. The term with exponent equal to zero does not show the variable since
x raised to a power of zero is 1.

Abstract Data Type (ADT) of Polynomial:


An ADT Polynomial is the one that shows various operations that can be performed on
polynomials. These operations are implemented as functions subsequently the program.

Prepared by Thapaswini P S, Assistant Prof, Dept.of CSE Page 21


Lecture Notes | 21CS32-Data Structures and Applications| Module 1

Polynomial Representation:
One way to represent polynomials in C is to use typedef to create the type polynomial as
below:
#define MAX-DEGREE 101 /*Max degree of polynomial+1*/
typedef struct
{
int degree;
float coef[MAX-DEGREE];
} polynomial;

Now if a is a variable and is of type polynomial and n < MAX_DEGREE, the polynomial
A(x) = Σ ai xi would be represented as:
a.degree = n
a.coef[i] = an-i , 0 ≤ i ≤ n
In this representation, the coefficients are stored in order of decreasing exponents, such that
a.coef [i] is the coefficient of xn-i provided a term with exponent n-i exists;
Otherwise, a.coef [i] =0. This representation leads to very simple algorithms for most of the
operations; it wastes a lot of space.

For example A(x) = 3x20+ 2x5 +4 is represented in the memory as follows:

Prepared by Thapaswini P S, Assistant Prof, Dept.of CSE Page 22


Lecture Notes | 21CS32-Data Structures and Applications| Module 1

Initial version of polynomial addition function is as shown as follows:

Suppose if term(a)>term(b) then case 1 will be executed. Else if a<b case -1 will be
executed. Else if a==b, case 0 will be matched.

Representation of polynomials using array structures:


To preserve space an alternate representation that uses only one global array, terms to store
all polynomials.

Prepared by Thapaswini P S, Assistant Prof, Dept.of CSE Page 23


Lecture Notes | 21CS32-Data Structures and Applications| Module 1

Prepared by Thapaswini P S, Assistant Prof, Dept.of CSE Page 24


Lecture Notes | 21CS32-Data Structures and Applications| Module 1

Polynomial Addition:

Prepared by Thapaswini P S, Assistant Prof, Dept.of CSE Page 25


Lecture Notes | 21CS32-Data Structures and Applications| Module 1

Complete code is follows:

Prepared by Thapaswini P S, Assistant Prof, Dept.of CSE Page 26


Lecture Notes | 21CS32-Data Structures and Applications| Module 1

2) Adding Polynomial using an array of structures

Prepared by Thapaswini P S, Assistant Prof, Dept.of CSE Page 27


Lecture Notes | 21CS32-Data Structures and Applications| Module 1

1.13 Demonstration of Sparse Matrices with arrays

1) Give ADT of sparse matrix and show with a suitable example sparse matrix
representation storing as triples. Give a sample transpose function to transpose sparse
matrix. (Appeared in JUNE/JULY 2017)- 8 Marks

The Abstract Data type: An ADT Sparse matrix is the one that shows the various operations
that can be performed on sparse matrices.

Prepared by Thapaswini P S, Assistant Prof, Dept.of CSE Page 28


Lecture Notes | 21CS32-Data Structures and Applications| Module 1

Sparse Matrix Representation:


An element within a matrix can characterize by using the triple <row,col,value>. This means
that, an array of triples is used to represent a sparse matrix. Organize the triples so that the
row indices are in ascending order. The operations should terminate, so we must know the
number of rows and columns, and the number of nonzero elements in the matrix.

Prepared by Thapaswini P S, Assistant Prof, Dept.of CSE Page 29


Lecture Notes | 21CS32-Data Structures and Applications| Module 1

Consider the following sparse matrix, and the memory representation of sparse matrix stored
as triple.

The various informations are:


 The size of matrix: a[0].row,a[0].col
 The number of non-zero values: a[0].val
 The row index of a non zero: a[j].row
 The column index of a non zero element: a[j[.col
 The index of non-zero element: a[j].val

Prepared by Thapaswini P S, Assistant Prof, Dept.of CSE Page 30


Lecture Notes | 21CS32-Data Structures and Applications| Module 1

Transposing of a Matrix:
To transpose a matrix, interchange the rows and columns. This means that each element
a[i][j] in the original matrix becomes element a[j][i] in the transpose matrix.

A good algorithm for transposing a matrix:


for each row i
take element <i, j, value> and store it as
element <j, i, value> of the transpose;
If we process the original matrix by the row indices it is difficult to know exactly where to
place element <j, i, value> in the transpose matrix until we processed all the elements that
precede it.
This can be avoided by using the column indices to determine the placement of elements in
the transpose matrix. This suggests the following algorithm:

Prepared by Thapaswini P S, Assistant Prof, Dept.of CSE Page 31


Lecture Notes | 21CS32-Data Structures and Applications| Module 1

for all elements in column j


place element <i, j, value> in
element <j, i, value>
The columns within each row of the transpose matrix will be arranged in ascending order.

Prepared by Thapaswini P S, Assistant Prof, Dept.of CSE Page 32


Lecture Notes | 21CS32-Data Structures and Applications| Module 1

Laboratory Component:
1. Design, Develop and Implement a menu driven Program in C for the following Array
Operations
a. Creating an Array of N Integer Elements
b. Display of Array Elements with Suitable Headings
c. Exit.
Support the program with functions for each of the above operations

2. Design, Develop and Implement a menu driven Program in C for the following Array
operations
a. Inserting an Element (ELEM) at a given valid Position (POS)
b. Deleting an Element at a given valid Position POS)

Prepared by Thapaswini P S, Assistant Prof, Dept.of CSE Page 33

You might also like