0% found this document useful (0 votes)
4 views

DSL Practical

The document contains multiple Python programs that perform various operations, including calculating student marks, string manipulations, matrix computations, searching algorithms, and sorting techniques. It also includes a C++ program for managing a student club using a singly linked list, allowing for member addition, deletion, and concatenation of two lists. Each program is structured with functions to handle specific tasks, demonstrating fundamental programming concepts.

Uploaded by

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

DSL Practical

The document contains multiple Python programs that perform various operations, including calculating student marks, string manipulations, matrix computations, searching algorithms, and sorting techniques. It also includes a C++ program for managing a student club using a singly linked list, allowing for member addition, deletion, and concatenation of two lists. Each program is structured with functions to handle specific tasks, demonstrating fundamental programming concepts.

Uploaded by

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

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

def get_marks():
n = int(input("Enter the number of students in the class: "))
marks = []
print("Enter marks scored by each student (use -1 for absent
students):")
for _ in range(n):
mark = int(input(f"Enter marks for student {_ + 1}: "))
marks.append(mark)
return marks

def average_score(marks):
valid_marks = [mark for mark in marks if mark != -1]
if valid_marks:
return sum(valid_marks) / len(valid_marks)
else:
return 0
def highest_and_lowest_score(marks):
valid_marks = [mark for mark in marks if mark != -1]
if valid_marks:
return max(valid_marks), min(valid_marks)
else:
return None, None

def count_absent_students(marks):
return marks.count(-1)

def highest_frequency_mark(marks):
from collections import Counter
valid_marks = [mark for mark in marks if mark != -1]
if valid_marks:
frequency = Counter(valid_marks)
most_common = frequency.most_common(1)
return most_common[0][0]
else:
return None

def main():
marks = get_marks()

avg = average_score(marks)
print(f"\nThe average score of the class is: {avg:.2f}")

highest, lowest = highest_and_lowest_score(marks)


if highest is not None:
print(f"The highest score is: {highest}")
print(f"The lowest score is: {lowest}")
else:
print("No valid marks to determine highest and lowest scores.")

absent_count = count_absent_students(marks)
print(f"The number of students who were absent: {absent_count}")

freq_mark = highest_frequency_mark(marks)
if freq_mark is not None:
print(f"The mark with the highest frequency is: {freq_mark}")
else:
print("No valid marks to determine the highest frequency mark.")

if __name__ == "__main__":
main()

Write a Python program to compute following operations


on
String:
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

def string_operations():
user_string = input("Enter a string: ")

words = user_string.split()
longest_word = max(words, key=len)
print(f"Word with the longest length: {longest_word}")

char = input("Enter a character to find its frequency: ")


char_frequency = user_string.count(char)
print(f"Frequency of '{char}' in the string: {char_frequency}")

is_palindrome = user_string == user_string[::-1]


print(f"Is the string a palindrome? {'Yes' if is_palindrome else 'No'}")

substring = input("Enter a substring to find its first occurrence: ")


first_index = user_string.find(substring)
if first_index != -1:
print(f"Index of the first appearance of the substring: {first_index}")
else:
print("Substring not found in the string.")

word_count = {}
for word in words:
word_count[word] = word_count.get(word, 0) + 1
print("Occurrences of each word:")
for word, count in word_count.items():
print(f"{word}: {count}")

if __name__ == "__main__":
string_operations()

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

def input_matrix(rows, cols):


print(f"Enter the elements of a {rows}x{cols} matrix:")
return [[int(input(f"Element [{i+1},{j+1}]: ")) for j in range(cols)] for i in
range(rows)]

def print_matrix(matrix):
for row in matrix:
print(row)

def add_matrices(matrix1, matrix2):


return [[matrix1[i][j] + matrix2[i][j] for j in range(len(matrix1[0]))] for i
in range(len(matrix1))]

def subtract_matrices(matrix1, matrix2):


return [[matrix1[i][j] - matrix2[i][j] for j in range(len(matrix1[0]))] for i in
range(len(matrix1))]

def multiply_matrices(matrix1, matrix2):


rows_matrix1, cols_matrix1 = len(matrix1), len(matrix1[0])
rows_matrix2, cols_matrix2 = len(matrix2), len(matrix2[0])

if cols_matrix1 != rows_matrix2:
print("Matrix multiplication not possible due to incompatible
dimensions.")
return None

result = [[0 for _ in range(cols_matrix2)] for _ in range(rows_matrix1)]


for i in range(rows_matrix1):
for j in range(cols_matrix2):
for k in range(cols_matrix1):
result[i][j] += matrix1[i][k] * matrix2[k][j]
return result
def transpose_matrix(matrix):
return [[matrix[j][i] for j in range(len(matrix))] for i in
range(len(matrix[0]))]

if __name__ == "__main__":
rows, cols = map(int, input("Enter the number of rows and columns for
the matrices: ").split())

print("Matrix 1:")
matrix1 = input_matrix(rows, cols)
print("Matrix 2:")
matrix2 = input_matrix(rows, cols)

print("\nMatrix 1:")
print_matrix(matrix1)
print("\nMatrix 2:")
print_matrix(matrix2)

print("\nAddition of matrices:")
addition_result = add_matrices(matrix1, matrix2)
print_matrix(addition_result)

print("\nSubtraction of matrices:")
subtraction_result = subtract_matrices(matrix1, matrix2)
print_matrix(subtraction_result)
print("\nMultiplication of matrices:")
multiplication_result = multiply_matrices(matrix1, matrix2)
if multiplication_result:
print_matrix(multiplication_result)

print("\nTranspose of Matrix 1:")


transpose_result = transpose_matrix(matrix1)
print_matrix(transpose_result)

print("\nTranspose of Matrix 2:")


transpose_result = transpose_matrix(matrix2)
print_matrix(transpose_result)

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

def linear_search(arr, target):


for i in range(len(arr)):
if arr[i] == target:
return True
return False

def sentinel_search(arr, target):


n = len(arr)
last = arr[-1]
arr[-1] = target
i=0

while arr[i] != target:


i += 1

arr[-1] = last

if i < n - 1 or arr[-1] == target:


return True
return False

def main():
roll_numbers = [105, 123, 132, 107, 120, 115]

print("Roll numbers of students who attended training:", roll_numbers)

target_roll = int(input("Enter the roll number to check if the student


attended the training program: "))
found_linear = linear_search(roll_numbers, target_roll)
found_sentinel = sentinel_search(roll_numbers[:], target_roll)
print("Using Linear Search:", "Found" if found_linear else "Not Found")
print("Using Sentinel Search:", "Found" if found_sentinel else "Not
Found")

if __name__ == "__main__":
main()

Write a python program to store roll numbers of student


array
who attended training program in sorted order. Write
function
for searching whether particular student attended training
program or not, using Binary search and Fibonacci search

def binary_search(arr, x):


low, high = 0, len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == x:
return mid
elif arr[mid] < x:
low = mid + 1
else:
high = mid - 1
return -1

def fibonacci_search(arr, x):


n = len(arr)
fib2 = 0
fib1 = 1
fib = fib2 + fib1

while fib < n:


fib2 = fib1
fib1 = fib
fib = fib2 + fib1

offset = -1

while fib > 1:


i = min(offset + fib2, n - 1)

if arr[i] < x:
fib = fib1
fib1 = fib2
fib2 = fib - fib1
offset = i
elif arr[i] > x:
fib = fib2
fib1 = fib1 - fib2
fib2 = fib - fib1
else:
return i

if fib1 and offset + 1 < n and arr[offset + 1] == x:


return offset + 1

return -1

roll_numbers = [101, 104, 108, 112, 115, 118, 123, 127]

search_roll = int(input("Enter roll number to check: "))

binary_result = binary_search(roll_numbers, search_roll)


if binary_result != -1:
print(f"Roll number {search_roll} found at index {binary_result} using
Binary Search.")
else:
print(f"Roll number {search_roll} not found using Binary Search.")

fibonacci_result = fibonacci_search(roll_numbers, search_roll)


if fibonacci_result != -1:
print(f"Roll number {search_roll} found at index {fibonacci_result} using
Fibonacci Search.")
else:
print(f"Roll number {search_roll} not found using Fibonacci Search.")

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.

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_scores(arr):
top_scores = arr[-5:][::-1]
print("Top 5 scores:", top_scores)

if __name__ == "__main__":
scores = [78.5, 82.3, 69.8, 90.4, 88.7, 75.2, 95.5, 60.4, 84.6]

selection_sorted_scores = scores.copy()
selection_sort(selection_sorted_scores)
print("Scores sorted using Selection Sort:", selection_sorted_scores)
display_top_scores(selection_sorted_scores)

bubble_sorted_scores = scores.copy()
bubble_sort(bubble_sorted_scores)
print("\nScores sorted using Bubble Sort:", bubble_sorted_scores)
display_top_scores(bubble_sorted_scores)

Write a Python program to store second year percentage of


students in array. Write function for sorting array of floating
point numbers in ascending order using
a) Insertion sort
b) Shell Sort and display top five scores

def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j=i-1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key

def shell_sort(arr):
n = len(arr)
gap = n // 2

while gap > 0:


for i in range(gap, n):
temp = arr[i]
j=i
while j >= gap and arr[j - gap] > temp:
arr[j] = arr[j - gap]
j -= gap
arr[j] = temp
gap //= 2
def display_top_scores(arr):
print("Top 5 scores:", arr[-1:-6:-1])

if __name__ == "__main__":
percentages = [78.5, 88.2, 90.0, 67.5, 85.3, 92.1, 74.6, 89.9, 81.4]

print("Original Percentages:", percentages)

sorted_insertion = percentages[:]
insertion_sort(sorted_insertion)
print("Sorted using Insertion Sort:", sorted_insertion)
display_top_scores(sorted_insertion)

sorted_shell = percentages[:]
shell_sort(sorted_shell)
print("Sorted using Shell Sort:", sorted_shell)
display_top_scores(sorted_shell)

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 Display
members
Two linked lists exists for two divisions. Concatenate two
lists.

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

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

class PinnacleClub {
private:
Node* head;
Node* tail;
public:
PinnacleClub() : head(nullptr), tail(nullptr) {}

void addMember(int prn, string name, string position) {


Node* newNode = new Node{ name, prn, nullptr };

if (position == "president") {
newNode->next = head;
head = newNode;
if (tail == nullptr) {
tail = head;
}
} else if (position == "secretary") {
if (tail == nullptr) {
head = tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
} else {
if (head == nullptr) {
head = tail = newNode;
} else {
newNode->next = head->next;
head->next = newNode;
}
}
}

void deleteMember(int prn) {


if (head == nullptr) {
cout << "The list is empty.\n";
return;
}

Node* temp = head;


Node* prev = nullptr;

if (head->prn == prn) {
head = head->next;
if (head == nullptr) {
tail = nullptr;
}
delete temp;
return;
}

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


prev = temp;
temp = temp->next;
}

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

prev->next = temp->next;
if (temp == tail) {
tail = prev;
}

delete temp;
}

int totalMembers() {
int count = 0;
Node* temp = head;
while (temp != nullptr) {
count++;
temp = temp->next;
}
return count;
}
void displayMembers() {
if (head == nullptr) {
cout << "The list is empty.\n";
return;
}

Node* temp = head;


while (temp != nullptr) {
cout << "PRN: " << temp->prn << ", Name: " << temp->name <<
"\n";
temp = temp->next;
}
}

void concatenate(PinnacleClub& other) {


if (head == nullptr) {
head = other.head;
tail = other.tail;
} else if (other.head != nullptr) {
tail->next = other.head;
tail = other.tail;
}

other.head = nullptr;
other.tail = nullptr;
}

~PinnacleClub() {
while (head != nullptr) {
Node* temp = head;
head = head->next;
delete temp;
}
}
};

int main() {
PinnacleClub divisionA, divisionB;

divisionA.addMember(1, "Akash", "president");


divisionA.addMember(2, "Vedant", "member");
divisionA.addMember(3, "Bhavesh", "secretary");

divisionB.addMember(4, "Akshada", "president");


divisionB.addMember(5, "Darshan", "member");
divisionB.addMember(6, "Ananya", "secretary");

cout << "Members of Division A:\n";


divisionA.displayMembers();
cout << "\nMembers of Division B:\n";
divisionB.displayMembers();

divisionA.concatenate(divisionB);

cout << "\nMembers after concatenation:\n";


divisionA.displayMembers();

cout << "\nTotal members in concatenated list: " <<


divisionA.totalMembers() << "\n";

return 0;
}

Second year Computer Engineering class, set A of students


like Vanilla Ice-cream and set B
of students like butterscotch ice-cream. Write C++ program
to store two sets using linked
list. compute and display
a) Set of students who like both vanilla and butterscotch
b) Set of students who like either vanilla or butterscotch or
not both
c) Number of students who like neither vanilla nor
butterscotch
#include <iostream>
#include <unordered_set>

using namespace std;

struct Node {
int studentId;
Node* next;
};

void insert(Node*& head, int studentId) {


Node* newNode = new Node();
newNode->studentId = studentId;
newNode->next = head;
head = newNode;
}

void printList(Node* head) {


Node* temp = head;
while (temp != nullptr) {
cout << temp->studentId << " ";
temp = temp->next;
}
cout << endl;
}

bool isInList(Node* head, int studentId) {


Node* temp = head;
while (temp != nullptr) {
if (temp->studentId == studentId)
return true;
temp = temp->next;
}
return false;
}

Node* intersection(Node* headA, Node* headB) {


Node* result = nullptr;
Node* tempA = headA;

while (tempA != nullptr) {


if (isInList(headB, tempA->studentId)) {
insert(result, tempA->studentId);
}
tempA = tempA->next;
}
return result;
}
Node* unionSets(Node* headA, Node* headB) {
Node* result = nullptr;
Node* tempA = headA;

while (tempA != nullptr) {


insert(result, tempA->studentId);
tempA = tempA->next;
}

Node* tempB = headB;


while (tempB != nullptr) {
if (!isInList(headA, tempB->studentId)) {
insert(result, tempB->studentId);
}
tempB = tempB->next;
}
return result;
}

Node* difference(Node* headA, Node* headB) {


Node* result = nullptr;
Node* tempA = headA;

while (tempA != nullptr) {


if (!isInList(headB, tempA->studentId)) {
insert(result, tempA->studentId);
}
tempA = tempA->next;
}

Node* tempB = headB;


while (tempB != nullptr) {
if (!isInList(headA, tempB->studentId)) {
insert(result, tempB->studentId);
}
tempB = tempB->next;
}

return result;
}

int countStudents(Node* head) {


int count = 0;
Node* temp = head;
while (temp != nullptr) {
count++;
temp = temp->next;
}
return count;
}
int main() {
Node* setA = nullptr;
Node* setB = nullptr;

insert(setA, 5);
insert(setA, 4);
insert(setA, 3);
insert(setA, 2);
insert(setA, 1);

insert(setB, 8);
insert(setB, 7);
insert(setB, 6);
insert(setB, 5);
insert(setB, 4);

cout << "Students who like Vanilla Ice-cream (Set A): ";
printList(setA);

cout << "Students who like Butterscotch Ice-cream (Set B): ";
printList(setB);

cout << "Students who like both Vanilla and Butterscotch: ";
Node* both = intersection(setA, setB);
printList(both);

cout << "Students who like either Vanilla or Butterscotch, but not both:
";
Node* eitherButNotBoth = difference(setA, setB);
printList(eitherButNotBoth);

int totalStudents = 10;


int studentsWhoLikeEither = countStudents(unionSets(setA, setB));
int studentsWhoLikeNeither = totalStudents - studentsWhoLikeEither;

cout << "Number of students who like neither Vanilla nor Butterscotch:
";
cout << studentsWhoLikeNeither << endl;

return 0;
}

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-


a) To print original string followed by reversed string using

stack
b) To check whether given string is palindrome or not

#include <iostream>
#include <stack>
#include <cctype>
#include <string>

void printOriginalAndReversed(const std::string& str) {


std::stack<char> charStack;

for (char ch : str) {


if (std::isalnum(ch)) {
charStack.push(std::tolower(ch));
}
}

std::cout << "Original string: " << str << std::endl;

std::cout << "Reversed string: ";


while (!charStack.empty()) {
std::cout << charStack.top();
charStack.pop();
}
std::cout << std::endl;
}

bool isPalindrome(const std::string& str) {


std::string filteredStr;

for (char ch : str) {


if (std::isalnum(ch)) {
filteredStr += std::tolower(ch);
}
}

int start = 0;
int end = filteredStr.length() - 1;

while (start < end) {


if (filteredStr[start] != filteredStr[end]) {
return false;
}
start++;
end--;
}

return true;
}

int main() {
std::string inputString;

std::cout << "Enter a string: ";


std::getline(std::cin, inputString);

printOriginalAndReversed(inputString);

if (isPalindrome(inputString)) {
std::cout << "The given string is a palindrome." << std::endl;
} else {
std::cout << "The given string is not a palindrome." << std::endl;
}

return 0;
}

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.

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

bool isWellParenthesized(const string& expr) {


stack<char> s;

for (char ch : expr) {

if (ch == '(' || ch == '{' || ch == '[') {


s.push(ch);
}

else if (ch == ')' || ch == '}' || ch == ']') {

if (s.empty()) return false;


char top = s.top();
if ((ch == ')' && top == '(') ||
(ch == '}' && top == '{') ||
(ch == ']' && top == '[')) {
s.pop();
} else {
return false;
}
}
}

return s.empty();
}

int main() {
string expression;

cout << "Enter an expression: ";


getline(cin, expression);

if (isWellParenthesized(expression)) {
cout << "The expression is well-parenthesized." << endl;
} else {
cout << "The expression is not well-parenthesized." << endl;
}
return 0;
}

Write program to implement a priority queue in C++ using


an inorder list to store the items in the queue. Create a class
that includes the data items (which should be template) and
the priority (which should be int). The inorder list should
contain these objects, with operator <= overloaded so that
the items with highest priority appear at the beginning of
the list (which will make it relatively easy to retrieve the
highest item.)

#include <iostream>
#include <list>

template <typename T>


class PriorityQueue {
private:
struct QueueItem {
T data;
int priority;

QueueItem(T d, int p) : data(d), priority(p) {}


bool operator<=(const QueueItem& other) const {
return priority <= other.priority;
}
};

std::list<QueueItem> queue;

public:

void insert(T data, int priority) {


QueueItem newItem(data, priority);

auto it = queue.begin();
while (it != queue.end() && *it <= newItem) {
++it;
}
queue.insert(it, newItem);
}

T pop() {
if (queue.empty()) {
std::cerr << "Queue is empty!" << std::endl;
exit(1);
}
T data = queue.front().data;
queue.pop_front();
return data;
}

bool isEmpty() const {


return queue.empty();
}

void print() const {


for (const auto& item : queue) {
std::cout << "(" << item.data << ", Priority: " << item.priority << ") ";
}
std::cout << std::endl;
}
};

int main() {
PriorityQueue<std::string> pq;

pq.insert("Task A", 3);


pq.insert("Task B", 1);
pq.insert("Task C", 2);
std::cout << "Priority Queue: ";
pq.print();

std::cout << "Popped item: " << pq.pop() << std::endl;


std::cout << "Priority Queue after pop: ";
pq.print();

pq.insert("Task D", 4);


std::cout << "Priority Queue after adding Task D: ";
pq.print();

return 0;
}

Pizza parlour 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.

#include <iostream>
using namespace std;

class PizzaParlor {
private:
int front, rear, size;
string* queue;

public:
PizzaParlor(int m) {
size = m;
queue = new string[size];
front = rear = -1;
}

~PizzaParlor() {
delete[] queue;
}

bool isFull() {
return (rear + 1) % size == front;
}

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

void addOrder(string order) {


if (isFull()) {
cout << "Sorry, the pizza parlor is at full capacity. Cannot take more
orders." << endl;
} else {
if (front == -1) {
front = 0;
}
rear = (rear + 1) % size;
queue[rear] = order;
cout << "Order placed: " << order << endl;
}
}

void serveOrder() {
if (isEmpty()) {
cout << "No orders to serve." << endl;
} else {
cout << "Serving order: " << queue[front] << endl;
if (front == rear) {
front = rear = -1;
} else {
front = (front + 1) % size;
}
}
}
void displayOrders() {
if (isEmpty()) {
cout << "No orders in the queue." << endl;
} else {
cout << "Current orders in the queue: ";
int i = front;
while (i != rear) {
cout << queue[i] << " ";
i = (i + 1) % size;
}
cout << queue[rear] << endl;
}
}
};

int main() {
int M;
cout << "Enter the maximum number of orders the pizza parlor can
accept: ";
cin >> M;

PizzaParlor parlor(M);

int choice;
string order;
do {
cout << "\nMenu: \n";
cout << "1. Place an order\n";
cout << "2. Serve an order\n";
cout << "3. Display orders\n";
cout << "4. Exit\n";
cout << "Enter your choice: ";
cin >> choice;

switch (choice) {
case 1:
cout << "Enter your order: ";
cin.ignore();
getline(cin, order);
parlor.addOrder(order);
break;
case 2:
parlor.serveOrder();
break;
case 3:
parlor.displayOrders();
break;
case 4:
cout << "Exiting...\n";
break;
default:
cout << "Invalid choice, please try again.\n";
}
} while (choice != 4);

return 0;
}

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.

#include <iostream>
using namespace std;

class Deque {
private:
int *arr;
int front, rear, size;
int capacity;

public:
Deque(int cap) {
capacity = cap;
arr = new int[capacity];
front = -1;
rear = -1;
size = 0;
}

bool isEmpty() {
return size == 0;
}

bool isFull() {
return size == capacity;
}

void insertFront(int value) {


if (isFull()) {
cout << "Deque is full. Cannot insert at the front.\n";
return;
}
if (front == -1) {
front = 0;
rear = 0;
} else if (front == 0) {
front = capacity - 1;
} else {
front--;
}
arr[front] = value;
size++;
}

void insertRear(int value) {


if (isFull()) {
cout << "Deque is full. Cannot insert at the rear.\n";
return;
}
if (rear == -1) {
front = 0;
rear = 0;
} else if (rear == capacity - 1) {
rear = 0;
} else {
rear++;
}
arr[rear] = value;
size++;
}
void deleteFront() {
if (isEmpty()) {
cout << "Deque is empty. Cannot delete from the front.\n";
return;
}
if (front == rear) {
front = -1;
rear = -1;
} else if (front == capacity - 1) {
front = 0;
} else {
front++;
}
size--;
}

void deleteRear() {
if (isEmpty()) {
cout << "Deque is empty. Cannot delete from the rear.\n";
return;
}
if (front == rear) {
front = -1;
rear = -1;
} else if (rear == 0) {
rear = capacity - 1;
} else {
rear--;
}
size--;
}

int getFront() {
if (isEmpty()) {
cout << "Deque is empty.\n";
return -1;
}
return arr[front];
}

int getRear() {
if (isEmpty()) {
cout << "Deque is empty.\n";
return -1;
}
return arr[rear];
}

void display() {
if (isEmpty()) {
cout << "Deque is empty.\n";
return;
}
int i = front;
while (true) {
cout << arr[i] << " ";
if (i == rear) break;
i = (i + 1) % capacity;
}
cout << endl;
}

~Deque() {
delete[] arr;
}
};

int main() {
Deque dq(5);

dq.insertRear(10);
dq.insertRear(20);
dq.insertFront(5);
dq.insertFront(1);
dq.insertRear(30);
cout << "Deque elements: ";
dq.display();

dq.deleteFront();
dq.deleteRear();

cout << "Deque elements after deletions: ";


dq.display();

cout << "Front element: " << dq.getFront() << endl;


cout << "Rear element: " << dq.getRear() << endl;

return 0;
}

You might also like