DS 19 Experiments
DS 19 Experiments
Write a C++ program to implement Array data structure with the following
operations
a. Traversal
b. Insertion
c. Deletion
d. Sorting
e. Searching (linear Search)
Code
#include <iostream>
class Array {
private:
int
*arr;
int
size;
int capacity;
public:
Array(int capacity) {
this->capacity =
capacity; this->size =
0;
this->arr = new int[capacity];
}
~Array()
{ delete[]
arr;
}
void insert(int
element) { if (size
< capacity) {
arr[size] = element;
size++;
std::cout << "Element " << element << " inserted successfully." <<
std::endl;
} else {
std::cout << "Array is full. Cannot insert element." << std::endl;
}
}
if (index != -1) {
for (int i = index; i < size - 1; i+
+) { arr[i] = arr[i + 1];
}
size--;
std::cout << "Element " << element << " removed successfully." <<
std::endl;
} else {
std::cout << "Element " << element << " not found in the array." <<
std::endl;
}
}
void sort() {
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1;
j++) { if (arr[j] > arr[j +
1]) {
int temp =
arr[j]; arr[j] =
arr[j + 1];
arr[j + 1] =
temp;
}
}
}
std::cout << "Array sorted successfully." << std::endl;
}
}
}
std::cout << "Element " << element << " not found in the array." <<
std::endl;
}
void display()
{ if (size
== 0) {
std::cout << "Array is empty." <<
std::endl; return;
}
int main() {
int capacity;
std::cout << "Enter the capacity of the
array: "; std::cin >> capacity;
Array
arr(capacity); int
choice, element;
while (true) {
std::cout << "\nArray
Operations:\n"; std::cout << "1.
Insert\n";
std::cout << "2. Delete\n";
std::cout << "3. Sort\n";
std::cout << "4. Search\n";
std::cout << "5. Display\n";
std::cout << "6. Exit\n";
std::cout << "Enter your choice:
"; std::cin >> choice;
switch
(choice)
{ case 1:
std::cout << "Enter element to
insert: "; std::cin >> element;
arr.insert(element
); break;
case 2:
std::cout << "Enter element to
delete: "; std::cin >> element;
arr.remove(element);
brea
k; case
3:
arr.sort(
);
break;
case 4:
std::cout << "Enter element to
search: "; std::cin >> element;
arr.search(element);
brea
k; case
5:
arr.display
(); break;
case 6:
return
0; default:
std::cout << "Invalid choice. Please try again." << std::endl;
}
}
return 0;
}
Experiment 2
Code
#include
<iostream> using
namespace std;
class Matrix {
private:
int matrix[MAX_SIZE]
[MAX_SIZE]; int rows, cols;
public:
// Constructor to initialize the matrix with
zeros Matrix(int r, int c) {
rows = r;
cols = c;
for (int i = 0; i < r; i+
+) { for (int j = 0; j
< c; j++) {
matrix[i][j] = 0;
}
}
}
if (cols != otherMatrix.rows) {
cout << "Matrix multiplication is not possible. Number of columns
in the first matrix must be equal to the number of rows in the second
matrix." << endl;
return result;
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < otherMatrix.cols;
j++) { for (int k = 0; k < cols;
k++) {
result.matrix[i][j] += matrix[i][k] * otherMatrix.matrix[k][j];
} } }
return result;
}
int main() {
int rows, cols;
cout << "Enter the number of rows and columns for the
first matrix: "; cin >> rows >> cols;
Matrix matrix1(rows,
cols);
matrix1.inputMatrix();
cout << "Enter the number of rows and columns for the second
matrix: "; cin >> rows >> cols;
Matrix matrix2(rows,
cols);
matrix2.inputMatrix();
cout << "Performing Matrix Operations:" <<
endl; Matrix result;
// Matrix Addition
result = matrix1.add(matrix2);
result.displayMatrix();
// Matrix Subtraction
result = matrix1.subtract(matrix2);
result.displayMatrix();
// Matrix Multiplication
result = matrix1.multiply(matrix2);
result.displayMatrix();
// Transpose of Matrix 1
result =
matrix1.transpose();
result.displayMatrix();
return 0;
}
Experiment 3
Code
#include
<iostream>
#include
<string>
#include
<algorithm>
int main() {
std::string str1, str2, reversedStr,
searchString; int wordCount;
// Reverse a string
std::cout << "Enter a string to
reverse: "; std::getline(std::cin,
reversedStr);
std::string reversed = reverseString(reversedStr);
std::cout << "Reversed String: " << reversed <<
std::endl;
return 0;
}
Experiment 4
Code
#include <iostream>
if (targetNode == head) {
Node* newNode =
createNode(data); newNode-
>next = head;
head = newNode;
return;
}
if (current->next == nullptr) {
std::cout << "Target node not found in the list." <<
std::endl; return;
}
Node* newNode =
createNode(data); newNode-
>next = targetNode; current-
>next = newNode;
}
if (current == nullptr) {
std::cout << "Key not found in the list." <<
std::endl; return;
}
prev->next = current-
>next; delete current;
}
while (current !=
nullptr) { next =
current->next;
current->next =
prev; prev =
current;
current = next;
}
head = prev;
}
int main() {
Node* head = nullptr;
// Insertion
head = createNode(10);
insertAfter(head, 20);
insertBefore(head, head->next, 15);
insertAfter(head, 30);
// Traversal
std::cout << "Linked List after Insertions:" << std::endl;
traverse(head);
// Deletion
deleteNode(head, 15);
std::cout << "Linked List after Deletion:" <<
std::endl; traverse(head);
// Reversal
reverseList(head);
std::cout << "Reversed Linked List:" <<
std::endl; traverse(head);
return 0;
}
Experiment 5
Write a C++ program to add two Polynomials Equations using Linked List
Code
#include
<iostream> using
namespace std;
if (poly == nullptr)
{ poly =
newTerm;
} else {
Term* current = poly;
while (current->next !=
nullptr) { current = current-
>next;
}
current->next = newTerm;
}
}
return result;
}
// Function to display a
polynomial void
displayPolynomial(Term* poly) {
if (poly == nullptr)
{ cout << "0" <<
endl; return;
}
int main() {
Term* poly1 = nullptr;
Term* poly2 = nullptr;
// Free memory
freePolynomial(poly1);
freePolynomial(poly2);
freePolynomial(result);
return 0; }
Experiment 6
Code
#include
<iostream> using
namespace std;
if (current->next != nullptr) {
current->next->prev = current->prev;
}
delete
current;
return;
}
current = current->next;
}
}
int main() {
Node* head = nullptr;
// Delete an
element
deleteNode(head,
3);
return 0;
}
Experiment 7
Code
#include
<iostream>
struct Node {
int data;
Node*
next;
Node(int value) : data(value), next(nullptr) {}
};
class CircularLinkedList {
private:
Node*
head; public:
CircularLinkedList() :
head(nullptr) {} void
insertAtBeginning(int value) {
Node* newNode = new
Node(value); if (!head) {
newNode->next = newNode; // Point to itself if the list
is empty head = newNode;
} else {
newNode->next = head-
>next; head->next =
newNode;
}
}
void deleteNode(int
value) { if (!head) {
std::cout << "List is empty. Deletion failed." <<
std::endl; return;
}
Node* current =
head; Node* previous
= nullptr; do {
if (current->data ==
value) { if (previous)
previous->next = current-
>next; else
head = current->next;
delete current;
std::cout << "Node with value " << value << " deleted."
<< std::endl; return; }
previous = current;
current = current-
>next;
} while (current != head);
std::cout << "Node with value " << value << " not found." << std::endl;
}
void
traverse()
{ if (!head)
{
std::cout << "List is empty." <<
std::endl; return;
}
Node* current =
head; do {
std::cout << current->data
<< " "; current = current-
>next;
} while (current !=
head); std::cout <<
std::endl; } };
int main() {
CircularLinkedList
myList;
myList.insertAtBeginning
(1);
myList.insertAtBeginning
(2);
myList.insertAtBeginning
(3);
myList.insertAtBeginning
(4);
Code
#include
<iostream> using
namespace std;
class Stack {
private:
int*
arr;
int
top;
int capacity;
public:
Stack(int size) {
capacity =
size;
arr = new
int[capacity]; top = -
1;
}
~Stack()
{ delete[]
arr;
}
bool isEmpty()
{ return top ==
-1;
}
bool isFull() {
return top == capacity - 1;
}
void push(int
value) { if
(isFull()) {
cout << "Stack is full. Cannot push " << value
<< endl; return;
}
arr[++top] = value;
cout << value << " pushed into the stack." << endl;
}
void pop() {
if (isEmpty()) {
cout << "Stack is empty. Cannot pop."
<< endl; return;
}
cout << arr[top] << " popped from the
stack." << endl; top--;
}
int peek() {
if (isEmpty()) {
cout << "Stack is empty." <<
endl; return -1; // Return a
sentinel value
}
return arr[top];
}
};
int main() {
Stack myStack(5);
myStack.push(
1);
myStack.push(
2);
myStack.push(
3);
myStack.push(
4);
myStack.push(
5);
cout << "Top element after popping: " << myStack.peek() << endl;
return 0;
}
Experiment 9
Code
#include <iostream>
int main()
{ Stack
stack;
stack.push(
1);
stack.push(
2);
stack.push(
3);
stack.display();
std::cout << "Top element: " << stack.peek() << std::endl;
stack.pop();
stack.display();
std::cout << "Top element: " << stack.peek() << std::endl;
return 0; }
Experiment 10
Code
#include <iostream>
public:
Queue() {
front = -1; // Initialize front to -1 (empty
queue) rear = -1; // Initialize rear to -1
(empty queue)
}
if (isEmpty()) {
front = rear = 0; // Initialize front and rear for the first element
} else {
rear = (rear + 1) % MAX_SIZE; // Increment rear with wrap-around
}
arr[rear] = value; // Add the element to the rear
}
if (front == rear) {
front = rear = -1; // Reset front and rear for the last element
} else {
front = (front + 1) % MAX_SIZE; // Increment front with wrap-around
}
}
std::cout <<
"Queue: "; int
current = front;
while (current !=
rear) {
std::cout << arr[current] << " ";
current = (current + 1) % MAX_SIZE; // Move to the next element with wrap-
around
}
std::cout << arr[current] << std::endl;
}
};
int main()
{ Queue
queue;
queue.enqueue(
1);
queue.enqueue(
2);
queue.enqueue(
3);
queue.display();
std::endl; queue.dequeue();
queue.display();
return 0;
}
Experiment 11
Code
#include
<iostream>
#include
<queue>
if (head == nullptr)
{ head =
newNode;
} else {
Node* temp = head;
while (temp->next !=
nullptr) { temp = temp-
>next;
}
temp->next = newNode;
}
}
// Function to remove an element from the beginning of the
linked list void dequeue() {
if (head == nullptr) {
cout << "Linked List is empty. Dequeue operation not possible."
<< endl; return;
}
Node* temp =
head; head =
head->next;
delete temp;
}
private:
Node* head;
};
int main() {
LinkedList
linkedList; int
choice, value;
do {
cout << "1.
Enqueue\n"; cout <<
"2. Dequeue\n"; cout
<< "3. Display\n";
cout << "4. Exit\n";
cout << "Enter your
choice: "; cin >> choice;
switch (choice)
{ case 1:
cout << "Enter value to
enqueue: "; cin >> value;
linkedList.enqueue(value);
break
; case
2:
linkedList.dequeue()
; break;
case 3:
linkedList.display();
break;
case 4:
cout << "Exiting the program.\
n"; break;
default:
cout << "Invalid choice. Please try again.\n";
}
} while (choice != 4);
return 0;
}
Experiment 12
Code
#include
<iostream>
#include
<stack>
#include
<string>
while (!operatorStack.empty()) {
postfix +=
operatorStack.top();
operatorStack.pop();
}
return postfix;
}
int main() {
string infixExpression;
cout << "Enter an infix expression: ";
getline(cin, infixExpression);
string postfixExpression =
infixToPostfix(infixExpression); cout << "Postfix
expression: " << postfixExpression << endl;
return 0;
}
Experiment 13
Code
#include
<iostream>
#include
<stack>
#include
<string>
#include
<cmath>
double
result;
switch (c) {
case '+':
result = operand1 +
operand2; break;
case '-':
result = operand1 -
operand2; break;
case '*':
result = operand1 *
operand2; break;
case '/':
if (operand2 == 0) {
cerr << "Division by zero is not allowed." <<
endl; exit(1);
}
result = operand1 /
operand2; break;
case '^':
result = pow(operand1, operand2);
break;
}
operandStack.push(result);
}
}
if (operandStack.size() != 1) {
cerr << "Invalid postfix expression." <<
endl; exit(1);
}
return operandStack.top();
}
int main() {
string postfixExpression;
cout << "Enter a postfix
expression: "; cin >>
postfixExpression;
double result =
evaluatePostfix(postfixExpression); cout <<
"Result: " << result << endl;
return 0;
}
Experiment 14
Code
#include <iostream>
inorderTraversal(root-
>left); std::cout << root-
>data << " ";
inorderTraversal(root-
>right);
}
int main() {
// Construct a sample binary
tree Node* root = new Node(1);
root->left = new
Node(2); root->right =
new Node(3);
root->left->left = new
Node(4); root->left->right =
new Node(5); root->right-
>left = new Node(6); root-
>right->right = new
Node(7);
// Cleanup: Deallocate memory for the binary tree nodes (not shown in
the code). return 0;
}
Experiment 15
Write a C++ program to implement Binary search tree and perform following operations
a. Searching for a particular node
b. Insertion of a new node
c. Deletion of a particular node
Case1:When node N has no
children Case2:Node N has
exactly one child Case3:Node N
has two children
Code
#include <iostream>
class BinarySearchTree {
public:
BinarySearchTree() : root(nullptr) {}
private:
Node* root;
return node;
}
return node;
}
int main() {
BinarySearchTree
bst;
bst.insert(50);
bst.insert(3
0);
bst.insert(7
0);
bst.insert(2
0);
bst.insert(4
0);
bst.insert(6
0);
bst.insert(8
0);
return 0;
}
Experiment 16
Code
#include
<iostream>
#include
<vector>
if (arr[mid] == target) {
return mid; // Element found, return its index
} else if (arr[mid] < target) {
left = mid + 1; // Continue searching in the right half
} else {
right = mid - 1; // Continue searching in the left half
}
}
int main() {
std::vector<int> sortedArray = {1, 2, 3, 4, 5, 6, 7,
8, 9, 10}; int target = 6;
<< std::endl;
} return 0;}
Experiment 17
Code
#include
<iostream>
#include
<vector>
// Bubble Sort
void bubbleSort(std::vector<int>&
arr) { int n = arr.size();
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1;
j++) { if (arr[j] > arr[j
+ 1]) {
std::swap(arr[j], arr[j + 1]);
}
}
}
}
// Quick Sort
int partition(std::vector<int>& arr, int low,
int high) { int pivot = arr[high];
int i = (low - 1);
// Heap Sort
void heapify(std::vector<int>& arr, int
n, int i) { int largest = i;
int left = 2 * i +
1; int right = 2 *
i + 2;
if (largest != i)
{ std::swap(arr[i],
arr[largest]);
heapify(arr, n, largest);
}
}
void heapSort(std::vector<int>&
arr) { int n = arr.size();
for (int i = n / 2 - 1; i >= 0;
i--) { heapify(arr, n, i);
}
// Insertion Sort
void insertionSort(std::vector<int>&
arr) { int n = arr.size();
for (int i = 1; i < n;
i++) { int key =
arr[i];
int j = i - 1;
while (j >= 0 && arr[j] >
key) { arr[j + 1] =
arr[j];
j--;
}
arr[j + 1] = key;
}
}
// Merge Sort
void merge(std::vector<int>& arr, int left, int middle,
int right) { int n1 = middle - left + 1;
int n2 = right - middle;
std::vector<int>
leftArr(n1);
std::vector<int>
rightArr(n2);
int i = 0, j = 0, k =
j < n2) {
if (leftArr[i] <=
rightArr[j]) { arr[k] =
leftArr[i];
i++;
} else {
arr[k] =
rightArr[j]; j++;
}
k+
+;
}
int main() {
std::vector<int> arr = {64, 34, 25, 12, 22, 11, 90};
// Bubble Sort
std::vector<int> bubbleSorted = arr;
bubbleSort(bubbleSorted);
// Quick Sort
std::vector<int> quickSorted = arr;
quickSort(quickSorted, 0, quickSorted.size() -
1);
// Heap Sort
std::vector<int> heapSorted = arr;
heapSort(heapSorted);
// Insertion Sort
std::vector<int> insertionSorted = arr;
insertionSort(insertionSorted);
// Merge Sort
std::vector<int> mergeSorted = arr;
mergeSort(mergeSorted, 0, mergeSorted.size() - 1);
return 0;
}
Experiment 18
Code
#include
<iostream>
#include
<vector>
#include
<queue>
#include
<stack>
class Graph {
public:
Graph(int vertices) : V(vertices)
{ adj.resize(V);
}
visited[startVertex] =
true;
queue.push(startVerte
x);
while (!queue.empty()) {
int currentVertex =
queue.front(); std::cout <<
currentVertex << " ";
queue.pop();
while (!stack.empty()) {
int currentVertex =
stack.top(); std::cout <<
currentVertex << " ";
stack.pop();
int main() {
Graph graph(6);
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(1, 3);
graph.addEdge(2, 4);
graph.addEdge(2, 5);
return 0;
}
Experiment 19
Write a C++ program to create a file, store information and perform following operation
Code
#include
<iostream>
#include
<fstream>
#include
<string>
#include
<vector>
std::vector<std::string>
lines; std::string line;
int currentLine = 1;
while (std::getline(inputFile,
line)) { if (currentLine !=
lineToDelete) {
lines.push_back(line);
}
currentLine++;
}
inputFile.close();
std::ofstream
outputFile(filename); if (!
outputFile.is_open()) {
std::cerr << "Error: Cannot open file for writing " << filename <<
std::endl; return;
}
for (const std::string& updatedLine :
lines) { outputFile << updatedLine
<< "\n";
}
outputFile.close();
std::cout << "Line " << lineToDelete << " deleted from " << filename <<
std::endl;
}
int lineCount = 0;
std::string line;
file.close();
return lineCount;
}
// Function to append the content of one file at the end of another file
void appendFile(const std::string& sourceFile, const std::string&
destinationFile) { std::ifstream source(sourceFile);
if (!source.is_open()) {
std::cerr << "Error: Cannot open source file " << sourceFile <<
std::endl; return;
}
std::ofstream destination(destinationFile,
std::ios::app); if (!destination.is_open()) {
std::cerr << "Error: Cannot open destination file " << destinationFile <<
std::endl; source.close();
return;
}
std::string line;
source.close();
destination.close();
std::cout << "Content from " << sourceFile << " appended to " <<
destinationFile << std::endl;
}
std::ofstream
destination(destinationFile); if (!
destination.is_open()) {
std::cerr << "Error: Cannot open destination file " << destinationFile <<
std::endl; source.close();
return;
}
source.close();
destination.close();
std::cout << "File " << sourceFile << " copied to " << destinationFile <<
std::endl;
}
int main() {
// Create a sample file with some
content std::ofstream
file("sample.txt");
file << "Line
1\n"; file <<
"Line 2\n"; file
<< "Line 3\n";
file << "Line
4\n";
file.close();
// Delete a specific line from the
file
deleteLineFromFile("sample.txt",
3);
return 0;
}