DSA NOTES - Module1
DSA NOTES - Module1
MODULE 1
DATA STRUCTURES AND APPLICATIONS (M23BCS304)
Introduction: Data Structures, Classifications (Primitive & Non-Primitive), Data structure Operations, Review of
pointers and dynamic Memory Allocation
ARRAYS and STRUCTURES: Arrays, Dynamic Allocated Arrays, Structures and Unions, Polynomials, Sparse
Matrices, representation of Multidimensional Arrays, Strings
Data may be organized in many different ways logical or mathematical models of a program particularly
organization of data. This organized data is called “Data Structures”.
Data Structure involves two complementary goals. The first goal is to identify and develop useful, mathematical
entities and operations and to determine what class of problems can be solved by using these entities and operations.
The second goal is to determine representation for those abstract entities to implement abstract operations on this
concrete representation.
Data structure is a representation of the logical relationships existing between individual elements of data. A data
structure is a way of organizing all data items that considers not onlythe elements stored but also their relationship to
each other.
The logical or mathematical model of a particular organization of data is called a data structure.
Each record in a file may contain many field items but the value in a certain field may uniquely determine the record
in the file. Such a field K is called a primary key and the values k1, k2, ….. in such a field are called keys or key
values.
Records may also be classified according to length.
A file can have fixed-length records or variable-length records.
Pointers to data significantly improve performance for repetitive operations such as traversing strings, lookup
tables, control tables and tree structures. In particular, it is often much cheaper in time and space to copy and
dereference pointers than it is to copy and access the data to which the pointers point. Pointers are also used to hold
the addresses of entry points for called subroutines in procedural programming and for run-time linking to dynamic
link libraries (DLLs).
Pointer: A pointer is a special variable which contains address of a memory location. Using this pointer, the data
can be accessed. For example, assume that a program contains four occurrences of a constant 3.1459. During the
compilation process, four copies of 3.1459 can be created as shown below:
However, it is more efficient to use one copy of 3.1459 and three pointers referencing a single copy, since less space
is required for a pointer when compared to floating point number. This can be represented pictorially as shown
below:
The pointer in C is a variable that stores the address of another variable. This variable can be of type int, char, array,
function, or any other pointer. The size of the pointer depends on the architecture. However, in 32-bit architecture,
the size of a pointer is 2bytes.
Consider the following example to define a pointer that stores the address of an integer.
int n = 10;
int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of type integer.
Example:
void main ()
{
int a, *p;
a=10;
p= &a;
printf (“\n value of a = %d a=%d”, a, *p); // display value using pointer variable
printf (“\n address of a = %u a=%u”, &a, p); // display address using pointer variable
}
Declaring a pointer
The pointer in the c language can be declared using * (asterisk symbol). It is also known as an indirection
pointer used to dereference a pointer.
1. int *a;//pointer to int
2. char *c;//pointer to char
Example:
void main ()
{
int number=50;
int *p;
p=&number; //stores the address of the number variable
printf ("Address of p variable is %x \n”, p); // p contains the address of the number,printing p gives the address of the
number.
Dangling Pointers- The most common bug related to pointers and memory management is dangling/wild pointers.
Sometimes the programmer fails to initialize the pointer with a valid address, then this type of initialized pointer is
known as a dangling pointer in C.
Memory Allocation
Static Allocation – The process of allocating memory for variables during compilation time is called static memory
allocation.
Disadvantages of static allocations are:
The size of allocated memory space is fixed, it can’t be altered during runtime.
Wastage of memory space if more memory is allocated
1. malloc () function:
The “malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of memory
with the specified size. It returns a pointer of type void which can be cast into a pointer of any form. It doesn’t
Initialize memory at execution time so that it has initialized each block with the default garbage value initially.
Syntax of malloc() in C:
For Example:
ptr = (int*) malloc(100 * sizeof(int));
Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And, the pointer ptr holds the
address of the first byte in the allocated memory.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* ptr;
int n, i;
printf("Enter number of elements:");
scanf("%d",&n);
printf("Entered number of elements: %d\n", n);
// Dynamically allocate memory using malloc()
ptr = (int*)malloc(n * sizeof(int));
// Check if the memory has been successfully
// allocated by malloc or not
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
printf("Memory successfully allocated using malloc.\n");
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}
return 0;
}
Output
Enter number of elements:7
Entered number of elements: 7
Memory successfully allocated using malloc.
The elements of the array are: 1, 2, 3, 4, 5, 6, 7,
2. Calloc () function:
1. “calloc” or “contiguous allocation” method in C is used to dynamically allocate the specified number of
blocks of memory of the specified type. it is very much similar to malloc() but has two different points and
these are:
2. It initializes each block with a default value ‘0’.
3. It has two parameters or arguments as compare to malloc().
Syntax of calloc() in C
ptr = (cast-type*)calloc(n, element-size);
here, n is the no. of elements and element-size is the size of each element.
For Example:
Output
Enter number of elements: 5
Memory successfully allocated using calloc.
The elements of the array are: 1, 2, 3, 4, 5,
ptr pointer to a block of previously allocated memory either using malloc () /calloc().Size new size of the block.
It returns the address of the first byte of the allocated memory block if memory allocation is successful. The return
type of pointer is void. By typecasting appropriately, we can use it to store int, float, and char. etc.
It returns NULL if memory is not sufficient.
Example:
#include<stdlib.h>
void main ()
{
char * str;
str= (char *) malloc (10); strcpy (str,” Computer”); str= (char *)realloc(str,40);
strcpy (str,” Computer Science and Engineering”);
}
4. free () function:
The memory occupied by malloc () or calloc () functions must be released by calling the free () function. Otherwise,
it will consume memory until the program exits. It is the responsibility of the programmer to deallocate memory
whenever it is not required bythe program and initialize it to NULL.
Let's see the syntax of the free () function.
free(ptr)
ptr = NULL;
malloc () calloc ()
Allocates a block of memory of size Allocates multiple blocks of memory,
bytes each block with the same size
Allocated space will not be initialized Allocated space is initialized to zero.
Syntax of malloc is: Syntax of calloc is:
ptr =(data type *)malloc(size); ptr =(data type *)calloc(n, size);
It can allocate the memory block even if It can allocate multiple blocks of memory
the memory is not available only if the memory is available
contiguously. contiguously.
Arrays
An array is a special and very powerful data structure in C language. An array is a collection of similar data items.
All elements of the array share a common name. Each element in the array can be accessed by the subscript (or
index). An array is used to store, process, and print large amounts of data using a single variable.
Example: Marks of all students, Names of all employees, etc.
Single-Dimensional Array: A single-dimensional array (one-dimensional array) consists of related data items of
the same type. In Memory, all the data items are stored in contiguous locations one after the other.
Since an array is identified by a common name, any element in the array can be accessed by specifying one
subscript.
0th item can be accessed by specifying a[0], similarly we can access 1st ,2nd,3rd,and 4th item by specifying
a[1],a[2],a[3], and a[4] respectively.
1 2 3 4 5
NOTE: The address of array element in 1-dimensional array can be obtained by,
Address of a[i] = base address + sizeof (data type) * i
The difference between int * a and int a [5] and int *a [5] declarations are as shownbelow:
int *a; Pointer to an integer.
#include <stdio.h>
void main ()
{
int a[10], n, i, item, pos;
printf ("\n enter size of the array");
scanf ("%d", &n);
printf ("\n enter array elements");
for (i=0; i<n; i++)
scanf ("%d”, &a[i]);
printf ("\enter the position at which item to be inserted");
Pradeep B M, Assistant professor, Dept of CE, MITM. Page 11
M23BCS304
scanf ("%d", &pos);
printf ("\n enter element to be inserted");
scanf ("%d", &item);
for (i=n-1; i>=pos; i--)
a[i+1] =a[i];a[pos]=item;
n=n+1;
printf ("\n the array after insertion of %d is”, item);
for (i=0; i<n; i++)
printf ("%d “, a[i]);
}
Program to delete an element from a given position in an array.
#include <stdio.h>void main ()
{
int a[10], n, i, item, pos;
printf ("\n enter size of the array");
scanf ("%d", &n);
printf ("\n enter array elements");
for (i=0; i<n; i++)
scanf ("%d”, &a[i]);
printf ("\enter the position at which item to be inserted");
scanf ("%d", &pos);
printf ("\n enter element to be inserted");
scanf ("%d", &item);
for (i=pos; i<n-1; i++)
a[i] =a[i+1];
n--;
printf ("\n the array after deletion of %d is”, item);for (i=0; i<n; i++)
printf ("%d “, a[i]);
}
Program to Search a key element in an array using Linear Search Technique.
#include <stdio.h>
#include <stdlib.h>
#define MALLOC(p, s) \ //Macro for malloc( )
if (! (p=malloc(s))) \
{ \
printf ("\n Memory Insufficient"); \
exit (0); \
}
void main ()
{
int *a, n, i, key, flag=0;
printf ("\n enter size of the array");
scanf ("%d", &n);
MALLOC (a, n*sizeof(int));
printf ("\n enter array elements");
for (i=0; i<n; i++)
scanf ("%d”, &a[i]);
printf ("\n enter key element to be searched");
Pradeep B M, Assistant professor, Dept of CE, MITM. Page 12
M23BCS304
scanf ("%d”, &key);
for (i=0; i<n; i++)
{
if(a[i]==key)
{
printf ("\n key found");flag=1;
break;
}
}
if(flag==0)
printf ("\n key not found");
}
Program to Search a key element in an array using Binary Search Technique.
#include<stdio.h>
#include<stdlib.h>
#define MALLOC(p, s)\
if (!(p = malloc(s)))\
{\
printf ("\n Memory Insufficient");\exit (0); \
}
void main ()
{
int *a, n, i, key, flag=0, low, high, mid;
printf ("\n enter size of the array");
scanf ("%d", &n);
MALLOC (a, n*sizeof(int));
printf ("\n enter array elements");
for (i=0; i<n; i++)
scanf ("%d”, &a[i]);
printf ("\n enter key element to be searched");
scanf ("%d”, &key);
low=0;
high=n-1;
while (low <= high)
{
mid= (low + high)/2;
if(a[mid]==key)
{
printf ("\n key found");flag=1;
break;
}
else if(a[mid] > key)high = mid-1;
else
low = mid+1;
}
if(flag==0)
printf ("\n key not found");
}
To access an element of a two-dimensional array, you must specify the index number of both the row and column.
To loop through a multi-dimensional array, you need one loop for each of the array's dimensions.
The following example outputs all elements in the matrix array:
int matrix [2][3] = { {1, 4, 2}, {3, 6, 8} };
int i, j;
for (i = 0; i < 2; i++)
{
for (j = 0; j < 3; j++)
{
printf ("%d\n", matrix[i][j]);
}
}
b=make2Darray(row,col);
printf (“\nenter matrix B elements”);read_array(b,row,col);
c=make2Darray(row,col);for (i=0;i<row;i++)
for (j=0;j<col;j++) c[i][j] = a[i][j] + b[i][j];
printf (“\n addition of 2 matrices”); display_array(c,row,col);
}
Structures
A structure is defined as a group of variables of the same or different datatypes. Thevariables that are used to store
the data are called members of the structure Or fields of the structure.
We can define a structure by using the struct keyword and declare each of itsmembers inside curly braces:
struct person
{
// Structure definitionint age;
// Member (int variable)
char name[25];
// Member (string variable)
}; // End the structure with a semicolon
Tagged Structure
Structure variables
Type defined structures
a) Tagged Structure: The structure definition with the tag name is calledtagged structure. The tag name is the
name of the structure.
Syntax:
struct tagname
{
type1 member1;
type2 member2;
……. ………..
……. …………
};
Example:
struct student
Syntax:
struct
{
type1 member1;
type2 member2;
……. ………..
……. …………
} v1,v2,……vn;
20
Example:
struct student
{
char name [10];
int id;
float marks;
} S1, S2;
NOTE: This method of defining and declaring structure variables is rarely used.
c) Type-defined Structure:
The typedef keyword is associated with the structure definition. There are two ways to define the structure using
typedef.
NOTE: Members of the structure cannot be initialized in the structure definition asshown below. It results in a
syntax error.
struct str1
{
int i=10; char c=’A’;
float f=18.95;
};
Access Structure Members
We can access structure members by using the (.) dot operator through thestructure variable.
Syntax:
structure variable. member1;
structure variable. Member2;
Example:
struct str1
{
int i;
char c;
float f;
}s1;
Self-referential Structures:
A structure in which one or more of its members is a pointer to itself is called a self-referential structure.
Self-referential structures are widely useful in dynamic data structures like linked lists, trees, etc.
Example:
struct node
{
int data;
struct node *next; // next is a pointer to a struct node variable
};
typedef struct node *NODE;NODE first, last;
Unions:
The Union is a user-defined data type in C language that can contain elements of the different data types just like
structure. But unlike structures, all the members in the C union are stored in the same memory location. Due to
this, only one membercan store data at a time.
Syntax: Example:
typedef union typedef union
{ {
type1 member1; char grade;
type2 member2; int id;
……. ……….. float marks;
……. ………… } STUDENT;
} TYPE_ID; STUDENT x;
The size of the union is equal to the size of the largest [Link] the members share the same memory space.
Structures Union
Keyword struct is used to define a The keyword union is used to define a
structure union.
When a variable is associated with a structure, When a variable is associated with a union, the
the compiler allocates the memory for each compiler allocates the memory by considering
member. The size of the structure is greater the size of the largest member. So, the size of
than or equal to the sum of the sizes of its the unionis equal to the size of the largest
members. member.
A polynomial is an expression that contains more than two terms. A term is made up of coefficient and
exponent.
Example: P(x) = 4x3+6x2+7x+9P(x)
A polynomial may be represented using an array or structures. A structure may be defined such that it
contains two parts – one is the coefficient and the second is the corresponding exponent. The structure
definition may be given as shown below:
struct polynomial
{
int coefficient;
int exponent;
};
The sparse matrix can be defined as a matrix that has a greater number of zeroelements than the non-
zero elements.
Why do we need a sparse matrix?
The following are the benefits of using the sparse matrix -
Storage - We know that a sparse matrix contains fewer non-zero elements than zero, so less memory can be
used to store elements. It evaluates only the non-zero elements.
Computing time: In the case of searching in the sparse matrix, we need to traverse only the non-zero
elements rather than traversing all the sparse matrix elements. It saves computing time by logically designing
a data structure traversing non-zero elements.
Representation of sparse matrix:
Representing a sparse matrix by a 2D array leads to the wastage of lots of memory as zeroes in the matrix are
of no use in most of the cases. So, instead of storing zeroes with non-zero elements, we only store non-zero
elements. This means storingnon-zero elements with triples- (Row, Column, value).
#define MAXTERMS 50
typedef struct
{
int row;
int col;
int val;
} term;
term a[MAXTERMS];
The above Sparse matrix has 4 rows and 4 columns which means it contains 4*4
which is 16 elements inside it and each element is an integer value which contains 2 bytes of storage and the total
storage in the sparse matrix is 2*16 that is 32.
we can reduce this storage by eliminating the zero values. This can be done by
representing the non-zero values in array form as shown below.
ROW COLUMN VALUE
A[0] 4 4 5
A[1] 0 2 3
A[2] 1 3 8
A[3] 2 0 1
A[4] 2 2 3
A[5] 3 2 7
Transpose of Matrix
To transpose a matrix, interchange the rows and columns. This means that eachelement a[i][j] in the
original matrix becomes element a[j][i] in the transpose matrix.
Algorithm: -
for all elements in column j
place element in <i, j> value in element <j, i> value
The transpose function of the sparse matrix:
void transpose (term a [ ], term b [ ])
{
/* b is set to the transpose of a */ int n, i, j, k;
n = a [0].value; /* total number of elements */ b[0].row = a[0].col; /* rows in b = columns in a */
b[0].col = a[0].row; /* columns in b = rows in a */b[0].value = n;
k=1;
for (i = 0; i < a[0].col; i++) for (j = 1; j <= n; j++)
if (a[j]. col == i)
{
b[k]. row = a [ j]. col;
b[k]. col = a [ j]. row;
b[k]. val = a [ j]. val;k++;
}
}
B[0] 4 4 5
B[1] 0 2 1
B[2] 2 0 3
B[3] 2 2 2
B[4] 2 3 7
B[5] 3 1 8
Strings:
A String is a sequence of characters terminated with a null character ‘\0’. The String is stored as an array of
characters. The difference between a character array and a string is that the string in is terminated with a
unique character ‘\0’.
String Declaration:
Declaring a string is as simple as declaring a one-dimensional array. Below is the basic syntax for
declaring a string.
char stringname[size];
where, char ->data type
stringname ->variable name
size ->number of characters string can store (including ‘\0’)
Example:
char str [5];
char name [20];
String Initialization:
A string can be initialized in different ways as follows:
1) String literals(constants) can be assigned without size. Here, the nameof the string str acts as a
pointer because it is an array.
Example: char str [ ] = “Hello! Welcome to the class”;
2) String literals can be assigned with a predefined size. But we shouldalways account for one
extra space which will be assigned to the null character. If we want to store a string of size n then we
should always declare a string with a size equal to or greater than n+1.
Example: char str [6] = “Hello”;
3) We can also assign a string character by character. But we should remember to set the end character
as ‘\0’ which is a null character.
Example: char str [6] = {‘H’,’e’,’l’,’l’,’o’,’\0’};
4) We can assign character by character without size with the NULL character at the end. The size of
the string is determined by the compiler automatically.
Example: char str [ ] = {‘H’,’e’,’l’,’l’,’o’,’\0’};