DS Module1 Notes
DS Module1 Notes
MODULE-1
INTRODUCTION
TOPICS:
Module 1: Introduction: Data Structures, Classifications (Primitive & Non Primitive), Data structure
Operations, Review of Arrays, Structures, Self-Referential Structures, and Unions. Pointers and Dynamic
Memory Allocation Functions. Representation of Linear Arrays in Memory, Dynamically allocated arrays.
Array Operations: Traversing, inserting, deleting, searching, and sorting. Multidimensional Arrays,
Polynomials and Sparse Matrices.
Strings: Basic Terminology, Storing, Operations and Pattern Matching algorithms. Programming Examples.
1. INTRODUCTION
Page 1
Data structures and Applications 18CS32
EXAMPLE:
Attributes: Name Age Sex Roll Number Branch
A 17 M 109cs0132 CSE
Values:
B 18 M 109ee1234 EEE
Here, it is an example of student details where STUDENT is the given entity. Then
name, age, sex, roll number, branch are attributes and their values are properties (A, 17, M,
109cs0132, CSE). Collection of student details is student entity set and Roll number is the primary
key which uniquely indicates each student details.
DATA STRUCTURE
ta Structure is a way of collecting and organizing data in such a way that the operations
on these data can be performed in an effective
Data Structures is about rendering data elements in terms of some relationship, for better
organization and storage in computer.
To develop a program of an algorithm we should select an appropriate data structure for that
algorithm. Therefore, data structure is represented as:
Algorithm + Data structure = Program
For example, data can be player's name "Virat" and age 26. Here "Virat" is of String data type
and 26 is of integer data type. This data can be recorded as a Player record. Now, it is possible to
Algorithms manipulate the data in these structures in order to accomplish some task
Page 2
Data structures and Applications 18CS32
Anything that can store data can be called as a data structure, hence Integer, Float,
Boolean, Char etc, all are data structures. They are known as Primitive Data Structures and some
complex Data Structures, which are used to store large and connected data. They are called Non-
primitive Data Structures.
Examples:
Array
Stack
Queue
Linked List
Tree
Graph
All these data structures allow us to perform different operations on data. The s e l e c t i o n of
these data structures is based on which type of operation is required.
Page 3
Data structures and Applications 18CS32
Definitions:
Array: Array is a collection of data of same data type stored in consecutive memory location
and is referred by common name
Stack: A stack is a Last-In-First-Out (LIFO) linear data structure in which insertion and deletion
takes place at only one end called the top of the stack.
Queue: A Queue is a First in First-Out (FIFO) linear data structure in which insertions takes
place one end called the rear and the deletions takes place at one end called the Front.
Linked list: Linked list is a collection of data of same data type but the data items need not be
stored in consecutive memory locations.
Page 4
Data structures and Applications 18CS32
Trees: Trees are used to represent data that has some hierarchical relationship among the data
elements.(as shown in figure 2)
Figure 2: Trees
Graph: Graph is used to represent data that has relationship between pair of elements not
necessarily hierarchical in nature. For example electrical and communication networks, airline
routes, flow chart, graphs for planning projects.(as shown in figure 3)
Figure 3: Graph
1.2 DATA STRUCTURE OPERATIONS
The data in the data structures are processed by certain operations. The particular data structure
chosen largely depends on the frequency of the operation that needs to be performed on the data
structure.
Traversing
Searching
Insertion
Page 5
Data structures and Applications 18CS32
Deletion
Sorting
Merging
(1) Traversing: Accessing each record exactly once so that certain items in the record may be
processed.
(2) Searching: Finding the location of a particular record with a given key value, or finding the
location of all records which satisfy one or more conditions.
(3) Inserting: Adding a new record to the structure.
(4) Deleting: Removing the record from the structure.
(5) Sorting: Managing the data or record in some logical order (Ascending or descending order).
(6) Merging: Combining the record in two different sorted files into a single sorted file.
Operations on linear data structures
1. Add an element
2. Delete an element
3. Traverse all the elements
4. Sort the list of elements
5. Search for a data element
Apply one or more functionality to create different types of data structures.
For example Stack, Queue, and Linked Lists.
Operations applied on non-linear data structures
The following list of operations applied on non-linear data structures.
1. Add elements.
2. Delete elements
3. Display the elements
4. Sort the list of elements
5. Search for A data element by applying one or more functionalities and different ways of joining
randomly distributed data items to create different types of data structures.
For example Tree, Graphs and Files.
1.3 REVIEW OF STRUCTURES, UNIONS AND POINTERS
STRUCTURE DEFINITION
is a collection of data items of same or dissimilar data type. Each data item is
identified by its name and type. (Or) A Structure is a user defined data type that can store related
information together. (Or) A structure is a collection of different data items / heterogeneous data items
Page 6
Data structures and Applications 18CS32
under a single name. The variable within a structure are of different data types and each has a name
that is used to select it from the structure.
C arrays allow you to define type of variables that can hold several data items of the same kind
but structure is another user defined data type available in C programming, which allows you to
combine data items of different kinds.
Structures are used to represent a record, Suppose, track of books are kept in a library are
recorded then it is required to track the following attributes about each book:
Title
Author
Subject
Book ID
STRUCTURE DECLARATION
It is declared using a keyword struct followed by the name of the structure. The members of the
structure are declared within the structure.
Example:
struct struct-name
{
data_type1 member_name1;
data_type2 member_name2;
.. ..
data_typen member_namen;
}structurevariablename;
STRUCTURE INITIALIZATION
Assigning values to the data members of the structure is called initializing of structure.
Syntax:
struct struct_name
{
data _type member_name1;
data _type member_name2;
} structure variable={constant1,constant2};
Page 7
Data structures and Applications 18CS32
To input values for data members of the structure variable stud, can be written as,
tud.roll);
Page 8
Data structures and Applications 18CS32
Program to create a struct person , initializes its data member and print their values
#include<stdio.h>
#include<conio.h>
void main()
{
struct person{
char name[10];
int age;
float salary;
};
struct person p1;
clrscr();
strcpy(p1.name,"james");
p1.age=10;
p1.salary=35000;
printf("\n name=%s age=%d salary=%f",p1.name,p1.age,p1.salary);
getch();
}
ARRAY OF STRUCTUREs
An array of structure can also be declared. Each element of the array representing a structure
variable.
Example : struct employee emp[5];
The above code define an array emp of size 5 elements. Each element of array emp is of type employee
#include<stdio.h>
#include<conio.h>
struct employee
{
char ename[10];
int sal;
};
struct employee emp[5];
int i,j;
void ask()
{
for(i=0;i<3;i++)
{
printf("\nEnter %dst employee record\n",i+1);
printf("\nEmployee name\t");
scanf("%s",emp[i].ename);
printf("\nEnter employee salary\t");
scanf("%d",&emp[i].sal);
}
printf("\nDisplaying Employee record\n");
for(i=0;i<3;i++)
{
printf("\nEmployee name is %s",emp[i].ename);
Page 9
Data structures and Applications 18CS32
printf("\nSlary is %d",emp[i].sal);
}
}
void main()
{
clrscr();
ask();
getch();
}
Page 10
Data structures and Applications 18CS32
POINTERS TO STRUCTURES
Pointer to a structure is a variable that holds the address of a structure. The syntax to declare
pointer to a structure can be given as:
strcut struct_name *ptr;
eg: struct stud *ptr_stud;
To assign address of stud to the pointer using address operator(&) we would write ptr_stud=&stud; To
access the members of the structure (->) operator is used.
for example
ptr_stud->name=Raj;
Page 11
Data structures and Applications 18CS32
NESTED STRUCTURES
The structure should be declared separately and then be grouped into high level structure. The
data members of the nested structures can be accessed using (.) Dot operator.
Syntax to follow while accessing the data members of inner structure in nested structure with dot
operator is outer most structure variable. inner most structure variable. inner data member
;
Syntax to followed while accessing the data members of outer structure in nested structure with
dot operator is outer most structure variable .outer data member ;
Type1: declaring structure within a structure
Example :
struct student
{
char name[20];
int marks;
float per;
struct dob
{
int day,month,year;
}date;
}s1;
void main()
{
\n enter the student details-
,&s1. date.month,
&s1.date.year);
\
s1.date.day,s1.date.month,s1. date.year);
getch();
}
Type 2: declaring a structure variable of one within another structure
Example :
struct dob
{
int day,month,year;
Page 12
Data structures and Applications 18CS32
};
struct student
{
char name[20];
int marks;
float per;
struct dob date;
}s1;
void main()
{
\n enter the student details-
sc
&s1.date.year);
\
s1.date.day,s1.date.month,s1.date.year);
getch();
}
Nested structures with typedef
Example :
typedef struct
{
int month;
int day;
int year;
}date;
typedef struct
{
char name[10];
int age;
salary;
date dob;
}humanbeing;
humanbeing person1,person2;
If humanbeing person1 and person2 declares person1 and person2 variables of type humanbeing.
Then consider a person born on feb 11, 1944, can have the values for the date struct set as:
person1.dob.month=2;
person1.dob.day=11;
person1.dob.year=1944;
Similarly for considering person2, his dob is 3rd December 1956 then
person2.dob.month=12;
Page 13
Data structures and Applications 18CS32
person2.dob.day=3;
person2.dob.year=1956;
Program for illustration of nested structures with typedef
#include<stdio.h>
#include<conio.h>
void main()
{
typedef struct
{
int month;
int day;
int year;
}date;
typedef struct
{
char name[10];
int age;
salary;
date dob;
}humanbeing;
humanbeing person1;
strcpy(person1.name,"james");
person1.age=10;
person1.salary=35000;
Person1.dob.month=2;
Person1.dob.day=11;
Person1.dob.year=1944;
\n details of t
printf("\n name=%s age=%d salary=%f dob=%d-%d-%d",person1.name,
person1.age,person1.salary,Person1.dob.day,Person1.dob.month,Person1.dob.year);
getch();
}
UNIONS
Union is a collection of variables of different data types. Union information can only be stored in
one field at any one time.
A union is a special data type available in C that enables you to store different
data types in the same memory location.
union can define many members, but only one member can contain a value at any given time.
Unions provide an efficient way of using the same memory location for multi-purpose.
Declaring Union:
union union-name
{
data_type1 member_name1;
Page 14
Data structures and Applications 18CS32
data_type2 member_name2;
.. ..
data_typen member_namen;
}union variablename;
Example:
union data
{
char a;
int x;
float f;
}mydata;
The union tag is optional and each member definition is a normal variable definition, such as int
i; or float f; or any other valid variable definition.
At the end of the union's definition, before the final semicolon, you can specify one or more
union variables but it is optional. The memory occupied by a union will be large enough to hold the
largest member of the union. For example, in above example Data type will occupy 4 bytes of memory
space because this is the maximum space which can be occupied by float data.
Page 15
Data structures and Applications 18CS32
Dot operator can be used to access a member of the union. The member access operator is coded
as a period between the union variable name and the union member that we wish to access.
Page 16
Data structures and Applications 18CS32
Example 1
struct node
{
int val;
struct node*next;
}list;
Example 2:
typedef struct
{
char data;
struct list * link;
}list;
In this example each instance of the structure list have two components data and link.
Data is a single character, while link is a pointer to a list structure.
The value of link is either the address in memory of an instance of list or NULL pointer.
Page 17
Data structures and Applications 18CS32
1.5 POINTERS
are variables that hold address of another variable of same dat
Pointers are one of the most distinct and exciting features of C language. It provides power and
flexibility to the language.
Benefit of using pointers
Pointers are more efficient in handling Array and Structure.
Pointer allows references to function and thereby helps in passing of function as arguments to
other function.
It reduces length and the program execution time.
It allows C to support dynamic memory management.
Page 18
Data structures and Applications 18CS32
Concept of Pointer
Whenever a variable is declared, system will allocate a location to that variable in the memory,
to hold value. This location will have its own address number. Let us assume that system has allocated
memory location 80F for a variable a.
Example : int a = 10 ;
The value 10 can be accessed by either using the variable name a or the address 80F.Since the
memory addresses are simply numbers they can be assigned to some other variable. The variable that
holds memory address are called pointer variables. A pointer variable is therefore nothing but a
variable that contains an address, which is a location of another variable. Value of pointer variable will
be stored in another memory location.
Page 19
Data structures and Applications 18CS32
Dereferencing of Pointer
Once a pointer has been assigned the address of a variable. To access the value of variable, pointer is
dereferenced, using the indirection operator *.
void main()
{
int a,*p;
a = 10;
p = &a;
printf("%d",*p); //this will print the value of a.
printf("%d",*&a); //this will also print the value of a.
printf("%u",&a); //this will print the address of a.
printf("%u",p); //this will also print the address of a.
printf("%u",&p); //this will also print the address of p.
}
Pointer and Arrays
When an array is declared, compiler allocates sufficient amount of memory to
contain all the elements of the array. Base address which gives location of the first element is also
allocated by the compiler.
Suppose we declare an array arr,
int arr[5]={ 1, 2, 3, 4, 5 };
Assuming that the base address of arr is 1000 and each integer requires two byte,
the five element will be stored as follows in figure 6
Page 20
Data structures and Applications 18CS32
int *p;
p = arr;
or p = &arr[0]; //both the statements are equivalent.
Now we can access every element of array arr using p++ to move from one element to another. NOTE
: You cannot decrement a pointer once incremented. p-- won't work.
Pointer to Array
As studied above, we can use a pointer to point to an Array, and then we can use
that pointer to access the array. Lets have an example,
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i=0; i<5; i++)
{
printf("%d", *p);
p++;
}
In the above program, the pointer *p will print all the values stored in the array one by one. We can also
use the Base address (a in above case) to act as pointer and print all the values.
array
array
array
a[0] only
a++; compile time error, we cannot change base address of the array.
Page 21
Data structures and Applications 18CS32
ADT ARRAY
Objects: A set of pairs<index,value > where for each of index there is a value from the set item. Index
is a finite ordered set of one or more dimensions , for example -1} for one dimension, { (0 ,0
),(0,1),(0.2),(1,0),(1,2),(1,1),(2,1),(2,2),(2,0))} for two dimensions etc.
Page 22
Data structures and Applications 18CS32
Functions:
For all A C Array, I C index, x C item, j, size C integer
1. Array create (j, list) = return an array of j dimensions where list is a j-tuple whose ith element is the
size of ith dimension. Items are undefined.
2. Item retrieve (A, i) = if (I C index) return the item associated with index value i in array A else return
error.
3.array store (A, i, x) = if (i in index) return an array that is identical to array A expect the new pair
<i,x> has been inserted else return error.
end Array
Initialization:
Initialize arrays at the time of declaration.
Syntax:
Where ,value1, value2, valueN are the constant values known as initializers, which are assigned
to the array elements one after another.
Page 23
Data structures and Applications 18CS32
Where, A is an array, K is the index of the element for which address has to be calculated ,BA is
the base address of the array A,and W is the size of one element in memory
2. calculating the length of an array
Length = Upperbound-Lowerbound+1
Where , upperbound is index of the last element and lowerbound is index of the first element in
the array
Processing: For processing arrays we mostly use for loop. The total no. of passes is equal to the no. of
elements present in the array and in each pass one element is processed.
Example: This program reads and displays 3 elements of integer type.
#include<stdio.h>
main()
{
int a[3],i;
for(i=0;i<=2;i++) //Reading the array values
{
}
for(i=0;i<=2;i++) //display the array values
{
\
}
}
Example: C Program to Increment every Element of the Array by one & Print Incremented
Array.
#include <stdio.h> void main()
{
int i;
int array[4] = {10, 20, 30, 40};
for (i = 0; i < 4; i++)
arr[i]++;
for (i = 0; i < 4; i++)
printf("%d\t", array[i]);
}
Page 24
Data structures and Applications 18CS32
INSERT(LA,N,K,ITEM)
HERE LA is a linear array with N elements and K is a positive integer such that K<=N. this
algorithm inserts an element ITEM into Kth position in LA.
1.[Initalize the counter]. Set J=N.
2.repeat steps 3 and 4 while J>=K
3.[move jth element downward] set LA[J+1]=LA[J].
4.[Decrease the counter] set J=J-1
[end of step 2 loop]
5.[insert element] set LA[K]A=ITEM
6.[reset N] set N=N+1
7.Exit
DELETE(LA,N,K,ITEM)
HERE LA is a linear array with N elements and K is a positive integer such that K<=N. this
algorithm deletes an element ITEM into Kth position in LA.
1. Set ITEM=LA[K]
2. repeat for J=K to N-1
3.[move j+1st element upward] set LA[J]=LA[J+1].
4.[end of step 2 loop]
5.[reset N] set N=N-1
6.Exit
BUBBLE SORT(DATA,N)
Here DATA is an array with N elements . THIS Algorithm sorts the elemts in DATA.
1. repeat steps 2 and 3 for k=1 to N-1
Page 25
Data structures and Applications 18CS32
LINEAR SEARCH(DATA,N,ITEM,LOC)
Here DATA is a linear array with N elements and ITEM is a given item of information. this
algorithm finds the location LOC of item in DATA or set LOC=0 if the search is unsuccessful
1.[Insert ITEM at the end of DATA]. Set DATA[N+1]=ITEM.
2.[initialize the counter] set LOC=0,FOUND=0
3.[Search for ITEM]
Repeat for j=0 to N-1
If(ITEM=DATA[J]) then SET FOUND=1 and break
[end of loop]
4.[Succesful?] if FOUND=1Then SUCCESSFUL
else UNSUCCESSFUL
6.Exit
BINARY SEARCH(DATA,LB,UB,ITEM,LOC)
Here DATA is a sorted array with lower bound LB and upper bound UB and ITEM is a given
item of information. The variables BEG, END and MID denote respectively the beginning, end and
middle locations of a segment of elements of data. This algorithm finds the location LOC of item in
DATA or sets LOC=NULL
1.[Initialize segment variables ].
Set BEG=LB,END=UB and MID=INT((BEG+END)/2);
2. repeat steps 3 and 4 while BEG<=END and DATA[MID]!=ITEM
3. if ITEM<DATA[MID] then
Set END=MID-1
Page 26
Data structures and Applications 18CS32
ELSE
Set BEG=MID+1
[end of loop]
4. set MID=INT(BEG+END)/2
5. if DATA[MID]=ITEM Then
set LOC=MID
else
set LOC=NULL
6.Exit
Page 27
Data structures and Applications 18CS32
Here
LOC (A [J, K]) : is the location of the element in the Jth row and Kth column.
Base (A) : is the base address of the array A.
w : is the number of bytes required to store single element of the array A.
M : is the total number of rows in the array.
J : is the row number of the element.
K : is the column number of the element.
E.g.
A 3 x 4 integer array A is as below:
Subscript Elements Address
(1,1) 10 1000
(2,1) 20 1002
(3,1) 50 1004
(1,2) 60 1006
(2,2) 90 1008
(3,2) 40 1010
(1,3) 30 1012
(2,3) 80 1014
(3,3) 75 1016
(1,4) 55 1018
(2,4) 65 1020
(3,4) 79 1022
Suppose we have to find the location of A [3, 2]. The required values are:
Base (A) : 1000
w : 2 (because an integer takes 2 bytes in memory)
M : 3
J : 3
K : 2
Now put these values in the given formula as below:
LOC (A [3, 2]) = 1000 + 2 [3 (2-1) + (3-1)]
= 1000 + 2 [3 (1) + 2]
= 1000 + 2 [3 + 2]
= 1000 + 2 [5]
= 1000 + 10 = 1010
Page 28
Data structures and Applications 18CS32
LOC (A [J, K]) : is the location of the element in the Jth row and Kth column.
Base (A) : is the base address of the array A.
w : is the number of bytes required to store single element of the array A.
N : is the total number of columns in the array.
J : is the row number of the element.
K : is the column number of the element.
E.g.
A 3 x 4 integer array A is as below:
Subscript Elements Address
(1,1) 10 1000
(1,2) 60 1002
(1,3) 30 1004
(1,4) 55 1006
(2,1) 20 1008
(2,2) 90 1010
(2,3) 80 1012
(2,4) 65 1014
(3,1) 50 1016
(3,2) 40 1018
(3,3) 75 1020
(3,4) 79 1022
Suppose we have to find the location of A [3, 2]. The required values are:
Base (A) : 1000
w : 2 (because an integer takes 2 bytes in memory)
N : 4
J : 3
K : 2
Now put these values in the given formula as below:
LOC (A [3, 2]) = 1000 + 2 [4 (3-1) + (2-1)]
= 1000 + 2 [4 (2) + 1]
= 1000 + 2 [8 + 1]
= 1000 + 2 [9]
= 1000 + 18
= 1018
Example 1:
Write a C program to find sum of two matrices
#include <stdio.h>
#include<conio.h>
Page 29
Data structures and Applications 18CS32
void main()
{
float a[2][2], b[2][2], c[2][2];
int i,j;
clrscr();
printf("Enter the elements of 1st matrix\n");
/* Reading two dimensional Array with the help of two for loop. If there is an array of 'n'
dimension, 'n' numbers of loops are needed for inserting data to array.*/
for(i=0;i<2;I++)
for(j=0;j<2;j++)
{
scanf("%f",&a[i][j]);
}
printf("Enter the elements of 2nd matrix\n");
for(i=0;i<2;i++)
for(j=0;j<2;j++)
{
scanf("%f",&b[i][j]);
}
/* accessing corresponding elements of two arrays. */ for(i=0;i<2;i++)
for(j=0;j<2;j++)
{
c[i][j]=a[i][j]+b[i][j]; /* Sum of corresponding elements of two arrays. */
}
/* To display matrix sum in order. */
printf("\nSum Of Matrix:");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
printf("%f\t", c[i][j]);
printf("\n");
}
getch();
}
Example 2: Program for multiplication of two matrices
#include<stdio.h>
#include<conio.h>
int main()
{
int i,j,k;
int row1,col1,row2,col2,row3,col3;
int mat1[5][5], mat2[5][5], mat3[5][5];
clrscr();
Page 30
Data structures and Applications 18CS32
\n enter the nu
if(col1 != row2)
{
\n The number of columns in the first matrix must be equal to the number of rows
getch(); exit();
}
row3= row1; col3= col2;
\
for(i=0;i<row1;i++)
{
for(j=0;j<col1;j++)
[i][j]);
}
\
for(i=0;i<row2;i++)
{
for(j=0;j<col2;j++)
}
for(i=0;i<row3;i++)
{
for(j=0;j<col3;j++)
{
mat3[i][j]=0;
for(k=0;k<col3;k++)
mat3[i][j] +=mat1[i][k]*mat2[k][j];
}
}
prin \
for(i=0;i<row3;i++)
{
\
for(j=0;j<col3;j++)
\
}
Page 31
Data structures and Applications 18CS32
return 0;
}
Output:
Enter the number of rows in the first matrix: 2
Enter the number of columns in the first matrix: 2
Enter the number of rows in the second matrix: 2
Enter the number of columns in the second matrix: 2
Enter the elements of the first matrix
1234
Enter the elements of the second matrix
5678
The elements of the product matrix are
19 22
43 50
Page 32
Data structures and Applications 18CS32
if(n<1)
{
\
exit(EXIT_FAILURE);
}
MALLOC(list,n*sizeof(int));
This above main function fails only when n<1 or when sufficient memory is not allotted.
ptr=(int*)malloc(sizeof(int)*n);
if(ptr==NULL)
Page 33
Data structures and Applications 18CS32
{
\
return;
}
\
for(i=0;<n;i++)
\
for(i=0;i<n;i++)
getch();
}
x[0]
x[1]
x[2]
Figure 9: Two dimensional array
C finds the element x[i][j] by first accessing the point in x[i].this pointer gives the address in memory of
the zeroth element of row I of the array. Then by adding j*sizeof(int) to this pointer , the address of the
[j]th elemnt of row i is determined.
Example program for allocating memory dynamically for 2D array
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
void main()
{
int **a;
int p,q;
int **make2darray();
\
sc
\
a=make2darray(p,q);
getch();
Page 34
Data structures and Applications 18CS32
}
int **make2darray(int rows,int cols)
{
int **x,i;
x=malloc(rows*sizeof(*x));
for(i=0;i<rows;i++)
x[i]=malloc(cols*sizeof(**x));
return x;
}
2.4 APPLICATIONS OF ARRAYS
The two major applications of the arrays are polynomial and sparse matrix
1. POLYNOMIALS
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.
Examples :
A(x) = 3x20+2x5+4
B(x) = x4+10x3+3x2+1
The largest exponent of a polynomial is called its degree.
In the above example, degree of first polynomial is 20 and for the second polynomial it is 4.
Note: Coefficients that are zero are not displayed, the term with exponent zero does not show the
variable i.e. 4x2+5x+1 where 1 is a term having exponent zero so variable is not displayed.
Operations on polynomials
Addition
Subtraction
Multiplication
But division is not allowed.
Polynomial representation
In c, typedef is used to create the polynomial as below:-
#define MAX_DEGREE 101
typedef struct
{
int degree;
float coef[MAX_DEGREE];
}polynomial;
polynomial a;
Page 35
Data structures and Applications 18CS32
i
Conisder a is of type polynomial and n>MAX_DEGREE then polynomial ix for i=0 to n
would be represented as
a.degree=n;
a.coef[i]=an-i,0<=i<=n.
Page 36
Data structures and Applications 18CS32
Polynomial addition
Function which adds two polynomials A and B giving D, represented as D=A+B. using previous
polynomial representation the following figure 10 shows how two polynomials are represented
Ex: A(x)=2x1000+1
B(x) =x4-1+10x3+3x2+1
The index of the first term of A and B is given by startA and startB respectively,while finishA
and finishB give the index of the last term of A and B. the index of the next free location in the array is
given by avail.
Example startA=0,finishA=1,startB=2,finish=5 and avail=6.
This representation ha no limitation on the number of terms in a polynomial but total number of
non-zero terms should not exceed MAX_TERMS.
Poly is used to refer a polynomial and is translated poly into a <start,finish>pair. Any polynomial
A that has n nonzero terms has startA and finishA such that finishA=startA+n-1.
Function To Add Two Polynomials
void padd(int startA,int finishA,int startB, int finish,int *startD,int *FINISHd)
{
float coefficient;
*startd=avail;
while(startA<=finiSHs && startb<=finish)
switch(COMPARE(terms[startA].expon,terms[startB].expon))
{
case -1: /* a.expon<b.expon)*/
attach(terms[startB].coef,terms[startB].expon);
startB++;
break;
case 0:/* equal exponents*/
coefficient=terms[startA].coef+terms[startB].coef;
if(coefficient)
attach(coefficient , terms[startA].expon);
startA++;
startB++;
break;
case 1: /*a.expon>b.expon*/
attach(terms[startA].coef,terms[startA].expon);
startA++;
Page 37
Data structures and Applications 18CS32
}
for(;startA<=finishA;startA++)
attach(terms[startA].coef,terms[startA].expon);
for(;startB<=finishB;startB++)
attach(terms[startB].coef,terms[startB].expon);
*finishD=avail-1;
}
Function To Add a new term
void attach(float coefficient ,int exponent)
{
if(avail>=MAX_TERMS)
{
\
exit(0);
}
terms[avail].coef=coefficient;
terms[avail++].expon=exponent;
}
2. SPARSE MATRICES
Matrix contains m rows and n columns of elements. it has m rows and n columns. In general
mxn, is used to designate a matrix with m rows and n columns. The total no of elements in such matrix
is m*n. If m equals n then matrix is square.
A matrix containing more number of zero entries, such matrices is called as
In figure11, since this matrix contains many zeros it is called as sparse matrix. Here 8 of 36
elements are only having non-zero values so it is called as sparse matrix. When sparse matrix is
represented as two dimensional array hence space is wasted so need another form of representation to
save memory where only non-zero values are stored.
Page 38
Data structures and Applications 18CS32
Page 39
Data structures and Applications 18CS32
Transposing a Matrix
Transpose of a given matrix is obtained rows and columns. each element a[i][j].In the original
matrix becomes element b[j][i] in the transpose matrix.
The following algorithm is given by
The algorithm indicates that find all the elements in column 0 and store them in row 0 of the
transpose matrix, find all the elements in column1 and store them in row1 etc. Since the original matrix
ordered the rows, the columns within each row of incorporated in transpose. The first array a is the
original array which the second array b holds the transpose.(As shown in figure13)
Page 40
Data structures and Applications 18CS32
3. STRINGS
Strings are one-dimensional array of characters terminated by a null character '\0'. Thus a null-
terminated string contains the characters that comprise the string followed by a null. The following
declaration and initialization create a string consisting of the word "Hello". To hold the null character at
the end of the array, the size of the character array containing the string is one more than the number of
characters in the word "Hello."
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
If you follow the rule of array initialization then you can write the above statem
Page 41
Data structures and Applications 18CS32
#include <stdio.h>
int main ()
{
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
printf("Greeting message: %s\n", greeting );
return 0;
}
When the above code
Greeting message: Hello
ADT STRING
Objects: a finite set of zero or more characters
Functions:
For all s, t C string,i,j,m C non-negative intergers
String Null(m) = return a string whose maximum length is m characters , but is initally set to NULL we
Page 42
Data structures and Applications 18CS32
unction Description
char *strcat (char *dest, char *src) Concatenate dest and src strings; return result in
dest
char *strncat (char *dest, char *src, int n) Concatenate dest and n characters from src; return
result in dest
int strcmp (char *str1, char *str2) Compare 2 strings;
return < 0 if str1<str2;
0 if str1 = str2;
>0 if str1 > str2
int strncmp (char *str1, char *str2, int n) Compare first n characters;
return < 0 if str1<str2;
0 if str1 = str2;
>0 if str1 > str2
char *strcpy (char *dest, char *src) Copy src into dest; return dest
char *strncpy (char *dest, char *src, int n) Copy n characters from src into dest; return dest
size_t strlen (char *s)
char *strchr(char *s, int c) Return pointer to the first occurrence of c in s;
return NULL if not present
char *strrchr(char *s, int c) Return pointer to the last occurrence of c in s;
return NULL if not present
char *strtok(char *s, char *delimiters) Return a token from s;token is surrounded by
delimiters
char *strstr(char *s, char *pat) Return pointer to start of pat in s
size_t strspn (char *s, char *spanset) Scan s for characters in spanset; return length of
span
size_t strcspn (char *s, char *spanset) Scan s for characters not in spanset; return length
of span
char *strpbrk (char *s, char *spanset) Scan s for characters in spanset; return pointer to
first occurrence of a character from spanset
Page 43
Data structures and Applications 18CS32
#include <stdio.h>
#include <string.h>
int main ()
{
char str1[12] = "Hello";
char str2[12] = "World";
char str3[12];
int len ;
/* copy str1 into str3 */
strcpy(str3, str1);
printf("strcpy( str3, str1) : %s\n", str3 );
strcat( str1, str2);
printf("strcat( str1, str2): %s\n", str1 );
/* total lenghth of str1 after concatenation */
len = strlen(str1);
printf("strlen(str1) : %d\n", len );
return 0;
}
When the above code
strcpy( str3, str1) : Hello
strcat( str1, str2): HelloWorld
strlen(str1) : 10
STRING INSERTION FUNCTION
void strnins(char *s,char *t,int i)
{
Char string[MAX_SIZE],*temp = string;
if( i < 0 && i > strlen(s))
\
exit(EXIT_FAILURE);
}
if(! strlen(s))
strcpy(s,t);
else if if( strlen(t))
Page 44
Data structures and Applications 18CS32
{
strncpy(temp, s, i);
strcat(temp, t);
strcat(temp, (s+i));
strcpy(s,temp);
}
}
3.3 PATTERN MATCHING ALGORITHMS
C programming code to check if a given string is present in another string, For example the
string "programming" is present in "c programming". If the string is present then it's location (i.e. at
which position it is present) is printed. We create a function match which receives two character pointers
and return the position if matching occurs otherwise returns -1. naive string search algorithm is
implemented in this c program
Brute Force Pseudo-Code
-code
do
if (text letter == pattern letter)
compare next letter of pattern to next
letter of text
else
move pattern down text by one letter
while (entire pattern found or end of text)
1. PATTERN MATCHING BY CHECKING END INDICES FIRST
Page 45
Data structures and Applications 18CS32
{
int i = 0,j = 0;
int lens = strlen(string);
int lenp = strlen(pat);
while( i < lens && j < lenp)
{
if( string[i] == pat[j])
{
i++,j++;
}
else if(j == 0) j++;
else j = failure[j-1]+1;
}
return ( if(j == lenp) ? (i-lenp):-1);
}
Page 46
Data structures and Applications 18CS32
*pi=1024;
*pf=3.14;
free(pi);
free(pf);
getch();
}
it shows allocation and deallocation of memory
if((pi=(int *)malloc(sizeof(int))==NULL) || (pf=(float*)malloc(sizeof(float))==NULL))
{
exit(EXIT_FAILURE);
}
if(!(pi=malloc(sizeof(int))) || !(pf=malloc(sizeof(float)))
#define MALLOC(p,s)
If(!((p))=malloc(n,s))
{
exit(EXIT_FAILURE);
}
thus ,MALLOC(pi, sizeof(int));
MALLOC(pf,sizeof(float));
int *x;
x=calloc(n,sizeof(int));
Instead of calloc function a calloc macro can be defined as sown below
#define CALLOC(p,n,s)
if(!((p))=calloc(n,s))
{
exit(EXIT_FAILURE);
}
The function realloc resizes the memory allocated by either malloc or calloc.
Ex: realloc(p,s)
This realloc(p,s) function changes the size of the memory block pointed at p to s.the contents of
the first allocated s with oldsize bytes of the block are unchanged as a result of this resizing.when
s>oldsize the additional s-oldsize have an unspecified value and s<oldsize the rightmost oldsize-s bytes
of the old block are freed.when realloc is able to do the resizing it returns a pointer to the start of the
Page 47
Data structures and Applications 18CS32
new block and when it is unable to do the resizing the old block is unchanged and function returns the
value NULL.
#define REALLOC(p,s)
if(!((p))=realloc(p,s))
{
exit(EXIT_FAILURE);
}
The following functions are used in dynamic memory allocation and are defined in <stdlib.h>
1. malloc()
Declaration: void *malloc(size_t size); // ptr=(datatpe*)malloc(sizeof(datatype));
This function is used to allocate memory dynamically. The argument size specifies the number
of bytes to be allocated. On success, malloc() returns a pointer to the first byte of allocated memory. The
returned pointer is of type void, which can be type cast to appropriate type of pointer. The memory
allocated by malloc() contains garbage value .
2. calloc()
Declaration: void *calloc(size_t n,size_t size); //ptr=(datatype*)calloc(n,sizeof(datatype));
This function is used to allocate multiple blocks of memory. The first argument specifies the
number of blocks and the second one specifies the size of each block. The memory allocated by calloc()
is initialized to zero.
3. realloc()
Declaration: void *realloc(void *ptr,size_t newsize); //ptr=(datatype*)realloc(ptr,newsize)
The function realloc() is used to change the size of the memory block. It alters the size of the
memory block without losing the old data. This function takes two arguments, first is a pointer to the
block of memory that was previously allocated by malloc() or calloc() and second one is the new size for
that block.
4. free();
Declaration: void free(void *p); //free(ptr);
This function is used to release the memory space allocated dynamically. The memory released
by free() is made available to the heap again and can be used for some other purpose. We should not try
to free any memory location that was not allocated by malloc(), calloc() or realloc().
Page 48
Data structures and Applications 18CS32
C provides two additional Dynamic memory allocation functions calloc and realloc . The calloc function
allocates a user specified amount of memory and initializes the allocated memory to 0 , a pointer to the
start of the allocated memoey is returned. In case ther is insufficient memory to make the allocation , the
returned value is NULL.so, the example statements could be used to define a one dimensional array of
integers with the capacity of this array is n and x ranges from 0 to n-1 with initially 0 value.
The following program illustrates Dynamic memory allocation.
void main()
{
int *p,n,i;
/* If we
dynamically*/
if(p==NULL)
{
}
for(i=0;i<n;i++)
{
}
for(i=0;i<n;i++)
\ i));
}
PROGRAMMING EXAMPLES
1) Write a C program to sort N numbers in ascending order using Bubble sort and print both the
given and the sorted array
#include <stdio.h>
#define MAXSIZE 10
void main()
{
int array[MAXSIZE];
int i, j, num, temp;
Page 49
Data structures and Applications 18CS32
}
printf("Input array is \n");
for (i = 0; i < num; i++)
{
printf("%d\n", array[i]);
}
/* Bubble sorting begins */
for (i = 0; i < num; i++)
{
for (j = 0; j < (num - i - 1); j++)
{
if (array[j] > array[j + 1])
{
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
printf("Sorted array is...\n");
for (i = 0; i < num; i++)
{
printf("%d\n", array[i]);
}
}
2) Write a C program to input N numbers and store them in an array. Do a linear search for a
given key and report success or failure.
#include <stdio.h>
void main()
{
int array[10];
int i, num, keynum, found = 0;
clrscr();
printf("Enter the value of num \n");
scanf("%d", &num);
printf("Enter the elements one by one \n");
for (i = 0; i < num; i++)
{
scanf("%d", &array[i]);
}
printf("Input array is \n");
for (i = 0; i < num; i++)
{
printf("%d\n", array[i]);
}
printf("Enter the element to be searched \n");
scanf("%d", &keynum);
/* Linear search begins */
Page 50
Data structures and Applications 18CS32
3) Write a C program to input N numbers and store them in an array. Do a binary search for a
given key and report success or failure.
#include<stdio.h>
main()
{
int a[20],i,j,d,t,x,l=0,low,mid,high;
printf("\nEnter the number of elements\n");
scanf("%d",&d);
printf("Enter the numbers\n");
for(i=0;i<d;i++)
scanf("%d",&a[i]);
for(i=0;i<d;i++)
{
for(j=i+1;j<d;j++)
{
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
printf("\nThe sorted list :");
for(i=0;i<d;i++)
printf("%d ",a[i]);
printf("\nEnter the number to be searched\n");
scanf("%d",&x);
low=0;
high=d-1;
while(low<=high)
{
mid=(low+high)/2;
if(x<a[mid])
high=mid-1;
Page 51
Data structures and Applications 18CS32
else if(x>a[mid])
low=mid+1;
else
{
if(x==a[mid])
{
l++;
printf("The item %d is found at location %d\n",x,mid+1);
exit(0);
}
}
}
if(l==0)
printf("Item not found\n");
}
{
\
gets(stud.name);
}
else
{
\
}
\n e
\
else
Page 52
Data structures and Applications 18CS32
\
\
return 0;
}
ASSIGNMENT - I
Module-1
1. Define data structures. With a neat diagram, explain the different classifications of Data structures.
2. Define structure. How it is represented in C language. Give an example program using structures.
3. Differentiate structure and union.
4. What are self referential structures? Give one example.
5. Define nested structure. Give 2 ways of declaring nested structure with example program.
6. Define Array. Explain with program, the operations performed on array.
7. Write C programs to perform each of the following (i) linear search (ii) binary search (iii)bubble sort
taking a array of
8. Which are the 4 inbuilt functions to perform dynamic memory allocation. Discuss the importance of
Dynamic memory allocation. Write a C program to create an array dynamically.
9. Write a C function to create 2d array dynamically. Use MALLOC macro.
10. Illustrate with an example how sparse matrix is efficiently stored in triple format. Write its C
representation.
11. Write an ADT of Polynomial.
12. Write an ADT of Sparse Matrix
13. Define String. Write a C program to perform pattern matching.
14. Write a function to perform polynomial addition.
Module-2
15. Define Stack. List the operations performed on Stack.
16. Write an algorithm to convert infix expression to postfix expression.
17. Convert the below Expression to postfix using stack.(a+b)*((b^c)*f)/g
18. Define Recursion. Illustrate with an example how stack is used in recursion.
19. Write an algorithm for Evaluation of postfix expression.
20. Write a Recursive C program for each of the following:
(i) Tower of Hanoi
(ii) Computing GCD of two numbers.
(iii) Fibonacci series
(iv) To compute factorial of N.
Page 53