0% found this document useful (0 votes)
20 views60 pages

1st Module

Os notes of 3rd sem cse

Uploaded by

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

1st Module

Os notes of 3rd sem cse

Uploaded by

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

Data Structures and Applications Dept of CS&D

MODULE 1
INTRODUCTION TO DATA STRUCTURES

1.1 Data Structures

• “A data structure is a method of storing and organizing the data in a computer so that
it can be used efficiently”.

• Data Structure is a way of collecting and organizing data in such a way that we can
perform operations on these data in an effective way.

• Data Structures is about rendering data elements in terms of some relationship, for better
organization and storage.

• If the data contains a single value, then it can be represented using primitive data types.

• If the data contains set of values, then it can be represented using non-primitive data
types.

Need for Data Structures

The computers are electronics data processing machines. In order to solve a particular problem
we need to know:
1. How to represent data in a computer.
2. How to access them.
3. What are the steps to be performed in order to get the needed output.

These tasks can be achieved with the knowledge of Data structures & Algorithms.

1
Data Structures and Applications Dept of CS&D

The Study of data structure includes

1. Defining operations that can be performed on data.


2. Representing data in the memory.
3. Determining the amount of memory required to store the data.
4. Determining the amount of time needed to process the data.

1.2 Classification of Data Structures

The data structures can be classified as shown below:

Integer
Primitive Floating Point

Character

Double

Pointer

Data Structure

Arrays

Stacks
Linear
Queues

Linked List

Non-Primitive

Trees
2
Non-Linear

Graphs
Data Structures and Applications Dept of CS&D

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 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.
A data structure is said to be linear if its elements form a sequence or a linear list. The
linear data structures like an array, stacks, queues and linked lists organize data in linear order.

There are basically four ways of representing such linear structure in memory.
1. Arrays: An array is a collection of similar type of items (elements) stored sequentially
(continuously) one after the other in memory.
2. Stack: A stack is an ordered list in which insertions and deletions are made at one end called
the top.
3. Queue: A queue is an ordered list in which insertions and deletions take place at different
ends.”
4. Linked list: Linked list is a linear data structure that consists of a sequence of elements where
each element comprises of two items - the data and a reference (link) to the next node

A data structure is said to be non-linear if the data are not arranged in sequence or linear.
The insertion and deletion of data is not possible in linear fashion. i.e.,elements form a
hierarchical classification where, data items appear at various levels.

1.Trees: Tree is a non-linear data structure which organizes data in hierarchical fashion and the
tree structure follows a recursive pattern of organizing and storing data.
2. Graph: It is basically a collection of vertices (also called nodes) and edges that connect these
vertices.

3
Data Structures and Applications Dept of CS&D

1.3 Data Structures Operations

1. Traversing: It is used to access each data item exactly once so that it can be processed.
2. Searching: It is used to find the location of the data item with a given key value or finding the
locations of all data which satisfy one or more conditions.
3. Inserting: It is used to add a new data item in the given collection of data items.
4. Deleting: It is used to delete an existing data item from the given collection of data items.
5. Sorting: It is used to arrange the data items in some logical order. e.g., in ascending or
descending order in case of numerical data and in dictionary order in case of alphanumeric data.
6. Merging: It is used to combine the data items of two sorted files into single file in the sorted
form.

1.4 Review of Arrays

1.4.1 Arrays

An Array is a special and powerful data structure and it is used to store, process and print large
amounts of data.
“An array is a collection of similar type of items (elements) stored sequentially
(continuously) one after the other in memory”.

Ex: 1. int A[5] ; // Array of 5 Integers

A[0] 10
A[1] 20
A[2] 30
A[3] 40
A[4] 50

The Elements in the Array A can be accessed using the common name A, but with different
index.
The Element “10” is called 0th Element and it can be accessed using the Subscript 0 (called
Index “0”) along with name of the array “A”.

4
Data Structures and Applications Dept of CS&D

An “Index” is also called as Subscript ([ ]). It is used to indicate the position of an


element in the Array.
Basic Properties of the Arrays
1. All the elements in an array should be of the same data type.
2. The elements are stored continuously in the memory. (For example, in the array char B[5] , if
the first address is 1000 then the data is stored contiguously in the addresses 1000, 1001, 1002 and
so on).
3. The Subscript (index) of first item is always zero.
4. Each element of an array is accessed using the name of the Array, but with different subscript.
5. The Index of the Array is always an Integer number can’t be float.
Ex: a [1] or a [5].
a [1.5] is an Error.

1.4.2 Classification of Arrays

1. Single Dimensional Array


2. Multi-Dimensional Array

1. Single Dimensional Array


Definition:
Single dimensional array (One-dimensional array) is a linear list consisting of related
data items of same data type and in the memory, all the data items are stored contiguously
in memory locations one after the other.
Or
An array with one index is called as Single dimensional array (One-dimensional array)

Declaration of Single dimensional arrays


• As we declare the variables before they are used in a program, an array must also be
declared and defined before it is used using following syntax.

Syntax data_type array _name[size];

Where,
data_type: data type can be int, float, char etc.
array_name: name of the array which is a valid C variable.
size: it is the number of elements in the array.
Complete declaration ends with Semicolon.

5
Data Structures and Applications Dept of CS&D

Complete declaration ends with Semicolon. Ex: int Marks[5];


Declares Marks as an array consisting of 5 elements of integer data type.
Ex: int Marks[5];
Declares Marks as an array consisting of 5 elements of integer data type.

Ex: int Marks[5];


1000 45 Marks[0]
1002 55 Marks[1]
1003 65 Marks[2]
data type array_name 1004 75 Marks[3]
1005 85 Marks[4]

char name[5];

Memory Location Array Name

• 5 memory locations are reserved. sizeof(int) is 2 bytes, 2*5=10 bytes are


reserved.
• 5 memory locations are reserved. sizeof(char) is 1 bytes 1*5=5 bytes are
reserved.

Initialization of Single dimensional arrays


• Once an array is declared it must be initialized with some values using
Initialization.
“Process of assigning the values to the individual elements of an array is called as
Initialization of an array”.

Syntax data_type array_name[size]={v1,v2, ---- ,vn};

6
Data Structures and Applications Dept of CS&D

data_type: it can be int, float, char etc.


array_name: it is the name of the array.
size: it is the number of elements in the array.
v1,v2, ---- ,vn are the values and should be enclosed within „{„ and „}‟ separated by commas.

Ex: 1. int a[5] = {10, 20, 30, 40, 50};


The compiler allocates 5 memory locations and these locations are initialized with the integer
values in the order specified.

A[0] 10
A[1] 20
A[2] 30
A[3] 40
A[4] 50

Address Calculation in single (one) Dimension Arrays:


If the memory address of list[i] needs to be computed, then the size of the int would get by sizeof
(int), then memory address of list[i] is as follows:

list[i] = α + i * sizeof(int)
Where, α is base address.

list[3]= α + i * sizeof(int) list[0] list[1] list[2] list[3] list[4]


list[3]= α+3*sizeof(4)
= 2000+3*4
= 2012 2000 2004 2008 2012 2014

• For example, an array of 10 integer variables, with indices 0 through 9,


may be stored as 10 words at memory addresses 2000, 2004, 2008, ........ 2036, so that the
element with index i has the address 2000 + i× 4.[hereα is base address whose value is 2000
and sizeof (int) is4]

• For i=0,1,2… (size of int is 4 bytes(32bit machine))

7
Data Structures and Applications Dept of CS&D

1.4.3 Representation of Linear Arrays in Memory

A linear array is a list of homogeneous data element such that

a. The elements of the array are referenced respectively by an index set consisting of n
consecutive numbers.
b. The elements of the array are respectively in successive memory locations.
The number n of elements is called the length or size of the array. The length or the numbers of
elements of the array can be obtained from the index set by the formula

When LB = 0,
Length = UB – LB + 1
When LB = 1,
Length = UB

Where,
UB is the largest index called the Upper Bound
LB is the smallest index, called the Lower Bound

1.4.4 Representation of linear arrays in memory


Let LA be a linear array in the memory of the computer. The memory of the computer is simply
a sequence of address location as shown below:

1000
2000
3000
4000
5000

LOC (LA [K]) = address of the element LA [K] of the array LA


• The elements of LA are stored in successive memory cells.
• The computer does not keep track of the address of every element of LA,
but needs to keep track only the address of the first element of LA denoted by,
• Base (LA) and called the base address of LA.
• Using the base address of LA, the computer calculates the address of any
element of LAby the formula

LOC (LA[K]) = Base(LA) + w(K – lower bound)


Where, w is the number of words per memory cell for the array LA.
8
Data Structures and Applications Dept of CS&D

1.5 Array Operations

1.5.1 Traversing
Let array A be a collection of data elements stored in the memory of the computer. Suppose
if the contents of the each elements of array A needs to be printed or to count the numbers of
elements of array A it can be accomplished by Traversing.
Traversing is a accessing and processing each element in the array exactly once.

If you want to read n data items from the keyboard, the following statement can be used:

for(i=0;i<5;i++)
{
scanf(“%d”,&a[i]);
}
//If you want to print „n‟ data items from the keyboard, the following statement can be used:
for(i=0;i<5;i++)

{
printf(“%d\n”, a[i]);
}

1.5.2 Inserting
• Let A be a collection of data elements stored in the memory of the
computer. Inserting refers to the operation of adding another element to the array A.
• Inserting an element at the “end” of the linear array can be easily done
provided the memory space allocated for the array is large enough to accommodate the additional
element.
• Inserting an element in the middle of the array, then on average, half of
the elements must be moved downwards to new locations to accommodate the new element and
keep the order of the other elements.

Algorithm:
1. Start
2. Read pos, elem.
3. Create space for item to insert at position

for(i=n-1;i>=pos;i- -)
{
A[i+1] = A[i];
}
9
Data Structures and Applications Dept of CS&D

4. Insert item at the specified position


A[pos] = elem;

5. Update number of elements in the array


n=n+1;

6. Stop

Example: Let us consider an array Int A[5]={10,20,30,40,50};

Int A[5]={10,20,30,40,50};

A [0] A [1] A [2] A [3] A [4]


10 20 30 40 50

Let us consider an example of insertion of element 100 at position 3 i..e

ITEM=100 and pos=3 and n=5

Iteration 1: i = 4, a[5] = a[4]


A [0] A [1] A [2] A [3] A [4] A[5]
10 20 30 40 50 50

Iteration 2: i = 3, a[4] = a[3]


A [0] A [1] A [2] A [3] A [4] A[5]
10 20 30 40 40 50

Iteration 3: i=2, i>=pos,i-- //Condition fail


A[3]=100 //insert element to pos=3
A [0] A [1] A [2] A [3] A [4] A[5]
10 20 30 100 40 50

Iteration 4: Update number of elements in the array n=6

10
Data Structures and Applications Dept of CS&D

1.5.3 Deletion

Deleting refers to the operation of removing one element from the array A with specified position.

Algorithm:
1. Start

2. Read pos.

3. Move the elements towards left


for(i=pos ; i< n-1; i++)
{
A[i] = A[i+1];
}

4. Display deleted element at the specified position elem = a[pos];

5. Decrement the number of elements in the array


n=n-1;

6. Stop

Example: Let us consider an array, int A[5]={10,20,30,100,40,50};


A[0] A[1] A[2] A [3] A [4] A[5]
10 20 30 100 40 50

Let us consider an example of deleting an element 100 at position 3


i.e. ITEM=100 and K=3 and N=5

Iteration 1: i = 3, a[3] = a[4]


A[0] A[1] A[2] A [3] A [4] A[5]
10 20 30 40 40 50

11
Data Structures and Applications Dept of CS&D

Iteration 2: i = 4, a[4] = a[5]


A[0] A[1] A[2] A [3] A [4] A[5]
10 20 30 40 50 50

Iteration 3: i = 5, i<4 condition failed

Iteration 4: decrement the number of elements in the array n=5

1.6 Two dimensional arrays (Multi-dimensional arrays)

• Arrays which are specified with 2 subscripts (2 set of square bracket


[ ][ ]) are called 2- dimensional arrays.
• Arrays with two or more dimensions are called Multi-dimensional
arrays.
• In 2-Dimensional Array, the first index indicates the „row size‟( the
number of rows) and second index indicates the „column size‟( the number of columns).
Ex: int a[10][10]; //Two-dimensional array int b[3][4][5]; //Three-dimensional array

Declaration of Two-dimensional arrays


• As we declare the variables before they are used in a program, an array
must also be declared before it is used using the following syntax.

Syntax data_type array_name [row_size][col_size];

data_type: It can be int, float, char etc.


array_name: It is the name of the array.
row_size: It is the number of rows in the array.
col_size: It is the number of columns in the array.

12
Data Structures and Applications Dept of CS&D

• The size used during declaration of the array is useful to reserve the
specified memory locations.

Int a [2] [4]


a[0][0] a[0][1] a[0][2] a[0][3]
col_size col 0 col 1 col 2 col3

row_size row 0
row 1
array_name

data_type a[1][0] a[1][1] a[1][2] a[1][3]

• The array “a” is a 2-dimensional array with 2 rows and 4 columns. This
declaration informs the compiler to reserve 8 locations (2*4=8 locations, 2*8=16 bytes in
total) continuously one after the other.

Initialization of 2-dimensional arrays


• As we initialize a variable to the required value, we can initialize the
individual elements of the array during initialization.

Syntax:

data_type array_name[row_size][col_size]={
{a1,a2, ---- ,an},
{b1,b2, ---- ,bn},
……………...,
{z1,z2, ---- ,zn}
};

data_type: It can be int, float, char etc.


array_name: It is the name of the array.
row_size: It is the number of rows in the array.
col_size: It is the number of columns in the array.
13
Data Structures and Applications Dept of CS&D

a1 to an are the values assigned to 1st row, b1 to bn are the values assigned to 2nd row and so
on.

Ex: 1. int a[4][3]= {{11,22,33}, {44,55,66},{77,88,99},{10,20,30} };


The array has 4 rows and 3 columns.
Columns

0 1 2
0 11 22 33
44 55 66
1
77 88 99
Rows 2
3 10 20 30

1.6.2 Storage representation of 2-dimensional arrays


The elements in a 2-dimensional array can be stored using: 1. Row major order
2. Column major order

1. Row major order: the elements are stored row by row one row at a time.

Ex: int a[4][3] = {{11,22,33},{44,55,66},{77,88,99}};

a[0][0] a[0][1] a[0][2] a[1][0] a[1][1] a[1][2] a[2][1] a[2][2] a[2][3]


11 22 33 44 55 66 77 88 99
2000 2002 2004 2006 2008 2010 2012 2014 2016
|| row0 || || row1 || || row2 ||

14
Data Structures and Applications Dept of CS&D

2. Column major order: the elements are stored column by column one column at a time.

Ex: int a[4][3] = {{11,22,33},{44,55,66},{77,88,99}};


a[0][0] a[0][1] a[0][2] a[1][0] a[1][1] a[1][2] a[2][1] a[2][2] a[2][3]
11 44 77 22 55 88 33 66 99
2000 2002 2004 2006 2008 2010 2012 2014 2016
|| col 0 || || col 1 || || col 2 ||

1.7 Basic Algorithms

1.7.1 Searching Algorithms


• The process of identifying or finding a particular record or element is
called searching. This can be implemented using array. Here we have two searching techniques.

1. Linear Search: linear search or sequential search is a method for finding an element within a
list. It sequentially checks each element of the list until a match is found or the whole list has been
searched.
✓ Linear search is usually very simple to implement, and is practical when
the list has only a few elements, or when performing a single search in an unordered list.
A simple approach is to do linear search
• Start from the leftmost element of arr[] and one by one compare j with each element of
arr[].
• If j matches with an element, return the index number.
• If j doesn‟t match with any of elements, return -1 or element not found in an arr[].

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

15
Data Structures and Applications Dept of CS&D

Example: C Program to search the „key‟ element in an array using linear search algorithm.

#include <stdio.h>
void main()
{
int array[100], key, i, n;
printf("Enter number of elements in array\n"); scanf("%d", &n);
printf("Enter elements of array\n"); for (i = 0; i < n; i++)
scanf("%d", &array [ i ] );
printf("Enter a number to search\n"); scanf("%d", &key);
for (i = 0; i < n; i++)
{
}
if (i == n)
if (array[i] == key)
{
printf("%d is present at location %d.\n", key, i+1);
break;
}
printf("%d isn't present in the array.\n", key);
}

Output:
Enter number of elements in array:5
Enter elements of array 100
25
35
30
56
Enter a number to search: 30
30 is present at location 4

2. Binary Search:

• Binary search is a fast searching algorithm. This search algorithm works


on the principle of divide and conquers.
• Binary search works on sorted arrays. Binary search begins by
comparing the middle element of the array with the target value. If the target value matches the
middle element, its position in the array is returned.
16
Data Structures and Applications Dept of CS&D

If the target value is less than the middle element, the search continues in the lower half of the
array. If the target value is greater than the middle element, the search continues in the upper half
of the array.

How Binary Search Works?

For a binary search to work, it is mandatory for the target array to be sorted. The following is our
sorted array and let us assume that we need to search the location of value 31 using binary search.

10 14 19 26 27 31 33 35 42 44
0 1 2 3 4 5 6 7 8 9

First, we shall determine half of the array by using this formula


mid = low + (high - low) / 2
Here it is, 0 + (9 - 0 ) / 2 = 4 (integer value of 4.5). So, 4 is the mid of the array.

10 14 19 26 27 31 33 35 42 44
0 1 2 3 4 5 6 7 8 9

Now we compare the value stored at location 4, with the value being searched, i.e. 31. We find
that the value at location 4 is 27, which is not a match. As the value is greater than 27 and we have
a sorted array, so we also know that the target value must be in the upper portion of the array.

10 14 19 26 27 31 33 35 42 44
0 1 2 3 4 5 6 7 8 9

We change our low to mid + 1 and find the new mid value again.
low = mid + 1
mid = low + (high - low) / 2
Our new mid is 7 now. We compare the value stored at location 7 with our target value 31.

10 14 19 26 27 31 33 35 42 44
0 1 2 3 4 5 6 7 8 9

17
Data Structures and Applications Dept of CS&D

The value stored at location 7 is not a match; rather it is more than what we are looking for. So,
the value must be in the lower part from this location.

10 14 19 26 27 31 33 35 42 44
0 1 2 3 4 5 6 7 8 9

Hence, we calculate the mid again. This time it is 5.

10 14 19 26 27 31 33 35 42 44
0 1 2 3 4 5 6 7 8 9

We compare the value stored at location 5 with our target value. We find that it is a match.

10 14 19 26 27 31 33 35 42 44
0 1 2 3 4 5 6 7 8 9

We conclude that the target value 31 is stored at location 5.

Binary search halves the searchable items and thus reduces the count of comparisons to be made
to very less numbers.

Example: C Program to search key elements in array using binary search algorithms.

#include<stdio.h> void main()


{
int n, i, arr[50], key, first, last, middle; printf("Enter total number of elements :"); scanf("%d",&n);
printf("Enter array elements:\n"); for (i=0; i<n; i++)
{
scanf("%d",&arr[i]);
}
printf("Enter a number to find :"); scanf("%d", &key);
first = 0; last = n-1;
while (first <= last)
{
middle = (first+last)/2; if ( arr[middle] == key)

18
Data Structures and Applications Dept of CS&D

{
printf("%d found at location %d\n", key, middle+1); break;
}
else if ( arr[middle] < key)
{
first = middle + 1;
}
else
{
last = middle - 1;
}
middle = (first + last)/2;
}
if(first > last)
{
printf("Not found! %d is not present in the list.",key);
}
}

1.7.2 Sorting Algorithm

1. Bubble Sort.

✓ Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent
elements if they are in wrong order.
✓ Bubble sort algorithm starts by comparing the first two elements of an array and swapping if
necessary, i.e., if you want to sort the elements of array in ascending order and if the first element
is greater than second then, you need to swap the elements but, if the first element is smaller than
second, you mustn't swap the element.
✓ If there are n elements to be sorted then, the process mentioned above should be repeated n-1
times to get required result. But, for better performance, in second step, last and second last
elements are not compared because; the proper element is automatically placed at last after first
step. Similarly, in third step, last and second last and second last and third last elements are not
compared and so on.

19
Data Structures and Applications Dept of CS&D

Example: C Program to sort the given array elements using Bubble sort Algorithm.

#include<stdio.h>
void main()
{
int a[50],n,i,j,temp;
printf("Enter the size of array: "); scanf("%d",&n);
printf("Enter the array elements: "); for(i=0;i<n;++i) scanf("%d",&a[i]); for(i=1;i<n;++i)
for(j=0;j<(n-i);++j)
if(a[j]>a[j+1])
{
temp=a[j]; a[j]=a[j+1]; a[j+1]=temp;
}
printf("\nArray after sorting: "); for(i=0;i<n;++i)
printf("%d ",a[i]);
}

Output:
Enter the size of array: 5
Enter elements of array
30
25
35
10
56
Sorted elements:
10
25
30
35
56

20
Data Structures and Applications Dept of CS&D

3.1 STRINGS
“A string is a sequence of characters enclosed within double quotes”.

or

“String is an array of characters and terminated by NULL character which is denoted by


“\0”.

A string is stored as a sequence of characters in an array terminated by “\0” (NULL character).


Ex: Consider the String “BIET”.

This string is stored in the form of an array as shown below:

B I E T \0
A[0] A[1] A[2] A[3] A[4]

3.1.1 Declaring String variables

A string is declared like an array of characters.

Syntax: Char string_name[size/length]

Where,

char: data type used to declare the strings or characters.


string_name: It specifies the name of the given string.
size: The size or maximum length (number of characters including “\0”) of the string is specified
in square brackets.
Length of the String: The “length” is the number of characters stored in the string up to but not
including the null character.

Example
1. char name[21];
Size of the string is 21, means that it can store up to 20 characters plus one null character.

2. char str[10];
Size of the string is 10, means that it can store up to 10 characters plus one null character.

21
Data Structures and Applications Dept of CS&D

3.3.3 Initializing the Strings


We can initialize an array of characters (Strings) in the declaration itself.

Examples:
1. char a[9]={“C”, “O”, “M”, “P”, “U”, “T”, “E”, “R”, “\0”};

The compiler allocates 9 memory locations ranging from 0 to 8 and these locations are
initialized with the characters in the order specified.

a C O M P U T E R \0

0 1 2 3 4 5 6 7 8

2. char a[ ]={“C”, “O”, “M”, “P”, “U”, “T”, “E”, “R”, “\0”};

For this declaration, the compiler will set the array size to the total number of initial values.
i.e. 9. The characters will be stored in these memory locations in the order specified as shown
below:

a C O M P U T E R \0

0 1 2 3 4 5 6 7 8

3. char a[ ]= “COMPUTER”;

Here, the string length is 8 bytes. But string size is 9 bytes. So, the compiler reserves 8+1
memory locations and these locations are initialized with the characters in the order specified. The
string is terminated by “\0” by the compiler.

a C O M P U T E R \0

22
Data Structures and Applications Dept of CS&D

3.4 String Input / Output Functions

3.4.1. Token-Oriented I/O functions


The Input/Output operations performed by scanf() and printf() functions are called token-oriented
Input/Output.

Reading a String using scanf( )


It is possible to read a string using “scanf()”.

The conversion specification for reading a string using scanf() is “%s”.

The scanf() function stops reading characters when it finds the first white space character (
spaces, tabs and new line characters).

Printing a String using printf( )


The „printf()‟ function prints the given string (all the characters but not the null character).

The printf() conversion specification for a string variable is “%s”.

Example: char name[20];


printf(“Enter the name:\n”); scanf(“%s”, name);
printf(“The entered name is:%s”, name);

3.4.2. Line-Oriented I/O functions


The Input/Output operation performed by gets() and puts() functions are called line-oriented
Input/Output.

This type of I/O functions processes entire line (string with white spaces). Hence these are called
line- oriented I/O.

Reading a String using gets( )

gets() function is used to read a sequence of characters (string) with spaces in between.

The “gets()” function allows us to read an “entire line” of input including whitespace characters.

23
Data Structures and Applications Dept of CS&D

Printing a String using puts( )

“puts()” function is used for printing the given strings.

Whenever we want to display a sequence of characters stored in memory locations on the screen,
then puts() function can be used.

Syntax: puts(string);

Example: char name[20];


printf(“Enter the name:\n”); gets(name);
printf(“The entered name is:\n”); puts(name);

3.5 String Manipulation Functions


The standard library “string.h” contains many functions for the string manipulation.

Sl.No String Description of each function


Functions

1 strlen(str) Returns length of the string str

2 strcpy(dest,src) Copies the source string src to destination string


dest

3 strncpy(dest,src,n Copies n characters of the source string src to


destination string dest

4 strcat(s1,s2) Append string s2 to string s1

5 strncat(s1,s2) Append first n characters of string s2 to string s1

6 strcmp(s1,s2) Compare two strings s1 and s2

7 strncmp(s1,s2,n) Compare n characters of two strings s1 and s2

8 strrev(string) Reverse the given string

24
Data Structures and Applications Dept of CS&D

3.6 String Operations

3.6.1 Substring: Accessing a substring from a given string requires three pieces of information:
(1) The name of the string or the string itself.
(2) The position of the first character of the substring in the given string.
(3) The length of the substring or the position of the last character of the substring.

Syntax: SUBSTRING (string, initial, length)

The syntax denotes the substring of a string S beginning in a position K and having a length L.

Example: SUBSTRING ('TO BE OR NOT TO BE”, 4, 7) = 'BE OR N” SUBSTRING ('THE


END', 4, 4) = ' END'

3.6.2 Indexing: Indexing also called pattern matching, refers to finding the position where a
string pattern P first appears in a given string text T. This operation is called INDEX.

Syntax: INDEX (text, pattern)

If the pattern P does not appears in the text T, then INDEX is assigned the value 0. The arguments
“text” and “pattern” can be either string constant or string variable.

4.1 Structures

Structure is a user defined data type that can hold data items of same/different data types.
All data items grouped are logically related & can be accessed by using variables.
Declaration:
Syntax:
struct tag-name
{
data_type member 1;
data_type member 2;
………………………
………………………
data_type member n;
};
In this declaration, struct is a required keyword, tag-name is a name of the structure defined.
The individual members can be ordinary variables, pointers, arrays or other structures. The
member names within a particular structure must be distinct from one another.

25
Data Structures and Applications Dept of CS&D

Ex: struct person


{
char name[10]; int age;
float salary;
};
The above example declares a structure called person that has three fields:

name = a name that is a character array


age = an integer value representing the age of the person salary = a float value representing the
salary of the individual
Ex:
Struct student
{
char name[10];
int roll_no;
float marks;
};

To allocate the memory for the structure, we have to declare the variable as shown below:

Struct student s1,s2; [ size of variables s1,s2 is 22bytes each] Two ways to declare variables:

Initialization or Assigning values to fields


Initialization is the process of Assigning values to structure variables (structure members).
To assign values to the fields, use .(dot operator) as the structure member operator. This operator
is used to select a particular member of the structure.

Ex: Method-1
struct person
{
char name[10]; int age;
float salary;
}p;
strcpy(p.name,“james”); p.age = 10;
p.salary = 35000;

Method-2
struct student
{
char name[10]; int age;
float marks;
}s1={“virat”,19,25};
26
Data Structures and Applications Dept of CS&D

Accessing structure members


To access members of structures, we specify the variables followed by the dot operator
then followed by the name of the member.

Reading:
printf(“Enter name of the student\n”);
scanf(“%s”,&s.name);
printf(“Enter marks of the student\n”);
scanf(“%f”,&s.marks);

Writing:
printf(“name of the student is %s\n”,s.name);
printf(“marks of the student is %f\n”,s.marks);

4.2 Structure within a structure:


There is possibility to embed a structure within a structure. There are 2 ways to embed structure.
1.The structures are defined separately and a variable of structure type is declared inside the
definition of another structure. The accessing of the variable of a structure type that are nested
inside another structure can be done in the same way as accessing other member of that structure.

Example: The following example shows two structures, where both the structure are defined
separately.

Struct
{
int month;
int day;
int year;
}date;
A person born on February 11, 1944, would have the values for the date struct set as:
person1.dob.month = 2;
person1.dob.day = 11;
person1.dob.year = 1944;

27
Data Structures and Application Dept of CS&D

2. The complete definition of a structure is placed inside the definition of


another structure.

Example:
A person born on February 11, 1944, would have the values for the date struct
set as: person1.dob.month = 2;
person1.dob.day = 11;
person1.dob.year = 1944;

typedefstruct
{
char name[10];
int age;
float salary;
struct
{
int month;
int day;
int year;
} date;
} humanBeing;

4.3 Self-Referential Structures

A self-referential structure is the one in which one or more of its


components is a pointer to itself. Self-referential structures usually require
dynamic storage management routines (malloc and free) to explicitly obtain and
release memory.

Consider as an example:
Struct
{
char data;
struct list *link ;
} list;

Each instance of the structure list will have two components data and link.
data: is a single character,
link: link is a pointer to a list structure. The value of link is either the address in
memory of an instance of list or the null pointer.

28
Data Structures and Application Dept of CS&D

Consider these statements, which create three structures and assign values to
their respective fields: list item1, item2, item3;
item1.data = 'a';
item2.data = 'b';
item3.data = 'c';
item1.link = item2.1ink = item3.link = NULL;

a b c

Structure variables item1, item2 and item3 each contain the data items a, b, and
c respectively, and the null pointer. These structures can be attached together by
replacing the null link field in item 2 with one that points to item 3 and by
replacing the null link field in item 1 with one that points to item 2.

item1.link = &item2;
item2.1ink = &item3;

a b c

4.4 Unions

A union is a collection of data of similar data types or dissimilar data types.


A union declaration is similar to a structure, but the fields of a union must share
their memory space. This means that only one field of the union is "active" at
any given time.

Syntax:
union tag-name
{
data_type member 1;
data_type member 2;
………………………
………………………
data_type member n;
};

29
Data Structures and Application Dept of CS&D

Example:
data_type member 1;
data_type member 2;
………………………
……………………… data_type member n;
unionstudent
{
char name[10]; intage;;
float salary;
};

0 1 2 3 4 5 6 7

name
age

salary

The major difference between a union and a structure is that unlike structure
members which are stored in separate memory locations; all the members of
union must share the same memory space. This means that only one field of the
union is "active" at any given time.

Example: C program to show how structure behaves

#include <stdio.h>
struct student
{
int marks; char grade;
float percentage;
};

void main()
{
30
Data Structures and Application Dept of CS&D

struct student s1;


s1.marks=29;
s1.grade= “A”;
s1.percentage=99.5;
printf(" Marks= %d \n", s1.marks); printf(" Grade= %c \n", s1.grade);
printf("Percentage = %c \n", s1.percentage);
}

C program to show how union behaves

#include <stdio.h>
union student
{
int marks; char grade;
float percentage;
};

void main()
{
union student s1;
s1.marks=29;
printf(" Marks= %d \n", s1.marks);
s1.grade=‟A‟;
printf(" Grade= %c \n", s1.grade);
s1.percentage=99.5;
printf("Percentage = %c \n", s1.percentage);
}

Differences between structure and union in C:

C Structure C Union

keyword struct is used to define a keyword union is used to define a


structure union

Structure allocates storage space for Union allocates one common storage
all its members seperately space for all its members. Union finds
that which of its member needs high
storage space over other members and
allocates that much space.
31
Data Structures and Application Dept of CS&D

Structure occupies larger memory Union occupies lower memory space


space. over
structure.
We can access all members of We can access only one member of
structure at a time. union at a
time.
Address of each member will be in Address is same for all union
ascending order (different address). members.

5. Pointers and Dynamic Memory Allocation Functions

5.1 Pointers

Pointer is the important feature available in C.

As we store data/information in memory, computer stores data in its memory.

1. Computer memory is divided into number of cells called memory


locations.Each locationholds 1byte of data.

2. Each location is associated with address. Address of memory location ranges


from 0 to 65535.

3. We can’t change these addresses assigned by the system & hence these are
constant. But we can only use them to store the data.

These addresses are called pointer constants.

Data

Address

10
20
30
32
Data Structures and Application Dept of CS&D

40
0 50
1 …
2 …
3 … MEMORY
4 ... LOCATION
5
S
…..
65534
65535

Definition
“A pointer is a variable which contains the address of another variable as
its value”.

Declaring a Pointer Variable


Syntax data_type *pointer_variable_name;

where,
data_type: It can be int, float, char etc.
Asterisk (*): It tells the compiler that we are declaring a pointer variable.
pointer_variable_name: It is the name of the pointer variable.

Example:
1. int *ptr; // declares a pointer variable ptr of integer type.
2. float *temp; // declares a pointer variable temp of floating type.

Operators used with Pointers:


The two basic operators used with pointers are:

33
Data Structures and Application Dept of CS&D

i. The Address of operator (&): By using the address of (&) operator, we can
determine the address of the variable.

ii. The Indirection operator (*): It gives the value stored at a particular
address.

int a=3;
int *ptr;
ptr=&a;

Memory layout:

Ptr a
65530 3
Address:65530
Ptr=&a copies the address of “a” to the pointer variable “ptr”.

Example Program: Write a C program to print value and address of the


variable using pointers.

#include<stdio.h>
#include<conio.h>
void main ()
{
int a=20, *ptr1;
clrscr ();
ptr1 = &a; //ptr1 is a pointer to variable a
printf(“The address of a=%d and value of a=%d\n”,ptr1,*ptr1);
getch();
}

Memory layout:

Ptr1 a
65530 20

34
Data Structures and Application Dept of CS&D

Initializing a Pointer Variable

We can initialize the pointer variables by assigning the address of other variable
to them. However these variables must be declared in the program.

Syntax

data_type *pointer_variable_name = address_of_variable;

where,
data_type:. It can be int, float, char etc.
Asterisk (*): It tells the compiler that we are declaring a pointer variable.
pointer_variable_name: It is the name of the pointer variable.
address_of_variable: It is the address of another variable.

Example:
1. int a;

int *ptr;
ptr=&a;
or
int a;
int *ptr=&a; Both are equivalent.

5.2 Dynamic Memory Allocation Methods

Memory can be reserved for the variables either during compilation time
or during execution time (run time).
Based on this memory can be allocated for variables using two different
techniques:
1. Static allocation
2. Dynamic allocation

Static Allocation

35
Data Structures and Application Dept of CS&D

If memory space is allocated for variables during compilation time,


then it is called “Static Memory allocation”.
Size of memory space is “fixed”; it can’t be altered during execution
time.
Example: int a [10];
During compilation, the compiler will allocate 10 memory locations for the
array variable “a”. Inserting less than 10 elements leads to underutilization of
allocated space and more than 10 elements cannot be inserted.

Dynamic Allocation

“Dynamic memory allocation is the process of allocating memory space


during the execution time (Run time).”
The various predefined memory management functions that are used to
allocate or deallocate memory are:
1. malloc( )
2. calloc( )
3. realloc( )
4. free( )

5.3 Different Dynamic Memory allocation Functions:

1. malloc( ): Allocating a Block of Memory


This function reserves a block of memory of specified size and returns a
pointer of data type to that memory block.
If there is insufficient memory to make the allocation, then it returns a NULL
value.
Syntax:
ptr = (data_type *) malloc (size);

where,
ptr: ptr is a pointer variable of type int, float, char, double etc.
data_type: It can be any of the basic data type or user defined data type.
size: size is the number of bytes to be reserved for a block.

Example:
1. ptr = (int *) malloc(10);
Allocates a block of Memory of 10 bytes.

2. ptr = (int *) malloc(20);


36
Data Structures and Application Dept of CS&D

Allocates a block of Memory of 20 bytes.

2. calloc( ): Allocating multiple Blocks of Memory


This function allocates space for multiple Blocks, each of the same size
and initializes all of its bytes to zero (0).
If there is insufficient memory to make the allocation, then it returns a NULL
value.

Syntax ptr = (data_type *) calloc


(n,size);

where,

ptr: ptr is a pointer variable of type int, float, char, double etc.
data_type: It can be any of the basic data type or user defined data type.
n: n is the number of blocks to be allocated.
size: size is the number of bytes in each block.

Example:
1. ptr = (int *) calloc(10, 2);
Allocates 10 blocks of Memory each of 2 bytes.

2. ptr = (int *) calloc(5, 4);


Allocates 5 blocks of Memory each of 4 bytes.

3. realloc( ): Reallocating already allocated block of Memory by malloc( )


or calloc( )
This function reallocates memory space by modifying already allocated
memory.
The function relloc() resizes memory previously allocated by either malloc()
or calloc(), which means, the size of the memory changes by extending or
deleting the allocated memory.
When realloc() is able to do the resizing, it returns a pointer to the start of the
new block and when it is unable to do the resizing, the old block is unchanged
and the function returns the value NULL.

Syntax ptr = (data_type *)realloc (ptr, new_size);

37
Data Structures and Application Dept of CS&D

where,
ptr: it is a pointer to a block of previously allocated memory either using
malloc( ) or calloc( ).
data_type: It can be any of the basic data type or user defined data type.
new_size: it is the new size of the block.

Example:
char *str;
str = (char *) malloc(10); // malloc function allocates 10 memory blocks
strcpy(str, “Computer”);
str = (char *) realloc (str, 40); //realloc function allocates new memory
blocks from 10 to 40 strcpy(str, “Computer Science and Engineering”);

4. free( ): Freeing the memory allocated using malloc( ), calloc( ) or


realloc( )
This function is used to free the previously allocated memory using malloc( ),
calloc( ) or realloc( ).

Syntax free(ptr);

Ex:int *ptr;
ptr = (int *) malloc(100*sizeof(int)); free(ptr);

Difference between Static Memory Allocation and Dynamic Memory


allocation in C:

Static memory allocation Dynamic memory allocation

38
Data Structures and Application Dept of CS&D

In static memory allocation, memory In dynamic memory allocation,


is allocated while writing the C memory is allocated while executing
program the program
Compile time allocation Run time allocation

Memory size can’t be modified while Memory size can be modified while
execution execution
Example:Array
Example:Linked List

Difference between malloc() and calloc() Functions in C:

Malloc( ) Calloc( )

It allocates only single block of It allocates multiple blocks of


memory. memory.

int *ptr; int *ptr;


ptr = malloc( 20 * sizeof(int)); ptr = calloc( 20, 20 *sizeof(int) );
For the above, 20*4 bytes of memory For the above, 20blocks of memory
are allocated in one block.Total = 80 will be allocated and each
bytes contains20*4 bytes of memory.Total
= 1600 bytes.
malloc() doesn‟t initializes the calloc() initializes the allocated
allocated memory. It contains garbage memory to zero.
values

5.4 Polynomials

“A polynomial is a sum of terms, where each term has a form axe,


where x is the variable, a is the coefficient and e is the exponent.”

Example polynomials are:


A(x) =8x^6+3x^3+6x^2+3x+4

39
Data Structures and Application Dept of CS&D

The largest (or leading) exponent of a polynomial is called its degree.


Coefficients that are zero are not displayed. The term with exponent equal to
zero does not show the variable since x raised to a power of zero is 1.

Polynomial operations
1. Representation
2. Addition
3. Multiplication

5.4.1 Polynomial Representation


Consider the two polynomials A(x) = 2xl000+ 1
B(x) = x4 + 10x3 + 3x2 + 1

Start A finish A start B finish B avail

2 1 1 10 3 1 Coef
1000 0 4 3 2 0
exp

0 1 2 3 4 5 6

The above figure shows how these polynomials are stored in the array
terms.
The index of the first term of A and B is given by startA and startB, 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.
For above example, startA=0, finishA=1, startB=2, finishB=5, & avail=6.

5.4.2 Polynomial Addition


C function is written that adds two polynomials, A and B to obtain D =A + B.
40
Data Structures and Application Dept of CS&D

To produce D (x), padd( ) is used to add A (x) and B (x) term by term. Starting
at position avail, attach( ) which places the terms of D into the array, terms.
If there is not enough space in terms to accommodate D, an error message is
printed to the standard error device & exits the program with an error condition.

Function to add two polynomials:


#include<stdio.h>
typedef struct
{
int cf;
int px;
}POLY;

void main( )
{
POLY p1[20],p2[20],p3[20];
int m,n,k;
printf(“Enter the 1st polynomial:”);
scanf(%d”,&m);
readpoly(p1,m);
printf(“Enter the 2nd polynomial:”);
scanf(“%d”,&n);
readpoly(p2,n);
printf(“poly 1:”);
printpoly(p1,m);
printf(“poly 2:”);
k=addpoly(p1,m,p2,n,p3);
printf(“poly 3:”);
printpoly(p3,k);
}

readpoly(POLY p1,int m)
{
int i,cf,px;
for(i=0;i<n;i++)
{
printf(“cf,px”);
p[i].cf=cf;

41
Data Structures and Application Dept of CS&D

p[i].px=px;
}
}

int addpoly(POLY p1[ ],int m,POLY p2[ ],int n, POLY p3[ ])


{
int i,k,cf1,px1,pos,sum;
k=0;
for(i=0;i<m,i++)
{
cf1=p1[i].cf;
px1=p1[i].px;
pos=search(px1,p2,n);
if(pos>=0)
{
sum=cf1+p2[pos].cf;
if(sum!=0)
p3[k].cf=sum;
p2[pos].cf=-999;
}
Else
p3[k].cf=cf1;
p3[k].px=px1;
k++;
}
k=copypoly(p3,k,p2,n);
return k;
}

int cpoypoly(POLY p3[ ],int k,POLY p2[ ],int n)


{
int j;
for(j=0;j<n;j++)
{
if(p2[j].cf!=-999)
{
p3[k].cf=p2[j].cf;
p3[k].px=p2[j].px;
k++;
42
Data Structures and Application Dept of CS&D

}
}
return k;
}

void printpoly(POLY p[ ],int n)


{
int i;
for(i=0;i<n;i++)
{
if(p[i].cf!=0)
printf(“poly=%d”,p[i].px);
}
printf(“\n”);
}

5.5 Sparse Matrices


A matrix which contains many zero entries or very few non-zero
entries is called as sparse matrix.
A matrix contains m rows and n columns of elements as illustrated in
below figures. In this figure, the elements are numbers. The first matrix has five
rows and three columns and the second has six rows and six columns. We write
m x n (read "m by n") to designate a matrix with m rows and n columns. The
total number of elements in such a matrix is mn. If m equals n, the matrix is
square.
In the figure B, matrix contains only 8 non-zero elements out of
36elements and that is sparse matrix.

col0 col1 col2 col0 col1 col2 col3 col4 col5

row0 -27 3 4 row0 15 0 0 22 0 -15


row1 6 82 -2 row1 0 11 3 0 0 0
row2 109 -64 11 row2 0 0 0 -6 0 0
row3 12 8 9 row3 0 0 0 0 0 0
row4 48 27 47 row4 91 0 0 0 0 0
row5 0 0 28 0 0 0

43
Data Structures and Application Dept of CS&D

Note: A sparse matrix can be represented in 1-Dimension, 2- Dimension and 3-


Dimensional array. When a sparse matrix is represented as a two-dimensional
array as shown in Figure B, more space is wasted.

Example: Consider the space requirements necessary to store a 1000 x 1000


matrix that has only 2000 non-zero elements. The corresponding two-
dimensional array requires space for 1,000,000 elements. The better choice is by
using a representation in which only the nonzero elements are stored.

5.5.1 Sparse Matrix Representation


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

Example 1: Below figures shows the sparse matrix representation of a matrix


using triplet<row,col,value>
The below figure shows the representation of matrix in the array “a” a[0].row
contains the number of rows, a[0].col contains the number of columns and
a[0].value contains the total number of nonzero entries.

Positions 1 through 8 store the triples representing the nonzero entries. The row
index is in the field row, the column index is in the field col, and the value is in
the field value. The triples are ordered by row and within rows by columns.

col0 col1 col2 col3 col4 col5


row0 15 0 0 22 0 -15 a[0] 6 6 8
a[1] 0 0 15
row1 0 11 3 0 0 0 a[2] 0 3 22
a[3] 0 5 -15
row2 0 0 0 -6 0 0 a[4] 1 1 11
a[5] 1 2 3
row3 91 0 0 0 0 0 a[6] 2 3 -6
a[7] 4 0 91
row4 0 0 28 0 0 0 a[8] 5 2 28

Sparse matrix stored as triplet.

44
Data Structures and Application Dept of CS&D

0th index of array a contains number of rows, number of columns and


number of values.
Example 2: For example, consider a matrix of size 5 X 6 containing 6 number
of non-zero values. This matrix canbe represented as shown in the figure below:

Rows Columns Values


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

5.5.2 Transposing a Matrix


To transpose a matrix, interchange the rows and columns. This means that
each element a[i][j] in the original matrix becomes element a[j][i] in the
transpose matrix.
Row col value Row col value
a[0] 6 6 8 6 6 8
a[1] 0 0 15 0 0 15
a[2] 0 3 22 0 4 91
a[3] 0 5 -15 1 1 11
a[4] 1 1 11 2 1 3
a[5] 1 2 3 2 5 28
a[6] 2 3 -6 3 0 22
a[7] 4 0 91 3 2 -6
a[8] 5 2 28 5 0 -15

45
Data Structures and Application Dept of CS&D

a. Spare matrix stored as triplet b. transpose of spare matrix stored as triple


we can declare sparse matrix as follows
#define MAX_TERMS 101
typdef struct
{
int row,col,val;
} TERM;
TERM a[MAX_TERMS];

Function to read the sparse matrix as triplet


void read_sparse_matrix(TERMS a[],int m,int n)
{
int i,j,k,item;
a[0].row=m[0].col=n,k=1;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&item);
if(item==0)
continue;
a[k].row=i,a[k].col=j,a[k].val=item;
k++;
}
}
a[0].val=k-1;

46
Data Structures and Application Dept of CS&D

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

A good algorithm for transposing a matrix:


for each row i
take element <i, j, value> and store it as
element <j, i, value> of the transpose;

If we process the original matrix by the row indices it is difficult to know


exactly where to place element <j, i, value> in the transpose matrix until we
processed all the elements that precede it.

This can be avoided by using the column indices to determine the placement of
elements in the transpose matrix. This suggests the following algorithm:

for all elements in column j


place element <i, j, value>
in element <j, i, value>

The columns within each row of the transpose matrix will be arranged in
ascending order.

void transpose (term a[], termb[])

{ /* b is set to the transpose of a */


int n, i, j, currentb;
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;
if (n > 0)
{
currentb = 1;
for (i = 0; i < a[O].col; i++)
for (j= 1; j<=n; j++)
if (a[j].col == i)
{
47
Data Structures and Application Dept of CS&D

b[currentb].row = a[j].col;
b[currentb].col = a[j].row;
b[currentb].value = a[j].value;
currentb++;
}
}
}

PATTREN MATCHING

✓ The process of searching for a pattern string in a given text string is


called pattern matching.
✓ strstr(string,pat) : this function is used to check pattern in given text.

Analysis: The while loop is iterated until the end of either the string or the
pattern is reached. Since i is never decreased, the lines that increase i cannot be
executed more than m=strlen(string) times. The resetting of j to failure [j-1]+1
decreases the value of j. so, this can‟t be done more times than j is incremented
by the statement j++ as otherwise, j falls off the pattern. Each time the statement
j++ is executed, i is also incremented. So, j can‟t be incremented more than m
times. No statement of code is executed more than m times.
return ((j == lenp) ? (i - lenp) : -1 )
48
Data Structures and Application Dept of CS&D

This statement checks to see whether or not we found the pattern. If we didn‟t
find the pattern, the pattern index j is not equal to the length of the pattern and
we return -1. If we found the pattern, then the starting position is i the length
of the pattern.

Algorithm 2: (Pattern Matching)

P and T are strings with lengths R and S, and are stored as arrays with one
character per element. This algorithm finds the INDEX of P in T.

1.[Initialize.]
Set K= 1 and MAX= S - R + 1
2. Repeat Steps 3 to 5

while K ≤ MAX
3. Repeat for L = 1 to R [Tests each character of P] If P[L] ≠ T[K + L – l], then:
49
Data Structures and Application Dept of CS&D

Go to Step 5 [End of inner loop.]


4.[Success.]
Set INDEX = K, and Exit
5. Set K= K + 1
[End of Step 2 outer loop] 6.[Failure.]
Set INDEX = 0
7. Exit

Observation of algorithms
P is an r-character string and T is an s-character string. Algorithm contains two
loops, one inside the other. The outer loop runs through each successive R-
character substring WK = T[K] T[K + 1] ... T[K+R-l] of T. The inner loop
compares P with WK, character by character. If any character does not match,
then control transfers to Step 5, which increases K and then leads to the next
substring of
T. If all the R characters of P do match those of some WK then P appears in T
and K is the INDEX of P in T. If the outer loop completes all of its cycles, then
P does not appear in T and so INDEX = 0.

1. STACKS:
Definition
“A stack is an ordered list in which insertions (pushes) and deletions (pops) are made at one end
called the top.”
Given a stack S= (a0, ... ,an-1), where a0 is the bottom element, an-1 is the top element, and ai is
on top of element ai-1, 0 < i < n.

50
Data Structures and Application Dept of CS&D

As shown in above figure, the elements are added in the stack in the order A, B, C, D, E, then E
is the first element that is deleted from the stack and the last element is deleted from stack is A.
Figure illustrates this sequence of operations.
Since the last element inserted into a stack is the first element removed, a stack is also known as
a Last-In-First-Out (LIFO) list.

1.1 STACK OPERATIONS:


The two basic operations associated with stacks are:
1.Push(): is the term used to insert an element into a stack.
2.Pop(): is the term used to delete an element from a stack.
3.Display(): prints the contents of stack if not empty

51
Data Structures and Application Dept of CS&D

Push( )
Function push checks whether stack is full. If it is, it calls stackFull( ),
which prints an error message and terminates execution. When the stack is not
full, increment top and assign item to stack [top].
void push()
{
if (top >= STACK_SIZE-1)
{
stackFull();
}
else
{
printf(“enter the element to be pushed on to stack\n”);
scanf(“%d”,&item);
top= top+1;
stack[top] = item;
}
}

Pop( )
Deleting an element from the stack is called pop operation. The element
is deleted only from the top of the stack and only one element is deleted at a
time
void pop ( )
{
if (top == -1)
{
return stackEmpty();
}
else
{
item= stack[top]; top= top-1;
printf(“deleted element is %d\n”,item);
}
}

52
Data Structures and Application Dept of CS&D

Display( )

void Display( )
{
int i;
if(top==-1)
{
printf(“stack is full”);
return;
}
printf(“contents of the stack\n”);
for(i=0;i<=top;i++)
printf(“%d\n”,s[i]);
}

1.2 STACKS USING DYNAMIC ARRAYS:

Before inserting,we check whether sufficient space is available in the stack.

if (top SIZE-1)
{
printf("Stack overflow\n");
return;
}

But, once the stack is full, instead of returning the control, we can increase the
size of array realloc() function and the above code can be modified as shown
below:

if (top-SIZE-1)
{
printf("Stack Full: update size, insert item'n ");
SIZE++;
s = (int*) realloc(s, SIZE*sizeof(int));
}

53
Data Structures and Application Dept of CS&D

When above condition fails, it means we can insert an item. If the above
condition is true, spe what sufficient. So, using realloc() we increase the size by
1 and we can insert an item. To inser an item, we have to increment top by 1 as
shown below:

top=top + 1;

Then,the item can be inserted on top of the stack using:

s[top]=item;

1.3 APPLICATIONS OF STACK:


1. Stack is used by compilers to check for balancing of parentheses, brackets
and braces.
2. Stack is used to convert an infix expression into postfix/prefix form.
3. Stack is used to evaluate a postfix expression.
4. Used In recursion, to solve the problems like,Tower of Hanoi,Factorial of a
given number,GCD of two numbers,Fibbacci sequence & Ackermans function
etc
5. Used in other applications like a) To check whether a string is palindrome or
not. b) To check whether given expression is valid or not.
6. During a function call the return address and arguments are pushed onto a
stack and on return they are popped off.

2. EXPRESSIONS:
It is sequence of operators and operands that reduces to a single value after
evaluation is called an expression.
X=a/b–c+d*e–a*c
above expression contains operators (+, –, /, *) operands (a, b, c, d, e).
Types of Expressions
Prefix Expression or Polish notation
Infix Expression
Postfix Expression or Reverse Polish notation

54
Data Structures and Application Dept of CS&D

Infix Expression:
In this expression, the binary operator is placed in-between the operand. The
expression can be parenthesized or un- parenthesized.

Example:
Infix expression A+B

Prefix or polished expression:In this operand appears after the expression


AB+

Postfix or Reverse Polish Expression:


In this expression, the operator appears after its operand.
Example: A B +
Here, A & B are operands and + is operand

Precedence and Associativity of the operators

The rules that determine the order in which different operators are evaluated are
called precedence rules or precedence of operators.

DESRIPTION OPERATOR PRIORITY ASSOCIATIVITY


Exponentiation $,^ 6 Right to Left
Multiplication * 4 Left to Right
Division / 4 Left to Right
Mod % 4 Left to Right
Addition + 2 Left to Right
Subtraction - 2 Left to Right

In an expression,If two or more operators have the same priority and are
evaluated from left-to right,then the operators are called left associative
operator.

In an expression,If two or more operators have the same priority and are
evaluated from right-to left,then the operators are called right associative
operator.

55
Data Structures and Application Dept of CS&D

Example 1: Convert infix Expression to Postfix using stack ( A + ( B – C ) *


D)

56
Data Structures and Application Dept of CS&D

Below example shows conversion of infix to post fix

57
Data Structures and Application Dept of CS&D

Below example shows conversion from infix to prefix

4. EVALUATION OF POSTFIX EXPRESSION:


1. Scan the postfix expression from left to right.
2. If the scanned symbol is an operand, then push it onto the stack.
3. If the scanned symbol is an operator, pop two operands from the stack.

The first operand popped is operand2 and the second operand popped is
operand1.
4. Perform the desired operation and push the result onto stack
5. Repeat above steps till the end of the expression reached.

58
Data Structures and Application Dept of CS&D

Example: Evaluate the following postfix Expression. ABC-D*+E^F+


A=6, B=3, C=2, D=5, E=1, F=7

Example 2: Evaluate the following postfix Expression. ABC+*CBA-+* where


A=1, B =2, C=3

59
Data Structures and Application Dept of CS&D

Example 3: Evaluate the following postfix Expression. AB+C-BA+C^- where


A=1, B =2, C=3

60

You might also like