VIDHYA SAGAR WOMENS COLLEGE, CHENGALPATTU
DEPT OF COMPUTER SCIENCE
ONLINE CASS
DATA
STRUCTURE
Staff Incharge: [Link] [Link].,[Link].,NET
[Link]
Dept of Computer Science
UNIT-1
Objectives
To Understand the concept of
Data Structure
Types of Data Structure
Operation on Data Structure
Arrays
Types of Arrays
DATA STRUCTURE
Data structure is a particuAr way to
store and organize data in a computer so
that it can be used effectively.
In DS, Any Organization for collection of
records can be searched, Processed or
modified, in any order
A data Structure requires a certain
amount of:
Space
Time
Programming Effort
Data Structure mainly specifies the following
four things
Organization of Data
Accessing methods
Degree of associativity
Processing alternatives for information
***Algorithm + Data Structure = Program
CASSIFICATION OF DATA
STRUCTURE
Primitive Data type
Primitive data structures are basic structures and
are directly operated upon by machine
instructions.
These data types are avaiAble in most
programming Anguages as built in type.
Integer
Float
Character
Boolean
Composite Data Type
These are derived from primitive data structures.
The non-primitive data structures emphasize on
structuring of a group of homogeneous or
heterogeneous data items.
A Non-primitive data type is further divided
into Linear and Non-Linear data structure
Linear data structures
A data structure is said to be Linear, if its
elements are connected in linear fashion by
means of logically or in sequence memory
locations.
Array
List
Stack
Queue
Nonlinear data structures
Nonlinear data structures are those data
structure in which data items are not arranged in
a sequence.
Tree
Graph.
OPERATION ON DATA
STRUCTURES
Create:- The create operation results in
reserving memory for program elements.
Destroy:- Destroy operation destroys memory
space allocated for specified data structure..
Selection:- Selection operation deals with
accessing a particuAr data within a data
structure.
Updation:- It updates or modifies the data in the
data structure.
Searching:- It finds the presence of desired data
item in the list of data items, it may also find the
locations of all elements that satisfy certain
conditions.
Sorting:- Sorting is a process of arranging all data
items in a data structure in a particuAr order, say for
example, either in ascending order or in descending
order.
Merging:- Merging is a process of combining the
data items of two different sorted list into a single
sorted list.
Splitting:- Splitting is a process of partitioning
single list to multiple list.
Traversal:- Traversal is a process of visiting each
and every node of a list in systematic manner.
DAY 2
DATA STRUCTURE USING
C++
IDENTIFIERS &VARIABLES IN C++
Identifier is a name which is used to identify
the element
A variable is a way to store the element in
particuAr memory Location.
Example
void main() {
int i = 5;
int j;
cout<<“Please enter j value: “;
cin>>j;
FOR LOOP
For loop is used to print the set of statement
repeatedly until met the condition
Syntax
for(initialization;condition;increament/
decreament operator){
//Repeated statement
}
Ex:
for(int i=0;i<5;i++){
cout<<i;
}
ARRAYS
An array is a collection of elements with the
same data type
An array can store either all integers, all
floating point numbers, all characters, or any
other complex data type, but all of same
type.
Arrays are always stored in consecutive
memory locations
TYPES OF ARRAYS
There are two types of Arrays
One Dimensional Arrays
Two Dimensional Arrays / Multidimensional Array
ONE DIMENSIONAL ARRAYS
A one-dimensional array is one in which only
one subscript specification is needed to specify
a particuAr element of the array.
A one-dimensional array is a list of reAted
variables.
One-dimensional array can be decAred as
follows :
Datatype varname[Expression];
int a[5];
ARRAY REPRESENTATION
Element − Each item stored in an array is called an
element.
Index − Each location of an element in an array has
a numerical index, which is used to identify the
element.
Arrays can be decAred in various ways in different
Anguages
int arr[10]={31,23,34,64,55,26,37,98,92,10};
Index:0 to 9
int:- datatype
arr:- arrayname
[ ]:- size of the array
EXAMPLE: C++ ARRAY
C++ PROGRAM TO STORE AND CALCUATE THE SUM OF
5 NUMBERS ENTERED BY THE USER USING ARRAYS.
#include <iostream>
using namespace std;
int main() {
int numbers[5]; Output
Enter 5 numbers:
int sum = 0; 3
cout << "Enter 5 numbers: "; 4
5
for (int i = 0; i < 5; ++i) { 4
cin >> numbers[i]; 2
Sum = 18
sum += numbers[i];
}
cout << "Sum = " << sum << endl;
return 0;
}
TWO DIMENSIONAL ARRAY
Two dimensional arrays are also called table or
matrix, two dimensional arrays have two
subscripts.
Two dimensional array in which elements are
stored column by column is called as column
major matrix.
Two dimensional array in which elements are
stored row by row is called as row major
matrix.
First subscript denotes number of rows and
second subscript denotes the number of
columns.
The simplest form of the Multi Dimensionl
Array is the Two Dimensionl Array
TWO DIMENSIONAL ARRAYS CAN BE DECARED AND
INITIALIZED AS FOLLOWS :
DecAration:
int arr[10] ;//one dimensional
int arr2d[10][10] ;
Initialization:
int a[3][3] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 } ;
1 (0,0) 2 (0,1) 3 (0,2)
4 (1,0) 5 (1,1) 6 (1,2)
7 (2,0) 8 (2,1) 9 (2,2)
EXAMPLE : TWO DIMENSIONAL ARRAY
C++ PROGRAM TO DISPAY ALL ELEMENTS OF AN INITIALIZED
TWO DIMENSIONAL ARRAY.
#include <iostream>
using namespace std;
int main(){
int test[3][2] ={ {2, -5}, {4, 0}, {9, 1} };
for(int j = 0; j < 2; ++j){
for(int i = 0; i < 3; ++i){
cout<< "test[" << i << "][" << j << "] = " <<
test[i][j] << endl;
Output
} test[0][0] = 2
} test[0][1] = -5
test[1][0] = 4
return 0; test[1][1] = 0
test[2][0] = 9
}
test[2][1] = 1
DAY 3
BASIC OPERATIONS ON ARRAY
Traverse − print all the array elements one
by one.
Insertion – Add an element at the given
index.
Deletion − Deletes an element at the given
index.
Search − Searches an element using the
given index or by the value.
Update − Updates an element at the given
index.
TRAVERSE OPERATION
This operation is used to traverse through the
elements of an array.
Example
Following program traverses and prints the elements of an array:
#include <iostream>
using namespace std;
main() {
int A[] = {1,3,5,7,8};
cout<<"The original array elements are :”<<endl;
for(int i = 0; i<5; i++) {
cout<< “A[“<<i<<“]=”<<A[i]<<endl;
}
return 0;
}
OUTPUT
When we compile and execute the above
program, it produces the following result −
The original array elements are :
A[0] = 1
A[1] = 3
A[2] = 5
A[3] = 7
A[4] = 8
INSERTION OPERATION
Insert operation is to insert one or more data
elements into an array.
Based on the requirement, a new element
can be added at the beginning, end, or any
given index of array.
Here, we see a practical implementation of
insertion operation, where we add data at
the given index.
#include <iostream>
using namespace std;
void main() { int A[] = {1,3,5,7,8};
Int n=5;
int item ,pos;
cout<<"The original array elements are :”<<endl;;
for(int i = 0; i<5; i++) {
cout<< “A[“<<i<<“]=”<<A[i]<<endl;
}
cout<<"\n\nEnter the position to insert number :: ";
cin>>pos;
while( n>= pos) {
cout<<"\nEnter number to be inserted :: ";
cin>>item;
A[n+1] = A[n];
--pos;
}
A[pos] = item;
printf("The array elements after insertion :\n");
for(i = 0; i<n; i++) {
cout<< “A[“<<i<<“]=”<<A[i]<<endl; }
return 0;
OUTPUT
When we compile and execute the above program, it produces the following result
−
The original array elements are :
A[0] = 1
A[1] = 3
A[2] = 5
A[3] = 7
A[4] = 8
Enter the position to insert number:4
Enter number to be inserted:10
The array elements after insertion :
A[0] = 1
A[1] = 3
A[2] = 5
A[3] = 10
A[4] = 7
A[5] = 8
DELETION OPERATION
Deletion refers to removing an existing
element from the array and re-organizing all
elements of an array.
EXAMPLE:
#include <iostream>
using namespace std;
void main() {
int A[] = {1,3,5,7,8};
int pos;
cout<<"The original array elements are :”<<endl;;
for(int i = 0; i<5; i++) {
cout<< “A[“<<i<<“]=”<<A[i]<<endl;
}
cout << "Enter the position of element to be delete\n";
cin >> pos;
while(pos<5){
--pos;
for(i=pos;i<4;i++) {
a[i]=a[i+1];
}
cout<<"\n\nNew Data in Array: ";
for(i=0;i<4;i++) {
cout<< “A[“<<i<<“]=”<<A[i]<<endl;
}
return 0;
}
OUTPUT:
The original array elements are :
A[0] = 1
A[1] = 3
A[2] = 5
A[3] = 7
A[4] = 8
Enter poss. of Element to Delete: 3
New data in Array:
A[0] = 1
A[1] = 3
A[2] = 7
A[3] = 8
SEARCH OPERATION
You can perform a search for an array
element based on its value or its index.
EXAMPLE
#include <iostream>
using namespace std;
void main() {
int A[] = {1,3,5,7,8};
int item;
int j = 0;
cout<<“The original array elements are ”<<endl;
for(int i = 0; i<5; i++) {
cout<< “A[“<<i<<“]=”<<A[i]<<endl;
}
cout<<“enter the element to be searched”;
cin>>item;
for(int j=0;j<5;j++){
if( A[j] == item ) {
break;
}
}
cout<<"Found element “<<item<<“ at position “<< j+1;
return 0;
}
OUTPUT
The original array elements are :
A[0] = 1
A[1] = 3
A[2] = 5
A[3] = 7
A[4] = 8
Found element 5 at position 3
UPDATE OPERATION
Update operation refers to updating an
existing element from the array at a given
index.
EXAMPLE
#include <iostream>
using namespace std;
void main() {
int A[] = {1,3,5,7,8};
int k = 3, item = 10;
cout<<"The original array elements are :\n”;
for(int i = 0; i<5; i++) {
cout<< “A[“<<i<<“]=”<<A[i]<<endl;
}
A[k-1] = item;
cout<<"The array elements after updation “<<endl;
for(int i = 0; i<5; i++) {
cout<< “A[“<<i<<“]=”<<A[i]<<endl;
}
return 0;
}
OUTPUT
When we compile and execute the above program, it
produces the following result −
The original array elements are :
A[0] = 1
A[1] = 3
A[2] = 5
A[3] = 7
A[4] = 8
The array elements after updation :
A[0] = 1
A[1] = 3
A[2] = 10
A[3] = 7
A[4] = 8
ORDERED LIST
An ordered list is a container which holds a sequence of
objects.
Each object has a unique position in the sequence.
ordered lists provide the following operations:
FindPosition
used to find the position of an object in the ordered list;
operator []
used to access the object at a given position in the ordered
list;
Withdraw(Position&)
used to remove the object at a given position from the
ordered list.
InsertAfter
used to insert an object into the ordered list after the object
at a given position; and
InsertBefore
used to insert an object into the ordered list before the
object at a given position.
THANK YOU
UNIT-2
Objectives
To Understand the concept of
Stacks
Operations on stack
Applications of
Queues
CircuAr Queue
Operations on Queues
Queue Applications.
STACKS IN DATA STRUCTURE
A stack is a non-primitive linear data
structure.
It is an ordered list follows particular order
The order is Last-in-First-out (LIFO) which
means the last added element will be
removed first from the stack.
The addition of new data item and deletion of
already existing data item is done from only
one end, known as top of stack(TOS).
Operations on a Stack
A stack supports two basic operations:
Push Operation
Pop Operation
PUSH OPERATION :
The push operation is used to insert an
element into the stack.
The new element is added at the topmost
position of the stack.
Before inserting the value, we must check if
TOP=MAX–1, the stack is full and no more
insertions can be done.
If an attempt is made to insert a value in a
stack that is already full, an OVERFLOW
message is printed.
POP OPERATION :
The pop operation is used to delete the
topmost element from the stack.
Before deleting the value, we must first
check if TOP=NULL, the stack is empty and
no more deletions can be done.
If an attempt is made to delete a value from
a stack that is already empty, an
UNDERFLOW message is printed.
EXAMPLE: WRITE A PROGRAM TO PERFORM PUSH AND POP
OPERATIONS ON A STACK.
#include <iostream>
using namespace std;
int stack[100], n=100, top=-1;
void push(int val) {
if(top>=n-1)
cout<<"Stack Overflow"<<endl;
else {
top++;
stack[top]=val;
}
}
//POP THE ELEMENT
void pop() {
if(top<=-1)
cout<<"Stack
Underflow"<<endl;
else {
cout<<"The popped element is
"<< stack[top] <<endl;
top--;
}
}
void display() {
if(top>=0) {
cout<<"Stack elements are:";
for(int i=top; i>=0; i-
cout<<stack[i]<<" ";
cout<<endl;
} else
cout<<"Stack is empty“;
}
int main() {
int ch, val;
cout<<"1) Push in stack"<<endl;
cout<<"2) Pop from stack"<<endl;
cout<<"3) Display stack"<<endl;
cout<<"4) Exit"<<endl;
do{
cout<<"Enter choice: "<<endl;
cin>>ch;
switch(ch) {
case 1: {
cout<<"Enter value to be
pushed:"<<endl;
cin>>val;
push(val);
break;
}
case 2: {
pop();
break;
}
case 3: {
dispAy();
break
}
case 4: {
cout<<"Exit"<<endl;
break;
}
default: {
cout<<"Invalid
Choice"<<endl
}
}
}
while(ch!=4);
return 0;
}
OUTPUT
1) Push in stack
2) Pop from stack
3) Display stack
4) Exit
Enter choice: 1
Enter value to be pushed: 2
Enter choice: 1
Enter value to be pushed: 6
Enter choice: 1
Enter value to be pushed: 8
Enter choice: 3
The stack elements are :8 6 2
Enter choice: 2
The popped element is 8
Enter choice: 3
Stack elements are:6 2
Enter choice: 5
Invalid Choice
Enter choice: 4
Exit
APPLICATION OF STACKS
Reversing a list
Parentheses checker
Conversion of an infix expression into a
postfix expression
Evaluation of a postfix expression
Recursion
Tower of Hanoi
CONVERSION OF INFIX TO
POSTFIX EXPRESSION USING
STACK
To convert Infix expression to Postfix
expression, we will use the stack data
structure.
Infix Expression : Infix Expression contains
operator in-between every pair of operands,
Expression of the form a op b.
Postfix expression: Postfix Expression
contains operator followed for every pair of
operands,
Expression of the form a b op.
WHY POSTFIX REPRESENTATION OF THE
EXPRESSION?
Infix expressions are readable and solvable
by humans but compiler doesn't have
integrated order of operators.
Hence to solve the Infix Expression compiler
will scan the expression multiple times to
solve the sub-expressions in expressions
orderly which is very in-efficient.
To avoid this traversing, Infix expressions are
converted to Postfix expression before
evaluation.
ALGORITHM
Step 1 : Scan the Infix Expression from left to right.
Step 2 : If the scanned character is an operand, send it with
final Infix to Postfix string.
Step 3 : Else,
If the scanned character is a (incoming) operator.
Then check whether stack is empty or contains only ‘(‘ or ‘[‘
or ‘{‘ or already contain some operator.
if empty or the stack contains a ‘(‘ or ‘[‘ or ‘{‘ ,then
operator pushed into stack.
If not empty (already contain a operators) ,check the
priority.
Step 4 :if the incoming operator is greater priority with instack
operator, then the new operator pushed into stack.
Or
If the incoming operator is less priority/equal priority with
instack operator then the instack operator popped out to
result
Step 5 : If the scanned character is an ‘)’or ‘]’
or ‘}’, pop the stack and and output it until a
‘(‘ or ‘[‘ or ‘{‘ respectively is encountered,
and discard both the parenthesis.
Step 6 : Repeat steps 2-5 until infix expression
is scanned.
Step 7 : Print the output
Step 8 : Pop and output from the stack until it
is not empty.
EXAMPLE
Infix Expression : 3+4*5/6
Step 1 : Initially Stack is Empty ans the very first literal of
Infix Expression is '3' which is operand hence push it on
output stack.
Stack : Output : 3
Step 2 : Next literal of expression is + which is operand,
hence needed to be pushed on stack but intially stack is
empty hence literal will directly pushed on to stack.
Stack : + Output : 3
Step 3 : Further 4 is an operand should be pushed on stack.
Stack : + Output : 3 4
Step 4 : Next literal is * which is an operator, as stack is not
empty, priority should be checked of instack operator(top of
stack) and of incoming operator i.e * as priority of in stack
operator is less than incoming operator, * will be pushed on
to stack.
Stack : + * Output : 3 4
CONTINUE…..
Step 5 : Next literal is 5 which is an operand, hence should
be pushed on to output stack.
Stack : + * Output : 3 4 5
Step 6 : Next literal is / which is an operator, as stack is
not empty, priority should be checked of instack
operator(top of stack) i.e * and of incoming operator i.e /,
as priority of / and * are equal hence * will be poped out of
stack and will be stored on output stack and operator / will
be stored on stack.
Stack : + / Output : 3 4 5 *
Step 7 : Next literal is 6 which is an operand, hence should
be pushed on output stack.
Stack : + / Output : 3 4 5 * 6
Step 8 : As now all literals are traversed, despite stack is
not empty, hence pop all literals from stack and pushed it
on to output stack.
Postfix Expression : 3 4 5 * 6 / +
#include<iostream>
#include<stack>
using namespace std;
void Postfix(char *a)
{ stack <char> s;
char output[50],t;
for(int i=0;a[i]!='\0';i++)
{ char ch = a[i];
switch(ch)
{
case '^':
case '-':
case '+':
case '/':
case '*': [Link](ch);
break;
case ')': t=[Link]();
[Link]();
cout<<t;
break;
CONTINUE…
if (isalpha(ch))
cout<<ch;
}
}
int main()
{
char a[] = "(((a*b)+(c/d))-e)";
Postfix(a);
return 0;
}
Output:
ab*cd/+e-
QUEUES IN DATA STRUCTURES
A Queue is also a non-primitive linear data
structure.
It is an ordered list follows particular order
(FIFO)-FIRST IN-FIRST OUT(which element
inserted first, that will be deleted first.
This means that the removal of elements
from a queue is possible in the same order in
which the insertion of elements is made into
the queue
A queue is also a list of elements with
insertions permitted at one end—called the
rear, and deletions permitted from the other
end—called the front
OPERATIONS ON A QUEUES
The basic operations that can be performed
on queue are :
ENQUEUE: To insert an element in a queue.
DEQUEUE: To delete an element from the queue.
ALGORITHM TO INSERT AN ELEMENT IN A QUEUE
we first check for the overflow condition.
IF REAR = MAX-1 Write OVERFLOW
we check if the queue is empty.
if
the queue is empty, then both FRONT and
REAR are set to zero, so that the new value can
be stored at the 0th location.
Otherwise, if the queue already has some
values, then REAR is incremented so that it
points to the next location in the array.
The value is stored in the queue at the
location pointed by REAR.
ALGORITHM TO DELETE AN ELEMENT FROM A QUEUE
we check for underflow condition.
An underflow occurs if FRONT = –1 or FRONT > REAR.
Write UNDERFLOW
Else,the queue has some values, then
FRONT is incremented so that it now points
to the next value in the queue.
CIRCULAR QUEUE
Circular Queue is also a linear data
structure, which follows the principle
of FIFO(First In First Out),
But instead of ending the queue at the
last position, it again starts from the
first position after the last
Hence making the queue behave like a
circular data structure.
BASIC FEATURES OF CIRCULAR QUEUE
In circular queue, head pointer will always point to the front of
the queue, and tail pointer will always point to the end of the
queue.
Initially, the head and the tail pointers will be pointing to
the same location, this would mean that the queue is
empty.
New data is always added to the location pointed by
the tail pointer, and once the data is added, tail pointer is
incremented to point to the next available location.
In a circular queue, data is not actually removed from the queue.
Only the head pointer is incremented by one position
when dequeue is executed. As the queue data is only the data
between head and tail, hence the data left outside is not a part of
the queue anymore, hence removed.
The head and the tail pointer will get reinitialised to 0 every time
they reach the end of the queue.
Also, the head and the tail pointers can cross each other. In other
words, head pointer can be greater than the tail. Sounds odd?
This will happen when we dequeue the queue a couple of times
and the tail pointer gets reinitialised upon reaching the end of the
queue.
IMPLEMENTATION OF CIRCULAR QUEUE
Initialize the queue, with size of the queue defined
(maxSize), and head and tail pointers.
enqueue: Check if the number of elements is equal to
maxSize - 1:
If Yes, then return Queue is full.
If No, then add the new data element to the
location of tail pointer and increment
the tail pointer.
dequeue: Check if the number of elements in the
queue is zero:
If Yes, then return Queue is empty.
If No, then increment the head pointer.
Finding the size:
If, tail >= head, size = (tail - head) + 1
But if, head > tail, then size = maxSize -
(head - tail) + 1