Updated Lab Manual
Updated Lab Manual
Patil Pratishthan’s
Approved by A.I.C.T.E, New Delhi , Maharashtra State Government, Affiliated to Savitribai Phule Pune
UniversitySector No. 29, PCNTDA , Nigidi Pradhikaran, Akurdi, Pune 411044. Phone: 020–27654470, Fax: 020-
27656566 Website :www.dypiemr.ac.in Email : principal.dypiemr@gmail.com
Department of
Artificial Intelligence and Data Science
LAB MANUAL
Course Objectives:
To understand basic techniques and strategies of algorithm analysis, the memory requirement for
various data structures like array, linked list, stack, queue etc using concepts of python and C++
programming language.
Course Outcomes:
On completion of the course, learner will be able to–
CO1: Use algorithms on various linear data structure using sequential organization to solve real
life problems.
CO2: Analyze problems to apply suitable searching and sorting algorithm to various applications.
CO3: Analyze problems to use variants of linked list and solve various real life problems.
CO4: Designing and implement data structures and algorithms for solving different kinds of
problems.
Department of AI&DS 2
Data Structure Laboratory Manual (217522) SE Sem1
Group D
9 D25 47
A palindrome is a string of character that‘s the same forward and backward.
Typically, punctuation, capitalization, and spaces are ignored. For example,
“Poor Dan is in a droop” is a palindrome, as can be seen by examining the
characters “poor danisina droop” and observing that they are the same forward
and backward. One way to check for a palindromeis to reverse the characters in
the string and then compare with them the original-in a palindrome, the sequence
will be identical. Write C++ program with functions-
a) To print original string followed by reversed string using stack
b) To check whether given string is palindrome or not
10 D26 In any language program mostly syntax error occurs due to unbalancing 51
delimiter such as (),{},[]. Write C++ program using stack to check whether given
expression is well parenthesized or not.
Group E
11 E29 Queues are frequently used in computer programming, and a typical example is 56
the creation of a job queue by an operating system. If the operating system does
not use priorities, thenthe jobs are processed in the order they enter the system.
Write C++ program for simulating job queue. Write functions to add job and
delete job from queue.
12 E31 A double-ended queue (deque) is a linear list in which additions and deletions 61
may be madeat either end. Obtain a data representation mapping a deque into a
one-dimensional array. Write C++ program to simulate deque with functions to
add and delete elements from either end of the deque.
13 E32 Pizza parlor accepting maximum M orders. Orders are served in first come first 64
served basis. Order once placed cannot be cancelled. Write C++ program to
simulate the system using circular queue using array.
Department of AI&DS 4
Assignment no: 01
Aim: To study and understand the concept of set theory using python.
Problem definition:
In second year, computer engineering class, group A student’s play cricket, group B students play
badminton and group C students play football. Write a Python program using functions to compute
following: -
a) List of students who play both cricket and badminton
b) List of students who play either cricket or badminton but not both
c) Number of students who play neither cricket nor badminton
d) Number of students who play cricket and football but not badminton.
(Note-While realizing the group, duplicate entries should be avoided, do not use SET built-in
functions)
Learning Objectives:
To understand basic techniques and strategies of algorithm using concepts of python.
Learning Outcome:
Students will be able to use algorithms on various linear data structure using sequential
organization to solve real life problems.
Theory:
Python:
Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is
designed to be highly readable. It uses English keywords frequently where as other languages use
punctuation, and it has fewer syntactical constructions than other languages.
Set Operations:
We have to perform here different set operations like Union, Intersections, Difference, Symmetric
Difference.
Universal set U:
Often a discussion involves subsets of some particular set called the universe of discourse (or
briefly universe), universal set or space. The elements of a space are often called the
points of thespace. We denote the universal set by U.
Example. The set of all even integers could be considered a subset of a universal set consisting of
all the integers. Or they could be considered a subset of a universal set consisting of all the
rational numbers. Or of all the real numbers.
Often the universal set may not be explicitly stated and it may be unclear as to just what it is. At
other times it will be clear.
1. Union Operation: In set theory the union of collection of sets is the set of all distinct elements in
the collection. The union of two sets A and B is the set consisting of all elements in A plus all
elements in B and is denoted by A𝖴B or A + B.
1. Intersection operation: In set theory intersection is a operation where we collect common elements
of different sets. The intersection of two sets A and B is the set consisting of all elements that occur
in both A and B (i.e. all elements common to both) and is denoted by A∩B, A · B or AB.
3. Symmetric Difference: The symmetric difference between two sets S and t is the union of
S-T and T-S. The symmetric difference using Venn diagram of two subsets A and B is a sub set of
U, denoted by A 𝗈 B and is defined by A 𝗈 B = (A – B) 𝖴 (B – A)
Input: Enter the total number of students in class, also enter the student who plays cricket,
badminton and football.
Algorithm/Pseudo code:
1. Function for union:
def
find_union_set(A,B,C): for
i in range(len(A)):
C.append(A[i])
for i in range(len(B)):
flag = search_set(A,B[i]);
if(flag == 0) :
C.append(B[i])
Software required: Open Source Python, Programming tool like Jupyter Notebook, Pycharm,
Spyder.
Problem Statement: Write a Python program to store marks scored in subject “Fundamental of
Data Structure” by N students in the class. Write functions to compute following:
a) The average score of class
b) Highest score and lowest score of class
c) Count of students who were absent for the test
d) Display mark with highest frequency
Learning Objectives:
To understand basic techniques and strategies of algorithm analysis, the memory requirement for
various data structures using the concepts of python.
Learning Outcome: Students will be able to use algorithms on various linear data structure using
sequential organization to solve real life problems
Theory: Lists are one of the most powerful tools in python. They are just like the arrays declared
in other languages. But the most powerful thing is that list need not be always homogenous. A
single list can contain strings, integers, as well as objects. Lists can also be used for implementing
stacks and queues. Lists are mutable, i.e., they can be altered once declared.
A tuple is a sequence of immutable Python objects. Tuples are just like lists with the exception that
tuples cannot be changed once declared. Tuples are usually faster than lists
Input: enter marks scored in subject “Fundamental of Data Structure” by N students in the class.
Output: Average score, highest score, lowest score, count of absentees, marks with highest
frequency.
Algorithm/Pseudocode:
def find_average_score_of_class(A) :
sum = 0
for i in range(len(A)) :
if(A[i] != -1) :
sum = sum +
A[i] avg = sum /
len(A)
display_marks(A)
print("\nAverage score of class is %.2f\n\n"%avg)
if(A[i] == -1) :
count += 1
display_marks(A
)
print("\tAbsent Student Count = %d"%count)
def display_mark_with_highest_frequency(A) :
freq = 0
for i in range(len(A)) :
count = 0
if(A[i] != -1) :
for j in range(len(A)):
if(A[i] == A[j]) :
count += 1
if(freq < count)
:
Marks =
A[i] freq =
count
display_marks(A)
print("\nMarks with highest frequency is %d (%d)"%(Marks,freq))
Software required: Open Source Python, Programming tool like Jupyter Notebook, PyCharm,
Spyder.
Conclusion: Thus, we have studied the implementation of various python operations.
Assignment no: 03
Aim: To study and understand the concept of a bank account based transaction using Python.
Problem definition:
Write a Python program that computes the net amount of a bank account based a transaction log
from console input. The transaction log format is shown as following: D 100 W 200 (Withdrawal is not
allowed if balance is going negative. Write functions for withdraw and deposit) D means deposit while W
means withdrawal. Suppose the following input is supplied to the program:
D 300, D 300 , W 200, D 100 Then, the output should be: 500
Learning Objectives:
To understand the concept of function using python.
Learning Outcome:
Students will be able to use algorithms on various data structures using sequential
organization to solve real life problems.
Theory:
We define a Bank class representing a bank. It has an attribute called customers, which is initially an empty
dictionary.
create_account():
The "create_account()" method takes an account number and an optional initial balance as arguments. It
checks if the account number already exists in the customers' dictionary. If it does, it prints a message
indicating that the account number already exists. Otherwise, the account number is added as a key with the
initial balance as the value.
Make_deposit():
The "make_deposit()" method takes an account number and an amount as arguments. It checks if the
account number exists in the customer's dictionary. If it does, it adds the amount to the current balance of
the account. An error message is printed if the account number does not exist.
Make_withdrawal():
The "make_withdrawal()" method takes an account number and an amount as arguments. It checks if the
account number exists in the customer's dictionary. If it does, it checks if the account has sufficient funds to
withdraw. If it does, it subtracts the amount from the current account balance. Otherwise, it prints an error
message indicating insufficient funds. An error message is displayed if the account number does not exist.
Check_balance():
The "check_balance()" method takes an account number as an argument. It checks if the account number
exists in the customer's dictionary. If it does, it retrieves and prints the current account balance. If the
account number does not exist, it prints a message.
In the example usage section, we create an instance of the Bank class called bank. We use various
methods to create customer accounts, make deposits, withdraw, and check account balances.
Algorithm/Pseudocode:
• Deposit:
def deposit(self):
self.print_current_balance()
• Withdraw:
def withdraw(self):
else:
self.total_amount -= amount_to_withdraw
self.print_current_balance()
Software required: Open Source Python, Programming tool like Jupyter Notebook, Spyder.
Conclusion: Thus, we have studied and implemented the bank account based transaction using
Python
Assignment No- 04
Problem Statement: a) Write a Python program to store names and mobile numbers of your
friends in sorted order on names. Search your friend from list using binary search (recursive and
non- recursive). Insert friend if not present in phonebook
b) Write a Python program to store names and mobile numbers of your friends in sorted order on
names. Search your friend from list using Fibonacci search. Insert friend if not present in
phonebook.
Learning Objectives:
To understand concept of searching.
To compare time complexity of various searching techniques.
Learning Outcome: Students will be able to analyze problems to apply suitable searching and
sorting algorithm to various applications.
Theory:
Binary Search:
For a binary search to work, it is mandatory for the target array to be sorted. We shall learn the
process of binary search with a pictorial example. The following is our sorted array and let us
assume that we need to search the location of value 31 using binary search.
Here it is, 0 + (9 - 0 ) / 2 = 4 (integer value of 4.5). So, 4 is the mid of the array.
Now we compare the value stored at location 4, with the value being searched, i.e. 31. We find that
the value at location 4 is 27, which is not a match. As the value is greater than 27 and we have a
sorted array, so we also know that the target value must be in the upper portion of the array.
We change our low to mid + 1 and find the new mid value again.
low = mid + 1
mid = low + (high - low) / 2
Our new mid is 7 now. We compare the value stored at location 7 with our target value 31.
The value stored at location 7 is not a match, rather it is more than what we are looking for. So, the
value must be in the lower part from this location.
Binary search halves the searchable items and thus reduces the count of comparisons to be made to
very less numbers.
Fibonacci Search:
Fibonacci search is an efficient search algorithm based on divide and conquer principle that can
find an element in the given sorted array with the help of Fibonacci series in O(log N) time
complexity. This is based on Fibonacci series which is an infinite sequence of numbers denoting a
pattern which is captured by the following equation:
F(n+1)=F(n)+F(n-1)
where F(i) is the ith number of the Fibonacci series where F(0) and F(1) are defined as 0 and 1 respectively.
0,1,1,2,3,5,8,13....
F(0) = 0
F(1) = 1
F(2) = F(1) + F(0) = 1 + 0 = 1
F(3) = F(2) + F(1) = 1 + 1 = 2
F(4) = F(3) + F(2) = 1 + 2 = 3 and so continues the series
Other searches like binary search also work for the similar principle on splitting the search space to
a smaller space but what makes Fibonacci search different is that it divides the array in unequal
parts and operations involved in this search are addition and subtraction only which means light
arithmetic operations takes place and hence reducing the work load of the computing machine.
Input: Enter the names and mobile numbers of your friend in sorted order
Algorithm/Pseudo code:
Binary Search:
Procedure binary_search
A ← sorted array
n ← size of array
x ← value to be searched
Set lowerBound = 1
Set upperBound = n
if A[midPoint] < x
set lowerBound = midPoint + 1
if A[midPoint] > x
set upperBound = midPoint - 1
if A[midPoint] = x
EXIT: x found at location
midPoint end while
end procedure
Fibonacci Search:
Let the length of given array be n [0...n-1] and the element to be searched be
x. Then we use the following steps to find the element with minimum steps:
1. Find the smallest Fibonacci number greater than or equal to n. Let this number be fb(M)
[m’th Fibonacci number]. Let the two Fibonacci numbers preceding it be fb(M-1) [(m-1)’th
Fibonacci number] and fb(M-2) [(m-2)’th Fibonacci number].
2. While the array has elements to be checked:
-> Compare x with the last element of the range covered by fb(M-2)
-> If x matches, return index value
-> Else if x is less than the element, move the third Fibonacci variable two Fibonacci
down, indicating removal of approximately two-third of the unsearched array.
-> Else x is greater than the element, move the third Fibonacci variable one Fibonacci down. Reset
offset to index. Together this results into removal of approximately front one-third of the
unsearched array.
3. Since there might be a single element remaining for comparison, check if fbMm1 is '1'. If
Yes, compare x with that remaining element. If match, return index value.
Software required: Open Source Python, Programming tool like Jupyter Notebook, PyCharm,
Spyder.
Conclusion: Thus, we have studied the implementation of various sorting techniques (Bubble and
Selection)
Assignment No- 05
Problem Statement: Write a Python program to store first year percentage of students in array.
Write function for sorting array of floating-point numbers in ascending order using a) Selection
Sort
b) Bubble sort and display top five scores
Learning Objectives:
To understand concept of sorting.
To compare time complexity of various sorting techniques.
Learning Outcome: Students will be able to analyze problems to apply suitable searching and
sorting algorithm to various applications.
Theory:
Bubble Sort
Bubble sort is a simple and well-known sorting algorithm. It is used in practice once in a blue
moon and its main application is to make an introduction to the sorting algorithms. Bubble sort
belongs to O(n2) sorting algorithms, which makes it quite inefficient for sorting large data
volumes. Bubble sort is stable and adaptive.
Example :
Selection Sort
Selection sort is one of the O(n2) sorting algorithms, which makes it quite inefficient for sorting
large data volumes. Selection sort is notable for its programming simplicity and it can over
perform other sorts in certain situations (see complexity analysis for more details).
Input: Enter the first percentage of students
Output: sorting by selection and bubble sort and display top 5 students marks
Begin SelectionSort(list)
for all elements of list
for j to all element of
list
if list[i] > list[j]
swap(list[i],
list[j])
end if
end for
end for
return
list
end BubbleSort
Software required: Open Source Python, Programming tool like Jupyter Notebook, PyCharm,
Spyder.
Conclusion: Thus, we have studied the implementation of various sorting techniques (Bubble and
Selection)
Assignment No- 06
Problem Statement: Write a Python program to store first year percentage of students in array.
Write function for sorting array of floating-point numbers in ascending order using quick sort and
display top five scores.
Learning Objectives:
To understand concept of sorting.
To find time complexity of Quick Sort.
Learning Outcome: Students will be able to analyze problems to apply suitable searching and
sorting algorithm to various applications.
Theory of Quick sort:
Quicksort is a fast sorting algorithm, which is used not only for educational purposes, but widely
applied in practice. On the average, it has O(n log n) complexity, making quicksort suitable for
sorting big data volumes. The idea of the algorithm is quite simple and once you realize it, you can
write quicksort as fast as bubble sort.
Algorithm
The divide-and-conquer strategy is used in quicksort. Below the recursion step is described:
Choose a pivot value. We take the value of the middle element as pivot value, but it can beany
value, which is in range of sorted values, even if it doesn't present in the array.
Partition. Rearrange elements in such a way, that all elements which are lesser than the pivot go to
the left part of the array and all elements greater than the pivot, go to the right partof the array.
Values equal to the pivot can stay in any part of the array. Notice, that array maybe divided in
non-equal parts.
Sort both parts. Apply quicksort algorithm recursively to the left and the right parts.
Partition algorithm in detail
There are two indices i and j and at the very beginning of the partition algorithm i points to the first
element in the array and j points to the last one. Then algorithm moves i forward, until an element
with value greater or equal to the pivot is found. Index j is moved backward, until an element with
value lesser or equal to the pivot is found. If i ≤ j then they are swapped and i steps to the next
position (i + 1), j steps to the previous one (j - 1). Algorithm stops, when i becomes greater than j.
After partition, all values before i-th element are less or equal than the pivot and all values after j-
th element are greater or equal to the pivot.
/* partition */
while (i <= j) {
while (arr[i] < pivot)
i++;
while (arr[j] > pivot)
j--;
if (i <= j) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;
j--;
}
};
/* recursion */
if (left < j)
quickSort(arr, left, j);
if (i < right)
quickSort(arr, i, right);
Software required: Open Source Python, Programming tool like Jupyter Notebook, PyCharm,
Spyder.
Problem definition: Department of Computer Engineering has student's club named 'Pinnacle
Club'. Students of Second, third and final year of department can be granted membership on
request. Similarly, one may cancel the membership of club. First node is reserved for president of
club and last node is reserved for secretary of club. Write C++ program to maintain club member‘s
information using singly linked list. Store student PRN and Name. Write functions to
a) Add and delete the members as well as president or even secretary.
b) Compute total number of members of club
c) Display members
d) Display list in reverse order using recursion
e) Two linked lists exist for two divisions. Concatenate two lists.
Learning objectives
To understand concept of sll.
To analyze the working of functions.
Learning outcome
Students will be able to analyze problems to use variants of linked list and solve various real-life
problems.
Theory:
Linked list:
Linked list is one of the fundamental data structures, and can be used to implement other data
structures. In a linked list there are different numbers of nodes. Each node is consists of two fields.
The first field holds the value or data and the second field holds the reference to the next node or
null if the linked list is empty.
The singly-linked list is the easiest of the linked list, which has one link per node.
This process will run until the linked list’s next is NULL.
Input:
Enter members, president and secretary having their PRN and Name to be stored in the singly
linked list. Every node would contain 2 fields: data and next pointer.
Output:
Insertion of node at front, at end, at any given position, deletion of node, reverse of linked list,
count total number of nodes, merge two linked list.
Algorithm:
Step 4: end .
Algorithm to Delete any member Node
Step 1: p - pointer to linked list
deleted
k = next(k)
if k = NIL then
next(pred) = next(k)
return p
end
DeleteNode.
Step 5: end
Algorithm to Count the total number of members nodes in the link list.
Step 1: count = 0
Step 2: Increment count as each node is
traversed current = head
while (current != NULL) then
count++
Step 3: end
Assignment no: 08
Problem definition: Second year Computer Engineering class, set A of students like Vanilla
Ice-cream and set B of students like butterscotch ice-cream. Write C/C++ program to store two
sets using linked list. compute and display i. Set of students who like either vanilla or
butterscotch or both ii. Set of students who like both vanilla and butterscotch iii. Set of students
who like only vanilla not butterscotch iv. Set of students who like only butterscotch not vanilla
v. Number of students who like neither vanilla nor butterscotch
Learning objectives
To understand concept of set operations and linked list.
Learning outcome
Students will be able to analyze problems to use variants of linked list and solve various real- life
problems.
Theory:
Set
Elements are the objects contained in a set. A set may be defined by a common property
amongst the objects. For example, the set E of positive even integers is the set E={2,4,6,8,10..}
Definition (Union): The union of sets A and B, denoted by A B , is the set defined as
A B={x|x A x B}
Data Structure Laboratory Manual (210246)
A B={x|x A x B}
Definition (Difference): The difference of sets A from B , denoted by A - B , is the set defined as
A-B={x|x A x B}
Singly linked lists contain nodes which have a data field as well as a 'next' field, which points
to the next node in line of nodes. Operations that can be performed on singly linked lists
include insertion, deletion and traversal.
A singly linked list whose nodes contain two fields: an integer value and a link to the next
node
List1: 10->15->4->20
lsit2: 8->4->2->10
Output: 1
Data Structure Laboratory Manual (210246)
Input: enter set A of students like Vanilla Ice-cream and set B of students like butterscotch
ice-cream.
Algorithm:
cur2=cur2->next;
if(found==1)
{
cout<<cur
1->dat
a<<" ";
cur1=c
}
ur1->n
else
ext;
found=
0;
cur1=cur1->next;
cur2=Vanilla;
}
}
else
}
if(found==1)
{
}
else
{
cur2=cur2->next; found=0;
cout<<cur2->data<<" "; cur2=cur2->next;
cur1=Butter;
}
}
cur2=cur2->next
}
else{
}
if(found==1)
{
}
else
{
cur1=cur1->next; found=0;
cout<<cur1->data<<" ";
cur1=cur1->next;
cur2=Vanilla;
}
}
Set of students who like either vanilla or butterscotch or both
void uni()
{
onlyB();
intersection();
onlyV();
}
if(f==0)
{ cout<<"\n"<<temp->roll; }
temp=temp->next;
}
}
Software required: g++ / gcc compiler- / 64 bit fedora.
Problem Statement: A palindrome is a string of character that‘s the same forward and
backward. Typically, punctuation, capitalization, and spaces are ignored. For example, ǁPoor Dan
is in a droopǁ is a palindrome, as can be seen by examining the characters ―poor danisina droopǁ
and observing that they are the same forward and backward. One way to check for a palindrome
is to reverse the characters in the string and then compare with them the original-
in a palindrome, the sequence will be identical. Write C++ program with functions-
1. To check whether given string is palindrome or not that uses a stack to determine
whether a string is a palindrome.
2. To remove spaces and punctuation in string, convert all the Characters to
lowercase, and then call above Palindrome checking function to check for a palindrome
3. To print string in reverse order using stack
Learning Objectives:
To understand concept of stack and string. To
analyze the string is palindrome or not.
Learning Outcome: Students will be able to implement stack and queue data structures and
algorithms for solving different kinds of problems.
Theory:
Stack
It is named stack as it behaves like a real-world stack, for example − deck of cards or pile
of plates etc. A stack is an abstract data type that serves as a collection of elements, with two
principal operations: push, which adds an element to the collection, and pop, which removes the
most recently added element that was not yet removed. The order in which elements come off a
stack gives rise to its alternative name, LIFO (for last in, first out). Additionally, a peek operation
may give access to the top without modifying the stack.
A real-world stack allows operations at one end only. For example, we can place or
remove a card or plate from top of the stack only. Likewise, Stack ADT allows all data
operations at one end only. At any given time, We can only access the top element of a stack.
This feature makes it LIFO data structure. LIFO stands for Last-in-first-out. Here, the element
which is placed (inserted or added) last, is accessed first. In stack terminology, insertion
operation is called PUSH operation and removal operation is called POP operation.
StackRepresentation
Below given diagram tries to depict a stack and its operations −
A stack can be implemented by means of Array, Structure, Pointer and Linked-List. Stack can
either be a fixed size one or it may have a sense of dynamic resizing. Here, we are going to
implement stack using arrays which makes it a fixed size stack implementation. Basic Operations
Stack operations may involve initializing the stack, using it and then de-initializing it. Apart
from these basic stuffs, a stack is used for the following two primary operations −
peek() − get the top data element of the stack, without removing it.
At all times, we maintain a pointer to the last PUSHed data on the stack. As this pointer always
represents the top of the stack, hence named top. The toppointer provides top value ofthe stack
without actually removing it.
Input:
Enter the string.
Output:
Entered string is palindrome or not
Algorithm:
Problem Statement: In any language program mostly syntax error occurs due to unbalancing
delimiter such as (),{},[]. Write C++ program using stack to check whether given expression is
well parenthesized or not.
Learning Objectives:
To understand concept of stack.
To analyze the working of various functions of stack.
Learning Outcome: Students will be able to implement stack and queue data structures and
algorithms for solving different kinds of problems.
Theory:
Stack
A stack is a container of objects that are inserted and removed according to the last-in
first-out (LIFO) principle.
In the pushdown stacks only two operations are allowed:
A stack is a limited access data structure - elements can be added and removed from the
stack only at the top. push adds an item to the top of the stack, pop removes the item from the
top. A helpful analogy is to think of a stack of books; you can remove only the top book, also
you can add a new book on the top.
The name "stack" for this type of structure comes from the analogy to a set of physical
items stacked on top of each other, which makes it easy to take an item off the top ofthe stack,
while getting to an item deeper in the stack may require taking off multiple other items first.[1]
Considered as a linear data structure, or more abstractly a sequential collection, the push
and pop operations occur only at one end of the structure, referred to as the top of the stack. A
stack may be implemented to have a bounded capacity. If the stack is full and does not contain
enough space to accept an entity to be pushed, the stack is then considered to bein an overflow
state. The pop operation removes an item from the top of the stack.
Balanced parentheses
We now turn our attention to using stacks to solve real computer science problems.
You have no doubt written arithmetic expressions such as
(5+6)∗(7+8)/(4+3)(5+6)∗(7+8)/(4+3)
where parentheses are used to order the performance of operations.
Balanced parentheses means that each opening symbol has a corresponding closing
symbol and the pairs of parentheses are properly nested. Consider the following correctly
balanced strings of parentheses:
The ability to differentiate between parentheses that are correctly balanced and those that
are unbalanced is an important part of recognizing many programming language structures.
The challenge then is to write an algorithm that will read a string of parentheses from left
to right and decide whether the symbols are balanced. To solve this problem we need to make an
important observation. As you process symbols from left to right, the most recent opening
parenthesis must match the next closing symbol . Also, the first opening symbol processed may
have to wait until the very last symbol for its match. Closing symbols match opening symbols in
the reverse order of their appearance; they match from the inside out. This is a clue that stacks
can be used to solve the problem.
Input:
Enter any expression having number of opening & closing brackets.
Output:
Entered expression is well parenthesized or not.
Algorithm:
Problem Statement: Queues are frequently used in computer programming, and a typical
example is the creation of a job queue by an operating system. If the operating system does not
use priorities, then the jobs are processed in the order they enter the system. Write C++ program
for simulating job queue. Write functions to add job and delete job from queue.
Learning Objectives:
To understand concept of queue.
To analyze the various functions of queue.
Learning Outcome: Students will be able to implement stack and queue data structures and
algorithms for solving different kinds of problems.
Theory:
A queue is logically a first in first out (FIFO or first come first serve) linear data
structure. The concept of queue can be understood by our real life problems. For example a
customer come and join in a queue to take the train ticket at the end (rear) and the ticket is issued
from the front end of queue. That is, the customer who arrived first will receive the ticket first. It
means the customers are serviced in the order in which they arrive at the servicecentre. It is a
homogeneous collection of elements in which new elements are added at one end called rear, and
the existing elements are deleted from other end called front. The basic operations that can be
performed on queue are A minimal set of operations on a queue is as follows:
Step 15:End
Step 1:Is_Full()
tep 2: if(Rear == max − 1)
return 1;
else
End Step 3: End
return 0;
Algorithm to adds an element in the queue
Step 1: Add(int Element)
Step 2:if(Is_Full())
then
print Error, Queue is full Queue[++Rear] = Element;
else
End
Step 3: End
Step 1: Delete()
Step 2:if(Is_Empty())
then
print Sorry, queue is Emptyreturn(Queue[++Front]);
else
End
Step 3: End
elseEnd
Step3: End
Problem Statement: A double-ended queue (deque) is a linear list in which additions and
deletions may be made at either end. Obtain a data representation mapping a deque into a one-
dimensional array. Write C++ program to simulate deque with functions to add and delete
elements from either end of the deque.
Learning Objectives:
To understand concept of double-ended queue (deque).
To analyze the various functions of double-ended queue (deque).
Learning Outcome: Students will be able to implement stack and queue data structures and
algorithms for solving different kinds of problems.
Theory:
DeQueue:
Dequeue is a data structure in which elements may be added to or deleted from the front or the
rear. Like an ordinary queue, a double-ended queue is a data structure it supports the following
operations: enq_front, enq_back, deq_front, deq_back, and empty. Dequeue can be behave like a
queue by using only enq_front and deq_front , and behaves like a stack by using only enq_front
and deq_rear. .The DeQueue is represented as follows.
The output restricted Dequeue allows deletions from only one end and input restricted
Dequeue allow insertions at only one end.
Algorithm:
Algorithm to add an element into DeQueue :
Assumptions: pointer f,r and initial values are -1,-1
Q[] is an array
max represent the size of a queue
step1. Start
step2. Check the queue is empty or not as if (f == r) if yes queue is empty
step3. If false update pointer f as f = f+1 and delete element at position f as element = Q[f]
step4. If ( f== r) reset pointer f and r as f=r=-1
step5. Stop
Algorithm to delete an element from back :
step1. Start
step2. Check the queue is empty or not as if (f == r) if yes queue is empty
step3. If false delete element at position r as element = Q[r]
step4. Update pointer r as r = r-1
step5. If (f == r ) reset pointer f and r as f = r= -1
step6. Stop
Problem Statement: Pizza parlor accepting maximum M orders. Orders are served in first come
first served basis. Order once placed cannot be cancelled. Write C++ program to simulate the
system using circular queue using array.
Learning Objectives:
To understand concept of circular queue.
To analyze the various functions of circular queue.
Learning Outcome: Students will be able to implement stack and queue data structures and
algorithms for solving different kinds of problems.
Theory:
Circular Queue:
1. In case of a 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.
2. Initially, the head and the tail pointers will be pointing to the same location, this would
mean that the queue is empty.
3. 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.
4. 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.
5. The head and the tail pointer will get reinitialized to 0 every time they reach the end of
the queue
6. 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 reinitialized upon reaching the end of the queue.
Input: Enter the orders of Pizza Parlor.
Output: Add orders and serve orders of pizza.