Practical 1
def compute_average(marks):
valid_marks = [mark for mark in marks if mark != -1]
if len(valid_marks) == 0:
return 0
return sum(valid_marks) / len(valid_marks)
def find_highest_and_lowest(marks):
valid_marks = [mark for mark in marks if mark != -1]
if len(valid_marks) == 0:
return None, None
return max(valid_marks), min(valid_marks)
def count_absent_students(marks):
return marks.count(-1)
def find_highest_frequency(marks):
valid_marks = [mark for mark in marks if mark != -1]
if len(valid_marks) == 0:
return None, 0
frequency = {mark: valid_marks.count(mark) for mark in valid_marks}
most_frequent_mark = max(frequency, key=frequency.get)
return most_frequent_mark, frequency[most_frequent_mark]
# Input: Number of students and their marks
n = int(input("Enter the number of students: "))
marks = []
print("Enter marks for each student (-1 for absent):")
for i in range(n):
mark = int(input(f"Student {i + 1}: "))
marks.append(mark)
# Perform computations
average = compute_average(marks)
highest, lowest = find_highest_and_lowest(marks)
absent_count = count_absent_students(marks)
most_frequent_mark, frequency = find_highest_frequency(marks)
# Display results
print("\nResults:")
print(f"Average score of the class: {average:.2f}")
if highest is not None and lowest is not None:
print(f"Highest score: {highest}")
print(f"Lowest score: {lowest}")
else:
print("No valid scores available.")
print(f"Number of students absent: {absent_count}")
if most_frequent_mark is not None:
print(f"Mark with the highest frequency: {most_frequent_mark} (Frequency: {frequency})")
else:
print("No valid scores to compute frequency.")
Output:
Practical 2
def longest_word(string):
words = string.split()
longest = max(words, key=len)
return longest
def char_frequency(string, char):
return string.count(char)
def is_palindrome(string):
cleaned_string = ''.join(filter(str.isalnum, string)).lower()
return cleaned_string == cleaned_string[::-1]
def first_substring_index(string, substring):
return string.find(substring)
def word_occurrences(string):
words = string.split()
occurrences = {}
for word in words:
occurrences[word] = occurrences.get(word, 0) + 1
return occurrences
# Input string
input_string = input("Enter a string: ")
# Menu of operations
print("\nSelect an operation:")
print("a) Display word with the longest length")
print("b) Determine the frequency of occurrence of a particular character")
print("c) Check whether the string is a palindrome")
print("d) Display the index of the first appearance of a substring")
print("e) Count the occurrences of each word in the string")
choice = input("Enter your choice (a/b/c/d/e): ").strip().lower()
if choice == 'a':
longest = longest_word(input_string)
print(f"The word with the longest length is: {longest}")
elif choice == 'b':
char = input("Enter the character to find its frequency: ")
frequency = char_frequency(input_string, char)
print(f"The frequency of '{char}' in the string is: {frequency}")
elif choice == 'c':
if is_palindrome(input_string):
print("The given string is a palindrome.")
else:
print("The given string is not a palindrome.")
elif choice == 'd':
substring = input("Enter the substring to find its first appearance: ")
index = first_substring_index(input_string, substring)
if index != -1:
print(f"The substring '{substring}' first appears at index: {index}")
else:
print(f"The substring '{substring}' was not found in the string.")
elif choice == 'e':
occurrences = word_occurrences(input_string)
print("Occurrences of each word:")
for word, count in occurrences.items():
print(f"{word}: {count}")
else:
print("Invalid choice. Please try again.")
Output:
a)Display word with the longest length
b) Determine the frequency of occurrence of a particular character.
c) Check whether the string is palindrome.
d) Display the index of the first appearance of a substring .
e) Count the occurrence of each word in the string.
Practical 3
import numpy as np
def input_matrix(rows, cols):
print(f"Enter the elements for a {rows}x{cols} matrix:")
matrix = []
for i in range(rows):
row = list(map(int, input(f"Enter row {i+1} (space-separated): ").split()))
matrix.append(row)
return np.array(matrix)
def matrix_operations():
print("Matrix Operations:")
print("a) Addition of two matrices")
print("b) Subtraction of two matrices")
print("c) Multiplication of two matrices")
print("d) Transpose of a matrix")
choice = input("Enter your choice (a/b/c/d): ").strip().lower()
if choice in ['a', 'b', 'c']:
rows1 = int(input("Enter the number of rows for the first matrix: "))
cols1 = int(input("Enter the number of columns for the first matrix: "))
matrix1 = input_matrix(rows1, cols1)
rows2 = int(input("Enter the number of rows for the second matrix: "))
cols2 = int(input("Enter the number of columns for the second matrix: "))
matrix2 = input_matrix(rows2, cols2)
if choice == 'a': # Addition
if matrix1.shape == matrix2.shape:
result = matrix1 + matrix2
print("Result of matrix addition:")
print(result)
else:
print("Error: Matrices must have the same dimensions for addition.")
elif choice == 'b': # Subtraction
if matrix1.shape == matrix2.shape:
result = matrix1 - matrix2
print("Result of matrix subtraction:")
print(result)
else:
print("Error: Matrices must have the same dimensions for subtraction.")
elif choice == 'c': # Multiplication
if cols1 == rows2:
result = np.dot(matrix1, matrix2)
print("Result of matrix multiplication:")
print(result)
else:
print("Error: Number of columns of the first matrix must equal the number of rows of the second
matrix for multiplication.")
elif choice == 'd': # Transpose
rows = int(input("Enter the number of rows for the matrix: "))
cols = int(input("Enter the number of columns for the matrix: "))
matrix = input_matrix(rows, cols)
result = matrix.T
print("Transpose of the matrix:")
print(result)
else:
print("Invalid choice. Please select a valid option.")
# Call the function to execute the operations
matrix_operations()
Output:
a) Addition of two matrices.
b) Subtraction of two matrices .
c) Multiplication of two matrices .
d) Transpose of a matrix.
Practical 4
def selection_sort(arr):
n = len(arr)
for i in range(n):
min_idx = i
for j in range(i + 1, n):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], 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_n=5):
return arr[-top_n:][::-1] if len(arr) >= top_n else arr[::-1]
# Input: Number of students and their percentages
n = int(input("Enter the number of students: "))
percentages = []
print("Enter the percentages of students:")
for i in range(n):
percentages.append(float(input(f"Student {i+1}: ")))
# Menu for sorting options
print("\nChoose a sorting method:")
print("a) Selection Sort")
print("b) Bubble Sort")
choice = input("Enter your choice (a/b): ").strip().lower()
if choice == 'a':
selection_sort(percentages)
print("Sorted percentages (Selection Sort):", percentages)
elif choice == 'b':
bubble_sort(percentages)
print("Sorted percentages (Bubble Sort):", percentages)
else:
print("Invalid choice. Exiting.")
exit()
# Display top 5 scores
top_scores = display_top_scores(percentages)
print("Top 5 scores:", top_scores)
Output:
a) Selection sort :
b) Bubble sort :
Practical 5
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j=i-1
while j >= 0 and key < arr[j]:
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, top_n=5):
return arr[-top_n:][::-1] if len(arr) >= top_n else arr[::-1]
# Input: Number of students and their percentages
n = int(input("Enter the number of students: "))
percentages = []
print("Enter the percentages of students:")
for i in range(n):
percentages.append(float(input(f"Student {i+1}: ")))
# Menu for sorting options
print("\nChoose a sorting method:")
print("a) Insertion Sort")
print("b) Shell Sort")
choice = input("Enter your choice (a/b): ").strip().lower()
if choice == 'a':
insertion_sort(percentages)
print("Sorted percentages (Insertion Sort):", percentages)
elif choice == 'b':
shell_sort(percentages)
print("Sorted percentages (Shell Sort):", percentages)
else:
print("Invalid choice. Exiting.")
exit()
# Display top 5 scores
top_scores = display_top_scores(percentages)
print("Top 5 scores:", top_scores)
Output:
a)Insertion sort :
b) Shell sort :
Practical 6
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_scores(arr, top_n=5):
return arr[-top_n:][::-1] if len(arr) >= top_n else arr[::-1]
# Input: Number of students and their percentages
n = int(input("Enter the number of students: "))
percentages = []
print("Enter the percentages of students:")
for i in range(n):
percentages.append(float(input(f"Student {i+1}: ")))
# Sort the percentages using Quick Sort
sorted_percentages = quick_sort(percentages)
print("Sorted percentages (Quick Sort):", sorted_percentages)
# Display top 5 scores
top_scores = display_top_scores(sorted_percentages)
print("Top 5 scores:", top_scores)
Output:
Practical 7
#include <iostream>
#include <string>
using namespace std;
// Node structure
struct Node {
int PRN;
string name;
Node* next;
};
// Class for Pinnacle Club
class PinnacleClub {
private:
Node* head;
public:
PinnacleClub() : head(nullptr) {}
// Add a member
void addMember(int PRN, string name, bool isPresident = false, bool isSecretary = false) {
Node* newNode = new Node{PRN, name, nullptr};
if (isPresident) { // Adding President
newNode->next = head;
head = newNode;
} else if (isSecretary || head == nullptr) { // Adding Secretary or first member
if (head == nullptr) {
head = newNode;
} else {
Node* temp = head;
while (temp->next != nullptr) {
temp = temp->next;
}
temp->next = newNode;
} else { // Adding general member
Node* temp = head;
while (temp->next != nullptr && temp->next->next != nullptr) {
temp = temp->next;
newNode->next = temp->next;
temp->next = newNode;
// Delete a member
void deleteMember(int PRN) {
if (head == nullptr) {
cout << "List is empty. No member to delete.\n";
return;
if (head->PRN == PRN) { // Deleting President
Node* temp = head;
head = head->next;
delete temp;
cout << "President deleted.\n";
return;
Node* temp = head;
while (temp->next != nullptr && temp->next->PRN != PRN) {
temp = temp->next;
if (temp->next == nullptr) {
cout << "Member with PRN " << PRN << " not found.\n";
} else {
Node* toDelete = temp->next;
temp->next = temp->next->next;
delete toDelete;
cout << "Member with PRN " << PRN << " deleted.\n";
// Compute total members
int countMembers() {
int count = 0;
Node* temp = head;
while (temp != nullptr) {
count++;
temp = temp->next;
return count;
// Display members
void displayMembers() {
if (head == nullptr) {
cout << "No members in the list.\n";
return;
Node* temp = head;
cout << "Members of the Pinnacle Club:\n";
while (temp != nullptr) {
cout << "PRN: " << temp->PRN << ", Name: " << temp->name << "\n";
temp = temp->next;
// Concatenate another list
void concatenate(PinnacleClub& other) {
if (head == nullptr) {
head = other.head;
} else {
Node* temp = head;
while (temp->next != nullptr) {
temp = temp->next;
temp->next = other.head;
other.head = nullptr; // Clearing the other list
};
int main() {
PinnacleClub divA, divB;
// Adding members
divA.addMember(1, "President A", true);
divA.addMember(2, "Member A1");
divA.addMember(3, "Secretary A", false, true);
divB.addMember(4, "President B", true);
divB.addMember(5, "Member B1");
divB.addMember(6, "Secretary B", false, true);
// Display members
cout << "Division A:\n";
divA.displayMembers();
cout << "\nDivision B:\n";
divB.displayMembers();
// Total members in Division A
cout << "\nTotal members in Division A: " << divA.countMembers() << "\n";
// Concatenating two lists
cout << "\nConcatenating Division A and Division B...\n";
divA.concatenate(divB);
// Display concatenated list
cout << "\nAfter concatenation:\n";
divA.displayMembers();
// Deleting a member
cout << "\nDeleting a member with PRN 2...\n";
divA.deleteMember(2);
divA.displayMembers();
return 0;
Output
Practical 8
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
// Node structure for doubly linked list
struct Node {
int bit;
Node* prev;
Node* next;
Node(int b) : bit(b), prev(nullptr), next(nullptr) {}
};
// Class for Binary Number
class BinaryNumber {
private:
Node* head;
Node* tail;
public:
BinaryNumber() : head(nullptr), tail(nullptr) {}
// Function to insert a bit at the end of the doubly linked list
void insertBit(int bit) {
Node* newNode = new Node(bit);
if (!head) {
head = tail = newNode;
} else {
tail->next = newNode;
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 the 1's complement
void onesComplement() {
Node* temp = head;
while (temp) {
temp->bit = (temp->bit == 0) ? 1 : 0;
temp = temp->next;
// Function to compute the 2's complement (1's complement + 1)
void twosComplement() {
onesComplement(); // First take 1's complement
Node* temp = tail;
int carry = 1;
while (temp && carry) {
int sum = temp->bit + carry;
temp->bit = sum % 2;
carry = sum / 2;
temp = temp->prev;
}
// Function to add two binary numbers (current binary + another binary)
void add(BinaryNumber& other) {
Node* temp1 = tail;
Node* temp2 = other.tail;
int carry = 0;
while (temp1 || temp2 || carry) {
int sum = carry;
if (temp1) {
sum += temp1->bit;
temp1 = temp1->prev;
if (temp2) {
sum += temp2->bit;
temp2 = temp2->prev;
carry = sum / 2;
int resultBit = sum % 2;
// Insert the result bit at the front of the current binary number
insertAtFront(resultBit);
// Helper function to insert a bit at the front of the binary number
void insertAtFront(int bit) {
Node* newNode = new Node(bit);
if (!head) {
head = tail = newNode;
} else {
newNode->next = head;
head->prev = newNode;
head = newNode;
// Destructor to delete dynamically allocated memory
~BinaryNumber() {
Node* temp = head;
while (temp) {
Node* next = temp->next;
delete temp;
temp = next;
};
int main() {
BinaryNumber bin1, bin2;
// Input: Binary number 1
cout << "Enter binary number 1 (Enter each bit followed by Enter, followed by -1 to finish):\n";
int bit;
while (true) {
cin >> bit;
if (bit == -1) break;
bin1.insertBit(bit);
// Input: Binary number 2
cout << "Enter binary number 2 (Enter each bit followed by Enter, followed by -1 to finish):\n";
while (true) {
cin >> bit;
if (bit == -1) break;
bin2.insertBit(bit);
// Display the binary numbers
cout << "Binary Number 1: ";
bin1.display();
cout << "Binary Number 2: ";
bin2.display();
// Compute and display the 1's complement of the first binary number
BinaryNumber bin1Copy = bin1; // Copy bin1 to compute complement
bin1Copy.onesComplement();
cout << "1's Complement of Binary Number 1: ";
bin1Copy.display();
// Compute and display the 2's complement of the first binary number
bin1Copy = bin1; // Copy bin1 to compute complement
bin1Copy.twosComplement();
cout << "2's Complement of Binary Number 1: ";
bin1Copy.display();
// Add the two binary numbers
BinaryNumber binSum = bin1;
binSum.add(bin2);
cout << "Sum of Binary Number 1 and Binary Number 2: ";
binSum.display();
return 0;
}
Output:
Practical 9
#include <iostream>
#include <stack>
#include <unordered_map>
using namespace std;
// Function to check if the expression is well parenthesized
bool isWellParenthesized(const string& expression) {
stack<char> s; // Stack to hold opening brackets
unordered_map<char, char> matchingBrackets = {
{')', '('},
{'}', '{'},
{']', '['}
};
for (char ch : expression) {
// If the character is an opening bracket, push it onto the stack
if (ch == '(' || ch == '{' || ch == '[') {
s.push(ch);
// If the character is a closing bracket, check if it matches the top of the stack
else if (ch == ')' || ch == '}' || ch == ']') {
if (s.empty() || s.top() != matchingBrackets[ch]) {
return false; // Mismatch or extra closing bracket
s.pop(); // Pop the matching opening bracket
// If the stack is empty, all brackets are matched correctly
return s.empty();
}
int main() {
string expression;
// Input the expression
cout << "Enter the expression: ";
getline(cin, expression);
// Check if the expression is well parenthesized
if (isWellParenthesized(expression)) {
cout << "The expression is well parenthesized." << endl;
} else {
cout << "The expression is NOT well parenthesized." << endl;
return 0;
Output :
Practical 10
#include <iostream>
#include <stack>
#include <cctype>
#include <cmath>
#include <string>
using namespace std;
// Function to get precedence of operators
int precedence(char op) {
if (op == '+' || op == '-') {
return 1;
} else if (op == '*' || op == '/') {
return 2;
return 0;
// Function to perform arithmetic operations
int applyOperation(int a, int b, char op) {
switch (op) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return a / b;
default: return 0;
// Function to convert infix expression to postfix
string infixToPostfix(const string& infix) {
stack<char> operators;
string postfix = "";
for (char c : infix) {
// If the character is an operand, append it to the postfix expression
if (isalnum(c)) {
postfix += c;
// If the character is '(', push it to the stack
else if (c == '(') {
operators.push(c);
// If the character is ')', pop and append to postfix until '(' is encountered
else if (c == ')') {
while (!operators.empty() && operators.top() != '(') {
postfix += operators.top();
operators.pop();
operators.pop(); // Pop '(' from the stack
// If the character is an operator
else if (c == '+' || c == '-' || c == '*' || c == '/') {
while (!operators.empty() && precedence(operators.top()) >= precedence(c)) {
postfix += operators.top();
operators.pop();
operators.push(c); // Push the current operator to the stack
// Pop all remaining operators from the stack
while (!operators.empty()) {
postfix += operators.top();
operators.pop();
}
return postfix;
// Function to evaluate the postfix expression
int evaluatePostfix(const string& postfix) {
stack<int> values;
for (char c : postfix) {
// If the character is an operand, push it to the stack
if (isalnum(c)) {
values.push(c - '0'); // Convert character to integer
// If the character is an operator
else if (c == '+' || c == '-' || c == '*' || c == '/') {
int b = values.top(); values.pop();
int a = values.top(); values.pop();
int result = applyOperation(a, b, c);
values.push(result); // Push the result back to the stack
// The final result will be the only value left in the stack
return values.top();
int main() {
string infix, postfix;
// Input Infix Expression
cout << "Enter infix expression (with single character operands and operators): ";
cin >> infix;
// Convert infix to postfix
postfix = infixToPostfix(infix);
cout << "Postfix Expression: " << postfix << endl;
// Evaluate the postfix expression
int result = evaluatePostfix(postfix);
cout << "Result of evaluation: " << result << endl;
return 0;
Output:
Practical 11
#include <iostream>
#include <queue>
#include <string>
using namespace std;
// Function to add a job to the queue
void addJob(queue<string>& jobQueue, const string& job) {
jobQueue.push(job); // Add the job to the back of the queue
cout << "Job added: " << job << endl;
// Function to delete a job from the queue
void deleteJob(queue<string>& jobQueue) {
if (!jobQueue.empty()) {
cout << "Job deleted: " << jobQueue.front() << endl;
jobQueue.pop(); // Remove the job from the front of the queue
} else {
cout << "No jobs to delete. The queue is empty." << endl;
// Function to display all jobs in the queue
void displayJobs(const queue<string>& jobQueue) {
if (jobQueue.empty()) {
cout << "The job queue is empty." << endl;
return;
cout << "Jobs in the queue: ";
queue<string> tempQueue = jobQueue; // Create a temporary queue to preserve the original queue
while (!tempQueue.empty()) {
cout << tempQueue.front() << " ";
tempQueue.pop();
}
cout << endl;
int main() {
queue<string> jobQueue; // Queue to store jobs
int choice;
string job;
while (true) {
// Display menu
cout << "\nJob Queue Menu:\n";
cout << "1. Add Job\n";
cout << "2. Delete Job\n";
cout << "3. Display Jobs\n";
cout << "4. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
// Add job
cout << "Enter job name: ";
cin.ignore(); // To clear any leftover newline character from input buffer
getline(cin, job); // Get the full job name including spaces
addJob(jobQueue, job);
break;
case 2:
// Delete job
deleteJob(jobQueue);
break;
case 3:
// Display all jobs in the queue
displayJobs(jobQueue);
break;
case 4:
// Exit
cout << "Exiting program..." << endl;
return 0;
default:
cout << "Invalid choice, please try again." << endl;
return 0;
}
Output:
Practical 12
#include <iostream>
using namespace std;
class Deque {
private:
int* arr; // Array to store the elements of deque
int front, rear; // Indices for front and rear
int capacity; // Maximum size of the deque
int size; // Current size of the deque
public:
// Constructor to initialize the deque with a given capacity
Deque(int cap) {
capacity = cap;
arr = new int[capacity];
front = -1;
rear = -1;
size = 0;
// Destructor to free the dynamically allocated memory
~Deque() {
delete[] arr;
// Function to check if the deque is full
bool isFull() {
return size == capacity;
// Function to check if the deque is empty
bool isEmpty() {
return size == 0;
// Add an element at the front of the deque
void addFront(int x) {
if (isFull()) {
cout << "Deque is full, cannot add element to the front." << endl;
return;
// If the deque is empty, update front and rear
if (isEmpty()) {
front = 0;
rear = 0;
} else {
// Decrement front, circularly
front = (front - 1 + capacity) % capacity;
arr[front] = x;
size++;
cout << "Added " << x << " to the front." << endl;
// Add an element at the rear of the deque
void addRear(int x) {
if (isFull()) {
cout << "Deque is full, cannot add element to the rear." << endl;
return;
// If the deque is empty, update front and rear
if (isEmpty()) {
front = 0;
rear = 0;
} else {
// Increment rear, circularly
rear = (rear + 1) % capacity;
arr[rear] = x;
size++;
cout << "Added " << x << " to the rear." << endl;
// Remove an element from the front of the deque
void deleteFront() {
if (isEmpty()) {
cout << "Deque is empty, cannot delete element from the front." << endl;
return;
cout << "Deleted " << arr[front] << " from the front." << endl;
// If there is only one element, reset front and rear to -1
if (front == rear) {
front = -1;
rear = -1;
} else {
// Increment front, circularly
front = (front + 1) % capacity;
size--;
// Remove an element from the rear of the deque
void deleteRear() {
if (isEmpty()) {
cout << "Deque is empty, cannot delete element from the rear." << endl;
return;
cout << "Deleted " << arr[rear] << " from the rear." << endl;
// If there is only one element, reset front and rear to -1
if (front == rear) {
front = -1;
rear = -1;
} else {
// Decrement rear, circularly
rear = (rear - 1 + capacity) % capacity;
size--;
// Display the elements in the deque
void display() {
if (isEmpty()) {
cout << "Deque is empty." << endl;
return;
cout << "Deque elements: ";
int i = front;
while (i != rear) {
cout << arr[i] << " ";
i = (i + 1) % capacity;
cout << arr[rear] << endl; // Display the last element
};
int main() {
Deque dq(5); // Create a deque with capacity of 5
int choice, value;
while (true) {
cout << "\nDeque Operations Menu:" << endl;
cout << "1. Add element to the front" << endl;
cout << "2. Add element to the rear" << endl;
cout << "3. Delete element from the front" << endl;
cout << "4. Delete element from the rear" << endl;
cout << "5. Display deque" << endl;
cout << "6. Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "Enter value to add to front: ";
cin >> value;
dq.addFront(value);
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;
return 0;
default:
cout << "Invalid choice! Please try again." << endl;
return 0;
Output:
Deque Operations Menu:
1. Add element to the front
2. Add element to the rear
3. Delete element from the front
4. Delete element from the rear
5. Display deque
6. Exit
Enter your choice: 1
Enter value to add to front: 12
Added 12 to the front.
Deque Operations Menu:
1. Add element to the front
2. Add element to the rear
3. Delete element from the front
4. Delete element from the rear
5. Display deque
6. Exit
Enter your choice: 2
Enter value to add to rear: 23
Added 23 to the rear.
Deque Operations Menu:
1. Add element to the front
2. Add element to the rear
3. Delete element from the front
4. Delete element from the rear
5. Display deque
6. Exit
Enter your choice: 3
Deleted 12 from the front.
Deque Operations Menu:
1. Add element to the front
2. Add element to the rear
3. Delete element from the front
4. Delete element from the rear
5. Display deque
6. Exit
Enter your choice: 23
Invalid choice! Please try again.
Deque Operations Menu:
1. Add element to the front
2. Add element to the rear
3. Delete element from the front
4. Delete element from the rear
5. Display deque
6. Exit
Enter your choice: 4
Deleted 23 from the rear.
Deque Operations Menu:
1. Add element to the front
2. Add element to the rear
3. Delete element from the front
4. Delete element from the rear
5. Display deque
6. Exit
Enter your choice: 24
Invalid choice! Please try again.
Deque Operations Menu:
1. Add element to the front
2. Add element to the rear
3. Delete element from the front
4. Delete element from the rear
5. Display deque
6. Exit
Enter your choice: 5
Deque is empty.
Deque Operations Menu:
1. Add element to the front
2. Add element to the rear
3. Delete element from the front
4. Delete element from the rear
5. Display deque
6. Exit
Enter your choice: 24
Invalid choice! Please try again.
Deque Operations Menu:
1. Add element to the front
2. Add element to the rear
3. Delete element from the front
4. Delete element from the rear
5. Display deque
6. Exit
Enter your choice: 6
Exiting program.
=== Code Execution Successful ===
Practical 13
#include <iostream>
#include <string>
using namespace std;
class PizzaParlor {
private:
string* orders; // Array to store pizza orders
int front, rear; // Front and rear pointers for the circular queue
int capacity; // Maximum number of orders the parlor can accept
int size; // Current number of orders in the queue
public:
// Constructor to initialize the pizza parlor with a given maximum capacity
PizzaParlor(int maxOrders) {
capacity = maxOrders;
orders = new string[capacity];
front = -1;
rear = -1;
size = 0;
// Destructor to free the dynamically allocated memory
~PizzaParlor() {
delete[] orders;
// Check if the pizza parlor is full
bool isFull() {
return size == capacity;
// Check if the pizza parlor is empty
bool isEmpty() {
return size == 0;
// Function to place a new order
void placeOrder(const string& order) {
if (isFull()) {
cout << "Sorry, the pizza parlor is full. Cannot accept more orders at the moment." << endl;
return;
if (isEmpty()) {
front = 0; // Set front and rear when the first order is placed
rear = 0;
} else {
// Increment rear circularly
rear = (rear + 1) % capacity;
orders[rear] = order; // Add the new order to the rear of the queue
size++;
cout << "Order placed: " << order << endl;
// Function to serve the order (remove from the front of the queue)
void serveOrder() {
if (isEmpty()) {
cout << "No orders to serve. The queue is empty." << endl;
return;
cout << "Serving order: " << orders[front] << endl;
if (front == rear) {
// If there was only one order, reset front and rear
front = -1;
rear = -1;
} else {
// Increment front circularly
front = (front + 1) % capacity;
size--;
// Function to display all the orders in the queue
void displayOrders() {
if (isEmpty()) {
cout << "No orders in the queue." << endl;
return;
cout << "Current orders in the queue: ";
int i = front;
while (i != rear) {
cout << orders[i] << " ";
i = (i + 1) % capacity;
cout << orders[rear] << endl; // Display the last order
};
int main() {
int maxOrders;
cout << "Enter the maximum number of orders the pizza parlor can accept: ";
cin >> maxOrders;
PizzaParlor parlor(maxOrders); // Create a PizzaParlor object with the given capacity
int choice;
string order;
while (true) {
// Display menu
cout << "\nPizza Parlor Menu:" << endl;
cout << "1. Place Order" << endl;
cout << "2. Serve Order" << endl;
cout << "3. Display Orders" << endl;
cout << "4. Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
// Place a new order
cout << "Enter the pizza order: ";
cin.ignore(); // To clear any leftover newline character from input buffer
getline(cin, order); // Get the full order, including spaces
parlor.placeOrder(order);
break;
case 2:
// Serve an order
parlor.serveOrder();
break;
case 3:
// Display all orders in the queue
parlor.displayOrders();
break;
case 4:
// Exit the program
cout << "Exiting program..." << endl;
return 0;
default:
cout << "Invalid choice, please try again." << endl;
}
return 0;
Output:
Enter the maximum number of orders the pizza parlor can accept: 10
Pizza Parlor Menu:
1. Place Order
2. Serve Order
3. Display Orders
4. Exit
Enter your choice: 1
Enter the pizza order: 2
Order placed: 2
Pizza Parlor Menu:
1. Place Order
2. Serve Order
3. Display Orders
4. Exit
Enter your choice: 2
Serving order: 2
Pizza Parlor Menu:
1. Place Order
2. Serve Order
3. Display Orders
4. Exit
Enter your choice: 3
No orders in the queue.
Pizza Parlor Menu:
1. Place Order
2. Serve Order
3. Display Orders
4. Exit
Enter your choice: 4
Exiting program...
=== Code Execution Successful ===