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

Final FDS Code

Uploaded by

akashrathod8468
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Final FDS Code

Uploaded by

akashrathod8468
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Computer Engineering Nutan Maharashtra Institute Of Engg. And Tech.

Practical 1
Question 1:
Write a Python program to store marks scored in subject “Fundamental of Data Structure” by N students
in the class. Write functions to compute the 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

Code:
def gather_scores(): return absentees
scores = []
absentees = 0 def find_most_frequent_score(scores):
n = int(input("Enter the number of students: if len(scores) == 0:
")) return None
frequency = {}
for i in range(n): for score in scores:
score = input(f"Enter the score for student if score in frequency:
{i + 1} (or 'A' for absent): ") frequency[score] += 1
if score.upper() == 'A': else:
absentees += 1 frequency[score] = 1
else: return max(frequency, key=frequency.get)
try:
score = float(score) def main():
scores.append(score) scores, absentees = gather_scores()
except ValueError: average_score = calculate_average(scores)
print("Invalid input. Please enter a highest_score, lowest_score =
numeric score or 'A' for absent.") find_high_low(scores)
return gather_scores() # Restart input absent_count = count_absentees(absentees)
if invalid most_frequent_score =
find_most_frequent_score(scores)
return scores, absentees
print(f"Average score of the class:
def calculate_average(scores): {average_score}")
if len(scores) == 0: print(f"Highest score: {highest_score}")
return 0 print(f"Lowest score: {lowest_score}")
return sum(scores) / len(scores) print(f"Number of students absent:
{absent_count}")
def find_high_low(scores): print(f"Score with the highest frequency:
if len(scores) == 0: {most_frequent_score}")
return None, None
return max(scores), min(scores) if __name__ == "__main__":
main()
def count_absentees(absentees):

Pinak Dhabu Fundamentals Of Data Structures


Computer Engineering Nutan Maharashtra Institute Of Engg. And Tech.

OUTPUT:

Pinak Dhabu Fundamentals Of Data Structures


Computer Engineering Nutan Maharashtra Institute Of Engg. And Tech.

Practical 2
Question 2:
Write a Python program that computes the net amount of a bank account based on a transaction log from
console input. The transaction log format is shown as follows: 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
Code:
def deposit(balance, amount): try:
return balance + amount action, amount = transaction.split()
amount = float(amount)
def withdrawal(balance, amount):
if amount > balance: if action.upper() == 'D':
print("Withdrawal amount exceeds current balance = deposit(balance, amount)
balance. Transaction denied.") elif action.upper() == 'W':
return balance balance = withdrawal(balance,
return balance - amount amount)
else:
def main(): print("Invalid transaction type. Use
balance = 0 'D' for deposit and 'W' for withdrawal.")
print("Enter transactions (D for deposit, W except ValueError:
for withdrawal) followed by the amount. Type print("Invalid input. Please enter in the
'exit' to finish.") format 'D/W amount'.")

while True: print(f"Net amount in the account:


transaction = input("Transaction: ") {balance}")
if transaction.lower() == 'exit':
break if __name__ == "__main__":
main()

Pinak Dhabu Fundamentals Of Data Structures


Computer Engineering Nutan Maharashtra Institute Of Engg. And Tech.

OUTPUT:

Pinak Dhabu Fundamentals Of Data Structures


Computer Engineering Nutan Maharashtra Institute Of Engg. And Tech.

Practical 3
Question 3:
Write a Python program to compute the following operations on a matrix:
a) Addition of two matrices
b) Subtraction of two matrices
c) Multiplication of two matrices
d) Transpose of a matrix
Code:
def matrix_addition(A, B): for i in range(len(A)):
if len(A) != len(B) or len(A[0]) != len(B[0]): for j in range(len(A[0])):
raise ValueError("Matrices must have the result[j][i] = A[i][j]
same dimensions for addition.") return result
result = [[0 for _ in range(len(A[0]))] for _ in if __name__ == "__main__":
range(len(A))] A = [[1, 2, 3],
for i in range(len(A)): [4, 5, 6]]
for j in range(len(A[0])): B = [[7, 8, 9],
result[i][j] = A[i][j] + B[i][j] [10, 11, 12]]
return result print("Matrix A:")
def matrix_subtraction(A, B): for row in A:
if len(A) != len(B) or len(A[0]) != len(B[0]): print(row)
raise ValueError("Matrices must have the print("\nMatrix B:")
same dimensions for subtraction.") for row in B:
result = [[0 for _ in range(len(A[0]))] for _ in print(row)
range(len(A))] print("\nA + B:")
for i in range(len(A)): result_add = matrix_addition(A, B)
for j in range(len(A[0])): for row in result_add:
result[i][j] = A[i][j] - B[i][j] print(row)
return result print("\nA - B:")
def matrix_multiplication(A, B): result_sub = matrix_subtraction(A, B)
if len(A[0]) != len(B): for row in result_sub:
raise ValueError("Number of columns in A print(row)
must be equal to number of rows in B.") print("\nA * B (for compatible matrices):")
result = [[0 for _ in range(len(B[0]))] for _ in C = [[1, 2],
range(len(A))] [3, 4],
for i in range(len(A)): [5, 6]]
for j in range(len(B[0])): result_mul = matrix_multiplication(A, C)
for k in range(len(B)): for row in result_mul:
result[i][j] += A[i][k] * B[k][j] print(row)
return result print("\nTranspose of A:")
def matrix_transpose(A): result_transpose = matrix_transpose(A)
result = [[0 for _ in range(len(A))] for _ in for row in result_transpose:
range(len(A[0]))] print(row)

Pinak Dhabu Fundamentals Of Data Structures


Computer Engineering Nutan Maharashtra Institute Of Engg. And Tech.

OUTPUT:

Pinak Dhabu Fundamentals Of Data Structures


Computer Engineering Nutan Maharashtra Institute Of Engg. And Tech.

Practical 4
Question 4:
Write a Python program to store first year percentage of students in an array. Write function for sorting an
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): def main():
n = len(arr) percentages = []
for i in range(n): num_students = int(input("Enter the number
min_index = i of students: "))
for j in range(i + 1, n):
if arr[j] < arr[min_index]: for i in range(num_students):
min_index = j score = float(input(f"Enter the percentage
arr[i], arr[min_index] = arr[min_index], for student {i + 1}: "))
arr[i] percentages.append(score)

def bubble_sort(arr): selection_sorted = percentages.copy()


n = len(arr) selection_sort(selection_sorted)
for i in range(n): print("\nSorted percentages using Selection
swapped = False Sort:")
for j in range(0, n - i - 1): print(selection_sorted)
if arr[j] > arr[j + 1]: display_top_scores(selection_sorted)
arr[j], arr[j + 1] = arr[j + 1], arr[j]
swapped = True bubble_sorted = percentages.copy()
if not swapped: bubble_sort(bubble_sorted)
break print("\nSorted percentages using Bubble
Sort:")
def display_top_scores(arr, top_n=5): print(bubble_sorted)
print(f"Top {top_n} scores:") display_top_scores(bubble_sorted)
for score in arr[-top_n:]:
print(score) if __name__ == "__main__":
main()

Pinak Dhabu Fundamentals Of Data Structures


Computer Engineering Nutan Maharashtra Institute Of Engg. And Tech.

OUTPUT:

Pinak Dhabu Fundamentals Of Data Structures


Computer Engineering Nutan Maharashtra Institute Of Engg. And Tech.

Practical 5
Question 5:
Write a Python program to store second year percentage of students in an array. Write function for sorting
an array of floating point numbers in ascending order using:
a) Insertion sort
b) Shell Sort and display top five scores
Code:
def insertion_sort(arr): break
for i in range(1, len(arr)): except ValueError as e:
key = arr[i] print(f"Invalid input: {e}. Please try
j=i-1 again.")
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j] while True:
j -= 1 try:
arr[j + 1] = key scores_input = input(f"Enter the
percentages for {num_students} students
def shell_sort(arr): (comma-separated): ")
n = len(arr) percentages = [float(score.strip()) for
gap = n // 2 score in scores_input.split(',')]
while gap > 0: if len(percentages) != num_students:
for i in range(gap, n): raise ValueError(f"You must enter
temp = arr[i] exactly {num_students} scores.")
j=i break
while j >= gap and arr[j - gap] > temp: except ValueError as e:
arr[j] = arr[j - gap] print(f"Invalid input: {e}. Please try
j -= gap again.")
arr[j] = temp
gap //= 2 insertion_sorted = percentages.copy()
insertion_sort(insertion_sorted)
def display_top_scores(arr, top_n=5): print("\nSorted percentages using Insertion
print(f"Top {top_n} scores:") Sort:")
for score in arr[-top_n:]: print(insertion_sorted)
print(score) display_top_scores(insertion_sorted)

def main(): shell_sorted = percentages.copy()


percentages = [] shell_sort(shell_sorted)
print("\nSorted percentages using Shell
while True: Sort:")
try: print(shell_sorted)
num_students = int(input("Enter the display_top_scores(shell_sorted)
number of students: "))
if num_students <= 0: if __name__ == "__main__":
raise ValueError("Number of students main()
must be a positive integer.")

Pinak Dhabu Fundamentals Of Data Structures


Computer Engineering Nutan Maharashtra Institute Of Engg. And Tech.

OUTPUT:

Pinak Dhabu Fundamentals Of Data Structures


Computer Engineering Nutan Maharashtra Institute Of Engg. And Tech.

Practical 6
Question 6:
Write a Python program to store first year percentage of students in an array. Write function for sorting an
array of floating point numbers in ascending order using quick sort and display top five scores.
Code:
def quicksort(arr): except ValueError as e:
if len(arr) <= 1: print(f"Invalid input: {e}. Please try
return arr again.")
else:
pivot = arr[len(arr) // 2] while True:
left = [x for x in arr if x < pivot] try:
middle = [x for x in arr if x == pivot] scores_input = input(f"Enter the
right = [x for x in arr if x > pivot] percentages for {num_students} students
return quicksort(left) + middle + (comma-separated): ")
quicksort(right) percentages = [float(score.strip()) for
score in scores_input.split(',')]
def display_top_scores(arr, top_n=5): if len(percentages) != num_students:
print(f"Top {top_n} scores:") raise ValueError(f"You must enter
for score in arr[-top_n:]: exactly {num_students} scores.")
print(score) break
except ValueError as e:
def main(): print(f"Invalid input: {e}. Please try
percentages = [] again.")

while True: sorted_percentages = quicksort(percentages)


try: print("\nSorted percentages:")
num_students = int(input("Enter the print(sorted_percentages)
number of students: "))
if num_students <= 0: display_top_scores(sorted_percentages)
raise ValueError("Number of students
must be a positive integer.") if __name__ == "__main__":
break main()

Pinak Dhabu Fundamentals Of Data Structures


Computer Engineering Nutan Maharashtra Institute Of Engg. And Tech.

OUTPUT:

Pinak Dhabu Fundamentals Of Data Structures


Computer Engineering Nutan Maharashtra Institute Of Engg. And Tech.

Practical 7
Question 7:
Department of Computer Engineering has a student club named 'Pinnacle Club'. Students of second, third,
and final year of the department can be granted membership on request. Similarly, one may cancel the
membership of the club. The first node is reserved for the president of the club and the last node is
reserved for the secretary of the club. Write a C++ program to maintain club members’ 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 the club
c) Display members
d) Two linked lists exist for two divisions. Concatenate two lists.
Code:
#include <iostream>
#include <string> if (head->prn == prn) {
using namespace std; Member* temp = head;
struct Member { head = head->next;
string prn; delete temp;
string name; cout << "Member with PRN " << prn
Member* next; << " deleted." << endl;
}; return;
class MemberList { }
private: Member* current = head;
Member* head; Member* previous = nullptr;
public: while (current && current->prn != prn) {
MemberList() : head(nullptr) {} previous = current;
void addMember(const string& prn, const current = current->next;
string& name) { }
Member* newMember = new Member{prn, if (current) {
name, nullptr}; previous->next = current->next;
if (!head) { delete current;
head = newMember; cout << "Member with PRN " << prn
} else { << " deleted." << endl;
Member* temp = head; } else {
while (temp->next) { cout << "Member with PRN " << prn
temp = temp->next; << " not found." << endl;
} }
temp->next = newMember; }
} int totalMembers() const {
cout << "Member added: " << name << " int count = 0;
(" << prn << ")" << endl; Member* temp = head;
} while (temp) {
void deleteMember(const string& prn) { count++;
if (!head) { temp = temp->next;
cout << "No members to delete." << }
endl; return count;
return; }
}

Pinak Dhabu Fundamentals Of Data Structures


Computer Engineering Nutan Maharashtra Institute Of Engg. And Tech.

void displayMembers() const { }


if (!head) { }
cout << "No members in the club." << };
endl;
return; int main() {
} MemberList clubMembers;
Member* temp = head; clubMembers.addMember("PRN001",
cout << "Members List:" << endl; "Alice");
while (temp) { clubMembers.addMember("PRN002",
cout << "PRN: " << temp->prn << ", "Bob");
Name: " << temp->name << endl; clubMembers.addMember("PRN003",
temp = temp->next; "Charlie");
} clubMembers.displayMembers();
} cout << "Total members: " <<
void concatenate(MemberList& other) { clubMembers.totalMembers() << endl;
if (!head) { clubMembers.deleteMember("PRN002");
head = other.head; clubMembers.displayMembers();
} else { MemberList divisionB;
Member* temp = head; divisionB.addMember("PRN004", "David");
while (temp->next) { divisionB.addMember("PRN005", "Eve");
temp = temp->next; cout << "Members in Division B:" << endl;
} divisionB.displayMembers();
temp->next = other.head; clubMembers.concatenate(divisionB);
} cout << "After concatenating Division B into
other.head = nullptr; Club Members:" << endl;
} clubMembers.displayMembers();
~MemberList() { cout << "Total members after concatenation:
while (head) { " << clubMembers.totalMembers() << endl;
Member* temp = head; return 0;
head = head->next; }
delete temp;

Pinak Dhabu Fundamentals Of Data Structures


Computer Engineering Nutan Maharashtra Institute Of Engg. And Tech.

OUTPUT:

Pinak Dhabu Fundamentals Of Data Structures


Computer Engineering Nutan Maharashtra Institute Of Engg. And Tech.

Practical 8
Question 8:
Write a C++ program for storing binary numbers using doubly linked lists. Write functions to:
a) Compute 1's and 2's complement
b) Add two binary numbers
Code:
#include <iostream> tail->next = newNode;
#include <stdexcept> newNode->prev = tail;
#include <initializer_list> tail = newNode;
}
using namespace std; }

struct Node { void onesComplement() {


int data; Node* current = head;
Node* next; while (current) {
Node* prev; current->data = (current->data == 0) ?
1 : 0;
Node(int value) : data(value), next(nullptr), current = current->next;
prev(nullptr) {} }
}; }

class DoublyLinkedList { void twosComplement() {


private: onesComplement();
Node* head; DoublyLinkedList oneList = {1};
Node* tail; addBinary(oneList);
}
public:
DoublyLinkedList() : head(nullptr), void addBinary(DoublyLinkedList& other) {
tail(nullptr) {} Node* p1 = tail;
Node* p2 = other.tail;
DoublyLinkedList(std::initializer_list<int> int carry = 0;
values) : head(nullptr), tail(nullptr) { DoublyLinkedList result;
for (int value : values) {
insert(value); while (p1 || p2 || carry) {
} int sum = carry;
} if (p1) {
sum += p1->data;
void insert(int value) { p1 = p1->prev;
if (value != 0 && value != 1) { }
throw invalid_argument("Binary digit if (p2) {
must be 0 or 1."); sum += p2->data;
} p2 = p2->prev;
Node* newNode = new Node(value); }
if (!head) { result.insert(sum % 2);
head = tail = newNode; carry = sum / 2;
} else { }

Pinak Dhabu Fundamentals Of Data Structures


Computer Engineering Nutan Maharashtra Institute Of Engg. And Tech.

binary1.insert(0);
reverse(result); binary1.insert(1);
result.print(); binary1.insert(1);
}
DoublyLinkedList binary2;
void reverse(DoublyLinkedList& list) { binary2.insert(1);
Node* current = list.head; binary2.insert(1);
Node* prev = nullptr; binary2.insert(0);
while (current) { binary2.insert(1);
Node* nextNode = current->next;
current->next = prev; cout << "Binary Number 1: ";
current->prev = nextNode; binary1.print();
prev = current;
current = nextNode; cout << "Binary Number 2: ";
} binary2.print();
list.head = prev;
} binary1.onesComplement();
cout << "1's Complement of Binary
void print() { Number 1: ";
Node* current = head; binary1.print();
while (current) {
cout << current->data; binary1 = DoublyLinkedList();
current = current->next; binary1.insert(1);
} binary1.insert(0);
cout << endl; binary1.insert(1);
} binary1.insert(1);

~DoublyLinkedList() { cout << "2's Complement of Binary


Node* current = head; Number 1: ";
while (current) { binary1.twosComplement();
Node* nextNode = current->next;
delete current; cout << "Sum of Binary Number 1 and
current = nextNode; Binary Number 2: ";
} binary1.addBinary(binary2);
}
}; } catch (const exception& e) {
cerr << "Error: " << e.what() << endl;
int main() { }
try {
DoublyLinkedList binary1; return 0;
binary1.insert(1); }

Pinak Dhabu Fundamentals Of Data Structures


Computer Engineering Nutan Maharashtra Institute Of Engg. And Tech.

OUTPUT:

Pinak Dhabu Fundamentals Of Data Structures


Computer Engineering Nutan Maharashtra Institute Of Engg. And Tech.

Practical 9
Question 9:
Implement a C++ program for expression conversion from infix to postfix and its evaluation using stack
based on given conditions:
1. 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> while (!operators.empty() &&
#include <stack> precedence(operators.top()) >=
#include <string> precedence(ch)) {
#include <cctype> postfix += operators.top();
using namespace std; postfix += ' ';
int precedence(char op) { operators.pop();
if (op == '+' || op == '-') return 1; }
if (op == '*' || op == '/') return 2; operators.push(ch);
return 0; }
} }
string infixToPostfix(const string& infix) { }
stack<char> operators; if (!token.empty()) {
string postfix; postfix += token + ' ';
string token; }
for (char ch : infix) { while (!operators.empty()) {
if (isspace(ch)) { postfix += operators.top();
continue; postfix += ' ';
} operators.pop();
if (isalnum(ch) ) { }
token += ch; return postfix;
} else { }
if (!token.empty()) { int evaluatePostfix(const string& postfix) {
postfix += token + ' '; stack<int> operands;
token.clear(); string token;
}
if (ch == '(') { for (char ch : postfix) {
operators.push(ch); if (isspace(ch)) {
} else if (ch == ')') { if (!token.empty()) {
while (!operators.empty() && operands.push(stoi(token));
operators.top() != '(') { token.clear();
postfix += operators.top(); }
postfix += ' '; continue;
operators.pop(); }
} if (isdigit(ch)) {
operators.pop(); token += ch;
} else { } else {
if (!token.empty()) {
operands.push(stoi(token));

Pinak Dhabu Fundamentals Of Data Structures


Computer Engineering Nutan Maharashtra Institute Of Engg. And Tech.

token.clear();
} if (!token.empty()) {
int right = operands.top(); operands.push(stoi(token));
operands.pop(); }
int left = operands.top(); return operands.top();
operands.pop(); }
switch (ch) { int main() {
case '+': operands.push(left + right); string infix;
break; cout << "Enter an infix expression (multi-
case '-': operands.push(left - right); digit numbers and operators): ";
break; getline(cin, infix);
case '*': operands.push(left * right); string postfix = infixToPostfix(infix);
break; cout << "Postfix expression: " << postfix <<
case '/': operands.push(left / right); endl;
break;
} return 0;
} }
}

OUTPUT:

Pinak Dhabu Fundamentals Of Data Structures


Computer Engineering Nutan Maharashtra Institute Of Engg. And Tech.

Practical 10
Question 10:
In any language, programs mostly encounter syntax errors due to unbalancing delimiters such as (), {}, [].
Write a C++ program using stack to check whether the given expression is well parenthesized or not.
Code:
#include <iostream> std::string test1 = "{[()]}";
#include <stack> std::string test2 = "{[(])}";
#include <string> std::string test3 = "((()))";
using namespace std; std::string test4 = "([{}])";
bool isWellParenthesized(const std::string& std::string test5 = "((())";
expression) { std::cout << "Test Case 1: " <<
std::stack<char> s; (isWellParenthesized(test1) ? "Well-
parenthesized" : "Not well-parenthesized") <<
for (char ch : expression) { std::endl;
if (ch == '(' || ch == '[' || ch == '{') { std::cout << "Test Case 2: " <<
s.push(ch); (isWellParenthesized(test2) ? "Well-
} else if (ch == ')' || ch == ']' || ch == '}') { parenthesized" : "Not well-parenthesized") <<
if (s.empty()) { std::endl;
return false; std::cout << "Test Case 3: " <<
} (isWellParenthesized(test3) ? "Well-
char top = s.top(); parenthesized" : "Not well-parenthesized") <<
if ((ch == ')' && top == '(') || std::endl;
(ch == ']' && top == '[') || std::cout << "Test Case 4: " <<
(ch == '}' && top == '{')) { (isWellParenthesized(test4) ? "Well-
s.pop(); parenthesized" : "Not well-parenthesized") <<
} else { std::endl;
return false; std::cout << "Test Case 5: " <<
} (isWellParenthesized(test5) ? "Well-
} parenthesized" : "Not well-parenthesized") <<
} std::endl;
return s.empty(); return 0;
} }
int main() {

Pinak Dhabu Fundamentals Of Data Structures


Computer Engineering Nutan Maharashtra Institute Of Engg. And Tech.

OUTPUT:

Pinak Dhabu Fundamentals Of Data Structures


Computer Engineering Nutan Maharashtra Institute Of Engg. And Tech.

Practical 11
Question 11:
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 a C++ program for simulating a job queue. Write functions to
add job and delete job from the queue.
Code:
#include <iostream> return;}
struct Job { Job* current = head;
int jobId; std::cout << "Current jobs in the queue: ";
Job* next; while (current != nullptr) {
}; std::cout << current->jobId << " ";
class JobQueue { current = current->next;
private: }
Job* head; std::cout << std::endl;
Job* tail; }
public: int main() {
JobQueue() : head(nullptr), tail(nullptr) {} JobQueue queue;
void addJob(int jobId); int choice, jobId;
void removeJob(); do {
void displayQueue();}; std::cout << "1. Add Job\n2. Remove
void JobQueue::addJob(int jobId) { Job\n3. Display Queue\n4. Exit\n";
Job* newJob = new Job(); std::cout << "Enter your choice: ";
newJob->jobId = jobId; std::cin >> choice;
newJob->next = nullptr; switch (choice) {
if (tail) { case 1:
tail->next = newJob; std::cout << "Enter job ID to add: ";
} else { std::cin >> jobId;
head = newJob; } queue.addJob(jobId);
tail = newJob;} break;
void JobQueue::removeJob() { case 2:
if (head == nullptr) { queue.removeJob();
std::cout << "Queue is empty. No job to break;
remove." << std::endl; case 3:
return; } queue.displayQueue();
Job* temp = head; break;
head = head->next; case 4:
if (head == nullptr) { std::cout << "Exiting program." <<
tail = nullptr; } std::endl;
std::cout << "Removed job with ID: " << break;
temp->jobId << std::endl; default:
delete temp; std::cout << "Invalid choice. Please
} try again." << std::endl;
void JobQueue::displayQueue() { }
if (head == nullptr) { } while (choice != 4);
std::cout << "Queue is empty." << return 0;
std::endl; }

Pinak Dhabu Fundamentals Of Data Structures


Computer Engineering Nutan Maharashtra Institute Of Engg. And Tech.

OUTPUT:

Pinak Dhabu Fundamentals Of Data Structures


Computer Engineering Nutan Maharashtra Institute Of Engg. And Tech.

Practical 12
Question 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 a C++ program to
simulate deque with functions to add and delete elements from either end of the deque.
Code:
#include <iostream> throw std::underflow_error("Deque is
#include <stdexcept> empty"); }
class Deque { int value = arr[front];
private: front = (front - 1 + capacity) % capacity;
int* arr; size--;
int capacity; return value; }
int front; int removeBack() {
int back; if (size == 0) {
int size; throw std::underflow_error("Deque is
public: empty"); }
Deque(int cap) : capacity(cap), front(-1), int value = arr[back];
back(0), size(0) { back = (back + 1) % capacity;
arr = new int[capacity]; size--;
} return value; }
~Deque() { int getSize() const {
delete[] arr; return size;
} }
void addFront(int value) { bool isEmpty() const {
if (size == capacity) { return size == 0; }};
throw std::overflow_error("Deque is int main() {
full"); } Deque deque(5);
front = (front + 1) % capacity; try {
arr[front] = value; deque.addBack(10);
size++; deque.addBack(20);
if (size == 1) { deque.addFront(5);
back = front; } } deque.addFront(1);
void addBack(int value) { std::cout << "Current size: " <<
if (size == capacity) { deque.getSize() << std::endl;
throw std::overflow_error("Deque is std::cout << "Removed from front: " <<
full"); } deque.removeFront() << std::endl;
back = (back - 1 + capacity) % capacity; std::cout << "Removed from back: " <<
arr[back] = value; deque.removeBack() << std::endl;
size++; std::cout << "Current size: " <<
if (size == 1) { deque.getSize() << std::endl;
front = back; } } } catch (const std::exception& e) {
int removeFront() { std::cerr << e.what() << std::endl;}
if (size == 0) { return 0;}

Pinak Dhabu Fundamentals Of Data Structures


Computer Engineering Nutan Maharashtra Institute Of Engg. And Tech.

OUTPUT:

Pinak Dhabu Fundamentals Of Data Structures


Computer Engineering Nutan Maharashtra Institute Of Engg. And Tech.

Practical 13
Question 13:
A pizza parlor accepts a maximum of M orders. Orders are served on a first-come, first-served basis.
Orders once placed cannot be canceled. Write a C++ program to simulate the system using a circular
queue using an array.
Code:
#include <iostream> cout << "Order added: " << order <<
#include <string> endl;
using namespace std; }
class CircularQueue {
private: void serveOrder() {
string* queue; if (isEmpty()) {
int front; cout << "No orders to serve." << endl;
int rear; return;
int maxSize; }
int currentSize; cout << "Serving order: " << queue[front]
public: << endl;
CircularQueue(int size) { front = (front + 1) % maxSize;
maxSize = size; currentSize--;
queue = new string[maxSize]; if (isEmpty()) {
front = -1; front = -1;
rear = -1; rear = -1;
currentSize = 0; }
} }
~CircularQueue() {
delete[] queue; void displayStatus() {
} if (isEmpty()) {
bool isFull() { cout << "Order queue is empty." <<
return currentSize == maxSize; endl;
} return;
}
bool isEmpty() { cout << "Current orders in the queue: ";
return currentSize == 0; for (int i = 0; i < currentSize; i++) {
} cout << queue[(front + i) % maxSize]
<< (i < currentSize - 1 ? ", " : "");
void addOrder(const string& order) { }
if (isFull()) { cout << endl;
cout << "Order queue is full. Cannot }
accept new orders." << endl; };
return;
} int main() {
rear = (rear + 1) % maxSize; int maxOrders;
queue[rear] = order; cout << "Enter the maximum number of
if (front == -1) { orders (M): ";
front = 0; cin >> maxOrders;
}
currentSize++; CircularQueue orderQueue(maxOrders);
int choice;

Pinak Dhabu Fundamentals Of Data Structures


Computer Engineering Nutan Maharashtra Institute Of Engg. And Tech.

string order; break;


case 2:
do { orderQueue.serveOrder();
cout << "\nPizza Parlor Order System" << break;
endl; case 3:
cout << "1. Add Order" << endl; orderQueue.displayStatus();
cout << "2. Serve Order" << endl; break;
cout << "3. Display Order Status" << case 4:
endl; cout << "Exiting the system..." <<
cout << "4. Exit" << endl; endl;
cout << "Enter your choice: "; break;
cin >> choice; default:
cout << "Invalid choice. Please try
switch (choice) { again." << endl;
case 1: }
cout << "Enter the order: "; } while (choice != 4);
cin.ignore();
getline(cin, order); return 0;
orderQueue.addOrder(order); }

OUTPUT:

Pinak Dhabu Fundamentals Of Data Structures

You might also like