Download as pdf or txt
Download as pdf or txt
You are on page 1of 260

|| JAI SRI GURUDEV ||

SRI ADICHUNCHANAGIRI SHIKSHANA TRUST ®

ADICHUNCHANAGIRI INSTITUTE OF TECHNOLOGY


(An ISO 9001 : 2008 Certified)
Affiliated to Visvesvaraya Technological University, Belagavi ,
Approved by AICTE and Accredited by NAAC, New Delhi
Jyothinagar, Chikkamagaluru – 577 102.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

ONLINE CLASS USING ZOOM APPLICATION

Subject: Data Structures and Applications


Subject Code: 18CS32

Presented By: Semester and Section : 3rd and ‘A’


Mr. GOPINATH C. B., B.E., M.Tech., Class # : 21
Assistant Professor
29 September 2020 Date : 29-09-2020 (02:30PM TO 04:30PM)
MODULE - 1

Introduction: Data Structures, Classifications (Primitive & Non-primitive),

Data structure Operations, Review of Arrays, Structures, Self-Referential

Structures, and Unions. Pointers and Dynamic Memory Allocation Functions.

Representation of Linear Arrays in Memory, Dynamically allocated arrays.

Array Operations: Traversing, inserting, deleting, searching, and sorting.

Multidimensional Arrays, Polynomials and Sparse Matrices.

Strings: Basic Terminology, Storing, Operations and Pattern Matching

algorithms. Programming Examples.


Data Structures

Definition:

Data may be organized in many different ways. The logical or mathematical

model of a particular organization of data is called a Data Structure.

The Data Structures mainly deals with the study of :

 How efficiently the data can be stored in a computer/memory.

 How efficiently the data can be organized in a computer/memory.

 How efficiently the data can be retrieved from the computer/memory.


Classification of Data Structures OR Types of Data Structures:

Data structures are generally classified into two types

 Primitive Data Structures

 Non-primitive Data Structures

Primitive Data Structures:

Primitive data structures are the fundamental data types which are supported

by a programming language.

Examples: integer, real, character and boolean.

The term ‘data type’, ‘basic data type’ and ‘primitive data type’ are often used

interchangeably.
Non-primitive Data Structures:

Non-primitive data structures are those data structures which are created

using primitive data structures.

Examples: arrays, linked lists, stacks, queues, trees and graphs.

Non-primitive data structures can further be classified into two types

 Linear Data Structures

 Non-linear Data Structures


Linear Data Structures:

In Linear data structures, the elements of a data structure are stored in a

linear or sequential order.

Examples: arrays, linked lists, stacks and queues

Non-linear Data Structures:

In Non-linear data structures, the elements of a data structure are not stored

in a sequential order.

Examples: trees and graphs


Data Structures

Primitive Data Structures Non-primitive Data Structures


Integer Arrays

Real Linked Lists

Character Stacks
Queues
Boolean
Trees
Graphs

Linear Data Structures Non-linear Data Structures


Arrays Trees
Linked Lists Graphs
Stacks
Queues
Figure: Classification of Data Structures.
Primitive Data Structures:
Integer: It is used to store whole numbers and it is denoted by keyword ‘int’.

Example: 10, -10, etc.,

Real: It is used to store real numbers.

 Single Precision Floating Point: It is denoted by keyword ‘float’.

Example: 3.142623, 10.000222, etc.,

 Double Precision Floating Point: It is denoted by keyword ‘double’.

Example: 2.1234567891234567, etc.,

Character: It is used to store characters and it is denoted by keyword ‘char’.

Example: ‘A’, “india”, etc.,

Boolean: It is used to store true or false. Every non-zero value corresponds to true and
0 value corresponds to false and it is denoted by keyword ‘bool’.

Example: bool x = false;

Where bool is a keyword and defined in “stdbool.h” header file.


Non-primitive Data Structures:

Arrays: An array is a collection of elements of same data type and stored in


consecutive memory locations. Referenced by an index or subscript.

Stacks: A stack is a linear data structure in which insertion and deletion of elements
are done at only one end, which is known as the top of the stack. Stack is also called as
Last-In, First-Out (LIFO).

Queues: A queue is a linear data structure in which the element that is inserted first is
the first one to be taken out. The elements in a queue are added at one end called the
rear and removed from the other end called the front. Queue is also called as First-In,
First-Out (FIFO).

Linked Lists: A linked list is a set of dynamically allocated nodes, arranged in such a
way that each node contains one value and one pointer. The pointer always points to
the next member of the list. If the pointer is NULL, then it is the last node in the list.
Non-primitive Data Structures (Contd…):

Trees: A tree is a non-linear data structure which consists of a collection of nodes

arranged in a hierarchical order. One of the nodes is designated as the root node and

the remaining nodes can be partitioned into disjoint sets such that each set is a sub-

tree of the root.

Graphs: A graph is a non-linear data structure which is a collection of vertices (also

called nodes) and edges that connect these vertices.


Data Structure Operations:

The different operations that can be performed on the various data

structures are

 Traversing

 Searching

 Inserting

 Deleting

 Sorting

 Merging
Traversing: It means to access each data item exactly once so that it can be

processed.

Example: To print the names of all the students in a class.

Searching: It is used to find the location of one or more data items that satisfy

the given constraint. Such a data item may or may not be present in the given

collection of data items.

Example: To find the names of all the students who secured 100 marks in

subject.

Inserting: It is used to add new data items to the given list of data items.

Example: To add the details of a new student who has recently joined the

course.
Deleting: It means to remove (delete) a particular data item from the given

collection of data items.

Example: To delete/remove the name of a student who has left the course.

Sorting: Data items can be arranged in some order like ascending order or

descending order depending on the type of application.

Example: Arranging the names of students in a class in an alphabetical order.

Merging: Combing the records in two different sorted files into single sorted

file.
Today’s Class Assignment Questions.

Note: Write these assignment questions in 200 pages RULED long note book.

1. What is data structure? What are the various types of data

structure? Explain in detail.

2. Define data structure. List and explain data structure

operations.
THANK YOU
|| JAI SRI GURUDEV ||
SRI ADICHUNCHANAGIRI SHIKSHANA TRUST ®

ADICHUNCHANAGIRI INSTITUTE OF TECHNOLOGY


(An ISO 9001 : 2008 Certified)
Affiliated to Visvesvaraya Technological University, Belagavi ,
Approved by AICTE and Accredited by NAAC, New Delhi
Jyothinagar, Chikkamagaluru – 577 102.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

ONLINE CLASS USING ZOOM APPLICATION

Subject: Data Structures and Applications


Subject Code: 18CS32

Presented By: Semester and Section : 3rd and ‘A’


Mr. GOPINATH C. B., B.E., M.Tech., Class # : 22
Assistant Professor
30 September 2020 Date : 30-09-2020 (10:00AM TO 10:40AM)
Pointers and

Dynamic Memory Allocation

Functions
Pointer
Pointer is a variable that holds the address of another variable.
The two most important operators used with the pointer type are:
 Address Operator (&)
 Dereferencing (or Indirection) Operator (*)
Declaration of Pointer Variable:
Syntax : data_type *ptr_variable_name;
Example : int *ptr;
Initialization of Pointer Variable:
Syntax : ptr_variable_name = &variable_name;
Example:
int a = 10; a Variable Name
int *ptr;
10 Value
ptr = &a;
*ptr = a; 2010 Memory Address
Note: ptr holds the address of variable ‘a’.

*ptr holds the value of variable ‘a’.


Example:
a Variable Name
#include<stdio.h> Value
10
main()
2010 Memory Address
{

int a = 10;

int *ptr;
Output
ptr = &a;
10
printf(“%d\n”,a);

printf(“%d\n”,&a); 2010

printf(“%d\n”,ptr); 2010

printf(“%d\n”,*ptr); 10
}
Uses of Pointers

 To pass arguments by reference

 For accessing array elements

 To return multiple values

 To allocate memory dynamically.

 To implement data structures like arrays, linked lists, stacks, queues, trees and

graphs.
Pointer to Pointer
Pointer is a variable that holds the address of another variable.
Pointer storing the address of another pointer variable . That is one pointer
variable pointing to another pointer variable.
Declaration of Pointer-to-Pointer Variable:
Syntax : data_type **ptr_variable_name;
Example : int **ptr;
Initialization of Pointer-to-Pointer Variable:
Syntax : ptr_variable_name = &another_ptr_variable_name;
Example:
int a = 10; ptr2 ptr1 a Variable Name
int *ptr1,**ptr2; 3000 2000 10 Value

ptr1 = &a; 4000 3000 2000 Memory Address


ptr2 = &ptr1;
Note: ptr1 holds the address of variable ‘a’.
*ptr1 holds the value of variable ‘a’.
ptr2 holds the address of pointer variable ‘ptr1’.
*ptr2 holds the value of pointer variable ‘ptr1’ (value stored at ptr1 is address of ‘a’).
**ptr2 holds the value of variable ‘a’.
Note: ptr1 holds the address of variable ‘a’. ptr2 ptr1 a Variable Name
*ptr1 holds the value of variable ‘a’. 3000 2000 10 Value

ptr2 holds the address of pointer variable ‘ptr1’. 4000 3000 2000 Memory Address

*ptr2 holds the value of pointer variable ‘ptr1’ (value stored at ptr1 is address of ‘a’).
**ptr2 holds the value of variable ‘a’.
 ptr1  holds the address of variable ‘a’. That is, ptr1 = 2000
 *ptr1  holds the value of variable ‘a’.
Means *ptr1 = value(address(a)).
*ptr1 = value(2000)
That is, *ptr1 = 10
 ptr2  holds the address of pointer variable ‘ptr1’. That is, ptr2 = 3000
 *ptr2  holds the value of pointer variable ‘ptr1’.
Means *ptr2 = value(address(ptr1)).
*ptr2 = value(3000)
That is, *ptr2 = 2000
 **ptr2  holds the value of variable ‘a’.
Means **ptr2 = value(value(address(ptr1))).
**ptr2 = value(value(3000))
**ptr2 = value(2000)
That is, **ptr2 = 10 (value stored in variable ‘a’)
NULL Pointer

A NULL pointer is a pointer that does not point to any memory location. It

represents an invalid memory location.

When a NULL value is assigned to a pointer, then the pointer is considered as

NULL pointer.

Example:

main()

int *ptr = NULL; // This is a NULL Pointer

}
Uses of NULL Pointer
1. It is used to initialize a pointer when that pointer is not assigned any valid
memory address yet.
Example:
main()
{
int *ptr = NULL;
}
2. Useful for handling errors when using malloc() function.
Example:
main()
{
int *ptr;
ptr = (int*)malloc(2*sizeof(int));
if(ptr==NULL)
printf(“Memory could not be allocated”);
else
printf(“Memory allocated successfully”);
}
Facts about NULL Pointer
1. The value of NULL is 0. We can either use NULL or 0 but this 0 is written in
context of pointers and is not equivalent to the integer 0.
Example:
main()
{
int *ptr = NULL;
printf(“%d”, ptr);
}
Output: 0

2. Size of NULL pointer depends upon the platform and is similar to the size of
the normal pointers.
Example:
main()
{
printf(“%d”,sizeof(NULL));
}
Output: 8
Best Practices:

1. It is good practice to initialize a pointer as NULL.

2. It is a good practice to perform NULL check before dereferencing any

pointer to avoid surprises.


Dangling Pointer
A dangling pointer is a pointer which points to some non-existing memory
location.
Example:
main()
{
int *ptr;
ptr = (int*)malloc(2*sizeof(int));
. . . .
. . . .
free(ptr); Memory is released which
} is allocated by malloc()
function

But the pointer ‘ptr’ is still


pointing to the deallocated memory
and it is called Dangling Pointer.
Solution for Dangling Pointer

Example:

main()

int *ptr;

ptr = (int*)malloc(2*sizeof(int));

. . . .

. . . .

free(ptr);

ptr = NULL; // Now, ptr is no more dangling

}
THANK YOU
|| JAI SRI GURUDEV ||
SRI ADICHUNCHANAGIRI SHIKSHANA TRUST ®

ADICHUNCHANAGIRI INSTITUTE OF TECHNOLOGY


(An ISO 9001 : 2008 Certified)
Affiliated to Visvesvaraya Technological University, Belagavi ,
Approved by AICTE and Accredited by NAAC, New Delhi
Jyothinagar, Chikkamagaluru – 577 102.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

ONLINE CLASS USING ZOOM APPLICATION

Subject: Data Structures and Applications


Subject Code: 18CS32

Presented By: Semester and Section : 3rd and ‘A’


Mr. GOPINATH C. B., B.E., M.Tech., Class # : 23
Assistant Professor
1 October 2020 Date : 01-10-2020 (02:15PM TO 03:30PM)
Dynamic Memory Allocation

Functions
Static Memory Allocation:

 Memory allocated during compile time is called Static Memory.

 The memory allocated is fixed and cannot be increased or decreased

during run time.

Example:

#include<stdio.h>
Here, the memory is
main()
allocated at compile
{
time and size is
int arr[5] = {1,2,3,4,5}; fixed.

}
Problems Faced in Static Memory Allocation:

 If you are allocating memory for an array during compile time then you

have to fix the size at the time of declaration. Size is fixed and user

cannot increase or decrease the size of the array at run time.

 If the values stored by the user in the array at run time is less than the

size specified then there will be wastage of memory.

 If the values stored by the user in the array at run time is more than the

size specified then the program may crash or misbehave.


Dynamic Memory Allocation:
The process of allocating memory at the time of execution (run time) is
called Dynamic Memory Allocation.

 Heap is the segment of memory where


Stack dynamic memory allocation takes place.
 Unlike stack where memory is allocated or
deallocated in a defined order. Heap is an area
of memory where memory is allocated or

Heap deallocated without any order or randomly.


 There are certain built-in functions that can
Uninitialized Data
help in allocating or deallocating some memory
Initialized Data
space at run time.
Text/Code Segment
Please Note:

 Pointers play an Important Role in Dynamic

Memory Allocation.

 Allocated Memory can only be accessed through

pointers.
Dynamic Memory Allocation:

The process of allocating memory at the time of execution (run time) is

called Dynamic Memory Allocation.

The different types of Dynamic Memory Allocation Functions are

 malloc()
Built-in Functions and these
 calloc()
functions defined under “Stdlib.h”
 realloc()
header file.
 free()
Dynamic Memory Allocation using malloc():

 malloc() is a built-in function declared in the header file <stdlib.h>.

 malloc() is the short name for “memory allocation” and is used to

dynamically allocate a single large block of contiguous memory

according to the size specified.

 It initializes each block with default Garbage Value.

Syntax:

(void* )malloc(size_t size);

malloc() function simply allocates a memory block according to the

size specified in the heap and an success it returns a pointer pointing to

the first byte the allocated memory else return NULL.

size_t is defined in <stdlib.h> as unsigned int.


Why void pointer?

 malloc() does not have an idea of what it is pointing to.

 It is only allocates memory requested by the user without knowing

the type of data to be stored inside the memory.

 The void pointer can be typecasted to an appropriate type.

Example: 2001 4
B
2002 Y
int *ptr; Memory T
2003
E
ptr = (int* )malloc(4); 2004 S

In the above example, malloc() allocates 4 bytes of memory in the

heap and the address of the first byte is stored in the pointer ptr.
Example Program:
Output 1:
#include<stdio.h> Enter an number
#include<stdlib.h> 100
Entered number is 100
main()
{
Output 2:
int *ptr; Memory not allocated
ptr = (int*)malloc(sizeof(int));
if(ptr==NULL) Here, assume size of integer is 4 bytes
{ 2001 100
printf(“Memory not allocated\n”); 4
exit(0);
2002 B
}
Y
printf(“Enter an number”);
T
scanf(“%d”,ptr); 2003
printf(“Entered number is %d”,*ptr); E
} S
2004
Example Program: Output 1:
#include<stdio.h> Enter the number of Integers
#include<stdlib.h> 3
main() Enter an integer: 10
{ Enter an integer: 20
int i,n, *ptr; Enter an integer: 30
printf(“Enter the number of Integers\n”); 10 20 30
scanf(“%d”,&n); Output 2:
ptr = (int* )malloc(n*sizeof(int)); Memory not allocated
if(ptr==NULL)
Here, assume size of integer is 2 bytes
{
printf(“Memory not allocated\n”); 2001 10
exit(0);
6
} 2002
for(i=0;i<n;i++) B
{ 2003 20 Y
printf(“Enter an integer: ”);
scanf(“%d”,ptr+i); 2004 T
} E
for(i=0;i<n;i++) 2005 30
S
printf(“%d\t”,*(ptr+i));
2006
}
THANK YOU
|| JAI SRI GURUDEV ||
SRI ADICHUNCHANAGIRI SHIKSHANA TRUST ®

ADICHUNCHANAGIRI INSTITUTE OF TECHNOLOGY


(An ISO 9001 : 2008 Certified)
Affiliated to Visvesvaraya Technological University, Belagavi ,
Approved by AICTE and Accredited by NAAC, New Delhi
Jyothinagar, Chikkamagaluru – 577 102.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

ONLINE CLASS USING ZOOM APPLICATION

Subject: Data Structures and Applications


Subject Code: 18CS32

Presented By: Semester and Section : 3rd and ‘A’


Mr. GOPINATH C. B., B.E., M.Tech., Class # : 24
Assistant Professor
2 October 2020 Date : 02-10-2020 (02:30PM TO 04:30PM)
Dynamic Memory Allocation using calloc():
 calloc() is a built-in function declared in the header file <stdlib.h>.
 calloc() is the short name for “contiguous allocation” and is used
to dynamically allocate the specified number of blocks of memory of
the specified type.
 It initializes each block with default ‘0’ value.
Syntax:
(void* )calloc(size_t n, size_t size);

Number of Blocks Size of Each Block

calloc() function simply allocates a specified number of blocks of


memory of the specified type and an success it returns a pointer
pointing to the first byte the allocated memory else return NULL.
size_t is defined in <stdlib.h> as unsigned int.
Example:
int *ptr;
ptr = (int* )calloc(5,4);
In the above example, calloc() allocates 5 blocks of memory in the
heap and size of each block is 4 bytes and the address of the first
byte is stored in the pointer ptr.

Block 1 Block 2 Block 3 Block 4 Block 5

0 0 0 0 0
2001 2005 2009 2013 2017

4 Bytes 4 Bytes 4 Bytes 4 Bytes 4 Bytes

Total Memory Allocated = 20 Bytes


Example Program:
Output 1:
#include<stdio.h> Enter an number
#include<stdlib.h> 100
main() Entered number is 100
{
Output 2:
int *ptr;
Memory not allocated
ptr = (int*)calloc(1,sizeof(int));
if(ptr==NULL)
{
printf(“Memory not allocated\n”); Here, assume size of integer is 4 bytes
exit(0); Block 1
}
printf(“Enter an number”); 0
100
scanf(“%d”,ptr);
printf(“Entered number is %d”,*ptr); 2001

} 4 Bytes
Example Program: Output 1:
#include<stdio.h> Enter the number of Integers
#include<stdlib.h> 3
main() Enter an integer: 10
{ Enter an integer: 20
int i,n, *ptr; Enter an integer: 30
printf(“Enter the number of Integers\n”); 10 20 30
scanf(“%d”,&n); Output 2:
ptr = (int* )calloc(n,sizeof(int)); Memory not allocated
if(ptr==NULL)
{
printf(“Memory not allocated\n”); Here, assume size of integer is 2 bytes
exit(0); Block 1 Block 2 Block 3
}
for(i=0;i<n;i++) 0 0 0
{ 10 20 30
printf(“Enter an integer: ”);
scanf(“%d”,ptr+i); 2001 2003 2005
} 2 Bytes 2 Bytes 2 Bytes
for(i=0;i<n;i++)
printf(“%d\t”,*(ptr+i)); Total Memory Allocated = 6 Bytes
}
Dynamic Memory Allocation using realloc():
 realloc() is a built-in function declared in the header file <stdlib.h>.
 realloc() is the short name for “re-allocation” and is used to
change the size of the memory block without losing the old data.
Syntax:
(void* )realloc(void *ptr, size_t newsize);
Pointer to the Previously
Allocated Memory New Size

 In other words, if the memory previously allocated with the help of malloc() or
calloc() is insufficient, realloc() can be used to dynamically re-allocate
memory.
 re-allocation of memory maintains the already present value and new blocks.
 If space is insufficient, allocation fails and returns a NULL pointer.
 size_t is defined in <stdlib.h> as unsigned int.
Example: Assume size of ‘int’ data type is 4 bytes.
int *ptr;
ptr = (int* )malloc(size(int));
In the above example, malloc() allocates 4 bytes of memory in the heap
and the address of the first byte is stored in the pointer ptr.

ptr
2001 2004
4 Bytes
ptr = (int* )realloc(ptr, 2*sizeof(int));
In the above example, realloc() allocates (2*sizeof(int)) 8 bytes of
memory in the heap and the address of the first byte is stored in the
pointer ptr.

ptr
2001 2008
8 Bytes
 This function (realloc()) moves the contents of the old block to new
block and the data of the old block is not lost.
 We may lose the data when the new size is smaller than the old size.
 Newly allocated bytes are uninitialized.
Example Program: printf(“Enter two more integers\n”);
#include<stdio.h> for(i=2;i<4;i++)
#include<stdlib.h> {
main() scanf(“%d”,ptr+i);
{ }
int i,*ptr; //Printing the integers which are stored
ptr = (int*)malloc(2*sizeof(int)); //in the memory
if(ptr==NULL) printf(“The stored integer nos are\n”);
{ for(i=0;i<4;i++)
printf(“Memory not allocated\n”); {
exit(0); printf(“%d\t”,*(ptr+i));
} }
printf(“Enter two integers\n”); } // Closing of main()
for(i=0;i<2;i++)
{
scanf(“%d”,ptr+i); Output:
} Enter two integers
//Suppose I want store 2 more integers 100
//then allocate memory for 2 more integers
200
ptr = (int*)realloc(ptr,4*sizeof(int));
Enter two more integers
if(ptr==NULL)
300
{
printf(“Memory not allocated\n”);
400
exit(0); The stored integer nos are
} 100 200 300 400
Releasing Dynamically Allocated Memory using free():

 free() is a built-in function declared in the header file <stdlib.h>.

 free() is used to release (deallocate) the dynamically allocated

memory in heap.

 The memory allocated in heap using functions malloc() and

calloc() will not be released (deallocated) automatically after

using the memory. The space remains there and cannot be used.

 It is programmer’s responsibility to release the memory after use by

using free() function.

Syntax:

free(pointer_variable_name);
Example: Assume size of ‘int’ data type is 2 bytes.
main()
{
int *ptr;
ptr = (int*)malloc(4*sizeof(int));
. . . .
. . . .
free(ptr);
ptr = NULL;
}
In the above example, malloc() allocates 8 bytes of memory in the
heap and the address of the first byte is stored in the pointer ptr.
Example Program:
#include<stdio.h>
#include<stdlib.h>
main()
{
int i,n, *ptr; Output 1:
printf(“Enter the number of Integers\n”);
scanf(“%d”,&n); Enter the number of Integers
ptr = (int* )malloc(n*sizeof(int)); 3
if(ptr==NULL)
Enter an integer: 10
{
printf(“Memory not allocated\n”); Enter an integer: 20
exit(0);
Enter an integer: 30
}
for(i=0;i<n;i++) The stored integer nos are
{ 10 20 30
printf(“Enter an integer: ”);
scanf(“%d”,ptr+i); Output 2:
} Memory not allocated
printf(“The stored integer nos are\n”);
for(i=0;i<n;i++)
printf(“%d\t”,*(ptr+i));
free(ptr);
ptr = NULL;
}
THANK YOU
|| JAI SRI GURUDEV ||
SRI ADICHUNCHANAGIRI SHIKSHANA TRUST ®

ADICHUNCHANAGIRI INSTITUTE OF TECHNOLOGY


(An ISO 9001 : 2008 Certified)
Affiliated to Visvesvaraya Technological University, Belagavi ,
Approved by AICTE and Accredited by NAAC, New Delhi
Jyothinagar, Chikkamagaluru – 577 102.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

ONLINE CLASS USING ZOOM APPLICATION

Subject: Data Structures and Applications


Subject Code: 18CS32
Semester and Section : 3rd and ‘A’
Presented By: Class # : 24, 25, 26 and 27
Date : 03-10-2020 (11:00AM TO 11:40AM)
Mr. GOPINATH C. B., B.E., M.Tech., Date : 05-10-2020 (12:00PM TO 12:40PM)
Date : 07-10-2020 (10:00AM TO 10:40AM)
Assistant Professor
8 October 2020
Date : 08-10-2020 (02:30PM TO 03:45PM)
Structures
Definition:
 A structure is a collection of data items, where each item is identified as to
its type and name. The keyword used is ‘struct’.
 In other words, structure is a collection of one or more variables of same or
different data types .
 Each member within a structure is assigned unique storage area of location.
Syntax:
struct structure_name OR struct
{ {
data_type1 variable1; data_type1 variable1;
data_type2 variable2; data_type2 variable2;
. . . . . . . .
data_typen variablen; data_typen variablen;
}; }structure_variable;
Syntax: OR
struct structure_name struct
{ {
data_type1 variable1; data_type1 variable1;
data_type2 variable2; data_type2 variable2;
. . . . . . . .
data_typen variablen; data_typen variablen;
}; }structure_variable;

Example: Suppose, we need to store an employee details.


sturct employee sturct
{ {
int eno; int eno;
Structure Structure
char ename[20]; char ename[20];
Members Members
int age; int age;
}; }emp;
Structure Variable
main() main()
{ {
struct employee emp; . . . .
. . . . . . . .
. . . . . . . .
} User Defined Data Type Structure Variable
}
Accessing the Members of Structure:
Using structure_variable and dot (.) operator, we can access the
members of the structure. dot (.) operator
Syntax:
structure_variable.structure_member_name
Example:
struct
{
char name[10];
int age;
float salary;
}person;
In the above example, structure creates a variable whose name is ‘person’ and
which has 3 fields.
 A name that is a character array.
 An integer value representing the age of the person.
 A float value representing the salary of the person.
We can assign values to fields using the dot (.) operator:
strcpy(person.name,”Arun”);
person.age = 20;
person.salary = 35000;
Initialization of Structure Members:

Example:
#include<stdio.h>
Output:
struct
arun
{
20
char name[10];
int age; 35000.000000
float salary;
}emp={“arun”,20,35000};

main()
{
printf(“%s\n%d\n%f\n”,emp.name,emp.age,emp.salary);
}
Initialization of Structure Members:

Example:
#include<stdio.h>
Output:
struct employee
arun
{
20
char name[10];
int age; 35000.000000
float salary;
};

main()
{
struct employee emp = {“arun”,20,35000};
printf(“%s\n%d\n%f\n”,emp.name,emp.age,emp.salary);
}
Example: Output:
#include<stdio.h> Enter an employee name
struct arun
{ Enter an employee age
20
char name[10];
Enter an employee salary
int age;
35000
float salary; Employee details are
}emp; arun
20
main() 35000.000000
{
printf(“Enter an employee name\n”);
scanf(“%s”,emp.name);
printf(“Enter an employee age\n”);
scanf(“%d”,&emp.age);
printf(“Enter an employee salary\n”);
scanf(“%f”,&emp.salary);
printf(“Employee details are\n”);
printf(“%s\n%d\n%f\n”,emp.name,emp.age,emp.salary);
}
Example:
Output:
#include<stdio.h> Employee1 details are
arun
struct 20
35000.000000
{
Employee2 details are
char name[10]; varun
22
int age; 40000.000000
float salary;
}emp1= {“arun”,20,35000},emp2={“varun”,22,40000};

main()
{
printf(“Employee1 details are\n”);
printf(“%s\n%d\n%f\n”,emp1.name,emp1.age,emp1.salary);
printf(“Employee2 details are\n”);
printf(“%s\n%d\n%f\n”,emp2.name,emp2.age,emp2.salary);
}
Example:
#include<stdio.h>
struct employee Output:
{ Employee1 details are
char name[10];
int age; arun
float salary; 20
};
35000.000000
main() Employee2 details are
{
struct employee emp1, emp2; varun
emp1.name=“arun”; 22
emp1.age=20;
emp1.salary=35000; 40000.000000
emp2.name=“varun”;
emp2.age=22;
emp2.salary=40000;
printf(“Employee1 details are\n”);
printf(“%s\n%d\n%f\n”,emp1.name,emp1.age,emp1.salary);
printf(“Employee2 details are\n”);
printf(“%s\n%d\n%f\n”,emp2.name,emp2.age,emp2.salary);
}
Example: Output: Output (Continued):
#include<stdio.h> Enter an employee1 name Employee1 details are
arun
struct arun
Enter an employee1 age
{ 20 20
char name[10]; Enter an employee1 salary 35000.000000
int age; 35000 Employee2 details are
Enter an employee2 name varun
float salary;
varun
}emp1,emp2; 22
Enter an employee2 age
22 40000.000000
main() Enter an employee2 salary
40000
{
printf(“Enter an employee1 name\n”); scanf(“%s”,emp1.name);
printf(“Enter an employee1 age\n”); scanf(“%d”,&emp1.age);
printf(“Enter an employee1 salary\n”); scanf(“%f”,&emp1.salary);
printf(“Enter an employee2 name\n”); scanf(“%s”,emp2.name);
printf(“Enter an employee2 age\n”); scanf(“%d”,&emp2.age);
printf(“Enter an employee2 salary\n”); scanf(“%f”,&emp2.salary);
printf(“Employee1 details are\n”);
printf(“%s\n%d\n%f\n”,emp1.name,emp1.age,emp1.salary);
printf(“Employee2 details are\n”);
printf(“%s\n%d\n%f\n”,emp2.name,emp2.age,emp2.salary);
}
Array of Structures:

Structure is used to store the information of one particular object but if we need
to store the information of multiple objects then array of structure is used.
Example:
struct
{
char name[10];
int age;
float salary;
}emp;
In the above example, we can read only one employee details using structure
variable ‘emp’ as emp.name, emp.age and emp.salary. If we want to read more
than one employee details using the same structure, then the structure variable
has to be declared as an array that is emp[20].
Example:
struct
{
char name[10];
int age;
float salary;
}emp[10];
In the above example, using structure variable emp[10], we can read 10 employee
details.
emp[0].name, emp[0].age and emp[0].salary stores the details of first employee.
emp[1].name, emp[1].age and emp[1].salary stores the details of second employee.
emp[2].name, emp[2].age and emp[2].salary stores the details of third employee.
-- - - - - - -
emp[9].name, emp[9].age and emp[9].salary stores the details of tenth employee.
Example: Write a C program to read and display N employee
(details like name, age and salary) details using structure.
#include<stdio.h>
struct employee
{
char name[10];
int age;
float salary;
};
main()
{
struct employee emp[50];
int i,n;
printf(“Enter the number of employees\n”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
printf(“Enter the employee %d details\n”,i+1);
printf(“Enter employee name\n”);
scanf(“%s”,emp[i].name);
printf(“Enter employee age\n”);
scanf(“%d”,&emp[i].age);
printf(“Enter employee salary\n”);
scanf(“%f”,&emp[i].salary);
}
printf(“Employee details are\n”);
for(i=0;i<n;i++)
{
printf(“Details of employee %d\n”,i+1);
printf(“Name = %s\n”,emp[i].name);
printf(“Age = %d\n”,emp[i].age);
printf(“Salary = %f\n”,emp[i].salary);
}
} //closing of main()

Output: Output (continued):


Enter the number of employees
2 Employee details are
Enter the employee 1 details
Details of employee 1
Enter employee name
arun Name = arun
Enter employee age
20 Age = 20
Enter employee salary Salary = 35000.000000
35000
Enter the employee 2 details Details of employee 2
Enter employee name Name = varun
varun
Enter employee age Age = 22
22
Enter employee salary Salary = 40000.000000
40000
Type Definition:

 It is denoted by keyword ‘typedef’.

 It allows user to create their own data type (new data type).

Syntax:

typedef original_data_type new_data_type;

Where,

 typedef is a keyowrd.

 originial_data_type represents data type like int, float, double and char.

 new_data_type represents any valid variable name and is given by user.

Example:

typedef int integer;

integer a=10, b=20;


We can create our own structure data types by using the
typedef statement as below:
Syntax:
typedef struct
{
data_type1 variable1;
data_type2 variable2;
. . . .
data_typen variablen;
}structure_variable;
Example:
typedef struct
{
char name[20];
int age;
float salary;
}humanbeing;
Here, humanbeing is the name of the type defined by the structure definition
and we may follow this definition with declaration of variables such as
humanbeing person1, person2;
Example: Output: Output (Continued):
#include<stdio.h> Enter an employee1 name Employee1 details are
typedef struct arun
arun
Enter an employee1 age
{ 20
20
char name[10]; Enter an employee1 salary 35000.000000
int age; 35000 Employee2 details are
float salary; Enter an employee2 name varun
}employee; varun
22
Enter an employee2 age
22 40000.000000
main()
Enter an employee2 salary
{ 40000
employee emp1,emp2;
printf(“Enter an employee1 name\n”); scanf(“%s”,emp1.name);
printf(“Enter an employee1 age\n”); scanf(“%d”,&emp1.age);
printf(“Enter an employee1 salary\n”); scanf(“%f”,&emp1.salary);
printf(“Enter an employee2 name\n”); scanf(“%s”,emp2.name);
printf(“Enter an employee2 age\n”); scanf(“%d”,&emp2.age);
printf(“Enter an employee2 salary\n”); scanf(“%f”,&emp2.salary);
printf(“Employee1 details are\n”);
printf(“%s\n%d\n%f\n”,emp1.name,emp1.age,emp1.salary);
printf(“Employee2 details are\n”);
printf(“%s\n%d\n%f\n”,emp2.name,emp2.age,emp2.salary);
}
Example: Write a C program to read and display N employee
(details like name, age and salary) details using typedef
structure.
#include<stdio.h>
struct employee
{
char name[10];
int age;
float salary;
};
main()
{
typedef struct employee persons;
persons emp[50];
int i,n;
printf(“Enter the number of employees\n”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
printf(“Enter the employee %d details\n”,i+1);
printf(“Enter employee name\n”);
scanf(“%s”,emp[i].name);
printf(“Enter employee age\n”);
scanf(“%d”,&emp[i].age);
printf(“Enter employee salary\n”);
scanf(“%f”,&emp[i].salary);
}
printf(“Employee details are\n”);
for(i=0;i<n;i++)
{
printf(“Details of employee %d\n”,i+1);
printf(“Name = %s\n”,emp[i].name);
printf(“Age = %d\n”,emp[i].age);
printf(“Salary = %f\n”,emp[i].salary);
}
} //closing of main()

Output: Output (continued):


Enter the number of employees
2 Employee details are
Enter the employee 1 details
Details of employee 1
Enter employee name
arun Name = arun
Enter employee age
20 Age = 20
Enter employee salary Salary = 35000.000000
35000
Enter the employee 2 details Details of employee 2
Enter employee name Name = varun
varun
Enter employee age Age = 22
22
Enter employee salary Salary = 40000.000000
40000
Nested Structure (Structure within a Structure) using typedef statement:
Structure within a Structure is called Nested Structure.
Example: Associated with humanbeing structure we may wish to include the
date of his/her birth. We can do this by writing

typedef struct
main()
{
{
int day;
humanbeing person;
int month;
printf(“Enter employee name);
int year; scanf(“%s”,person.name);
}date; printf(“Enter employee age);
scanf(“%d”,person.age);
typedef struct
printf(“Enter employee name);
{ scanf(“%f”,person.salary);
char name[10]; printf(“Enter employee dob in dd mm yyyy format\n”);
int age; scanf(“%d%d%d”,&person.dob.day,&person.dob.month,
float salary; &person.dob.year);
date dob; }

}humanbeing;
Nested Structure (Structure within a Structure) without using typedef statement:

Example:
struct date
main()
{
{
int day;
struct employee person;
int month;
printf(“Enter employee name);
int year;
scanf(“%s”,person.name);
};
printf(“Enter employee age);
scanf(“%d”,person.age);
struct employee
printf(“Enter employee name);
{
scanf(“%f”,person.salary);
char name[10];
printf(“Enter employee dob in dd mm yyyy format\n”);
int age;
scanf(“%d%d%d”,&person.dob.day,&person.dob.month,
float salary;
&person.dob.year);
struct date dob;
}
};
Self-Referential Structures:

 Self-Referential Structures are those structures in which one or more

pointers points to the structure of the same type (pointer to itself) .

 Self-Referential Structure usually require dynamic storage management

routines (malloc()and free()) to explicitly obtain and release memory.

Example:

struct self

int p; Structure
Members
struct self *ptr;

};
Example: struct code { var1 var2
int i; i c ptr i c ptr
char c;
struct code *ptr; 65 ‘A’ NULL 66 ‘B’ NULL
};
1000 2000
main() Base Address Base Address
{
struct code var1;
struct code var2;

var1.i = 65;
var1.c = ‘A’; Access
var1.ptr = NULL; var1 var2
i c ptr i c ptr
var2.i = 66; 65 ‘A’ 2000 66 ‘B’ NULL
var2.c = ‘B’;
var2.ptr = NULL; 1000 2000
Base Address Base Address
var1.ptr = &var2;

printf(“%d\n”,var1.ptr->i);
printf(“%c\n”,var1.ptr->c); Output:
}
66
Note: we will see usefulness of Self-
B
Referential Structures in Linked List.
How Structure is different from Array OR Differences between Arrays and Structures:

Sl.
Arrays Structures
No.
Array refers to a collection consisting of Structure refers to a collection consisting of
1.
elements of homogeneous data type. elements of heterogeneous data type.

Syntax:

Syntax: struct sructure_name


{
2. data_type array_name[size]; data_type1 ele1;
data_type2 ele2;
. . . .
};

Array uses subscripts or square Structure uses dot (.) operator for
3.
bracket ([])for element access. element access.

Array is pointer as it points to the Structure is not a pointer.


4.
first element of the collection.
How Structure is different from Array OR Differences between Arrays and Structures:

Sl.
Arrays Structures
No.
Array size is fixed and is basically the Structure size is not fixed as each
5. number of elements multiplied by element of Structure can be of different
the size of an element. type and size.

Array declaration is done simply Structure declaration is done with the


6.
using [ ] and not any keyword. help of struct keyword.

Array traversal and searching is easy Structure traversal and searching is


7.
and fast. complex and slow.

Array elements are stored in Structure elements may or may not be


8.
continuous memory locations. stored in a continuous memory location.

Array elements are accessed by their Structure elements are accessed by their
9.
index number using subscripts. names using dot operator.
Unions
Definition:
 A union is a collection of data items, where each item is identified as to its
type and name. The keyword used is ‘union’.
 In other words, a union is a collection of one or more variables of same or
different data types .
 Memory allocated is shared by individual members of union .
Syntax:
union union_name OR union
{ {
data_type1 variable1; data_type1 variable1;
data_type2 variable2; data_type2 variable2;
. . . . . . . .
data_typen variablen; data_typen variablen;
}; }union_variable;
Syntax: OR
union union_name union
{ {
data_type1 variable1; data_type1 variable1;
data_type2 variable2; data_type2 variable2;
. . . . . . . .
data_typen variablen; data_typen variablen;
}; }union_variable;

Example: Suppose, we need to store an employee details.


union employee union
{ {
int eno; int eno;
Union Union
char enmae[20]; char enmae[20];
Members Members
int age; int age;
}; }emp;

main() main()
{ {
union employee emp; . . . .
. . . . . . . .
. . . . . . . .
} User Defined Data Type Union Variable
}
Accessing the Members of Union:
Using union_variable and dot (.) operator, we can access the members
of the union. dot (.) operator
Syntax:
union_variable.union_member_name
Example:
union
{
char name[10];
int age;
float salary;
}person;
In the above example, union creates a variable whose name is ‘person’ and
which has 3 fields.
 A name that is a character array.
 An integer value representing the age of the person.
 A float value representing the salary of the person.
We can assign values to fields using the dot (.) operator:
strcpy(person.age,”arun”);
person.age = 20;
person.salary = 35000;
Example:
#include<stdio.h>
Output:
union
{ 65
int a;
char b; A
}un;

main()
{
un.a = 10;
un.b = ‘A’;
printf(“%d\n%c\n”,un.a,un.b);
}

un.a un.b
Here, Assume size of ‘int’
un
data type 2 Bytes and size
2000 10 ‘A’
of ‘char’ data type 1 Byte.
2000
Base Address un.a and un.b are the
1 Byte for ‘char’ members of union.
2 Bytes for ‘int’
Example:
Output:
#include<stdio.h>
10
union
A
{
int a;
char b;
}un;

main()
{
un.a = 10;
printf(“%d\n”,un.a);
un.b = ‘A’;
printf(“%c\n”,un.b);
}
Differences between Structure and Union

Sl.
Structure Union
No.
The keyword ‘struct’ is used to define a The keyword ‘union’ is used to define a
1.
structure. union.
Syntax: Syntax:
struct union
{ {
data_type1 variable1; data_type1 variable1;
2.
data_type2 variable2; data_type2 variable2;
. . . . . . . .
data_typen variablen; data_typen variablen;
}structure_variable; }union_variable;
Example: Example:
struct union
{ {
3.
int a; int a;
char b; char b;
}S; }U;
Differences between Structure and Union
Sl.
Structure Union
No.
When a variable is associated with a When a variable is associated with a union,
structure, the compiler allocates the the compiler allocates the memory by
memory for each member. The size of considering the size of the largest memory. So,
structure is greater than or equal to the size of union is equal to the size of largest
sum of sizes of its members. member.
Example: Example:
struct union
{ Assume { Assume
4. int a; int a; int = 2 Bytes
int = 2 Bytes
char b; char b;
}S; char = 1 Byte }U; char = 1 Byte
U
S
2000
2000
2000 Base Address
2000 Base Address
1 Byte for char
2 Bytes 1 Byte
(int) (char)
2 Bytes for int
Total Memory Allocated for Structure = 3 Bytes Total Memory Allocated for Structure = 2 Bytes
Differences between Structure and Union
Sl.
Structure Union
No.
Each member within a structure is
Memory allocated is shared by individual
5. assigned unique storage area of
members of union.
location.

Altering the value of a member will


Altering the value of any of the member
6. not affect other members of the
will alter other member values.
structure

Individual member can be accessed Only one member can be accessed at a


7.
at a time. time.

Several members of a structure can Only the first member of a union can be
8.
initialize at once. initialized.
Assignment Question:
1. Define Pointers. How to declare and initialize pointers, explain with
example.

2. What do you mean by dynamic memory allocation? List and explain various
functions supported by C to carryout dynamic memory allocation.

3. What is structure? Explain different types of structure declaration with


example.

4. Give the difference between arrays and structures.

OR Explain, how structure is different from array.

5. Give the difference between structures and unions.

6. Explain self-referential structures with an example.

7. Explain typedef structure with an example.


THANK YOU
|| JAI SRI GURUDEV ||
SRI ADICHUNCHANAGIRI SHIKSHANA TRUST ®

ADICHUNCHANAGIRI INSTITUTE OF TECHNOLOGY


(An ISO 9001 : 2008 Certified)
Affiliated to Visvesvaraya Technological University, Belagavi ,
Approved by AICTE and Accredited by NAAC, New Delhi
Jyothinagar, Chikkamagaluru – 577 102.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

ONLINE CLASS USING ZOOM APPLICATION

Subject: Data Structures and Applications


Subject Code: 18CS32

Presented By: Semester and Section : 3rd and ‘A’


Mr. GOPINATH C. B., B.E., M.Tech., Class # : 29
Assistant Professor
14 October 2020 Date : 12-10-2020 (12:00PM TO 12:40PM)
Review of Array Concepts
Definition:

An array is a collection of values of same or similar data type and those

values are stored in consecutive memory locations.

Each value in an array is referenced by a single name, which is the name

of the array and a subscript or index, which indicates the position of the

value in the array.

The subscript or index is a Positive Integer number, which is enclosed in

a pair of square brackets [ ].

It can be used to store the values of different data types, such as int,

float, double, char and string.


Types of Arrays

Arrays are mainly classified into two types:

 One or Single Dimensional Array (1D Array)

 Multi-Dimensional Array

Multi-Dimensional Array further classified into many types:

 Two Dimensional Array (2D Array)

 Three Dimensional Array (3D Array)

etc.,
One Dimensional Array (1D Array)
One Dimensional Array is used for storing the values of same data type
in a Linear List (only one row).

Declaration of One Dimensional Array:

Syntax:

data_type array_name[size];
Where,

data_type represents data type of the array to be declared such


as int, float, double and char.

array_name represents the name of the array.

size represents the number of values of the data_type type that can
be stored in the array_name array.
One Dimensional Array (1D Array)
Example 1:

int a[10];
Where,
int represents data type.
a represents the name of the array.
10 represents size of the array.

Example 2:

float arr[5];
Where,
float represents data type.
arr represents the name of the array.
5 represents size of the array.
Structure of One Dimensional Array:

arr[0] arr[1] arr[2] arr[3] arr[4] .... arr[n-1]

Figure: Structure of One Dimensional Array.

In the above figure, arr[0] represents the First element of the

array, arr[1] represents the Second element of the array, arr[2]

represents the Third element of the array, arr[3] represents the

Fourth element of the array, arr[4] represents the Fifth

element of the array and arr[n-1] represents the nth element of

the array.
One Dimensional Array (1D Array)
Initialization of One Dimensional Array:

Syntax:

data_type array_name[size] = {list of values};


Where,

data_type represents data type of the array to be declared such


as int, float, double and char.

array_name represents the name of the array.

size represents the number of values of the data_type type that can
be stored in the array_name array.

list of values represents the values to be stored in the array_name


array. The values in the list are separated by commas.
Example:

int a[5] = {10,20,30,40,50};

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


a 10 20 30 40 50
2001 2001 2003 2005 2007 2009

Base Address
Memory Location Address

Array name or variable always holds the Base Address of the


memory block. Array variable is called Internal Pointer Variable.

In the above example, int represents data type, a represents name of the
array, size represents size of the array and 10,20,30,40 and 50
represents array elements which is stored in a[0],a[1],a[2],a[3] and
a[4] respectively.
Example (continued):

int a[5] = {10,20,30,40,50};

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


10 20 30 40 50

In the above example:

a[0] holds the value 10, that is a[0] = 10

a[1] holds the value 20, that is a[1] = 20

a[2] holds the value 30, that is a[2] = 30

a[3] holds the value 40, that is a[3] = 40

a[4] holds the value 50, that is a[4] = 50


Memory Occupied by One Dimensional Array:

Total Memory = array_size * sizeof(data_type)


Example:

int a[5];

Total Memory = 5 * 2 Bytes

Total Memory = 10 Bytes

In the above example, the array size is specified as 5 and its data

type is int which occupies 2 Bytes per value in 16 bit computer.

So, Total Memory occupied by array is 5 * 2 is equal to 10

Bytes. Similarly for other data types.


Note:

int arr[4] = {22,31,43,56};

Here, an array is of the Integer type and of size 4 is having four elements
in it. Number of elements in array should not be greater than the array
size.
a[0] a[1] a[2] a[3]

22 31 43 56

float arr[5] = {0.0,15.75,-10};

Here, an array is of the floating point type and of size 5 is having three
elements in it and remaining two elements to zero (0).

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

0.0 15.75 -10 0 0


Note:

int arr[] = {22,31,43,56};

Here, an array is of the Integer type and size of the array is

not specified which means that array can hold any number

of elements.

Applications of One Dimensional Array:

 It is used for searching of an element.

 It is used for sorting of elements.


How to Read/Insert Elements into the 1D Array
Example: int a[5];
a[0] a[1] a[2] a[3] a[4]
11 12 13 14 15

Here, we can insert 5 elements of integer type into the 1D array.


Suppose, we want to insert elements 11, 12, 13, 14 and 15. Here,
the size of the array is 5, that is n = 5. What is the Code?

Using for Loop Statement Using while Loop Statement


i = 0;
for(i=0; i<n; i++)
while(i<n)
{ {
scanf(“%d”,&a[i]);
scanf(“%d”,&a[i])
i++;
} }
How to Print/Display Elements from the 1D Array
Example: int a[5];
a[0] a[1] a[2] a[3] a[4]
11 12 13 14 15

Let us assume that a[0] holds the value 11, a[1] holds the value 12,
a[2] holds the value 13, a[3] holds the value 14 and a[4] holds the
value 15. What is the Code?

Using for Loop Statement Using while Loop Statement


i = 0;
for(i=0; i<n; i++)
while(i<n)
{ {
printf(“%d\n”,a[i]);
printf(“%d\n”,a[i])
i++;
} }
Write a C program, reading elements into the 1D array and displaying
elements from the 1D array.
#include<stdio.h>
void main()
{
int a[20], i, n;
printf(“Enter the size of the array\n”);
scanf(“%d”,&n);
printf(“Enter the array elements\n”);
for(i=0; i<n; i++)
{
scanf(“%d”,&a[i]);
}
printf(“The stored array elements are\n”);
for(i=0; i<n; i++)
{
printf(“%d\n”,a[i]);
}
}
Output 1
Enter the size of the array
5
Enter the array elements
10
20
30
40
50
The stored array elements are
10
20
30
40
50
Output 2
Enter the size of the array
7
Enter the array elements
100 150 200 250 300 350 400
The stored array elements are
100
150
200
250
300
350
400
Two Dimensional Array (2D Array)
Two Dimensional Array is used for storing the values of same data type
in a Table Format or Matrix Format.

Declaration of Two Dimensional Array:

Syntax:

data_type array_name[row_size][column_size];
Where,

data_type represents data type of the array to be declared such


as int, float, double and char.

array_name represents the name of the array.

row_size represents the number of rows.

column_size represents the number of columns.


Two Dimensional Array (2D Array)
Example 1:
int a[2][3];
Where,
int represents data type.
a represents the name of the array.
2 represents number of rows.
3 represents number of columns.

Example 2:
float arr[5][5];
Where,
float represents data type.
arr represents the name of the array.
5 represents number of rows.
5 represents number of columns.
Structure or Representation of Two Dimensional Array:
Here, we consider array variable or array name as ‘a’

C o l u m n s

a[0] a[1] . . . . a[n-1]

a[0] a[0][0] a[0][1] . . . . a[0][n-1]

R a[1] a[1][0] a[1][1] . . . . a[1][n-1]

o . . . . .
. . . . .
w . . . . .
. . . . .
s
a[m-1] a[m-1][0] a[m-1][1] . . . . a[m-1][n-1]

Figure: Structure of Two Dimensional Array.


Structure or Representation of Two Dimensional Array:

In the above figure, there are two index values, one for representing

position in terms of rows and another for representing position in terms

of columns.

Row index start from 0 and ends with m-1, where m is the number of

rows.

Column index start from 0 and ends with n-1, where n is the number

of columns.

a[0][0] holds the element present in First Row and First Column,

a[0][1] holds the element present in First Row and Second Column

and so on.
Two Dimensional Array (2D Array)
Initialization of Two Dimensional Array:

Syntax:
data_type array_name[row_size][column_size]={list of values};

Where,

data_type represents data type of the array to be declared such


as int, float, double and char.

array_name represents the name of the array.

row_size represents the number of rows.

column_size represents the number of columns.

list of values represents the values to be stored in the array_name


array. The values in the list are separated by commas.
Example :

int a[2][3] = {10,20,30,40,50,60};

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

a[0]
10 20 30
a[0][0] a[0][1] a[0][2]

a[1] 40 50 60
a[1][0] a[1][1] a[1][2]

In the above example, int represents data type, a represents name of


the array, 2 represents number of rows and 3 represents number of
columns. 10,20,30,40,50 and 60 represents array elements which
are stored in a[0][0],a[0][1],a[0][2],a[1][0],a[1][1] and
a[1][2] respectively.
Example (continued):

int a[2][3] = {10,20,30,40,50,60};

In the above example:


a[0][0] holds the value 10, that is a[0][0] = 10
a[0][1] holds the value 20, that is a[0][1] = 20
a[0][2] holds the value 30, that is a[0][2] = 30
a[1][0] holds the value 40, that is a[1][0] = 40
a[1][1] holds the value 50, that is a[1][1] = 50
a[1][2] holds the value 60, that is a[1][2] = 60
Memory Occupied by Two Dimensional Array:

Total Memory = row_size * column_size * sizeof(data_type)

Example:

int a[2][3];

Total Memory = 2 * 3 * 2 Bytes

Total Memory = 12 Bytes

In the above example, the row size is specified as 2, column size is

specified as 3 and its data type is int which occupies 2 Bytes per

value in 16 bit computer. So, Total Memory occupied by array is

2 * 3 * 2 is equal to 12 Bytes. Similarly for other data types.


Note:

int arr[2][3] = {22,31,43,56,65,78};

Here, an array is of the Integer type and of row size 2 and column size 3
is having six elements in it. Number of elements in array should not be
greater than the array size.

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

a[0]
22 31 43
a[0][0] a[0][1] a[0][2]

a[1] 56 65 78
a[1][0] a[1][1] a[1][2]
Note:

float arr[2][3] = {0.0,15.75,-10};

Here, an array is of the Floating Point type and of row size 2 and column
size 3 is having three elements in it and remaining three elements to
zero (0).

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

a[0]
0.0 15.75 -10
a[0][0] a[0][1] a[0][2]

a[1] 0 0 0
a[1][0] a[1][1] a[1][2]
Note:
int arr[][] = {1,1,1,1,1,1,1,1};
Here, an array is of the Integer type and row size and
column size of the array is not specified which means that
array can hold any number of elements.

For Example:
int arr[2][3] = {1,1,1,1,1,1};
The above initialization can also be done row by row. The
above example can be equivalently written as
int arr[2][3] = {{1,1,1},{1,1,1}};

Initialization of First Row Initialization of Second Row


Applications of Two Dimensional Array:

 It is used for reading and displaying elements of Matrix.

 It is used for adding, subtracting, multiplying and

dividing of two Matrices.

 It is used for searching and sorting elements of a Matrix.


How to Read/Insert Elements into the 2D Array
Example: int a[2][3];
Here, we can insert up to 6 elements of integer type into the 2D array.
Suppose, we want to insert elements 11, 12, 13, 14, 15 and 16.
Here, the row size of the array is 2, that is m = 2 and the column
size of the array is 3, that is n = 3. What is the Code?

Using while Loop Statement


Using for Loop Statement i = 0;
for(i=0; i<m; i++) while(i<m)
{
{
j = 0;
for(j=0; j<n; j++) while(j<n)
{ {
scanf(“%d”,&a[i][j]);
scanf(“%d”,&a[i][j]) j++;
} }
i++;
} }
How to Print/Display Elements from the 2D Array
Example: int a[2][3];
Let us assume that a[0][0] holds the value 11, a[0][1] holds the
value 12, a[0][2] holds the value 13, a[1][0] holds the value 14,
a[1][1] holds the value 15 and a[1][2] holds the value 16. What is
the Code?

Using for Loop Statement Using while Loop Statement


i = 0;
for(i=0; i<m; i++) while(i<m)
{ {
j = 0;
for(j=0; j<n; j++) while(j<n)
{ {
printf(“%d\t”,a[i][j]);
printf(“%d\t”,a[i][j])
j++;
} }
printf(“\n”); i++;
printf(“\n”);
} }
Write a C program, reading elements into the 2D array and displaying elements
from the 2D array.
#include<stdio.h>
void main()
{
int a[10][20], i, j, m, n;
printf(“Enter the row size and column size of the array\n”);
scanf(“%d%d”,&m,&n);
printf(“Enter the array elements\n”);
for(i=0; i<m; i++)
{
for(j=0; j<n; j++) This block of code represents
{ Reading/Inserting elements into
scanf(“%d”,&a[i][j]); the 2D array.
}
}
printf(“The stored array elements are\n”);
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{ This block of code represents

printf(“%d\t”,a[i][j]); Printing/Displaying elements from

} the 2D array.

printf(“\n”);
}
}
Output 1
Enter the row size and column size of the array
2 3
Enter the array elements
10
20
30
40
50
60
The stored array elements are
10 20 30

40 50 60
Output 2
Enter the row size and column size of the array
4 4
Enter the array elements
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
The stored array elements are
1 2 3 4

5 6 7 8

9 10 11 12

13 14 15 16
THANK YOU
|| JAI SRI GURUDEV ||
SRI ADICHUNCHANAGIRI SHIKSHANA TRUST ®

ADICHUNCHANAGIRI INSTITUTE OF TECHNOLOGY


(An ISO 9001 : 2008 Certified)
Affiliated to Visvesvaraya Technological University, Belagavi ,
Approved by AICTE and Accredited by NAAC, New Delhi
Jyothinagar, Chikkamagaluru – 577 102.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

ONLINE CLASS USING ZOOM APPLICATION

Subject: Data Structures and Applications


Subject Code: 18CS32
Semester and Section : 3rd and ‘A’
Presented By:
Class # : 30 and 31
Mr. GOPINATH C. B., B.E., M.Tech.,
Date : 13-10-2020 (02:30PM TO 04:30PM)
Assistant Professor
14 October 2020
Date : 14-10-2020 (10:00AM TO 10:50AM)
Linear Arrays
Definition:
A linear array is a list of a finite number ‘n’ of homogeneous data elements (i.e.,
data elements of the same type) such that:
 The elements of the array are referenced respectively by an index set
consisting of ‘n’ consecutive numbers.
 The element of the array are stored 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
Length = UB – LB + 1
Where, UB is the largest index, called the Upper Bound and LB is the smallest
index, called the Lower Bound of the array.
Note that, Length = UB when LB = 1.
The elements of an array ‘A’ may be denoted by the subscript notation:
A1, A2, A3, . . . . , An
OR by the parenthesis notation (used in FORTRAN, PL/1 and Basic):
A(1), A(2), A(3), . . . . , A(n)
OR by the bracket notation (used in Pascal):
A[1], A[2], A[3], . . . . , A[n]
Example:
Let array ‘A’ be a 6 elements linear array of integers such that,
A[1]=247, A[2]=56, A[3]=429, A[4]=135, A[5]=87 and A[6]=156
In the above example, the array index starts with ‘1’. So A[1], A[2], A[3],
A[4], A[5] and A[6] (abbreviated A[1:6]) are the number of the six array
elements, each of which contain an integer value.
When LB = 1, then Length = UB A[1:6] means
Here, LB = 1 and UB = 6
Lower Bound Upper Bound
Length = UB => Length = 6 i.e., LB = 1 i.e., UB = 6
Note: We will usually use the Bracket Notation. The number K in A[K] is called a

subscript or an index and A[K] is called a subscripted variable.

Example:

int DATA[6] = {246,56,429,135,87,156};

The array DATA is frequently pictured as in Figure (a) or in Figure(b).

DATA[0] DATA[1] DATA[2] DATA[3] DATA[4] DATA[5]


DATA[1] 246
246 56 429 135 87 156
DATA[2] 56
Figure (b)
DATA[3] 429

DATA[4] 135
Note:
DATA[5] 87
In Figure(a), the array index starts with ‘1’.
DATA[6] 156
In Figure(b), the array index starts with ‘0’.
Figure (a)
DATA[0] DATA[1] DATA[2] DATA[3] DATA[4] DATA[5]
DATA[1] 246
246 56 429 135 87 156
DATA[2] 56
In this example, what is the Length of an array DATA?
DATA[3] 429 Here, the array is abbreviated as DATA[0:5]
Lower Bound (LB) = 0
DATA[4] 135
Upper Bound (UB) = 5
DATA[5] 87 The formula is
Length = UB – LB + 1
DATA[6] 156 Length = 5 – 0 + 1
Length = 6

In this example, what is the Length of an array DATA?


Here, the array is abbreviated as DATA[1:6]
Lower Bound (LB) = 1
Upper Bound (UB) = 6
The formula is
Length = UB
Length = 6
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 addressed locations.
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 need to keep track of the address of every element of
LA, but needs to keep track only of the address of the first element of LA,
denoted by
Base(LA)
 Using Base(LA), the computer calculates the address of any element of LA
by the following formula:

LOC(LA[K]) = Base(LA) + w(K-Lower Bound)


Where ‘w’ is the number of words per memory cell for the array LA and K is
the subscript of array LA.
Example:
Consider the array AUTO, which records the number of automobiles sold each year
from 1932 through 1984. Suppose AUTO appears in memory is Base(AUTO) = 200,
w = 4 words per memory cell. Memory Representation
Then
200
LOC(AUTO[1932]) = 200
201
LOC(AUTO[1933]) = 204 AUTO[1932]
202
LOC(AUTO[1934]) = 208 . . . . etc., 203
The address of the array element for the year K = 1965 204
can be obtained by using following equation: 205
AUTO[1933]
206
LOC(AUTO[k]) = Base(AUTO)+w(K-Lower Bound)
207
Given Data:
208
Base(AUTO)=200, w=4, K=1965 and LB=1932 209
AUTO[1934]
LOC(AUTO[K]) = Base(AUTO)+w(K-Lower Bound) 210
LOC(AUTO[1965]) = 200 + 4 (1965 – 1932) 211
. . .
LOC(AUTO[1965]) = 332 (address) . . .
Example: Note:
Consider a linear array A number elements in an array (length
i. AAA(5:50)
of an array) can be determined by using
ii. BBB(-5:10)
below formula:
iii. CCC(18)
Find a number of elements in each array. Length = UB – LB + 1

Solution:
i. AAA(5:50)
Here, LB = 5 and UB = 50
Length = UB – LB + 1 => Length = 50 – 5 + 1 => Length = 46

ii. BBB(-5:10)
Here, LB = -5 and UB = 10
Length = UB – LB + 1 => Length = 10 – (-5) + 1 => Length = 16

iii. CCC(18)
Here, we assumed an array index starts with ‘1’. LB = 1 and UB = 18
Length = UB – LB + 1 => Length = 18 – 1 + 1 => Length = 18
Example:
Note:
Consider an array AAA[5:65], if
Base(AAA) = 300 and w = 4. Find The address of any element of Linear Array can be
the address of
determined by using below formula:
i. AAA[15]
ii. AAA[35] LOC(LA[K])=Base(LA)+w(K-Lower Bound)
iii. AAA[55]

Solution:
Given Data: Base(AAA) = 300, w = 4 and AAA[5:65], here LB = 5 and UB = 65
i. AAA[15], Here, K = 15
LOC(AAA[K]) = Base(AAA) + w(K-Lower Bound)
LOC(AAA[15]) = 300 + 4 (15 – 5) => LOC(AAA[15]) = 340
ii. AAA[35], Here, K = 35
LOC(AAA[K]) = Base(AAA) + w(K-Lower Bound)
LOC(AAA[35]) = 300 + 4 (35 – 5) => LOC(AAA[35]) = 420
iii. AAA[55], Here, K = 55
LOC(AAA[K]) = Base(AAA) + w(K-Lower Bound)
LOC(AAA[55]) = 300 + 4 (55 – 5) => LOC(AAA[55]) = 500
Multidimensional Arrays
 The linear arrays discussed so far are also called One-dimensional arrays,

since each element in the array is referenced by a single subscript.

 Most programming languages allow two-dimensional and three-dimensional

arrays. i.e, arrays where elements are referenced, respectively, by two and

three subscripts.

Multidimensional arrays are further classified into many types:

 Two-dimensional Arrays (2D)

 Three-dimensional Arrays (3D)

etc.,
Two-dimensional Arrays
Definition:
A two-dimensional m x n array A is collection of m*n data elements such that
each element is specified by a pair of integers (such as J, K), called subscripts,
with the property that
1 ≤ J ≤ m and 1 ≤ K ≤ n
The element of A with first subscript J and second subscript K will be denoted by
AJ,K or A[J, K]
Two-dimensional arrays are called matrices in mathematics and tables in
business applications, hence two-dimensional arrays are sometimes called
matrix arrays.
There is a standard way of drawing a two-dimensional m x n array A where the
elements of A form a rectangular array with m rows and n columns and where
the element A[J, K] appears in row J and column K (a row is a horizontal list of
elements and a column is a vertical list of elements).
Example:
The below example shows an two-dimensional array ‘A’ has 3 rows and 4
columns.
Columns

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


A[1] A[1,1] A[1,2] A[1,3] A[1,4]
Rows A[2] A[2,1] A[2,2] A[2,3] A[2,4]
A[3] A[3,1] A[3,2] A[3,3] A[3,4]

Figure: Two-dimensional 3 x 4 Array ‘A’.

Suppose A is a two-dimensional m x n array.


The first dimension of A contains the index set 1,....,m, with lower bound 1
and upper bound m.
The second dimension of A contains the index set 1,....,n, with lower bound 1
and upper bound n.
The length of a dimension is the number of integers in its index set. The pair of
lengths m x n (read “m by n”) is called the size of the array.
The length of a given dimension (i.e., the number of integers in its index set) can
be obtained from the formula
Length = upper bound – lower bound + 1
Example:
Consider an two-dimensional array
That is, INTEGER NUMB[2:5 , -3:1] (in FORTRAN Language)
Here the index sets of the dimensions consist, respectively, of the integers
2, 3, 4, 5 and -3,-2,-1, 0, 1
We can calculate the length of the first dimension (i.e., number of rows)
By using equation, Length = upper bound – lower bound + 1
Length = 5 – 2 + 1 => Length = 4 (number of rows i.e., m = 4)
We can calculate the length of the second dimension (i.e., number of columns)
By using equation, Length = upper bound – lower bound + 1
Length = 1 – (-3) + 1 => Length = 5 (number of columns i.e., n = 5)
The length of array NUMB can be calculated by using m x n.
The NUMB array contains i.e., m x n => 4 x 5 => 20 elements.
Representation of Two-dimensional Arrays in Memory

 Let A be a two-dimensional m x n array.

 Although A is pictured as a rectangular array of elements with m

rows and n columns, the array will be represented in memory by a

block m x n sequential locations.

Specifically, the programming language will store the array A either

(1) column by column, is called column-major order OR

(2) row by row, is called row-major order


Example:
Consider an two-dimensional array A
with size 3 x 4.
Using Column-major Order:

A[1,1]
A[2,1] Column 1
A[3,1]
A[1,2]
A[2,2] Column 2
A[3,2]
A[1,3]
A[2,3] Column 3
A[3,3]
A[1,4]
A[2,4] Column 4
A[3,4]

Figure: Column-major Order.


Example:
Consider an two-dimensional array A
with size 3 x 4.

Using Row-major Order:

A[1,1]
A[1,2]
Row 1
A[1,3]
A[1,4]
A[2,1]
A[2,2]
Row 2
A[2,3]
A[2,4]
A[3,1]
A[3,2]
Row 3
A[3,3]
A[3,4]

Figure: Row-major Order.


Similarly of LA, the address of 1st element i.e., A[1,1] of array A and computes

the address LOC(A[J,K]) of array A[J,K] using the below formula (recall

formula to find 1st element address of LA i,e., LOC(LA[K]) = Base(LA)+w(K-

Lower Bound))

Formula for Column-major Order:

LOC(A[J,K]) = Base(A) + w[M(K-1) + (J-1)]

Formula for Row-major Order:

LOC(A[J,K]) = Base(A) + w[N(J-1) + (K-1)]

Where,

w represents number of words per memory location of the array A

Base(A) represents Base address of array A

M represents number of rows

N represents number of columns


Example:
Consider the 25 x 4 matrix array SCORE. Suppose Base(SCORE)=200 and there
are w=4 words per memory cell and programming language stores two-
dimensional arrays using row-major order. Then, what is the address of
SCORE[12,3], the third test of the twelfth student?
Given Data:
Base(SCORE)=200, w=4, M=25 and N=4
Here, we need to find the address of SCORE[12,3] i.e., J = 12 and K=3
Formula for Row-major Order:
LOC(A[J,K]) = Base(A) + w[N(J-1) +(K-1)]
LOC(SCORE[12,3]) = Base(SCORE) + w[N(J-1) + (K-1)]
LOC(SCORE[12,3]) = 200 + 4[4(12-1) + (3-1)]
LOC(SCORE[12,3]) = 200 + 4[4(11) + 2]
LOC(SCORE[12,3]) = 200 + 4[44 + 2]
LOC(SCORE[12,3]) = 200 + 4[46]
LOC(SCORE[12,3]) = 200 + 184
LOC(SCORE[12,3]) = 384 (address)
Example:
Consider the 25 x 4 matrix array SCORE. Suppose Base(SCORE)=200 and there
are w=4 words per memory cell and programming language stores two-
dimensional arrays using column-major order. Then, what is the address of
SCORE[12,3], the third test of the twelfth student?
Given Data:
Base(SCORE)=200, w=4, M=25 and N=4
Here, we need to find the address of SCORE[12,3] i.e., J = 12 and K=3
Formula for Column-major Order:
LOC(A[J,K]) = Base(A) + w[M(K-1) +(J-1)]
LOC(SCORE[12,3]) = Base(SCORE) + w[M(K-1) + (J-1)]
LOC(SCORE[12,3]) = 200 + 4[25(3-1) + (12-1)]
LOC(SCORE[12,3]) = 200 + 4[25(2) + 11]
LOC(SCORE[12,3]) = 200 + 4[50 + 11]
LOC(SCORE[12,3]) = 200 + 4[61]
LOC(SCORE[12,3]) = 200 + 244
LOC(SCORE[12,3]) = 444 (address)
Example:
Consider an array X[-5:5, 3:33], if Base(X) = 400 and w = 4. Programming
language stores two-dimensional arrays using row-major order. Find the
address of X[5,10].
Given Data:
Base(X)=400 and w=4
M=? and N=?
We can calculate the length of the first dimension (i.e., number of rows)
By using equation, Length = upper bound – lower bound + 1
Length = 5 – (-5) + 1 => Length = 11 (number of rows i.e., M = 11)
We can calculate the length of the second dimension (i.e., number of columns)
By using equation, Length = upper bound – lower bound + 1
Length = 33 – 3 + 1 => Length = 31 (number of columns i.e., N = 31)
Now, we need to find the address of X[5,10] i.e., J = 5 and K=10
Formula for Row-major Order:
LOC(A[J,K]) = Base(A) + w[N(J-1) +(K-1)]
LOC(X[5,10]) = Base(X) + w[N(J-1) + (K-1)]
LOC(X[5,10]) = 400 + 4[31(5-1) + (10-1)]
LOC(X[5,10]) = 400 + 4[31(4) + 9]
LOC(X[5,10]) = 400 + 4[124 + 9]
LOC(X[5,10]) = 400 + 4[133]
LOC(X[5,10]) = 400 + 532
LOC(X[5,10]) = 932 (address)
THANK YOU
|| JAI SRI GURUDEV ||
SRI ADICHUNCHANAGIRI SHIKSHANA TRUST ®

ADICHUNCHANAGIRI INSTITUTE OF TECHNOLOGY


(An ISO 9001 : 2008 Certified)
Affiliated to Visvesvaraya Technological University, Belagavi ,
Approved by AICTE and Accredited by NAAC, New Delhi
Jyothinagar, Chikkamagaluru – 577 102.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

ONLINE CLASS USING ZOOM APPLICATION

Subject: Data Structures and Applications


Subject Code: 18CS32

Presented By: Semester and Section : 3rd and ‘A’

Mr. GOPINATH C. B., B.E., M.Tech., Class # : 32

Assistant Professor
22 October 2020
Date : 15-10-2020 (03:30PM TO 04:30PM)
General Multidimensional Arrays

Definition:

An n-dimensional m1xm2x....xmn array B is a collection of

m1*m2*....*mn data elements in which each element is specified by a

list of n integers such as K1,K2,….,Kn called subscripts with the

property that

1 ≤ K1 ≤ m1, 1 ≤ K2 ≤ m2, . . . . , 1 ≤ Kn ≤ mn

The element of B with subscripts K1,K2,….,Kn will be denoted by

BK1,K2,….,Kn or B[K1,K2,….,Kn]
Example: Suppose B is a three-dimensional array .
Declaration of Three-dimensional Array:
Syntax:
data_type array_name[size1][size2][size3];
Where, size1 represents number of rows
size2 represents number of columns
size3 represents number of pages
Example:
int B[2][4][3];
In the above example, B is a three-dimensional array. It contains 2 rows, 4
columns and 3 pages. Column1 Column1 Column1 Column1

Row1

Row2
Example: Consider an three-dimensional array B[2][4][3]. The array B

contains 2*4*3 = 24 data elements. These 24 elements of B are usually

pictured as in below figure. They appear in three layers called pages, where

each page consists of the 2*4 rectangular array of elements with the same third

subscript.

The three subscripts of an element in a three-dimensional array are called,

respectively, the row, column and page of the element.

Column1 Column2 Column3 Column4


B[1,1,3] B[1,2,3] B[1,3,3] B[1,4,3]
B[2,1,3] B[2,2,3] B[2,3,3] B[2,4,3]
Page3
B[1,1,2] B[1,2,2] B[1,3,2] B[1,4,2]
B[2,1,2] B[2,2,2] B[2,3,2] B[2,4,2]
Page2
Row1 B[1,1,1] B[1,2,1] B[1,3,1] B[1,4,1]
Row2 B[2,1,1] B[2,2,1] B[2,3,1] B[2,4,1]
Page1
 The array will be stored in memory in a sequence of memory

locations. Specifically, the programming language will store the

array B either in Column-major Order or in Row-major Order.

 By Row-major-Order, mean that the elements are listed so that the

last subscript varies first (most rapidly), the next-to-last subscript

varies second (less rapidly) and so on.

 By Column-major-Order, mean that the elements are listed so that

the first subscript varies first (most rapidly), the second subscript

varies second (less rapidly) and so on.


Using Column-major Order: Consider an array B[2][2][3]

B Subscripts Column1 Column2

[1,1,1] B[1,1,3] B[1,2,3]

[2,1,1]
B[2,1,3] B[2,2,3]
[1,2,1]
Page3
B[1,1,2] B[1,2,2]
[2,2,1]
[1,1,2]
B[2,1,2] B[2,2,2]
[2,1,2] Page2

Row1 B[1,1,1] B[1,2,1]


[1,2,2]
[2,2,2] Row2 B[2,1,1] B[2,2,1]
[1,1,3] Page1

[2,1,3]
[1,2,3]
[2,2,3]

Figure: Column-major Order.


Using Row-major Order: Consider an array B[2][2][3]

B Subscripts Column1 Column2

[1,1,1] B[1,1,3] B[1,2,3]

[1,1,2]
B[2,1,3] B[2,2,3]
[1,1,3]
Page3
B[1,1,2] B[1,2,2]
[1,2,1]
[1,2,2]
B[2,1,2] B[2,2,2]
[1,2,3] Page2

Row1 B[1,1,1] B[1,2,1]


[2,1,1]
[2,1,2] Row2 B[2,1,1] B[2,2,1]
[2,1,3] Page1

[2,2,1]
[2,2,2]
[2,2,3]

Figure: Row-major Order.


 Let C be an n-dimensional array. The length Li can be calculated by using
the following formula:
Li = upper bound – lower bound + 1
 For a given subscript Ki, the effective index Ei of Li is the number of indices
preceding Ki in the index set and Ei can be calculated from
Ei = Ki – lower bound
 Then the address LOC(C[K1,K2,....,KN]) of an arbitrary element of C can
be obtained from the formula (for n-dimensional array)
Base(C)+w[(((...(ENLN-1+EN-1)LN-2)+....+E3)L2+E2)L1+E1]
Or from the formula
Base(C)+w[(....((E1L2+E2)L3+E3)L4+....+EN-1)LN+EN]
Where array C can be stored in either in Row-major Order or Column-major
Order. Base(C) denotes address of 1st element of array C and w denotes
number of words per memory location.
Formula for three-dimensional array:
LOC(C[K1,K2,..,KN]) = Base(C)+w[(E1L2+E2)L3 + E3]
Example:

Suppose a three-dimensional array B is declared using

B[2:4,-4:-3,6:7]

Then length of three dimensions of B are respectively.

Bys using equation, Li = upper bound – lower bound + 1

L1 = 4 – 2 +1 = 3

L2 = -3 – (-4) +1 = 2

L3 = 7 – 6 +1 = 2

Accordingly, B contains

L1 * L2 * L3 = 3 * 2 * 2 = 12 elements.

Suppose, the programming language stores B in memory in row-major order

and Base(B)=200 and there are w=2 words per memory cell. Find the address of

B[3,-3,7].
Example (Continued): Suppose a three-dimensional array B is declared using
B[2:4,-4:-3,6:7]. That is B[3,2,2] = 3*2*2 = 12 elements.
The address of B[3,-3,7] is obtained as follows:
The effective indices are of the subscripts are, respectively.
By using equation, Ei = Ki – lower bound
E1 = 3 – 2 = 1
E2 = -3 –(-4) = 1
E3 = 7 – 6 = 1
Using row-major order , we have
LOC(B[3,-3,7]) = Base(B)+w[(E1L2+E2)L3 + E3]
E1L2 = 1 * 2 = 2
E1L2 + E2 = 2 + 1 = 3
(E1L2+E2)L3 = 3 * 2 = 6
(E1L2+E2)L3 + E3= 6 + 1 = 7
Therefore,
LOC(B[3,-3,7])= 200 + 2(7) = 214 (address)
Visualization of Previous Example:
Column -4 Column-3
Suppose a three-dimensional array B is declared using
B[2,-4,7] B[2,-3,7]
B[2:4,-4:-3,6:7]. That is B[3,2,2] = 3*2*2 = 12 elements. B[3,-4,7] B[3,-3,7]
B[4,-4,7] B[4,-3,7]
Using Row-Major Order:
Page7
Address B Subscripts Row2 B[2,-4,6] B[2,-3,6]

200 [2,-4,6] Row3 B[3,-4,6] B[3,-3,6]


Row4 B[4,-4,6] B[4,-3,6]
202 [2,-4,7]
Page6
204 [2,-3,6]
206 [2,-3,7] Here, finding the address of B[3,-3,7].
208 [3,-4,6] If Base(B)=200 and w=2
210 [3,-4,7] The address is 214.
212 [3,-3,6]
214 [3,-3,7]
216 [4,-4,6]
218 [4,-4,7]
220 [4,-3,6]
222 [4,-3,7]
THANK YOU
|| JAI SRI GURUDEV ||
SRI ADICHUNCHANAGIRI SHIKSHANA TRUST ®

ADICHUNCHANAGIRI INSTITUTE OF TECHNOLOGY


(An ISO 9001 : 2008 Certified)
Affiliated to Visvesvaraya Technological University, Belagavi ,
Approved by AICTE and Accredited by NAAC, New Delhi
Jyothinagar, Chikkamagaluru – 577 102.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

ONLINE CLASS USING ZOOM APPLICATION

Subject: Data Structures and Applications


Subject Code: 18CS32
Semester and Section : 3rd and ‘A’
Presented By: Class # : 33, 34 and 35
Mr. GOPINATH C. B., B.E., M.Tech., Date : 17-10-2020 (11:00AM TO 11:40AM)
Date : 19-10-2020 (12:00PM TO 12:40PM)
Assistant Professor
22 October 2020
Date : 20-10-2020 (02:30PM TO 04:00PM)
Example: A three-dimensional array MAZE is declared as follows:

MAZE[2:8,-4:1,6:10]

If Base(MAZE)=200 and w=4 and find the address of

MAZE[5,-1,8] using row-major order.

Solution:

The length of the three dimensions of MAZE are, respectively.

Bys using equation, Li = upper bound – lower bound + 1

L1 = 8 – 2 + 1 = 7

L2 = 1 – (-4) + 1 = 6

L3 = 10 – 6 +1 = 5

Accordingly, MAZE contains

L1 * L2 * L3 = 7 * 6 * 5 = 210 elements.
Example (Continued):
The address of MAZE[5,-1,8] is obtained as follows:
The effective indices are of the subscripts are, respectively.
By using equation, Ei = Ki – lower bound
E1 = 5 – 2 = 3
E2 = -1 –(-4) = 3
E3 = 8 – 6 = 2
Using row-major order , we have
LOC(MAZE[K1,K2,K3]) = Base(MAZE)+w[(E1L2+E2)L3 + E3]
E1L2 = 3 * 6 = 18
E1L2 + E2 = 18 + 3 = 21
(E1L2+E2)L3 = 21 * 5 = 105
(E1L2+E2)L3 + E3 = 105 + 2 = 107
Therefore,
LOC(MAZE[5,-1,8])= 200 + 4(107) = 200 + 428 = 628 (address)
Dynamically Allocated Arrays

Definition:

The process of allocating memory during execution time (run time) is

called Dynamic Memory Allocation.

 Dynamically Allocated Arrays for 1D Array

 Dynamically Allocated Arrays for 2D Array


Dynamically Allocated Arrays for 1D Array

 Array is a collection of homogeneous data types and one-dimensional array

is the simplest type of array that contains only one row for storing data.

 When writing computer programs, we often find ourselves in a situation

where we cannot reliably determine how large an array to use. A good

solution to this problem is to defer this decision to run time and allocate the

array when we have a good estimate of the required array size.

 If we want to allocate a memory while executing the program means, we

should go for dynamic memory allocation as shown below.


Since malloc() and calloc() may be invoked from several places in our
program, it is often convenient to define a macro that invokes malloc() and
calloc() and exits when malloc()and calloc() fails.
A possible macro definition for malloc() is:
#define MALLOC(p,s) \
if(!((p)= malloc(s))) { \
printf(“Insufficient Memory\n”); \
exit(0); \
}
A possible macro definition for calloc() is:
#define CALLOC(p,n,s) \
if(!((p)= calloc(n,s))) { \
printf(“Insufficient Memory\n”); \
exit(0); \
}
Example Program using malloc(): printf(“Enter the elements\n”);
#inlcude<stdio.h> for(i=0;i<n;i++)
#include<stdlib.h> {
scanf(“%d“,list+i);
#define MALLOC(p,s) \
}
if(!((p)= malloc(s))) { \
printf(“The elements are\n”);
printf(“Insufficient Memory\n”); \
for(i=0;i<n;i++)
exit(0); \ {
} printf(“%d\t“,*(list+i));
main() }
{ } // Closing of main()

int i,n,*list;
printf(“Enter size of an array\n”);
Output:
scanf(“%d”,&n);
Enter size of an array
if(n<1)
5
{
Enter the elements
printf(“Improper value of n\n”);
1 2 3 4 5
exit(0);
The elements are
}
1 2 3 4 5
MALLOC(list, n*sizeof(int));
Example Program using calloc(): printf(“Enter the elements\n”);
#inlcude<stdio.h> for(i=0;i<n;i++)
#include<stdlib.h> {
scanf(“%d“,list+i);
#define CALLOC(p,n,s) \
}
if(!((p)= calloc(n,s))) { \
printf(“The elements are\n”);
printf(“Insufficient Memory\n”); \
for(i=0;i<n;i++)
exit(0); \ {
} printf(“%d\t“,*(list+i));
main() }
{ } // Closing of main()

int i,n,*list;
printf(“Enter size of an array\n”);
Output:
scanf(“%d”,&n);
Enter size of an array
if(n<1)
5
{
Enter the elements
printf(“Improper value of n\n”);
1 2 3 4 5
exit(0);
The elements are
}
1 2 3 4 5
CALLOC(list,n,sizeof(int));
Dynamically Allocated Arrays for 2D Array

 C uses the so-called array-of-arrays representation to represent a

multidimensional array.

 In this representation, a two-dimensional array is represented as a one-

dimensional array in which each element is, a one-dimensional array.

For example:

int x[3][5];

We actually create a one-dimensional array x whose length is 3; each element of

x is a one-dimensional array whose length is 5.


For example:
int x[3][5];
We actually create a one-dimensional array x whose length is 3; each element of
x is a one-dimensional array whose length is 5.
The below figure shows the memory structure:

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

x[0]

x[1]

x[2]

Figure: Array-of-arrays representation.


C finds the element x[i][j] by first accessing the pointer in x[i]. This pointer
gives us the address, in memory, of zeroth element of row i of the array. Then
by adding j*sizeof(int) to this pointer, the address of the [j]th element of
row i (i.e., element x[i][j]) is determined.
A possible macro definition for malloc() is:
#define MALLOC(p,s) \
if(!((p)= malloc(s))) { \
printf(“Insufficient Memory\n”); \
exit(0); \
}
A possible macro definition for calloc() is:
#define CALLOC(p,n,s) \
if(!((p)= calloc(n,s))) { \
printf(“Insufficient Memory\n”); \
exit(0); \
}
A possible macro definition for realloc() is:
#define REALLOC(p,s) \
if(!((p)= realloc(s))) { \
printf(“Insufficient Memory\n”); \
exit(0); \
}
Example Program using malloc(): printf(“Enter the elements\n”);
#inlcude<stdio.h> for(i=0;i<rows;i++)
for(j=0;j<cols;j++)
#include<stdlib.h>
scanf(“%d“,*(x+i)+j);
#define MALLOC(p,s) \ printf(“The elements are\n”);
if(!((p)= malloc(s))) { \ for(i=0;i<rows;i++)
printf(“Insufficient Memory\n”); \ {
for(j=0;j<cols;j++)
exit(0); \
{
} printf(“%d\t“,*(*(x+i)+j));
main() }
{ printf(“\n”);
} // Closing of main()
int **x,i,j,rows,cols;
printf(“Enter size of an array\n”); Output:
scanf(“%d%d”,&rows,&cols); Enter size of an array
MALLOC(x, rows*sizeof(*x)); 2 2
for(i=0;i<rows;i++) Enter the elements
{ 2 2 2 2
MALLOC(x[i],cols*sizeof(**x)); The elements are
} 2 2
2 2
Abstract Data Type (ADT):
Abstract Data type (ADT) is a type for objects whose behaviour is defined by a
set of value and a set of operations.
ADT for Array:
objects: A set of pairs <index,value> where for each value of index
there is a value from the set item. Index is a finite ordered set of
one or more dimensions. For example, {0....n-1} for one dimension,
{(0,0),(0,1),(0,2),(1,0),(1,1),(1,2),(2,0),(2,1),(2,2)} for two
dimensions, etc.,
functions:
For all A ϵ Array, i ϵ index, x ϵ item, j,size ϵ integer
Array Create(j,list) ::= return an array of j dimensions where list is a j-tuple whose ith
element is the size of the ith dimension. Items are undefined.
Item Retrieve(A,i) ::= if(iϵindex) return the item asoociated with index value I in an
Array A, else return error
Array Store(A,i,x) ::= if(i in index) return an array that is identical to array A except
the new pair <i,x> has been inserted else return error.
end Array
Assignment Questions:
1. What do you mean by linear arrays? Explain how to represent linear arrays in
memory.
2. Explain about the representation of two dimensional arrays in memory.
3. Briefly discuss about the dynamically allocated arrays for 1D and 2D with
example.
4. Suppose each student in a class of 25 students is given 4 tests, assume the
students are numbered from 1 to 25 and the test scores are assigned in the
25x4 matrix called SCORE. Suppose Base(SCORE)=200, w=4 and the
programming language uses row-major order to store this 2D array, then find
the address of 3rd test of 12th student i.e., SCORE(12,3).
5. A three-dimensional array MAZE is declared as follows:
MAZE[2:8,-4:1,6:10]
If Base(MAZE)=200 and w=4 and find the address of
MAZE[5,-1,8] using row-major order.
THANK YOU
|| JAI SRI GURUDEV ||
SRI ADICHUNCHANAGIRI SHIKSHANA TRUST ®

ADICHUNCHANAGIRI INSTITUTE OF TECHNOLOGY


(An ISO 9001 : 2008 Certified)
Affiliated to Visvesvaraya Technological University, Belagavi ,
Approved by AICTE and Accredited by NAAC, New Delhi
Jyothinagar, Chikkamagaluru – 577 102.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

ONLINE CLASS USING ZOOM APPLICATION

Subject: Data Structures and Applications


Subject Code: 18CS32
Semester and Section : 3rd and ‘A’
Presented By:
Class # : 36 and 37
Mr. GOPINATH C. B., B.E., M.Tech.,
Date : 21-10-2020 (10:00AM TO 10:40AM)
Assistant Professor
22 October 2020
Date : 22-10-2020 (02:30PM TO 03:30PM)
ARRAY OPERATIONS

 Traversing Operation

 Inserting Operation

 Deleting Operation

 Sorting Operation

 Searching Operation
Traversing Operation:

 Let 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 A with a given property can be

accomplished by Traversing.

 Traversing is a accessing and processing each element in the array Exactly

Once.
Traversing Operation (Continued):

Algorithm 1: Traversing a Linear Array

Hear LA is a linear array with the lower bound LB and upper bound UB. This

algorithm traverses LA applying an operation PROCESS to each element of LA

using while loop.

1. [Initialize Counter] set K:= LB

2. Repeat step 3 and 4 while K ≤ UB

3. [Visit element] Apply PROCESS to LA [K]

4. [Increase counter] Set K:= K + 1

[End of step 2 loop]

5. Exit.
Traversing Operation (Continued):

Algorithm 2: Traversing a Linear Array

Hear LA is a linear array with the lower bound LB and upper bound UB. This

algorithm traverses LA applying an operation PROCESS to each element of LA

using repeat – for loop.

1. Repeat for K = LB to UB

Apply PROCESS to LA [K]

[End of loop]

2. Exit.
Traversing Operation (Continued):

Example: Consider the array AUTO which records the number of automobiles

sold each year from 1932 through 1984 .

To find the number NUM of years during which more than 300 automobiles were

sold, involves traversing AUTO.

1.[Initialization step.] Set NUM := 0

2. Repeat for K = 1932 to 1984:

If AUTO [K] > 300, then: Set NUM: = NUM + 1.

[End of loop.]

3.Return.
Traversing Operation (Continued):
Example: Consider the array AUTO which records the number of automobiles
sold each year from 1932 through 1936.
To find the number NUM of years during which more than 300 automobiles were
sold, involves traversing AUTO.
1.[Initialization step.] Set NUM := 0
2. Repeat for K = 1932 to 1936:
If AUTO [K] > 300, then: Set NUM := NUM + 1.
Index Value
[End of loop.]
3.Return. AUTO[1932] 300

AUTO[1933] 400
Here, NUM = 3
AUTO[1934] 350

AUTO[1935] 285

AUTO[1936] 310
Traversing Operation (Continued):

Example: Consider the array AUTO which records the number of automobiles

sold each year from 1932 through 1984 .

To print each year and the number of automobiles sold in that year.

1. Repeat for K = 1932 to 1984:

Write: K, AUTO[K].

[End of loop]

2. Return
Inserting Operation:

 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 collection 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.


Inserting Operation (Continued):

Algorithm : Inserting into a Linear Array INSERT (LA, N, K, ITEM)

Here LA is a linear array with N elements and K is a positive integer such that K ≤

N. This algorithm inserts an element ITEM into the Kt h position in LA.

1.[Initialize counter]set J:= N

2. Repeat step 3 and 4 while J ≥ K

3. [Move Jth element downward] Set LA [J+1] := LA[J]

4. [Decrease counter] Set J:= J – 1

[End of step 2 loop]

5.[Insert element]Set LA[K]:= ITEM

6.[Reset N] set N:= N+1

7. Exit.
Deleting Operation:

 Deleting refers to the operation of removing one element to the collection A.

 Deleting an element at the “end” of the linear array can be easily done with

difficulties.

 If element at the middle of the array needs to be deleted, then each

subsequent elements be moved one location upward to fill up the array.


Deleting Operation (Continued):

Algorithm : Deleting from a Linear Array DELETE (LA, N, K, ITEM)

Here LA is a linear array with N elements and K is a positive integer such that K ≤

N. this algorithm deletes the Kt h element from LA.

1.Set ITEM:= LA[K]

2.Repeat for J = K to N – 1

[Move J + 1 element upward]set LA[J]:= LA[J+1]

[End of loop]

3.[Reset the number N of elements in LA] set N:= N – 1

4. Exit
Example: Inserting and Deleting:

 Suppose NAME is an 8-element linear array, and suppose five names are in the array, as in Fig.(a).

 Observe that the names are listed alphabetically, and suppose we want to keep the array names alphabetical at

all times. Suppose Ford is added to the array. Then Johnson, Smith and Wagner must each be moved downward

one location, as in Fig.(b).

 Next suppose Taylor is added to the array; then Wagner must be moved, as in Fig.(c).

 Last, suppose Davis is removed from the array. Then the five names Ford, Johnson, Smith, Taylor and Wagner

must each be moved upward one location, as in Fig.(d).


THANK YOU
|| JAI SRI GURUDEV ||
SRI ADICHUNCHANAGIRI SHIKSHANA TRUST ®

ADICHUNCHANAGIRI INSTITUTE OF TECHNOLOGY


(An ISO 9001 : 2008 Certified)
Affiliated to Visvesvaraya Technological University, Belagavi ,
Approved by AICTE and Accredited by NAAC, New Delhi
Jyothinagar, Chikkamagaluru – 577 102.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

ONLINE CLASS USING ZOOM APPLICATION

Subject: Data Structures and Applications


Subject Code: 18CS32

Presented By: Semester and Section : 3rd and ‘A’

Mr. GOPINATH C. B., B.E., M.Tech., Class # : 38

Assistant Professor
31 October 2020
Date : 28-10-2020 (11:00AM TO 11:40AM)
Sorting Operation:

Sorting refers to the operation of rearranging the elements of a list. Here list be

a set of n elements. The elements are arranged in increasing or decreasing

order.

Example: suppose A is the list of n numbers. Sorting A refers to the operation of

rearranging the elements of A so they are in increasing order, i.e., so that,

A[1] < A[2] < A[3] < ... < A[N]

For example, suppose A originally is the list

8, 4, 19, 2, 7, 13, 5, 16

After sorting, A is the list

2, 4, 5, 7, 8, 13, 16, 19
Sorting Operation (Continued):
Bubble Sort:
Suppose the list of numbers A[1], A[2], ... , A[N] is in memory. The
bubble sort algorithm works as follows:
Algorithm: (Bubble Sort) BUBBLE (DATA,N)
Here DATA is an array with N elements. This algorithm sorts
the elements in DATA.
1.Repeat Steps 2 and 3 for K = 1 to N – 1.
2. Set PTR: = 1.[Initializes pass pointer PTR.]
3. Repeat while PTR ≤ N - K: [Executes pass.]
(a) If DATA[PTR] > DATA[PTR + 1], then:
Interchange DATA [PTR] and DATA [PTR + 1].
[End of If structure.]
(b) Set PTR: = PTR + 1.
[End of inner loop.]
[End of Step 1 outer loop.]
4.Exit.
Example
Example (Continued)
Complexity of the Bubble Sort Algorithm:

The time for a sorting algorithm is measured in terms of the number of

comparisons f(n). There are n – 1 comparisons during the first pass,

which places the largest element in the last position; there are n - 2

comparisons in the second step, which places the second largest element in

the next-to-last position; and so on. Thus


THANK YOU
|| JAI SRI GURUDEV ||
SRI ADICHUNCHANAGIRI SHIKSHANA TRUST ®

ADICHUNCHANAGIRI INSTITUTE OF TECHNOLOGY


(An ISO 9001 : 2008 Certified)
Affiliated to Visvesvaraya Technological University, Belagavi ,
Approved by AICTE and Accredited by NAAC, New Delhi
Jyothinagar, Chikkamagaluru – 577 102.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

ONLINE CLASS USING ZOOM APPLICATION

Subject: Data Structures and Applications


Subject Code: 18CS32

Presented By: Semester and Section : 3rd and ‘A’

Mr. GOPINATH C. B., B.E., M.Tech., Class # : 39

Assistant Professor
31 October 2020
Date : 28-10-2020 (03:00PM TO 04:00PM)
Searching Operation:

 Let DATA be a collection of data elements in memory, and suppose a specific

ITEM of information is given.

 Searching refers to the operation of finding the location LOC of ITEM in DATA,

or printing some message that ITEM does not appear there.

 The search is said to be successful if ITEM does appear in DATA and

unsuccessful otherwise.
Searching Operation (Continued):

Linear Search:

Suppose DATA is a linear array with n elements. Given no other information

about DATA, The way to search for a given ITEM in DATA is to compare ITEM with

each element of DATA one by one. That is, first test whether DATA [l] = ITEM, and

then test whether DATA[2] = ITEM, and so on. This method, which traverses

DATA sequentially to locate ITEM, is called Linear Search or Sequential Search.


Searching Operation (Continued):

Linear Search (Continued):

Algorithm: (Linear Search) LINEAR (DATA, N, ITEM, LOC)

Here DATA is a linear array with N elements, and ITEM is a given item of

information. This algorithm finds the location LOC of ITEM in DATA, or sets

LOC: = 0 if the search is unsuccessful.


1. [Insert ITEM at the end of DATA.] Set DATA [N + 1]: = ITEM.

2. [Initialize counter.] Set LOC: = l.

3. [Search for ITEM.]

Repeat while DATA [LOC] ≠ ITEM:

Set LOC:= LOC + 1.

[End of loop.]

4. [Successful?] If LOC = N + 1, then: Set LOC:= 0

5. Exit.
Searching Operation (Continued):
Linear Search (Continued):
Consider the array NAME in below figure (a), when n=6.
Example:
Suppose we want to know whether the name Paula appears in the array and if so, where.
Our algorithm temporarily places Paula at the end of the array, as pictured in below
figure(b), by setting NAME[7] = Paula.
Then the algorithm searches the array from top to bottom. Since Paula first appears in
NAME[N+1]. Paula is not in the original array.

Figure (a) Figure (b)


Searching Operation (Continued):
Linear Search (Continued):
Consider the array NAME in below figure (a), when n=6.
Example:
Suppose we want to know whether the name Susan appears in the array and if so, where.
Our algorithm temporarily places Susan at the end of the array, as pictured in below
figure(b), by setting NAME[7] = Susan.
Then the algorithm searches the array from top to bottom. Since Susan first appears in
NAME[4] (where 4 ≤n). Susan is in the original array.

Figure (a) Figure (b)


Complexity of the Linear Search Algorithm:

Worst Case:

Average Case:
Searching Operation (Continued):

Binary Search:

Suppose DATA is an array which is sorted in increasing numerical order or,

equivalently, alphabetically. Then there is an extremely efficient searching

algorithm, called Binary Search, which can be used to find the location LOC of a

given ITEM of information in DATA.


Searching Operation (Continued):

Binary Search (Continued):

Algorithm: (Binary Search) BINARY(DATA, LB, UB, ITEM, LOC)

Here DATA is a sorted array with lower bound LB and upper bound UB, and ITEM

is a given item of information. The variables BEG, END and MID denote, the

beginning, end and middle locations of a segment of elements of DATA. This

algorithm finds the location LOC of ITEM in DATA or sets LOC = NULL.
Searching Operation (Continued):
Binary Search (Continued):
Algorithm: (Binary Search) BINARY(DATA, LB, UB, ITEM, LOC)
1.[Initialize segment variables.]
Set BEG: = LB, END := UB and MID = INT((BEG + END)/2).
2.Repeat Steps 3 and 4 while BEG ≤ END and DATA [MID] ≠ ITEM.
3. If ITEM < DATA [MID], then:
Then ITEM can appear
Set END := MID – 1. only in the LEFT half of
Else: the segment
Set BEG := MID + 1.
[End of If structure.] Then ITEM can appear
4. Set MID := INT((BEG + END)/2). only in the RIGHT half of
[End of Step 2 loop.] the segment
5.If DATA[MID] = ITEM, then:
Set LOC := MID.
Else:
Set LOC := NULL.
[End of If structure.]
6.Exit.
Searching Operation (Continued):
Binary Search (Continued):
Let DATA be the following sorted 13 elements array:
DATA:11,22,30,33,40,44,55,60,66,77,80,88,99
Example:
Suppose ITEM=40. The search for ITEM in the array DATA, where the values of DATA[BEG]
and DATA[END] in each stage of the algorithm are indicated by circle and the value of
DATA[MID] by a square. Specifically, BEG, END and MID will have the following successive
values:
Searching Operation (Continued):
Binary Search (Continued):
Let DATA be the following sorted 13 elements array:
DATA:11,22,30,33,40,44,55,60,66,77,80,88,99
Example:
Suppose ITEM=85. Here BEG, END and MID will have the following successive values:
Complexity of the Binary Search Algorithm:

The complexity is measured by the number f(n) of comparisons to locate ITEM in

DATA where DATA contains n elements. Observe that each comparison reduces

the sample size in half. Hence we require at most f(n) comparisons to locate

ITEM where

2f(n) > n or equivalently f(n) = ⎿log2n⏌ + 1

That is, the running time for the worst case is approximately equal to log2n. One

can also show that the running time for the average case is approximately equal

to the running time for the worst case.


THANK YOU
POLYNOMIALS
What is a polynomial?
“A polynomial is a sum of terms, where each term has a form axe, where x is the variable, a is
the coefficient and e is the exponent.”
Two example polynomials are:
A(x) = 3x20 + 2x5 + 4
B(x) = x4 + 10x3 + 3x2 + 1
The largest (or leading) exponent of a polynomial is called its degree. Coefficients that are
zero are not displayed. The term with exponent equal to zero does not show the variable
since x raised to a power of zero is 1.
Assume there are two polynomials,
A(x) = Σaixi and B(x)= Σbixi
Then :
A(x)+B(x) = Σ(ai + bi)xi
A(x).B(x) = Σ(aixi.Σ(bjxj))
Similarly, we can define subtraction and division on polynomials.
Polynomial Representation in C:
One way to represent polynomials in C is to use typedef to create the type polynomial as
below:
#define MAX-DEGREE 101 /*Max degree of polynomial+1*/
typedef struct{
int degree;
float coef[MAX-DEGREE];
} polynomial;
Now if a is a variable and is of type polynomial and n<MAX_DEGREE,
the polynomial
𝐀(𝐗) = ∑𝐧𝐢=𝟎 𝐚𝐢 𝐱 𝐢 would be represented as:
a.degree = n
a.coef[i] = an-i, 0 ≤ i ≤ n
In this representation, the coefficients is stored in order of decreasing exponents, such that
a.coef[i] is the coefficient of xn-i provided a term with exponent n-i exists;
Otherwise, a.coef [i] =0. This representation leads to very simple algorithms for most of
the operations; it wastes a lot of space.

ADT Polynomial is
Objects: p(x) = a1xe1 +....+ anxen; a set of ordered pairs of <ei,ai> where ai in
Coefficients and ei in Exponents, ei are integers >= 0
Functions:
for all poly, poly1, poly2 ϵ Polynomial, coef ϵ Coefficients, expon ϵ Exponents
Polynomial Zero() ::= return the polynomial, p(x)=0

Boolean IsZero(poly) ::= if(poly) return FALSE


else return TRUE

Coefficient Coef(poly,expon) ::= if(expon ϵ poly) return its


coefficient
else return zero
Exponent LeadExp(poly) ::= return the largest exponent in
poly
Polynomial Attach(poly,coef,expon) ::= if(expon ϵ poly) return error
else return the polynomial poly
with the term <coef,expon>
inserted
Polynomial Remove(poly,expon) ::= if(expon ϵ poly)
return the polynomial poly with
the term whose exponent is
expon deleted
else return error
Polynomial SingleMulti(poly,coef,expon) ::= return the polynomial
poly.coef.xexpon

Polynomial Add(poly1,poly2) ::= return the polynomial


poly1+poly2
Polynomial Multi(poly1,poly2) ::= return the polynomial
poly1.poly2

end Polynomial
To preserve space an alternate representation that uses only one global array, terms to
store all polynomials.
The C declarations needed are:
MAX_TERMS 100 /*size of terms array*/
typedef struct{
float coef;
int expon;
} polynomial;
polynomial terms[MAX-TERMS];
int avail = 0;
Consider the two polynomials
A(x) = 2xl000+ 1
B(x) = x4 + 10x3 + 3x2 + 1
The below 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.
Polynomial Addition
 C function is written that adds two polynomials, A and B to obtain D =A + B.
 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
The below code represents Function to add two polynomials:
void padd(int startA, int finishA, int startB, int finishB, int *startD,int *finishD)
{
/* add A(x) and B(x) to obtain D(x)*/
float coefficient;
*startD = avail;

while (startA <= finishA && startB <= finishB)


switch(COMPARE(terms[startA].expon,terms[startB].expon))
{
case -1: /* a expon < b expon */
attach (terms [startB].coef, terms[startB].expon);
startB++;
break;

case 0: /* equal exponents */


coefficient = terms[startA].coef + terms[startB].coef;
if(coefficient)
attach(coefficient, terms[startA].expon);
startA++;
startB++;
break;
case 1: /* a expon > b expon */
attach (terms [startA].coef, terms[startA].expon);
startA++;
}

/* add in remaining terms of A(x) */


for(; startA <= finishA; startA++)
attach (terms[startA].coef, terms[startA].expon);

/* add in remaining terms of B(x) */


for( ; startB <= finishB; startB++)
attach (terms[startB].coef, terms[startB].expon);

*finishD = avail-1;
}
The below code represents Function to add a new term:
void attach(float coefficient, int exponent)
{
/* add a new term to the polynomial */
if (avail >= MAX-TERMS)
{
printf("Too many terms in the polynomial\n");
exit(0);
}
terms[avail].coef = coefficient;
terms[avail++].expon = exponent;
}
Example:
Consider the following two polynomials and perform addition
A(x) = 2xl000+ 1
B(x) = 3x2 + 1
Array representation of polynomial:

Here, startA=0, finishA=1, startB=2, finishB=3 and avail=4


Step1:
Step2:
Step3:
Step4:

The addition of two polynomial is


A(x) = 2xl000+ 1
B(x) = 3x2 + 1
D(x) = A(x) + B(x)
D(x) = 2xl000+ 3x2 + 2
Analysis of padd( ):

The number of non-zero terms in A and B is the most important factors in analyzing the
time complexity.

Let m and n be the number of non-zero terms in A and B, If m >0 and n > 0, the while loop
is entered. Each iteration of the loop requires O(1) time. At each iteration, the value of
startA or startB or both is incremented. The iteration terminates when either startA or
startB exceeds finishA or finishB. The number of iterations is bounded by m+n-1

The time for the remaining two for loops is bounded by O(n + m) because we cannot
iterate the first loop more than m times and the second more than n times. So, the
asymptotic computing time of this algorithm is O(n +m).
SPARSE MATRICES
In mathematics, 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 m*n. If m equals n, the matrix is square.

Figure (a) Figure (b)


What is Sparse Matrix?
A matrix which contains many zero entries or very few non-zero entries is called as Sparse
Matrix. In the figure (b) contains only 8 of 36 elements are nonzero and that is Sparse
Matrix.
Example for Sparse Matrix:

Important Note:
A sparse matrix can be represented in 1-Dimensional, 2- Dimensional and 3-
Dimensional array. When a sparse matrix is represented as a two-dimensional array as
shown in above 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
10,000,00 elements. The better choice is by using a representation in which only the
nonzero elements are stored.

ADT SparseMatrix is
Objects: a set of triples<row,column,value>, where row and column are
integers and form a unique combination and value comes from the set item.

Functions:
for all a,b ϵ SparseMatrix, x ϵ item, i,j,maxCol,maxRow ϵ index

SparseMatrix Create(maxRow,maxCol) ::= return a SparseMatrix that can


hold up to maxItems=maxRow*maxCol
and whose maximum row size is
maxRow and whose maximum column
size is maxCol

SparseMatrix Transpose(a) ::= return the matrix produced by


interchanging the row and
column value of every triple.

SparseMatrix Add(a,b) ::= if the dimensions of a and b


are the same return the matrix
produced by adding
corresponding items, namely
those with identical row and
column values
else return error

SparseMatrix Multiply(a,b) ::= if number of columns in a


equals number of rows in b
return the matrix d produced by
multiplying a by b according to
the formula:
d[i][j]=∑(a[i][k].b[k][j])
where d(i,j) is the (i,j)th
element
else return error.
Sparse Matrix Representation:
 An element within a matrix can characterize by using the triple <row,col,value>
This means that, an array of triples is used to represent a sparse matrix.

 Organize the triples so that the row indices are in ascending order.

 The operations should terminate, so we must know the number of rows and columns,
and the number of nonzero elements in the matrix.

Implementation of the Create operation as below:


SparseMatrix Create(maxRow,maxCol) ::=

#define MAX_TERMS 101 /* maximum number of terms +1*/


typedef struct{
int col;
int row;
int value;
}term;

term a[MAX_TERMS];

Example: Consider the following Sparse Matrix

Sparse Matrix Representation / Triplet Representation:


 The above 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 non-zero 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.

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 following code represents Transpose of a Sparse Matrix:
The columns within each row of the transpose matrix will be arranged in ascending
order.
void transpose(term a[], term b[])
{
/* 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[0].col;i++)
/*transpose by the columns in a*/
for(j=1;j<=n;j++)
/*find elements from the current column*/
if(a[j].col==i)
{
b[currentb].row = a[j].col;
b[currentb].col = a[j].row;
b[currentb].value = a[j].value;
currentb++;
}
}
}

Example:

Given Triplet Representation Transpose


Sparse Matrix of Sparse Matrix of Sparse Matrix
The detailed Procedures are as follows:
First, consider the given Sparse Matrix:

Then, write Sparse Matrix Representation/Triplet Representation

Based on the following algorithm, by using the column indices to determine the placement
of elements in the transpose matrix.
for all elements in column j
place element <i, j, value> in
element <j, i, value>
Step1:

Step2:
Step3:

Step4:
Step5:

Step6:
Step7:

Step8:
Step9:

The Resultant Transpose Matrix is as shown below:

Note:
Asymptotic Time Complexity of this algorithm is O(columns.elements).
Assignment Questions:

1. Define an array. List all the array operations. Briefly explain them
along with algorithm and example.
2. Give the ADT for polynomial and sparse matrix.
3. What is a polynomial? What is the degree of the polynomial?
Consider two polynomial A(x)=4x15-3x4+5 and B(x)=x4+10x2+1. Show
diagrammatically how these polynomials can be stored in a 1-D
array. Write a function to add 2 polynomials A and B store the result
in polynomial C.
4. What is sparse matrix? Express the given sparse matrix as triplet and
find its transpose and also write a transpose algorithm to transpose a
sparse matrix.

5. Express the given sparse matrix as triplet and find its transpose.
FAST TRANSPOSE OF A SPARSE MATRIX
As its name suggests, it is a faster way to transpose a sparse matrix and also a little bit hard
to understand. Time complexity is O(columns + elements). Here, we require 2 arrays,
namely, rowTerms and startingPos.
The following code represents Fast Transpose of a Sparse Matrix:
void fastTranspose(term a[], term b[])
{
/*the transpose of a is placed in b*/
int rowTerms[MAX-COL], startingPos[MAX_COL];
int i,j, numCols=a[0].col, numTerms=a[0].value;
b[0].row=numCols; b[0].col=a[0].row;
b[0].value=numTerms;
if(numTerms>0) { /*nonzero matrix*/
for(i=0;i<numCols;i++)
rowTerms[i]=0;
for(i=1;i<=numTerms;i++)
rowTerms[a[i].col]++;
startingPos[0]=1;
for(i=1;i<numCols;i++)
startingPos = startingPos[i-1] + rowterms[i-1];
for(i=1;i<=numTerms;i++)
{
j = startingPos[a[i].col]++;
b[j].row = a[i].col;
b[j].col = a[i].row;
b[j].value = a[i].value;
}
}/*Closing of if statement*/
}
Example:

Given Triplet Representation Transpose


Sparse Matrix of Sparse Matrix of Sparse Matrix
The detailed Procedures are as follows:
First, consider the given Sparse Matrix:

Then, write Sparse Matrix Representation/Triplet Representation


First, Interchanging total number of rows and total number of
columns.

Step2: Then, find two one dimensional arrays. That is, rowTerms
and startingPos
Find the rowTerms array:
Size of the rowTerms array = Number of columns present in the given sparse matrix.
Here, the size of rowTerms array = 6.
Find the startingPos array:
Size of the staringPos array = Size of rowTerms array + 1  6 + 1  7
Here, the size of rowTerms array = 7.

Next we will use this startingPos array, to


find out the place of triplet from the given
matrix in a transpose matrix.
The Resultant Transpose Matrix is as shown below:
STRINGS
 Basic Terminology
 Storing Strings
 Character Data Type
 String Operations
 Pattern Matching algorithms
Basic Terminology:

Each programming languages contains a character set that is used to communicate with the

computer.

The character set include the following:

Alphabet: ABCDEFGHIJKLMNOPQRSTUVWXYZ

Digits: 0 1 2 3 4 5 6 7 8 9

Special characters: + - / * ( ) , . $ = ‘ ⎕(Blank space)

 String: A finite sequence S of zero or more Characters is called string.

 Length: The number of characters in a string is called length of string.

 Empty or Null String: The string with zero characters.

 Concatenation: Let S1 and S2 be the strings. The string consisting of the characters of

S1 followed by the character S2 is called Concatenation of S1 and S2.

Example1: ‘THE’ // ‘END’ = ‘THEEND’

Example2: ‘THE’ // ‘ ’ // ‘END’ = ‘THE END’

 Substring: A string Y is called substring of a string S if there exist string X and Z such that

S = X // Y // Z

If X is an empty string, then Y is called an Initial substring of S, and Z is an empty

string then Y is called a terminal substring of S.

Example: ‘BE OR NOT’ is a substring of ‘TO BE OR NOT TO BE’

‘THE’ is an initial substring of ‘THE END’


Strings in C:
In C, the strings are represented as character arrays terminated with the
null character ‘\0’.

Declaration 1:

#define MAX_SIZE 100 /* maximum size of string */


char s[MAX_SIZE] = {“dog”};
char t[MAX_SIZE] = {“house”};

s[0] s[1] s[2] s[3] t[0] t[1] t[2] t[3] t[4] t[4]

d o g \0 h o u s e \0

The above figure shows how these strings would be represented internally in memory.

Declaration 2:
char s[ ] = {“dog”};
char t[ ] = {“house”};

Using these declarations, the C compiler will allocate just enough space to hold each
word including the null character.

Storing Strings:

Strings are stored in three types of structures:

1. Fixed length structures

2. Variable length structures with fixed maximum

3. Linked structures

1. Record Oriented, Fixed-Length Storage:

In fixed length structures each line of print is viewed as a record, where all have the

same length i.e., where each record accommodates the same number of characters.
Example: Suppose the input consists of the program. Using a record oriented, fixed
length storage medium (the length of each record occupied by 80 bytes), the input
data will appear in memory as pictured below.

Suppose, if new record needs to be inserted, then it requires that all succeeding records
be moved to new memory location. This disadvantage can be easily remedied as shown
in below figure.
That is, one can use a linear array POINT which gives the address of successive record,
so that the records need not be stored in consecutive locations in memory. Inserting a
new record will require only an updating of the array POINT.
The main advantages of this method are
1. The ease of accessing data from any given record
2. The ease of updating data in any given record (as long as the length of the new data
does not exceed the record length)

The main disadvantages are


1. Time is wasted reading an entire record if most of the storage consists of inessential
blank spaces.
2. Certain records may require more space than available.
3. When the correction consists of more or fewer characters than the original text,
changing a misspelled word requires record to be changed.

2. Variable length structures with fixed maximum:


The storage of variable-length strings in memory cells with fixed lengths can be done
in two general ways
1. One can use a marker, such as two dollar signs ($$), to signal the end of the string.
2. One can list the length of the string—as an additional item in the pointer array.

Example:
The other method to store strings one after another by using some separation marker,
such as the two dollar sign ($$) or by using a pointer giving the location of the string.

These ways of storing strings will save space and are sometimes used in secondary
memory when records are relatively permanent and require little changes.

These types of methods of storage are usually inefficient when the strings and their
lengths are frequently being changed.

3. Linked Storage:
Most extensive word processing applications, strings are stored by means of linked
lists.
In a one way linked list, a linearly ordered sequence of memory cells called nodes,
where each node contains an item called a link, which points to the next node in the
list, i.e., which consists the address of the next node.

Strings may be Stored in linked list as follows:


Each memory cell is assigned one character or a fixed number of characters and a
link contained in the cell gives the address of the cell containing the next character
or group of character in the string.
Example: TO BE OR NOT TO BE
Character Data Type:
The various programming languages handles character data type in different ways.
Constants:
Many programming languages denote string constants by placing the string in either
single or double quotation marks.
Example: ‘THE END’
“THE BEGINNING”
The string constants of length 7 and 13 characters respectively.

Variables:
Each programming languages has its own rules for forming character variables. These
variables fall into one of three categories

1. Static: In static character variable, whose length is defined before the program is
executed and cannot change throughout the program.
2. Semi-static: The length of the variable may vary during the execution of the program
as long as the length does not exceed a maximum value determined by the program
before the program is executed.
3. Dynamic: The length of the variable can change during the execution of the program.
STRING OPERATIONS:

The different String Operations are


 Substring
 Indexing
 Concatenation
 Length

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 denote 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'

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)

Example: INDEX('Data Structure','Data') = 1

INDEX('Data Structure','Struct') = 6

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.
Concatenation:

Let S1 and S2 be string. The concatenation of S1 and S2 which is denoted by S1 // S2, is the
string consisting of the characters of S1 followed by the character of S2.

Example:

Suppose S1 = 'DATA' and S2= ‘STRUCTURE' then


S1 // S2 = ‘DATASTRUCTURE’

Concatenation is performed in C language using strcat function as shown below

strcat (S1, S2);

Concatenates string S1 and S2 and stores the result in S1

strcat( ) function is part of the "string.h" header file; hence it must be included at the
time of pre- processing

Length:

The number of characters in a string is called its length.

Syntax: LENGTH (string)

Example: LENGTH (‘computer’) = 8

String length is determined in C language using the strlen( ) function, as shown below:

x = strlen("sunrise");

strlen( ) function returns an integer value 7 and assigns it to the variable X

Similar to strcat(), strlen() is also a part of "string.h", hence the header file must be
included at the time of pre-processing.
The different C String Functions are:
Programming Examples:

Write a C program to find the concatenation of two strings using pointer (don't
use library function).

#include<stdio.h>

main()

char str1[50], str2[50],str3[50], *a,*b;

int i,k=0;

printf("Enter the First String\n");

gets(str1);

printf("Enter the Second String\n");

gets(str2);

a=str1; b=str2;

for(i=0;str1[i]!='\0';i++)

str3[k] = str1[i];

k++;

for(i=0;str2[i]!='\0';i++)

str3[k] = str2[i];

k++;

str3[k]='\0';

printf("The Concatenatd String is %s\n",str3);

}
Write a C program to compare two strings data whether it is
same or not without using strcmp() built-in function.

#include<stdio.h>

#include<string.h>

#include<stdlib.h>

void main()

char str1[10],str2[10]; int len1, len2, i;

printf(“Enter two strings\n”);

scanf(“%s%s”,str1,str2);

len1 = strlen(str1);

len2 = strlen(str2);

if(len1 != len2)

printf(“Both strings are different

else

for(i=0; str1[i]!=‘\0’; i++)

if(str1[i]!=str2[i])

printf(“Both strings are different\n”);

exit(0);

printf(“Both strings are same\n”);

} // closing of main() function


Write a C program to reverse a given string without using
strrev() built-in function and also check whether a given
string is Palindrome or not.

#include<stdio.h>

#include<string.h>

void main()

char str1[20],str2[20]; int i, k, x;

printf(“Enter a string\n”);

gets(str1);

k = strlen(str1);

for(i=0; i<k; i++)

str2[i] = str1[k-i-1];

str2[i] = ‘\0’;

printf(“Reversed string is %s\n”,str2);

x = strcmp(str1,str2);

if(x == 0)

printf(“Given string is a Palindrome\n”);

else

printf(“Given string is not a Palindrome\n”);

} // closing of main() function


Write a C program to copy the content of one string to
another string without using strcpy() built-in function.

#include<stdio.h>

void main()

char str1[10],str2[10]; int i;

printf(“Enter a string\n”);

scanf(“%s”,str1);

for(i=0; str1[i]!=‘\0’; i++)

str2[i] = str1[i];

str2[i] = ‘\0’;

printf(“String2 = %s\n”,str2);

}
Write a C program to find the length of a given string
without using strlen() built-in function.

#include<stdio.h>

void main()

char str[20];

int len = 0;

printf(“Enter a string\n”);

gets(str);

for(i=0; str[i]!=‘\0’; i++)

len = len + 1;

printf(“Steing Length = %d\n”,len);

}
Pattern Matching Algorithms

Pattern matching is the problem of deciding whether or not a given string pattern P
appears in a string text T. The length of P does not exceed the length of T.
Characters are denoted by lowercase letters (a,b,c,....) and exponents may be used to
denote repetition.
Example: a3b3ab2 for aaabbbabb
(cd)3 for cdcdcd
The empty string may be denoted by ˄, the Geek letter lambda and the concatenation of
strings X and Y may be denoted by X.Y or simply XY.

First Pattern Matching Algorithm:


 The first pattern matching algorithm is one in which comparison is done by a given pattern

P with each of the substrings of T, moving from left to right, until a match is found.

WK = SUBSTRING (T, K, LENGTH (P))

 Where, WK denote the substring of T having the same length as P and beginning with the

Kth character of T.

 First compare P, character by character, with the first substring, W1. If all the characters

are the same, then P = W1 and so P appears in T and INDEX (T, P) = 1.

 Suppose it is found that some character of P is not the same as the corresponding character

of W1. Then P ≠ W1.

 Immediately move on to the next substring, W2 That is, compare P with W2. If P ≠ W2 then

compare P with W3 and so on.

 The process stops, When P is matched with some substring WK and so P appears in T and

INDEX(T,P) = K or When all the WK's with no match and hence P does not appear in T.

 The maximum value MAX of the subscript K is equal to LENGTH (T) - LENGTH (P) +1.
Let us assume, P is a 4 character string and T is a 20 characters string. P and T appear in

memory as Linear Array.

That is,

P = P[1]P[2]P[3]P[4] and T = T[1]T[2]T[3]T[4]....T[18]T[19]T[20]

Then P is compared with each of the following 4 character substrings of T:

W1 = T[1]T[2]T[3]T[4]

W2 = T[2]T[3]T[4]T[5]

. . . .

W17 = T[17]T[18]T[19]T[20]

Note that there are MAX=20-4+1 such substrings of T.

Algorithm: (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: 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.

Time Complexity:
The time complexity of this pattern matching algorithm is equal to O(n2).

Examples:
Note: The First Pattern Matching Algorithm is also known as Brute Force Algorithm or
Slow Algorithm.
Problem:
Second Pattern Matching Algorithm:
The second pattern matching algorithm uses a table which is derived from a particular
pattern P but is independent of the text T.
Suppose P = aaba
This algorithm contains the table that is used for the pattern P = aaba.
The Pattern Matching Table is obtained as follows:
 Let Qi denote the initial substring of P of length i, hence Q0 = ˄, Q1 = a, Q2 = a2, Q3 =
aab, Q4 = aaba = P (Here Q0 = ˄ is the empty string).
 The rows of the table are labeled by these initial substrings of P, excluding P itself.
 The columns of the table are labeled a, b and x, where x represents any character
that doesn't appear in the pattern P.
 Let f be the function determined by the table; i.e., let f(Qi, t) denote the entry in the
table in row Qi and column t (where t is any character). This entry f(Qi, t) is defined
to be the largest Q that appears as a terminal substring in the string (Qit) the
concatenation of Qi and t.

The Pattern Matching Graph is obtained as follows:


 First, a node in the graph corresponding to each initial substring Qi of P. The Q's are
called the states of the system, and Q0 is called the initial state.
 Second, there is an arrow (a directed edge) in the graph corresponding to each
entry in the table. Specifically, if
f(Qi, t) = Qj

then there is an arrow labeled by the character t from Qi to Qj

Example:

f(Q2, b) = Q3 so there is an arrow labeled b from Q2 to Q3

For notational convenience, all arrows labeled x are omitted, which must lead to the
initial state Q0.

Time Complexity:
The time complexity of this pattern matching algorithm is equal to O(n).
Algorithm: (Pattern Matching)

The pattern matching table F(Q1,T)of a pattern P is in memory and the input is an
N-character string T = T1 T2 T3 …… TN. The algorithm finds the INDEX of P in T.

1. [Initialize] set K := 1 and S1 = Q0


2. Repeat steps 3 to 5 while SK ≠ P and K ≤ N
3. Read TK
4. Set SK+1 := F(SK,TK) [Finds next state]
5. Set K := K+1 [updates counter]
[End of Step2 loop]
6. [Successful?]
If SK = P, then:
INDEX = K – LENGTH(P)
Else
INDEX = 0
[End of IF structure]
7. Exit.
The second pattern matching algorithm for the pattern P = aaba.

 Let T = T1 T2 T3 .... TN denote the n-character-string text which is searched for the
pattern P. Beginning with the initial state Q0 and using the text T, we will obtain a
sequence of states S1, S2, S3, ... as follows.
 Let S1 = Q0 and read the first character T1. The pair (S1, T1) yields a second state S2;
that is, F(S1, T1) = S2, Read the next character T2, The pair (S2, T2) yields a state S3,
and so on.

There are two possibilities:


1. Some state SK = P, the desired pattern. In this case, P does appear in T and its
index is K - LENGTH(P).
2. No state S1, S2, ... , SN +1 is equal to P. In this case, P does not appear in T.

NOTE: The Second Pattern Matching Algorithm is also known as Knuth Morris Pratt
(KMP) pattern matching algorithm or Fast algorithm.
Problem1:
Consider the pattern P=aaba. Construct the table and the
corresponding labelled directed graph used in the ‘Fast” or second
pattern matching algorithm.

The initial substrings of P are:

Figure: Pattern Matching Graph

Q0 = ˄, Q1 = a, Q2 = a2, Q3 = a2b and P = a2ba


Then, Construct Pattern Matching Table is as shown below

For each character t, the entry f(Qi,t) in the table is the largest Q which
appears as a terminal substring in the string Qit. We compute:
f(˄,a) = a

f(˄,b) = ˄
f(a,a) = a2
f(a,b) = ˄
f(a2,a) = a2
f(a2,b) = a2b
f(a2b,a) = P
f(a2b,b) = ˄
Problem2:
Consider the pattern P=aaabb. Construct the table and the
corresponding labelled directed graph used in the ‘Fast” or second
pattern matching algorithm.
The initial substrings of P are:

Figure: Pattern Matching Graph

Q0 = ˄, Q1 = a, Q2 = a2, Q3 = a3, Q4 = a3b and P = a3b2


Then, Construct Pattern Matching Table is as shown below

For each character t, the entry f(Qi,t) in the table is the largest Q which
appears as a terminal substring in the string Qit. We compute:
Problem3:
Find the table and corresponding graph for the second pattern
matching algorithm where the pattern is P = ababab.
The initial substrings of P are:

Figure: Pattern Matching Graph

Q0 = ˄, Q1 = a, Q2 = ab, Q3 = aba, Q4 = abab, Q5 = ababa


and P = ababab
Then, Construct Pattern Matching Table is as shown below

For each character t, the entry f(Qi,t) in the table is the largest Q which
appears as a terminal substring in the string Qit. We compute:

You might also like