0% found this document useful (0 votes)
6 views

MODULE-I

Uploaded by

happy worker
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

MODULE-I

Uploaded by

happy worker
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

DATA STRUCTURES AND APPLICATIONS

MODULE-I
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. Multi-dimensional
Arrays, Polynomials and Sparse Matrices. Strings: Basic Terminology, Storing, Operations and Pattern Matching algorithms.
Programming Examples.
Introduction
In computer science, several data structures are known depending on area of applications. Of them, few data structures are there which
are frequently used almost in all application areas and with the help of which almost all complex data structure can be conducted.
These data structures are known as fundamental data structures or classic data structures.
A data structure is a scheme for organizing data in the memory of a computer. Some of the more commonly used data structures
include lists, arrays, stacks, queues, heaps, trees, and graphs.
The way in which the data is organized affects the performance of a program for different tasks. Computer programmers decide which
data structures to use based on the nature of the data and the processes that need to be performed on that data.
Definition:
A data structure is a specialized format for organizing and storing data. General data structure types include the array, the file, the
record, the table, the tree, and so on.
Example: A Queue
A queue is an example of commonly used simple data structure. A queue has beginning and end, called the front and back of the
queue.

Data enters the queue at one end and leaves at the other. Because of this, data exits the queue in the same order in which it enters the
queue, like people in a checkout line at a supermarket.
Example: A Binary Tree
A binary tree is another commonly used data structure. It is organized like an upside down tree. Each spot on the tree, called a node,
holds an item of data along with a left pointer and a right pointer.

S.TAMILARASAN Page 1
DATA STRUCTURES AND APPLICATIONS

The pointers are lined up so that the structure forms the upside down tree, with a single node at the top, called the root node, and
branches increasing on the left and right as you go down the tree.
Data Structures in Alice
Alice has two built-in data structures that can be used to organize data, or to create other data structures:
• Lists
• Arrays

Lists
A list is an ordered set of data. It is often used to store objects that are to be processed sequentially. A list can be used
to create a queue.
Arrays
An array is an indexed set of variables, such as dancer [1], dancer [2], dancer [3]… It is like a set of boxes that hold things.
A list is a set of items. An array is a set of variables that each stores an item.
Classifications (Primitive & Non Primitive)
The figure shows types of classical data structure

Figure: Classification of classic data structures


Primitive Data Structures

S.TAMILARASAN Page 2
DATA STRUCTURES AND APPLICATIONS

Primitive Data Structures are the basic data structures that directly operate upon the machine instructions .they have different
representations on different computers. Integers, Floating point numbers, Character constants, String constants and Pointers come
under this category.
Non-primitive Data Structures
Non-primitive data structures are more complicated data structures and are derived from primitive data structures. They emphasize on
grouping same or different data items with relationship between each data item. Arrays, Lists and Files come under this category.
Linear Data Structure:
A data structure is said to be linear if its elements form a sequence. The elements of linear data structure represent by means of
sequential memory locations. The other way is to have the linear relationship between the elements represented by means of pointers
or links.
Example: Array and Linked List.
Non-linear data structure:
A data structure is said to be non-linear if its elements show a hierarchical relationship between each other. All elements assign the
memory as random form and you can fetch data elements through random access process.
Example: Trees and Graphs.

Data structure Operations


Data are processed by means of certain operations which appearing in the data structure. Data has situation on depends largely on the
frequency with which specific operations are performed. This section introduces the reader to some of the most frequently used of
these operations.
(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.
Review of Arrays
Definition:
An array is a collection of homogeneous data items and accessed using a common name.
Properties of Array
 Array might be belonging to any of the data types
 Array might be belonging to any of the data types
 Array size must be a constant value.
 Always, Contiguous
Example:
 int a[10]; // integer array
 char b[10]; // character array i.e. string
Types of arrays:
 One dimensional array

S.TAMILARASAN Page 3
DATA STRUCTURES AND APPLICATIONS

 Multi-dimensional array
 Two dimensional array
 Three dimensional arrays, four dimensional array etc…
Single dimensional or one dimensional array
A one-dimensional array is a list of related variables. The general form of a one-dimensional array declaration is:
 type array-Name [ array-Size ];
 where type can be any valid C data type and The array-Size must be an integer constant greater than zero
 Example:
 int sample[10];
 float numbers[100];
 char name[40];
Storing Values in Arrays
The values can be stored in array using following three methods:
 Initialization
 Assigning values
 Input values from keyboard
Initialization of One-Dimensional Array
Syntax:
<data_type> <array_name> [array_size] = {v1, v2, v3}; where v1, v2, v3 are values.
Example:
 int num[5]={2,4,34,3,4};
The above code can be pictorially represented as shown below:

Example program
#include<stdio.h>
Void main ()
{
int num[5]={2,4,34,3,4};
clrscr();
printf("Value in array num[0] : %d \n", num[0]);
printf("Value in array num[1] : %d \n", num[1]);
printf("Value in array num[2] : %d \n", num[2]);
printf("Value in array num[3] : %d \n", num[3]);
printf("Value in array num[4] : %d ",num[4]);
getch();
}

S.TAMILARASAN Page 4
DATA STRUCTURES AND APPLICATIONS

Assigning values to One-Dimensional Array


 int num[5];
 num[0]=2; //value 2 stored in array “num” at position 0
 num[1]=4; //value 4 stored in array “num” at position 1
 num[2]=34; //value 34 stored in array “num” at position 2
 num[3]=3; //value 3 stored in array “num” at position 3
 num[4]=4; //value 4 stored in array “num” at position 4
Example Program:
#include<stdio.h>
 void main()
 {
 int num[5];
 num[0]=2;
 num[1]=4;
 num[2]=34; Output
 num[3]=3; Value in array num[0] : 2
 num[4]=4; Value in array num[1] : 3
 clrscr(); Value in array num[2] : 34
 printf("Value in array num[0] : %d \n", num[0]); Value in array num[3] : 3
 printf("Value in array num[1] : %d \n", num[1]); Value in array num[4] : 4
 printf("Value in array num[2] : %d \n", num[2]);
 printf("Value in array num[3] : %d \n", num[3]);
 printf("Value in array num[4] : %d ",num[4]);
 getch();
 }
Reading/Writing to One-Dimensional Array
Example: Output
int num[5]; Enter 5 numbers:
scanf("%d", &num[0]); //read data from keyboard into array num at position 0. 2
scanf("%d", &num[1]); //read data from keyboard into array num at position 1.
3
scanf("%d", &num[2]); //read data from keyboard into array num at position 2. 4
scanf("%d", &num[3]); //read data from keyboard into array num at position 3. 5
scanf("%d", &num[4]); //read data from keyboard into array num at position 4. 6
In general, to read 5 values, we can write as follows: Value in array num[0]:
for(i=0;i<5;i++) Value in array num[1]:
 { Value in array num[2]:
 scanf("%d", &num[i]); Value in array num[3]:
 } Value in array num[4]:
 Similarly, to display 5 elements stored in the array, we can
write:

S.TAMILARASAN Page 5
DATA STRUCTURES AND APPLICATIONS

 for(i=0;i<5;i++)
 {
 printf("%d", num[i]);
 }
Example Program
 #include<stdio.h>
 void main()
 {
 int num[5], i;
 printf("enter 5 numbers:\n”);
 for(i=0;i<5;i++)
 {
 scanf("%d", &num[i]);
 }
 for(i=0;i<5;i++)
 {
 printf("Value in array num[%d] : %d \n ", i, num[i]);
 }
 }
Structures
Definition:
A Structure is a user defined data type that can store related information together under a single name.
Basics of Structures
It is declared using a keyword struct followed by the name of the structure. The variables of the structure are declared within the
structure.
Syntax
struct structure_name
{
data_type member1;
data_type member2;
data_type member3;
};
The variables that are used to store the data are called members of the structure.
Example:
struct person
{
char name [50];
int cit_no;
float salary;
};
Structure variable Declaration
A structure can be declared using 2 methods:

S.TAMILARASAN Page 6
DATA STRUCTURES AND APPLICATIONS

 Tagged Structure
When a structure is defined, it creates a user-defined type but, no storage is allocated.
Example:
struct person
{
char name [50];
int cit_no;
float salary;
};
void main ()
{
struct person p1, p2;
}
 The variables p1 and p2 are variables of type struct person.
 Once the structure variable is declared, the compiler allocates memory for the structure variables.
 The size of the memory allocated is the sum of size of individual members.
Type definition
We can create structure variable using the keyword typedef
typedef struct person
{
char name [50];
int cit_no;
float salary;
} EMP;
void main ()
{
EMP p1, p2;
}
The variables p1 and p2 are the variables of type EMP
Structure Variable Initialization
struct person
{
char name [50];
int cit_no;
float salary;
};
struct person p1= {"ram", 24, 23000};
Structure within structure in C using pointer variable:
This program explains how to use structure within structure in C using pointer variable. “student_college_detail’ structure is
declared inside “student_detail” structure in this program. One normal structure variable and one pointer structure variable is used
S.TAMILARASAN Page 7
DATA STRUCTURES AND APPLICATIONS

in this program.
Please note that combination of. (dot) and -> (arrow) operators are used to access the structure member which is declared inside the
structure.
Example:

Self-Referential Structures
 A self-referential structure is one in which one or more of its components are a pointer to itself.
 These require dynamic storage management functions
typedef struct
{

S.TAMILARASAN Page 8
DATA STRUCTURES AND APPLICATIONS

char data;
struct list *link; //list is a pointer to a list structure
}list;
Consider three structures and values assigned to their respective fields
list item1,item2,item3;
item1.data='a';
item2.data='b';
item3.data='c';
item1.link=item2.link=item3.link=NULL;
We can attach these structures together as follows:
item1.link=&item2;
tem2.link=&item3;

Array of Structure
A structure is a group of related different data type variables. Sometimes we need multiple variables of structure for that we can
use the array of structure.
 For example we have structure of student. We want the list of students of entire class but one variable of structure can be
representing only one student. So, to represent entire class variable we have to use array of student structure.
 We can declare the array of structure as simply as other data type array. And same way to other data type we can use this
variable with the subscript.
struct arrayname [size];

Unions
S.TAMILARASAN Page 9
DATA STRUCTURES AND APPLICATIONS

A union is like a structure in which all members are stored at the same address. Members of a union can only be accessed one at a
time. The union data type was invented to prevent memory fragmentation. The union data type prevents fragmentation by creating
a standard size for certain data. Just like with structures, the members of unions can be accessed with the dot (.) and arrow (->)
operators. Take a look at this example:
#include<stdio.h> typedef union myunion
{
double PI; int B;
}MYUNION; int main()
{
MYUNION numbers; numbers.PI = 3.14; numbers.B = 50;
return 0;
}
If you would want to print the values of PI and B, only B value will be printed properly since single memory is reserved to hold the
data members’ value of union. Hence, 50 will be displayed correctly.
Differences between structures and unions

ber

S.TAMILARASAN Page 10
DATA STRUCTURES AND APPLICATIONS

Pointers and Dynamic Memory Allocation Functions


Pointers
A pointer is a variable that contains the address of a variable.
Or
A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any
variable or constant, you must declare a pointer before using it to store any variable address.
The general form of a pointer variable declaration is –
type *var-name;
Pointers and Addresses
 Every variable is a memory-location and every memory-location has its address defined which can be accessed using
ampersand (&) operator in contiguous groups.
 A typical machine has an array of consecutively numbered or addressed memory cells that may be manipulated
individually or in contiguous groups.
 One common situation is that any byte can be a char, a pair of one-byte cells can be treated as a short integer, and four
adjacent bytes form a long.
 A pointer is a group of cells (often two or four) that can hold an address. So if ‘c’ is a char and ‘p’ is a pointer that points
to it.

S.TAMILARASAN Page 11
DATA STRUCTURES AND APPLICATIONS

Example:
P = &c
 The statement assigns the address of c to the variable p, and p is said to ``point to'' c. The “&” operator only applies to
objects in memory: variables and array elements. It cannot be applied to expressions, constants, or register variables.
 The unary operator * is the indirection or dereferencing operator; when applied to a pointer, it accesses the object the
pointer points to. Suppose that x and y is integers and ip is a pointer to int. This artificial sequence shows how to declare a
pointer and how to use &and *:
 int x = 1, y = 2, z[10];
 int *ip; /* ip is a pointer to int */
 ip = &x; /* ip now points to x */
 y = *ip; /* y is now 1 */
 *ip = 0; /* x is now 0 */
 ip = &z[0]; /* ip now points to z[0] */
Example Program
#include<stdio.h>
Void main()
{
int var1;
char var2;
printf(“\n Address of var1 variable: %d\n”, &var1);
printf(“\n Address of var2 variable: %d\n”, &var2);
return 0;
}

Output
Address of var1 variable: 1266
Address of var2 variable: 1268
Example
#include<stdio.h>
void main
{
int *pc; int c; c=22;
printf(“\n Value of c: %d\n”, c);
pc=&c;
printf(“\n Address of pointer pc: %d\n”,pc);
printf(“\n "Content of pointer pc: %d",*pc)
}

S.TAMILARASAN Page 12
DATA STRUCTURES AND APPLICATIONS

Output:
Address of c: 1232
Value of c: 22
Address of pointer pc: 1232
Content of pointer pc: 22

Explanation of Program and Figure


 Code int* pc; creates a pointer pc and code int c; creates normal variable c
 Code c=22; makes the value of c equal to 22, i.e., 22 is stored in the memory-location of variable c.
 Code pc=&c; makes pointer, point to address of c. Note that, &c is the address of variable c (because c is normal variable)
and pc is the address of pc (because pc is the pointer-variable)
NULL Pointer
A NULL pointer is defined as a special pointer value that points to '\0’(nowhere) in the memory. In other words, NULL pointer
does not point to any part of the memory.
For ex:
int *p=NULL;
Dynamic Memory Allocation Functions
 Dynamic memory allocation is the process of allocating memory-space during execution-time i.e. run time.
 If there is an unpredictable storage requirement, then the dynamic allocation technique is used.
 This allocation technique uses predefined functions to allocate and release memory for data during execution time.
 There are 4 library functions for dynamic memory allocation:
 Malloc()
 Calloc()
 Realloc()
 Free()
 These library functions are defined under "stdlib.h"
malloc ()and free()
 The name malloc stands for "memory allocation".
 This function is used to allocate the requirement memory-space during execution-time.
 The syntax is shown below:
data_type *p;
p=( data_type*)malloc(size);

S.TAMILARASAN Page 13
DATA STRUCTURES AND APPLICATIONS

Example:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &num);

ptr = (int*) malloc(num * sizeof(int)); //memory allocated using malloc


if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i = 0; i < num; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
}
calloc() and free()
 The name calloc stands for "contiguous allocation".
 This function is used to allocate the required memory-size during execution-time and at the same time, automatically
initialize memory with 0's.
 The syntax:
data_type *p;
p=(data_type*)calloc(n,size);
 If memory is successfully allocated, then address of the first byte of allocated space is returned.
 If memory allocation fails, then NULL is returned.
 The allocated memory is initialized automatically to 0's.
 Example: ptr=(int*)calloc(25, size(int));
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &num);

S.TAMILARASAN Page 14
DATA STRUCTURES AND APPLICATIONS

ptr = (int*) calloc(num, sizeof(int));


if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i = 0; i < num; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
}
realloc()
If the previously allocated memory is insufficient or more than sufficient. Then, you can change memory-size previously
allocated using realloc()
Syntax: ptr=( data_type*)realloc(ptr,newsize);
Example:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr, i , n1, n2;
printf("Enter size of array: ");
scanf("%d", &n1);
ptr = (int*) malloc(n1 * sizeof(int));
printf("Address of previously allocated memory: ");
for(i = 0; i < n1; ++i)
printf("%u\t",ptr + i);
printf("\nEnter new size of array: ");
scanf("%d", &n2);
ptr = realloc(ptr, n2);
for(i = 0; i < n2; ++i)
printf("%u\t", ptr + i);
return 0;
}
free()
 Dynamically allocated memory with either calloc () or malloc()does not get return on its own.

S.TAMILARASAN Page 15
DATA STRUCTURES AND APPLICATIONS

 The Programmer must use free()explicitly to release space.


 The syntax: free(ptr);
 This statement causes the space in memory pointed by ptr to be deallocated.
Array Operations:
MENU DRIVEN PROGRAM TO PERFORM VARIOUS ARRAY OPERATIONS
——MENU——-
1.CREATE
2.DISPLAY
3.INSERT
4.DELETE
5.SEARCH
6.MERGE
7.SORT
8.EXIT

#include<stdio.h>
#include<stdlib.h>
int a[20],b[20],c[40];
int m,n,p,val,i,j,key,pos,temp;
/*Function Prototype*/
void create();
void display();
void insert();
void del();
void search();
void merge();
void sort();
int main()
{
int choice;
do{
printf("\n\n--------Menu-----------\n");
printf("1.Create\n");
printf("2.Display\n");
printf("3.Insert\n");
printf("4.Delete\n");
printf("5.Search\n");
printf("6.Sort\n");
S.TAMILARASAN Page 16
DATA STRUCTURES AND APPLICATIONS

printf("7.Merge\n");
printf("8.Exit\n");
printf("-----------------------");
printf("\nEnter your choice:\t");
scanf("%d",&choice);
switch(choice)
{
case 1: create();
break;
case 2:
display();
break;
case 3:
insert();
break;

case 4:
del();
break;
case 5:
search();
break;
case 6:
sort();
break;
case 7:
merge();
break;
case 8:
exit(0);
break;
default:
printf("\nInvalid choice:\n");
break;
}
}while(choice!=8);
return 0;
}

S.TAMILARASAN Page 17
DATA STRUCTURES AND APPLICATIONS

void create() //creating an array


{
printf("\nEnter the size of the array elements:\t");
scanf("%d",&n);
printf("\nEnter the elements for the array:\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
}//end of create()
void display() //displaying an array elements
{
int i;
printf("\nThe array elements are:\n");
for(i=0;i<n;i++){
printf("%d\t",a[i]);
}
}//end of display()
void insert() //inserting an element in to an array
{
printf("\nEnter the position for the new element:\t");
scanf("%d",&pos);
printf("\nEnter the element to be inserted :\t");
scanf("%d",&val);
for(i=n-1;i>=pos;i--)
{
a[i+1]=a[i];
}
a[pos]=val;
n=n+1;
}//end of insert()

void del() //deleting an array element


{
printf("\nEnter the position of the element to be deleted:\t");
scanf("%d",&pos);
val=a[pos];

S.TAMILARASAN Page 18
DATA STRUCTURES AND APPLICATIONS

for(i=pos;i<n-1;i++)
{
a[i]=a[i+1];
}
n=n-1;
printf("\nThe deleted element is =%d",val);
}//end of delete()
void search() //searching an array element
{
printf("\nEnter the element to be searched:\t");
scanf("%d",&key);
for(i=0;i<n;i++)
{
if(a[i]==key)
{
printf("\nThe element is present at position %d",i);
break;
}
}
if(i==n)
{
printf("\nThe search is unsuccessful");
}
}//end of serach()
void sort() //sorting the array elements
{
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++) { if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("\nAfter sorting the array elements are:\n");
display();

S.TAMILARASAN Page 19
DATA STRUCTURES AND APPLICATIONS

}//end of sort
void merge() //merging two arrays
{
printf("\nEnter the size of the second array:\t");
scanf("%d",&m);
printf("\nEnter the elements for the second array:\n");
for(i=0;i<m;i++)
{
scanf("%d",&b[i]);
}
for(i=0,j=0;i<n;i++,j++)
{
c[j]=a[i];
}
for(i=0;i<m;i++,j++)
{
c[j]=b[i];
}
p=n+m;
printf("\nArray elements after merging:\n");
for(i=0;i<p;i++)
{
printf("%d\t",c[i]);
}
}//end of merge()
Multidimensional Arrays
 Array having more than one subscript variable is called Multi-Dimensional array. Multi-Dimensional Array is also called as
Matrix.
 A two dimensional array is used when elements are arranged in a tabular fashion.
 Syntax:
 <data-type> <array_name> [row_subscript][column-subscript];
 Example:
 int matrix[2][3];
 Pictorially Representation

 Initialization of Two Dimensional Arrays

S.TAMILARASAN Page 20
DATA STRUCTURES AND APPLICATIONS

Example:
 int matrix[2][3]= {1, 23, 11, 44, 5, 6};

Reading/Writing to One-Dimensional Array


Example:
 int matrix[2][3]
 scanf("%d", &matrix[0][0]); //read data from keyboard into matrix at row=0 col=0.
 scanf("%d", &matrix[0][1]); //read data from keyboard into matrix at row=0 col=1.
 scanf("%d", &matrix[0][2]); //read data from keyboard into matrix at row=0 col=2.
 scanf("%d", &matrix[1][0]); //read data from keyboard into matrix at row=1 col=0.
 scanf("%d", &matrix[1][1]); //read data from keyboard into matrix at row=1 col=1.
 scanf("%d", &matrix[1][2]); //read data from keyboard into matrix at row=1 col=2.
In general, to read 6 values, we can write:
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
scanf("%d", &matrix[i][j]);
}
}
Similarly to display 6 elements stored in the matrix, we can write:
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf("%d ", matrix[i][j]);
}
}
Example Program
#include<stdio.h>
void main()
{
int matrix[2][3], i, j;
printf(“\n Enter the 2*3b matrix :\n”);
for(i=0; i<2; i++)
{
for (j=0; j<3; j++)
S.TAMILARASAN Page 21
DATA STRUCTURES AND APPLICATIONS

{
Scanf(“%d”, &matrix[1][j]);
}
}
printf("elements of the matrix are: \n”);
for(i=0; i<2; i++)
{
for (j=0; j<3; j++)
{
printf(“%d\t”, &matrix[1][j]);
}
Printf(“\n”);
}
}
Polynomials
Polynomials come under the section Algebra in Mathematics. A polynomial is an expression of finite length constructed from
variables, constants and non-negative integer exponents. The operations addition, subtraction and multiplication determine its entire
structure. Polynomials are used in a wide variety of problems where they are called as polynomial equations.
An example of a polynomial is 3x2+2x+7; here, the total number of terms is 3. The coefficients of each term are 3, 2, 7 and degrees 2,
1, 0 respectively.
While adding two polynomials, following cases need to be considered.
When the degrees of corresponding terms of the two polynomials are same:
This is the normal case when corresponding coefficients of each term can be added directly. For example, the sum of the polynomials
5x3+2x2+7
7x3+9x2+12
-------------------
12x3+11x2+19
---------------------- is a simple addition where all the degrees of the corresponding terms are same. 2. When the degrees of
corresponding terms of the polynomials are different:
Here, the term with the larger degree pre-dominates.
9x4+5x3+ +2x
3x4+ +4x2+7x
------------------------
12x4+5x3+4x2+9x
---------------------------
Program to find the value of the polynomial f(x)=a4x4+a3x3+a2x2+a1x+a0 using Horner’s method
#include "stdio.h"
#include "conio.h"
void main()

S.TAMILARASAN Page 22
DATA STRUCTURES AND APPLICATIONS

{
float a[100],sum=0,x;
int n,i;
clrscr();
printf("Enter the degree of the polynomial:");
scanf("%d",&n);
printf("Enter the coefficients into the array:");
for(i=n;i>=0;i--)
{
scanf("%f",&a[i]);
}
printf("Enter the value of x:");
scanf("%f",&x);
for(i=n;i>0;i--)
{
sum=(sum+a[i])*x;
}
sum=sum+a[0];
printf("\nValue of the polynomial is =%f",sum);
getch();
}
Output
Enter the degree of the polynomial:
4
Enter the coefficients into the array:
3
2
1
1
2
Enter the value of x:
2
Value of the polynomial is:72.000000
This C Program evaluates the given polynomial equation. The polynomial equation formula is P(x)=AnXn + An-1Xn-1 + An-
2Xn-2+… +A1X + A0.
1. /*
2. * C program to evaluate a given polynomial by reading its coefficients
3. * in an array.
4. * P(x) = AnXn + An-1Xn-1 + An-2Xn-2+... +A1X + A0

S.TAMILARASAN Page 23
DATA STRUCTURES AND APPLICATIONS

5. *
6. * The polynomial can be written as:
7. * P(x) = A0 + X(A1 + X(A2 + X(A3 + X(Q4 + X(...X(An-1 + XAn))))
8. * and evaluated starting from the inner loop
9. */
10. #include <stdio.h>
11. #include <stdlib.h>
12. #define MAXSIZE 10
13.
14. void main()
15. {
16. int array[MAXSIZE];
17. int i, num, power;
18. float x, polySum;
19.
20. printf("Enter the order of the polynomial \n");
21. scanf("%d", &num);
22. printf("Enter the value of x \n");
23. scanf("%f", &x);
24. /* Read the coefficients into an array */
25. printf("Enter %d coefficients \n", num + 1);
26. for (i = 0; i <= num; i++)
27. {
28. scanf("%d", &array[i]);
29. }
30. polySum = array[0];
31. for (i = 1; i <= num; i++)
32. {
33. polySum = polySum * x + array[i];
34. }
35. power = num;
36.
37. printf("Given polynomial is: \n");
38. for (i = 0; i <= num; i++)
39. {
40. if (power < 0)
41. {
42. break;
43. }
44. /* printing proper polynomial function */
45. if (array[i] > 0)
46. printf(" + ");
47. else if (array[i] < 0)
48. printf(" - ");
49. else
50. printf(" ");
51. printf("%dx^%d ", abs(array[i]), power--);
52. }

S.TAMILARASAN Page 24
DATA STRUCTURES AND APPLICATIONS

53. printf("\n Sum of the polynomial = %6.2f \n", polySum);


54. }
Output
Enter the order of the polynomial
2
Enter the value of x
2
Enter 3 coefficients
3
2
6
Given polynomial is:
+ 3x^2 + 2x^1 + 6x^0
Sum of the polynomial = 22.00
Sparse Matrices
A matrix is a two-dimensional data object made of m rows and n columns, therefore having total m x n values. If most of the
elements of the matrix have 0 value, then it is called a sparse matrix.
Sparse matrix is a matrix which contains very few non-zero elements.
When a sparse matrix is represented with 2-dimensional array, we waste lot of space to represent that matrix. For example, consider a
matrix of size 100 X 100 containing only 10 non-zero elements. In this matrix, only 10 spaces are filled with non-zero values and
remaining spaces of matrix are filled with zero. That means, totally we allocate 100 X 100 X 2 = 20000 bytes of space to store this
integer matrix. And to access these 10 non-zero elements we have to make scanning for 10000 times.
A sparse matrix can be represented by using TWO representations, those are as follows...
1. Triplet Representation
2. Linked Representation
Triplet Representation
In this representation, we consider only non-zero values along with their row and column index values. In this representation, the 0 th
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
image.
In below 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.
000090
080000
400200 Sparse Matrix
000005
002000

S.TAMILARASAN Page 25
DATA STRUCTURES AND APPLICATIONS

Triplet representation as shown in the figure

Row Columns Values


5 6 6
0 4 9
1 1 8
2 0 4
2 3 2
3 5 5
4 2 2

Transposing a matrix
To transpose a matrix we must interchange the rows and columns. This means that each element a[i][j] in the original matrix becomes
element b[j][i] in the transpose matrix.

Row Columns Values


6 5 6
0 2 4
1 1 8
2 4 2
3 2 2
3 5 5
4 0 9

Program
#define MAX 20

void read_matrix(int a[10][10], int row, int column);


void print_sparse(int b[MAX][3]);
void create_sparse(int a[10][10], int row, int column, int b[MAX][3]);

int main()
{
int a[10][10], b[MAX][3], row, column;
printf("\nEnter the size of matrix (rows, columns): ");
scanf("%d%d", &row, &column);

read_matrix(a, row, column);

S.TAMILARASAN Page 26
DATA STRUCTURES AND APPLICATIONS

create_sparse(a, row, column, b);


print_sparse(b);
return 0;
}

void read_matrix(int a[10][10], int row, int column)


{
int i, j;
printf("\nEnter elements of matrix\n");
for (i = 0; i < row; i++)
{
for (j = 0; j < column; j++)
{
printf("[%d][%d]: ", i, j);
scanf("%d", &a[i][j]);
}
}
}

void create_sparse(int a[10][10], int row, int column, int b[MAX][3])


{
int i, j, k;
k = 1;
b[0][0] = row;
b[0][1] = column;
for (i = 0; i < row; i++)
{
for (j = 0; j < column; j++)
{
if (a[i][j] != 0)
{
b[k][0] = i;
b[k][1] = j;
b[k][2] = a[i][j];
k++;
}
}
b[0][2] = k - 1;

S.TAMILARASAN Page 27
DATA STRUCTURES AND APPLICATIONS

}
}

void print_sparse(int b[MAX][3])


{
int i, column;
column = b[0][2];
printf("\nSparse form - list of 3 triples\n\n");
for (i = 0; i <= column; i++)
{
printf("%d\t%d\t%d\n", b[i][0], b[i][1], b[i][2]);
}
}
Strings:
A string is a series of characters treated as a single unit. A string may include letters, digits and various special characters such as +, -,
*, / and $. String literals or string constants in C are written in double quotation marks.
Example:
 “1000 Main Street” (a street address)
 In C language strings are stored in array of char type along with null terminating character ‘\0’ at the end.
 When sizing the string array we need to add plus one to the actual size of the string to make space for the null terminating
character, ‘\0’
Example:
. char fname[4];
 The above statement declares a string called fname that can take up to 3 characters. It can be indexed just as a
regular array as well.
 fname[]={‘t’,’w’,’o’};

character t w o \0
ASCII 116 119 41 0
Syntax:
 char str[size];

Initialization of String
 Example:
 char s[5]={'r', 'a', 'm', 'a' };
 char s[9]="rama";
 The above code can be pictorially represented as shown below:
s[0] s[1] s[2] s[3] s[4]
r a m a \0

S.TAMILARASAN Page 28
DATA STRUCTURES AND APPLICATIONS

Example Program:
 #include<stdio.h>
 void main()
 {
 char s[5]={'r','a','m','a'}; //or char s[5]="rama";
 printf("Value in array s[0] : %c \n", s[0]);
 printf("Value in array s[1] : %c \n", s[1]);
 printf("Value in array s[2] : %c \n", s[2]);
 printf("Value in array s[3] : %c\n ", s[3]);
 }

Reading & Printing Strings

The strings can be read from the keyboard and can be displayed onto the monitor using following two formatted functions:
 Formatted input function: scanf()
 Formatted output function: printf()
Example Program
#include<stdio.h>
void main()
{
char name[10];
printf(“Enter your name: \n”);
scanf(“%s”, name);
printf(“welcome: ”);
printf(“%s”, name);
}

String Manipulation Functions from the Standard Library


 Strings are frequently needed to be manipulated by programmer according to the need of a problem.
 All string manipulation can be done manually by the programmer but, this makes programming complex and large. C
programming offers more string handling functions through <string.h> header file.

S.N Function Purpose


1. strcpy(s1, s2) Copies string s2 into s1
strcat(s1, s2) Concatenates string s2 onto the end of string s1
strcmp(s1, s2) Returns 0; if s1 and s2 are same; less than zero if s1<s2; greater than zero if s1>s2
strlen(s) Returns the length of string s
strchr(s, int c) Find a character in string
strstr(s1, s2) Find string s2 in string s1

S.TAMILARASAN Page 29
DATA STRUCTURES AND APPLICATIONS

strlen()
This function calculates the length of string. It takes only one argument, i.e., string-name. (OR)
 It is used to return the length of a string.
 syntax
 temp_variable = strlen (string_name);

Example program
 #include<string.h>
 #include<stdio.h>
 void main()
 {
 char c[20];
 int len;
 printf("Enter string whose length is to be found:");
 gets(c);
 len=strlen(c);
 printf("\n Length of the string :=%d ", len);
 }
strcpy()
 This function copies the content of one string to the content of another string. It takes 2 arguments. (OR)
 It is used to copy one string to another string. The content of the second string is copied to the content of the first string.
 syntax
 strcpy(destination, source);
 Where source and destination are both the name of the string.

Example Program
 #include<string.h>
 #include<stdio.h>
 void main()
 {
• char src[20],dest[20];
• printf("Enter string: ");
• gets(src);
• strcpy(dest, src); //Content of string src is copied to string dest
• printf("Copied string: ");
• puts(dest);
 }
strcat()
It is used to concatenate i.e., combine the content of two strings. (OR)

S.TAMILARASAN Page 30
DATA STRUCTURES AND APPLICATIONS

 This function joins 2 strings. It takes two arguments, i.e., 2 strings and resultant string is stored in the first string
specified in the argument.
 Syntax:
o strcat(first_string,second_string);
Example Program:
#include<stdio.h>
#include<string.h>
void main()
{
char str1[10], str2[10};
printf("Enter First String:");
gets(str1);
printf(“Enter Second String:”);
gets(str2);
printf("\n Enter Second String:");
gets(str2);
strcat(str1,str2); //concatenates str1 and str2 and
printf("\n Concatenated String is:= ");
puts(str1); //resultant string is stored in str1
}
strcmp()
This function compares 2 string and returns value 0, if the 2 strings are equal. It takes 2 arguments, i.e., name of two strings to
compare.(OR)
It is used to compare the contents of the two strings. If any mismatch occurs then it results the difference of ASCII
values between the first occurrences of 2 different characters.
 Syntax:
 strcmp(string 1, string 2);
 Example Program:
 #include <string.h>
 #include<stdio.h>
 void main()
{
 char str1[30],str2[30];
 printf("Enter first string: ");
 gets(str1);
 printf ("Enter second string: ");
 gets(str2);
 if(strcmp(str1,str2)==0)
 printf("Both strings are equal");
 else
 printf("Strings are unequal");

S.TAMILARASAN Page 31
DATA STRUCTURES AND APPLICATIONS

 }
Pattern Matching
 String matching is a most important problem.
 String matching consists of searching a query string (or pattern) P in a given text T.
 Generally the size of the pattern to be searched is smaller than the given text.
 There may be more than one occurrences of the pattern P in the text T. Sometimes we have to find all the occurrences of the pattern
in the text.
 There are several applications of the string matching. Some of these are
 Text editors
 Search engines
 Biological applications
 Since string-matching algorithms are used extensively, these should be efficient in terms of time and space.
 Let P [1..m] is the pattern to be searched and its size is m.
 T [1..n] is the given text whose size is n
 Assume that the pattern occurs in T at position (or shift) i. Then the output of the matching algorithm will be the integer i where 1
<= i <= n-m. If there are multiple occurrences of the pattern in the text, then sometimes it is required to output all the shifts where
the pattern occurs.

Let Pattern P = CAT


Text = ABABNACATMAN Then there is a match with the shift 7 in the text T

Brute Force String Matching algorithm.


 This algorithm is a simple and obvious one, in which we compare a given pattern P with each of the sub strings of the text T,
moving from left to right, until a match is found
 Let Si is the substring of T, beginning at the i th position and whose length is same as pattern P.
 We compare P, character by character, with the first substring S1. If all the corresponding characters are same, then the
pattern P appears in T at shift 1. If some of the characters of S1 are not matched with he corresponding characters of P, then
we try for the next substring S2. This procedure continues till the input text exhausts.
 In this algorithm we have to compare P with n-m+1 substrings of T.
 Example
 Let P=abc
 T= aabab
 Compare P with 1st substring of T

S.TAMILARASAN Page 32
DATA STRUCTURES AND APPLICATIONS

 Mismatch at the second character of T


 Compare P with 2nd substring of T

 Scince the corresponding character are same, there is a match at shift 1.


 Compare P with 3rd substring of T

Mismatch at the 3rd character of T

Algorithm For Brute-Force String matching


 Let P[0..m] is the given pattern and T[0..n] is the text.

1. i = 1; [ substring 1]
2. Repeat steps 3 to 5 while i <=n-m+1 do
3. for j= 1 to m [For each character of P]

If P[j] != T[i+j-1] then


goto step 5

4. Print "Pattern found at shift i "


5. i= i + 1
6. exit

 The complexity of the brute force string matching algorithm is O(nm)


 On average the inner loop runs fewer than m times to know that there is a mismatch.
 The worst case situation arises when first m character are matched for all substrings Si. If pattern is of the am-1b and text is of the
form an-1b, where an-1 denotes a repeated n -1 times. In this case the inner loop runs exactly for m times before knowing that
there is a mismatch. In this situation there will be exactly m*(n-m+1) number of comparisons.
//Implementation
#include<stdio.h>
#include<conio.h>
char Mainstr[100],Pat[100],Replace[100],ans[100];
int i,j,c,m,k;

S.TAMILARASAN Page 33
DATA STRUCTURES AND APPLICATIONS

void read()
{
printf("\nEnter a string \n");
gets(Mainstr);
printf("\nEnter a search string \n");
flushall();
gets(Pat);
printf("\nEnter a replace string \n");
flushall();
gets(Replace);
}
void find_replace()
{
i = m = c = j = 0;
while ( Mainstr[c] != '\0')
{
if ( Mainstr[m] == Pat[i] ) // ...... matching
{
i++;
m++;
if ( Pat[i] == '\0') //.....found occ
{
//.... copy replace string in ans string .....
for(k=0; Replace[k] != '\0';k++,j++) {
ans[j] = Replace[k];}
i=0;
c=m;
}
}
else //... mismatch
{
ans[j] = Mainstr[c];
j++;
c++;
m = c;
i=0;
}
}
ans[j] = '\0';
printf("\nThe resultant string is\n%s" ,ans);
}
void main()
{
clrscr();
read();
find_replace();
getch();

S.TAMILARASAN Page 34
DATA STRUCTURES AND APPLICATIONS

/* Output
Enter a string
Respected Sir
Enter a search string
Respected
Enter a replace string
Dear
The resultant string is
Dear Sir

S.TAMILARASAN Page 35
DATA STRUCTURES AND APPLICATIONS

Model Questions

1. What do you mean by Data Structure? What are the various operations performed on data structures? Explain
2. What are the various types of data structures? Brief with an example
3. Differentiate between linear and non – linear data structures
4. Declare and use a data structure in C for maintaining student details
5. Explain declaring pointer to structure with an example
6. How do we access data members of structure and structure with a pointer? Examples?
7. Define Unions with an example
8. Compare structures and unions with an example
9. What are the advantages of using unions?
10. What do you mean by self-referential structures? Explain with an example
11. What is a sparse matrix? Brief it with an example
12. Write a C program to check whether input matrix is a sparse or not
13. What are polynomials? Brief it with an example
14. Write a C program to add two polynomials
15. Define Array. Explain how one – dimensional arrays are declared and initialized with an example
16. Explain how one – dimensional arrays are declared and initialized with an example
17. Write a C program to perform basic operations on single dimensional array
18. Differentiate between array and a structure
19. Compare Single and Multi – Dimensional arrays
20. List some of the applications of arrays
21. Define String. Explain how a string can be declared and initialized with an example
22. List different string manipulation functions. Explain them along with syntax
23. Illustrate string manipulation functions with examples
24. What do you mean by dynamic memory allocation? Explain various functions under it

S.TAMILARASAN Page 36

You might also like