0% found this document useful (0 votes)
2 views55 pages

Ds Practical ..

The document contains multiple Python and C++ programming tasks related to data structures and algorithms, including operations on lists, strings, matrices, and linked lists. It covers various functionalities such as searching, sorting, and membership management in a club using linked lists. Each task is accompanied by code snippets demonstrating the required operations.

Uploaded by

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

Ds Practical ..

The document contains multiple Python and C++ programming tasks related to data structures and algorithms, including operations on lists, strings, matrices, and linked lists. It covers various functionalities such as searching, sorting, and membership management in a club using linked lists. Each task is accompanied by code snippets demonstrating the required operations.

Uploaded by

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

Name: Prajwal Charthad

Roll no: 133

1.In second year computer engineering class, group A student's play


cricket, group Bstudents 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)

CODE
def remove_duplicates(lst):
unique_list = []
for item in lst:

if item not in
unique_list:
unique_list.append(it
em)
return unique_list

def intersection(list1, list2):


common = []
for student in list1:
if student in list2:
common.append(stud
ent)

return common

def symmetric_difference(list1, list2):


either_but_not_both = []
for student in list1:
if student not in list2:
either_but_not_both.append(stud
ent)

for student in list2:


if student not in list1:
either_but_not_both.append(stud
ent)
return either_but_not_both

def neither_cricket_nor_badminton(total_students, cricket_list, badminton_list):


students_playing_cricket_or_badminton = cricket_list + badminton_list

students_playing_cricket_or_badminton =
remove_duplicates(students_playing_cricket_or_badminton)
neither = []
for student in total_students:

if student not in
students_playing_cricket_or_badminton:
neither.append(student)
return neither

def cricket_and_football_not_badminton(cricket_list, football_list, badminton_list):


cricket_and_football = []
for student in cricket_list:
if student in football_list and student not in badminton_list:
cricket_and_football.append(student)
return cricket_and_football

total_students = ["Alice", "Bob", "Charlie", "David", "Eve", "Frank", "Grace", "Hannah",


"Isaac", "Jack"]

cricket_players = ["Alice", "Bob", "Charlie", "David", "Frank",


"Grace"] badminton_players = ["Bob", "Eve", "Frank",
"Isaac"] football_players = ["Alice", "David", "Frank", "Jack"]

cricket_players = remove_duplicates(cricket_players)
badminton_players =
remove_duplicates(badminton_players)
football_players = remove_duplicates(football_players)

cricket_and_badminton = intersection(cricket_players, badminton_players)


print("Students who play both Cricket and Badminton:",
cricket_and_badminton)

either_cricket_or_badminton = symmetric_difference(cricket_players,
badminton_players)

print("Students who play either Cricket or Badminton but not both:",


either_cricket_or_badminton)

neither = neither_cricket_nor_badminton(total_students, cricket_players,


badminton_players) print("Number of students who play neither Cricket nor
Badminton:", len(neither))

cricket_and_football_not_badminton_list =
cricket_and_football_not_badminton(cricket_players, football_players,
badminton_players)
print("Students who play Cricket and Football but not Badminton:",
cricket_and_football_not_badminton_list)

OUTPUT
Name: Prajwal Charthad
Roll no: 133

2 Write a Python program to compute following operations on String: a) b) c) d)


e)
a) To display word with the longest length
b) To determines the frequency of occurrence of particular character in the
string
c) To check whether given string is palindrome or not
d) To display index of first appearance of the substring
e) To count the occurrences of each word in a given

string CODE

def longest_word(sentence):
words = sentence.split()
longest = max(words,
key=len) return longest

def character_frequency(sentence, char):

count = 0
for c in sentence:
if c == char:

count += 1
return count

def is_palindrome(sentence):
cleaned_sentence = ''.join(e for e in sentence if

e.isalnum()).lower() return cleaned_sentence ==

cleaned_sentence[::-1]

def substring_index(sentence,
substring): return
sentence.find(substring)

def
word_count(sentence)
: words =
sentence.split()
count_dict = {}
for word in words:

if word in count_dict:
count_dict[word] += 1

else:
count_dict[word] = 1

return count_dict

# Input string

sentence = "Python is fun and Python is


powerful" char = 'P'
substring = "fun"

# a) Display word with the longest length

print("Word with the longest length:", longest_word(sentence))

# b) Frequency of occurrence of a particular character


print(f"Frequency of character '{char}':", character_frequency(sentence, char))

# c) Check if the string is palindrome


print("Is the given string a palindrome?:", is_palindrome(sentence))

# d) Index of first appearance of a substring


print(f"First appearance of substring '{substring}':", substring_index(sentence,
substring))

# e) Count occurrences of each word in the given string


print("Word count:", word_count(sentence))
OUTPUT
Name: Prajwal Charthad
Roll no: 133

3 Write a Python program to compute following computation on matrix:


a) Addition of two matrices

b) Subtraction of two matrices


c) Multiplication of two matrices
d) Transpose of a
matrix. CODE
# Function to add two matrices
def matrix_addition(matrix1,
matrix2): result = []
for i in range(len(matrix1)):

row = []
for j in range(len(matrix1[0])):
row.append(matrix1[i][j] + matrix2[i][j])

result.append(ro
w) return result

# Function to subtract two matrices


def matrix_subtraction(matrix1,
matrix2): result = []

for i in range(len(matrix1)):

row = []
for j in range(len(matrix1[0])):
row.append(matrix1[i][j] - matrix2[i][j])

result.append(ro

w) return result

# Function to multiply two matrices


def matrix_multiplication(matrix1, matrix2):
result = [[0 for _ in range(len(matrix2[0]))] for _ in
range(len(matrix1))] for i in range(len(matrix1)):
for j in range(len(matrix2[0])):

for k in range(len(matrix2)):
result[i][j] += matrix1[i][k] * matrix2[k][j]
return result

# Function to transpose a matrix


def matrix_transpose(matrix):

result = []
for i in range(len(matrix[0])):

row = []
for j in
range(len(matrix)):
row.append(matrix[j][i])

result.append(ro
w) return result

# Input
matrices matrix1
= [[1, 2, 3],
[4, 5, 6],

[7, 8, 9]]

matrix2 = [[9, 8, 7],


[6, 5, 4],

[3, 2, 1]]

# a) Addition of two matrices


print("Addition of two
matrices:")
for row in matrix_addition(matrix1, matrix2):
print(row)
# b) Subtraction of two matrices
print("\nSubtraction of two
matrices:")
for row in matrix_subtraction(matrix1,
matrix2): print(row)

# c) Multiplication of two matrices


print("\nMultiplication of two
matrices:")
for row in matrix_multiplication(matrix1,
matrix2): print(row)

# d) Transpose of a matrix
print("\nTranspose of the first
matrix:") for row in
matrix_transpose(matrix1):
print(row)

OUTPUT
Name: Prajwal Charthad
Roll no: 133

4Write a Python program to store roll numbers of student in array who


attended training program in random order. Write function for searching
whether particular student attended training program or not, using Linear search
and Sentinel search.
CODE
def linear_search(roll_numbers,
target):
for index in range(len(roll_numbers)):

if roll_numbers[index] == target:

return
index return -
1

def sentinel_search(roll_numbers, target):


n = len(roll_numbers)
last = roll_numbers[-1]
roll_numbers[-1] =
target

index = 0
while roll_numbers[index] != target:

index += 1

roll_numbers[-1] = last # Restore the last element

if index < n - 1 or roll_numbers[-1] == target:

return
index return
-1

# Input: Roll numbers of students who attended the training


program roll_numbers = [103, 102, 101, 104, 106, 105]
# Input: Roll number to search
target_roll_number = int(input("Enter roll number to search: "))

# Linear Search

linear_result = linear_search(roll_numbers,
target_roll_number) if linear_result != -1:
print(f"Linear Search: Student with roll number {target_roll_number} attended the
training program (Index: {linear_result}).")
else:
print(f"Linear Search: Student with roll number {target_roll_number} did not attend
the training program.")

# Sentinel Search
sentinel_result = sentinel_search(roll_numbers,
target_roll_number) if sentinel_result != -1:
print(f"Sentinel Search: Student with roll number {target_roll_number} attended the
training
program (Index:
{sentinel_result}).") else:
print(f"Sentinel Search: Student with roll number {target_roll_number} did not
attend the training program.")

OUTPUT
Name: Prajwal Charthad
Roll no: 133

5Write a Python program to store first year percentage of students in an-ay. Write
function for sorting array of floating point numbers in ascending order using
a) Selection Sort
b) Bubble sort and display top five

scores. CODE
def selection_sort(arr):
n = len(arr)

for i in range(n):
min_index = i

for j in range(i + 1, n):


if arr[j] <
arr[min_index]:
min_index = j

arr[i], arr[min_index] = arr[min_index], arr[i]

def bubble_sort(arr):

n = len(arr)

for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:

arr[j], arr[j+1] = arr[j+1], arr[j]

def display_top_five_scores(arr):

print("Top five scores:", arr[-5:])

# Input: First year percentages of students


percentages = [76.5, 88.2, 45.0, 92.1, 67.4, 80.5, 55.3, 70.8, 91.0, 65.7]
# Sorting using Selection Sort
selection_sorted =
percentages.copy()
selection_sort(selection_sorted)
print("Sorted percentages using Selection
Sort:") print(selection_sorted)
display_top_five_scores(selection_sorted)

# Sorting using Bubble Sort


bubble_sorted =
percentages.copy()
bubble_sort(bubble_sorted)
print("\nSorted percentages using Bubble
Sort:") print(bubble_sorted)
display_top_five_scores(bubble_sorted)

OUTPUT
Name: Prajwal Charthad
Roll no: 133

6 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.
CODE
def quick_sort(arr):
if len(arr) <= 1:

return arr
pivot = arr[len(arr) // 2]

left = [x for x in arr if x < pivot]


middle = [x for x in arr if x ==
pivot] right = [x for x in arr if x >
pivot]

return quick_sort(left) + middle + quick_sort(right)

def display_top_five_scores(arr):
print("Top five scores:", arr[-5:])

# Input: First year percentages of students

percentages = [76.5, 88.2, 45.0, 92.1, 67.4, 80.5, 55.3, 70.8, 91.0, 65.7]

# Sorting using Ǫuick Sort

sorted_percentages =
quick_sort(percentages) print("Sorted
percentages using Ǫuick Sort:")
print(sorted_percentages)

# Displaying top five scores


display_top_five_scores(sorted_percentages)
OUTPUT
Name: Prajwal Charthad
Roll no: 133

7Department 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 Two linked lists exists for two divisions. Concatenate two
lists. CODE
#include
<iostream>
#include <string>

using namespace std;

struct Node
{ string
name;
string prn;
Node*
next;
};

// Class to represent the Pinnacle Club


class PinnacleClub {

private:

Node* president;
Node* secretary;

public:

PinnacleClub() {

president = new Node{"President", "PRN-PRES", nullptr}; // First node for


President secretary = nullptr; // Secretary initially set to nullptr
}

// Function to add a member


void addMember(string name, string prn) {
Node* newNode = new Node{name, prn,
nullptr}; if (secretary == nullptr) {
president->next = newNode;
secretary = newNode; // Secretary becomes the first member

} else {
Node* temp = president;
while (temp->next !=
nullptr) {
temp = temp->next;

}
temp->next = newNode; // Add to the end of the list
}

// Function to delete a member


void deleteMember(string
prn) { Node* temp =
president; Node* prev =
nullptr;

while (temp != nullptr && temp->prn !=


prn) { prev = temp;
temp = temp->next;
}

if (temp == nullptr) {
cout << "Member with PRN " << prn << " not found." <<
endl; return;
}

if (prev == nullptr) { // Deleting the first member (after


president) president->next = temp->next;
} else {
prev->next = temp->next;

}
delete temp; // Free memory
cout << "Member with PRN " << prn << " deleted successfully." << endl;

// Function to compute total number of members


int totalMembers() {
int count = 0;

Node* temp = president->next; // Start counting after


president while (temp != nullptr) {
count++;
temp = temp->next;

}
return count;

// Function to display members


void displayMembers() {
Node* temp =
president;

cout << "Club Members:" << endl;


while (temp != nullptr) {
cout << "Name: " << temp->name << ", PRN: " << temp->prn <<

endl; temp = temp->next;


}

// Function to concatenate two lists


void concatenate(PinnacleClub&
other) { if (this->secretary ==
nullptr) {

this->president->next = other.president->next;

} else {

Node* temp = this-


>president; while (temp->next
!= nullptr) {
temp = temp->next;

}
temp->next = other.president->next; // Concatenate the second list

~PinnacleClub() {
Node* current =
president; Node*
nextNode;
while (current != nullptr)
{ nextNode = current-
>next; delete current;
current = nextNode;
}
}

};

int main() {
PinnacleClub
divisionA;
PinnacleClub
divisionB;

divisionA.addMember("Divesh", "PRN-001");
divisionA.addMember("John", "PRN-002");
divisionA.addMember("Nobita", "PRN-003");

divisionB.addMember("Been", "PRN-004");
divisionB.addMember("Shinchan", "PRN-005");

cout << "Division A:" <<


endl;
divisionA.displayMembe
rs();
cout << "Total Members in Division A: " << divisionA.totalMembers() << endl;

cout << "\nDivision B:" << endl;


divisionB.displayMembers();
cout << "Total Members in Division B: " << divisionB.totalMembers() << endl;

cout << "\nConcatenating Division A and Division B:" <<


endl; divisionA.concatenate(divisionB);
divisionA.displayMembers();
cout << "Total Members after Concatenation: " << divisionA.totalMembers() << endl;

// Example of deleting a
member
divisionA.deleteMember("PRN-
002");
divisionA.displayMembers();
cout << "Total Members after Deletion: " << divisionA.totalMembers() << endl;

return 0;
}
OUTPUT
Name: Prajwal Charthad
Roll no: 133

8Write C++ program for storing binary number using doubly linked lists. Write
functions- a) To compute 1 's and 2's complement b Add two bin numbers
CODE
#include

<iostream>

#include <string>

using namespace std;

struct Node {

char bit; // Store a binary bit ('0' or


'1') Node* next; // Pointer to the
next node Node* prev; // Pointer
to the previous node

Node(char b) : bit(b), next(nullptr), prev(nullptr) {}

};

class BinaryNumber {

private:

Node* head; // Pointer to the first


node Node* tail; // Pointer to the
last node

public:

BinaryNumber() : head(nullptr), tail(nullptr) {}

// Function to insert bits at the end of the doubly linked list


void insertBit(char bit) {

Node* newNode = new Node(bit);


if (!head) {
head = tail = newNode; // If the list is empty

} else {
tail->next = newNode; // Insert at the

end newNode->prev = tail;


tail = newNode;

}
}

// Function to display the binary number


void display() {

Node* temp = head;


while (temp) {
cout << temp->bit;
temp = temp-
>next;
}

cout << endl;


}

// Function to compute 1's complement


void
onesComplement() {
Node* temp = head;
while (temp) {

temp->bit = (temp->bit == '0') ? '1' : '0'; // Flip


bits temp = temp->next;
}
}

// Function to compute 2's complement


void twosComplement() {

onesComplement(); // Compute 1's complement


addBinary("1"); // Add 1 to the 1's complement
}

// Function to add a binary number


void addBinary(const string& binary) {

Node* temp = tail; // Start from the last node


int carry = 0;
int i = binary.length() - 1;

while (temp || i >= 0 || carry) {


int sum = carry;

// Add current binary number bit if


available if (temp) {
sum += (temp->bit - '0'); // Convert char to int
temp = temp->prev; // Move to the previous node

// Add the new binary number bit if


available if (i >= 0) {
sum += (binary[i] - '0'); // Convert char

to int i--;
}

carry = sum / 2; // Calculate carry


char sumBit = (sum % 2) + '0'; // Determine
sum bit insertBit(sumBit); // Insert the sum bit
at the front
}

// Destructor to free memory


~BinaryNumber() {
Node* current =
head; while
(current) {
Node* nextNode = current-
>next; delete current;
current = nextNode;

}
}
};

int main() {

BinaryNumber binaryNumber;

// Input binary
number string
inputBinary;
cout << "Enter a binary
number: "; cin >> inputBinary;

for (char bit :


inputBinary) {
binaryNumber.insertBit(
bit);
}

cout << "Original Binary Number: ";


binaryNumber.display();

// Compute and display 1's


complement
binaryNumber.onesComplement()
; cout << "1's Complement: ";
binaryNumber.display();
// Compute and display 2's complement
binaryNumber.twosCompleme
nt(); cout << "2's
Complement: ";
binaryNumber.display();

// Adding another binary


number string binaryToAdd;
cout << "Enter another binary number to
add: "; cin >> binaryToAdd;

binaryNumber.addBinary(binaryTo
Add); cout << "Result after
addition: ";
binaryNumber.display();

return 0;

OUTPUT
Name: Prajwal Charthad
Roll no: 133

9 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" a palindrome, as can be seen by examining the
characters "poor dan is in a droop" an 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 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 CODE
#include
<iostream>
#include <stack>
#include
<cctype> #include
<string>

using namespace std;

// Function to remove punctuation, spaces, and convert to


lowercase string preprocessString(const string& str) {

string
processed; for
(char ch : str) { if
(isalnum(ch)) {
processed += tolower(ch); // Keep only alphanumeric characters

}
}

return processed;
}

// Function to print original string followed by reversed string using stack


void printReversedString(const string& str) {
stack<char> charStack;

// Push all characters of the original string to


the stack for (char ch : str) {
if (isalnum(ch)) {

charStack.push(tolower(ch)); // Push only alphanumeric and in lowercase

}
}

cout << "Original String: " << str <<


endl; cout << "Reversed String: ";

// Pop characters from the stack to display the


reversed string while (!charStack.empty()) {
cout << charStack.top();
charStack.pop();
}
cout << endl;

// Function to check whether the given string is a palindrome


bool isPalindrome(const string& str) {
string processed =
preprocessString(str); stack<char>
charStack;

// Push all characters of the processed string to


the stack for (char ch : processed) {
charStack.push(ch);

// Check if the string is a palindrome


for (char ch :
processed) { if
(charStack.top() != ch)
{

return false; // Not a palindrome if characters do not match


}

charStack.pop(); // Remove the top element after comparison


}

return true; // It's a palindrome


}

int main() {
string
input;
// Get user input

cout << "Enter a string: ";


getline(cin, input);

// Print original and reversed string


printReversedString(input);

// Check if the string is a


palindrome if
(isPalindrome(input)) {
cout << "The given string is a palindrome." << endl;

} else {
cout << "The given string is not a palindrome." << endl;
}
return 0;

}
OUTPUT
Name: Prajwal Charthad
Roll no: 133

10 Implement program for expression conversion as infix to postfix and its


evaluation using stack based on given conditions:
l. Operands and operator, both must be single character.
2. Input Postfix expression must be in a desired format.

3. Only '+','-','*' and '/' operators are


expected. CODE
#include
<iostream>
#include <stack>
#include <string>
#include
<cctype>
#include
<sstream>
#include <unordered_map>

using namespace std;

// Function to determine the precedence of operators


int precedence(char op) {
if (op == '+' || op == '-') return
1; if (op == '*' || op == '/')
return 2; return 0;

// Function to check if the character is an operator


bool isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/');

}
// Function to convert infix expression to postfix
expression string infixToPostfix(const string& infix) {
stack<char>
opStack; string
postfix;

for (char ch : infix)

{ if

(isalnum(ch)) {

postfix += ch; // Append operands to postfix


} else if (isOperator(ch)) {

while (!opStack.empty() && precedence(opStack.top()) >=


precedence(ch)) { postfix += opStack.top();
opStack.pop();
}
opStack.push(ch); // Push current operator to stack

}
}

while (!
opStack.empty()) {
postfix +=
opStack.top();
opStack.pop();
}

return postfix;
}

// Function to evaluate postfix expression


int evaluatePostfix(const string& postfix, const unordered_map<char, int>& values) {
stack<int> valueStack;

for (char ch : postfix)


{ if (isalnum(ch)) {
valueStack.push(values.at(ch)); // Get the value of the operand

} else if (isOperator(ch)) {
int right = valueStack.top();
valueStack.pop(); int left =
valueStack.top(); valueStack.pop();
switch (ch) {

case '+': valueStack.push(left + right);


break; case '-': valueStack.push(left -
right); break; case '*':
valueStack.push(left * right); break;
case '/': valueStack.push(left / right);
break;
}
}

return valueStack.top(); // The final result


}

int main() {

string infixExpression;

// Input infix expression


cout << "Enter an infix expression (e.g.,
a+b*c): "; getline(cin, infixExpression);

// Define the values for the


operands unordered_map<char,
int> values; char operand;
int value;

// Input values for each operand


cout << "Enter values for the operands (e.g., a=1 b=2 c=3): "
<< endl; while (true) {
cout << "Operand (enter 'x' to
finish): "; cin >> operand;
if (operand == 'x') break; // Exit if 'x' is
entered cout << "Value for " << operand
<< ": ";
cin >> value;
values[operand] = value; // Store the operand value

// Convert infix to postfix

string postfixExpression =
infixToPostfix(infixExpression); cout << "Postfix
expression: " << postfixExpression << endl;

// Evaluate postfix expression


int result = evaluatePostfix(postfixExpression,
values); cout << "Evaluation result: " << result <<
endl;

return 0;
}

OUTPUT
Name: Prajwal Charthad
Roll no: 133

11Ǫueues 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.

CODE

#include
<iostream> using
namespace std;

// Node structure for linked list


struct Node
{ int data;
Node*
next;

};

// Class for the


Ǫueue class
Ǫueue { private:

Node*
front;
Node* rear;

public:

Ǫueue() : front(nullptr), rear(nullptr) {}

// Function to add an element to the queue


void enqueue(int value) {

Node* newNode = new


Node(); newNode->data =
value; newNode->next =
nullptr;
if (rear == nullptr) { // Ǫueue is
empty front = rear = newNode;
} else {

rear->next =
newNode; rear =
newNode;
}
cout << "Enqueued: " << value << endl;

// Function to remove an element from the queue


void dequeue() {

if (front == nullptr) {
cout << "Ǫueue is empty. Cannot dequeue." <<
endl; return;
}

Node* temp = front;


front = front->next;

if (front == nullptr) { // Ǫueue is now


empty rear = nullptr;
}
cout << "Dequeued: " << temp->data <<
endl; delete temp; // Free memory
}

// Function to display the queue


void display() {

if (front == nullptr) {
cout << "Ǫueue is empty." <<

endl; return;
}

Node* temp = front;


cout << "Ǫueue: ";
while (temp !=
nullptr) {

cout << temp->data <<


" "; temp = temp->next;
}
cout << endl;
}

};

// Main function to test the queue


int main() {
Ǫueue q;

int choice,
value; do {
cout << "1. Enqueue\n2. Dequeue\n3. Display Ǫueue\n4.
Exit\n"; cout << "Enter your choice: ";
cin >> choice;

switch
(choice) {
case 1:
cout << "Enter value to
enqueue: "; cin >> value;
q.enqueue(valu
e); break;
case 2:
q.dequeue();
break;
case 3:
q.display(
); break;
case 4:
cout << "Exiting program." << endl;
break;
default:

cout << "Invalid choice! Please enter again." << endl;


}

} while (choice != 4);

return 0;

}
OUTPUT
Name: Prajwal Charthad
Roll no: 133

12 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.

CODE

#include
<iostream> using
namespace std;

class Deque {

private:
int* arr;
int front;
int rear;
int capacity;

public:

Deque(int size) {
capacity = size;

arr = new
int[capacity]; front = -
1;
rear = -1;

~Deque() {
delete[] arr;
}

bool isFull() {
return (front == 0 && rear == capacity - 1) || (front == rear + 1);
}

bool isEmpty() {
return front == -
1;
}

void addFront(int value)


{ if (isFull()) {
cout << "Deque is full. Cannot add " << value << " to front." <<
endl; return;
}

if (front == -1) { // First element being


added front = 0;
rear = 0;

} else if (front == 0) { // Wrap


around front = capacity - 1;
} else {
front--
;
}
arr[front] = value;
cout << "Added " << value << " to front." << endl;

void addRear(int
value) { if (isFull()) {
cout << "Deque is full. Cannot add " << value << " to rear." <<
endl; return;

}
if (front == -1) { // First element being
added front = 0;
rear = 0;
} else if (rear == capacity - 1) { // Wrap
around rear = 0;
} else {
rear++;
}
arr[rear] = value;

cout << "Added " << value << " to rear." << endl;

void
deleteFront() {
if (isEmpty()) {

cout << "Deque is empty. Cannot delete from front."


<< endl; return;
}

cout << "Deleted " << arr[front] << " from front."
<< endl; if (front == rear) { // Only one element
front = -1;

rear = -1;
} else if (front == capacity - 1) { // Wrap
around front = 0;
} else {
front++;
}

void deleteRear()

{ if (isEmpty())

{
cout << "Deque is empty. Cannot delete from rear." <<
endl; return;
}

cout << "Deleted " << arr[rear] << " from rear."
<< endl; if (front == rear) { // Only one element
front = -1;
rear = -1;
} else if (rear == 0) { // Wrap
around rear = capacity - 1;
} else {
rear--
;
}

void display()
{ if
(isEmpty()) {
cout << "Deque is empty." <<

endl; return;
}

cout << "Deque


elements: "; if (rear >=
front) {
for (int i = front; i <= rear; i++)
{ cout << arr[i] << " ";
}

} else {
for (int i = front; i < capacity; i++)
{ cout << arr[i] << " ";
}
for (int i = 0; i <= rear; i++) {
cout << arr[i] << " ";
}

}
cout << endl;

}
};

// Main function to test the deque


int main() {

Deque dq(5); // Create a deque of size 5

int choice,
value; do {
cout << "1. Add to Front\n2. Add to Rear\n3. Delete from Front\n4. Delete from Rear\
n5.
Display Deque\n6. Exit\n";

cout << "Enter your choice:


"; cin >> choice;

switch
(choice) {
case 1:
cout << "Enter value to add to
front: "; cin >> value;
dq.addFront(valu
e); break;
case 2:

cout << "Enter value to add to


rear: "; cin >> value;

dq.addRear(value);
break;
case 3:
dq.deleteFront
();
break;
case 4:
dq.deleteRear();
break;
case 5:
dq.display(
); break;
case 6:

cout << "Exiting program." << endl;

break;
default:

cout << "Invalid choice! Please enter again." << endl;


}

} while (choice != 6);

return 0;

}
OUTPUT
Name: Prajwal
Charthad Roll no:
133

13 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 systemusing circular queue using array
CODE

#include
<iostream>
#include <string>
using namespace
std;

class
CircularǪueue {
private:
string* orders;
int front;
int rear;

int capacity;

public:
CircularǪueue(int
size) { capacity =
size;
orders = new
string[capacity]; front = -1;
rear = -1;
}

~CircularǪueue(
) { delete[]
orders;
}
bool isFull() {
return (front == 0 && rear == capacity - 1) || (front == rear + 1);
}

bool isEmpty()
{ return front
== -1;
}

void placeOrder(string
order) { if (isFull()) {
cout << "Order queue is full. Cannot place order: " << order <<
endl; return;
}

if (front == -1) { // First order being


placed front = 0;
rear = 0;

} else if (rear == capacity - 1) { // Wrap


around rear = 0;
} else {
rear++;
}

orders[rear] = order;
cout << "Order placed: " << order << endl;

void serveOrder()
{ if (isEmpty()) {
cout << "No orders to serve." <<
endl; return;
}
cout << "Serving order: " << orders[front] <<
endl; if (front == rear) { // Only one order
front = -1;
rear = -1;

} else if (front == capacity - 1) { // Wrap


around front = 0;
} else {
front++;
}

void displayOrders()
{ if (isEmpty()) {
cout << "No orders in the queue." <<
endl; return;
}

cout << "Current orders in the


queue: "; if (rear >= front) {
for (int i = front; i <= rear; i+
+) { cout << orders[i] <<
" ";
}
} else {

for (int i = front; i < capacity; i++)


{ cout << orders[i] << " ";
}

for (int i = 0; i <= rear; i+


+) { cout << orders[i]
<< " ";
}
}

cout << endl;


}
};

// Main function to test the pizza parlor


simulation int main() {
int maxOrders;

cout << "Enter maximum number of orders that can be


accepted: "; cin >> maxOrders;

CircularǪueue
cq(maxOrders); int choice;
string order;

do {

cout << "1. Place Order\n2. Serve Order\n3. Display Orders\n4.


Exit\n"; cout << "Enter your choice: ";
cin >> choice;

switch
(choice) {
case 1:
cout << "Enter order:
"; cin >> order;
cq.placeOrder(ord
er); break;
case 2:
cq.serveOrder
(); break;
case 3:
cq.displayOrders
(); break;
case 4:
cout << "Exiting program." << endl;
break;
default:
cout << "Invalid choice! Please enter again." << endl;

}
} while (choice != 4);

return 0;
}
OUTPUT

You might also like