0% found this document useful (0 votes)
17 views84 pages

DS 19 Experiments

The document outlines a series of C++ programming experiments focused on data structures and algorithms. It includes tasks such as implementing array operations, matrix manipulations, string operations, linked list functionalities, and various sorting and searching algorithms. Each experiment is accompanied by code snippets demonstrating the implementation of the specified operations.

Uploaded by

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

DS 19 Experiments

The document outlines a series of C++ programming experiments focused on data structures and algorithms. It includes tasks such as implementing array operations, matrix manipulations, string operations, linked list functionalities, and various sorting and searching algorithms. Each experiment is accompanied by code snippets demonstrating the implementation of the specified operations.

Uploaded by

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

INDEX

S.No EXPERIMENTS DATE REMARK


.

1 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)

2 Write a C++ program to perform the following


operations on Matrices:
a. Addition
b. Subtraction
c. Multiplication
d. Transpose

3 Write a C++ program to perform following string


operations:
a. Concatenate two strings
b. Reverse a string
c. Find the no. of occurrences of a word in a string
4 Write a C++ program to perform following operations
on a Single Linked List data structure
a. Traversal
b. Insertion
1. Insertion after a particular node
2. Insertion before a particular node
c. Deletion
d. Reversal of a Liked List by revering the links:

5 Write a C++ program to add two Polynomial


Equations using Linked List.

6 Write a C++ program to perform following operations


on a Doubly Linked List
a. Traversal
b. Insertion
c. Deletion

7 Write a C++ program to perform following operations


on a Circular Linked List
a. Traversal
b. Insertion
c. Deletion

8 Write a C++ program to implement Stack using Array.

9 Write a C++ program to implement Stack using


Linked List.
10 Write a C++ program to implement Queue using
Array.
11 Write a C++ program to implement Linked List using
Queue
12 Write a C++ program for conversion of infix
expression to Postfix expression.

13 Write a C++ program for evaluation of Postfix


Expression.
14 Implement Binary tree traversal algorithms -Inorder,
preorder & postorder

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 N
Case 1: when node N has no
children Case 2: Node N has
exactly one child Case 3: Node N
has two children
16 Write a C++ program to implement Binary Search.

17 Write a C++ program to implement


a. Bubble Sort
b. Quick Sort
c. Heap Sort d. Insertion Sort
e. Merge Sort

18 Implement Graph traversal algorithms - BFS & DFS

19 Write a C++ program to create a file, store


information and perform following operation
a. Delete a specific line from a text file
b. Find the number of lines in a text file
c. Append the content of file at the end of another file
d. Copy file in to another file
Experiment 1

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;
}
}

void remove(int element) {


int index = -1;
for (int i = 0; i < size;
i++) { if (arr[i] ==
element) {
index =
i; break;
}
}

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;
}

void search(int element)


{ for (int i = 0; i <
size; i++) {
if (arr[i] == element) {
std::cout << "Element " << element << " found at index " << i << "."
<<
std::end
l; return;

}
}
std::cout << "Element " << element << " not found in the array." <<
std::endl;
}

void display()
{ if (size
== 0) {
std::cout << "Array is empty." <<
std::endl; return;
}

std::cout << "Array


elements: "; for (int i = 0; i
< size; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
}
};

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

Write a C++ program to perform following operations on Matrices


a. Addition
b. Subtraction
c. Multiplication
d. Transpose

Code
#include

<iostream> using

namespace std;

const int MAX_SIZE = 100;

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;
}
}
}

// Function to input values into the


matrix void inputMatrix() {
cout << "Enter matrix elements:"
<< endl; for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols;
j++) { cin >>
matrix[i][j];
}
}
}

// Function to display the


matrix void displayMatrix() {
cout << "Matrix:" <<
endl; for (int i = 0; i <
rows; i++) {
for (int j = 0; j < cols;
j++) { cout <<
matrix[i][j] << " ";
}
cout << endl;
}
}

// Function to add two


matrices Matrix add(Matrix
otherMatrix) {
Matrix result(rows, cols);

if (rows != otherMatrix.rows || cols != otherMatrix.cols) {


cout << "Matrix addition is not possible. Matrices must have the
same dimensions." << endl;
return result;
}

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


+) { for (int j = 0; j <
cols; j++) {
result.matrix[i][j] = matrix[i][j] + otherMatrix.matrix[i][j];
} }
return result; }

// Function to subtract two


matrices Matrix subtract(Matrix
otherMatrix) {
Matrix result(rows, cols);

if (rows != otherMatrix.rows || cols != otherMatrix.cols) {


cout << "Matrix subtraction is not possible. Matrices must have
the same dimensions." << endl;
return result;
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result.matrix[i][j] = matrix[i][j] - otherMatrix.matrix[i][j];
}
}
return result; }

// Function to multiply two matrices


Matrix multiply(Matrix
otherMatrix) {
Matrix result(rows, otherMatrix.cols);

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;
}

// Function to transpose the


matrix Matrix transpose() {
Matrix result(cols, rows);

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


+) { for (int j = 0; j <
cols; j++) {
result.matrix[j][i] = matrix[i][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

Write a C++ program to perform following string


operations a Concatenate two strings
b. Reverse a string
c. Find the no. of occurrences of a word in a string

Code
#include
<iostream>
#include
<string>
#include
<algorithm>

// Function to concatenate two strings


std::string concatenateStrings(const std::string& str1, const std::string&
str2) { return str1 + str2;
}

// Function to reverse a string


std::string reverseString(const std::string&
str) { std::string reversed = str;
std::reverse(reversed.begin(),
reversed.end()); return reversed;
}

// Function to find the number of occurrences of a word in a string


int countWordOccurrences(const std::string& inputString, const
std::string& word) { int count = 0;
size_t pos = 0;
while ((pos = inputString.find(word, pos)) !=
std::string::npos) { count++;
pos += word.length();
}
return count;
}

int main() {
std::string str1, str2, reversedStr,
searchString; int wordCount;

// Concatenate two strings


std::cout << "Enter the first string:
"; std::getline(std::cin, str1);
std::cout << "Enter the second
string: "; std::getline(std::cin, str2);
std::string concatenatedStr = concatenateStrings(str1, str2);
std::cout << "Concatenated String: " << concatenatedStr << std::endl;

// 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;

// Find the number of occurrences of a word in


a string std::cout << "Enter a string to search
in: "; std::getline(std::cin, searchString);
std::cout << "Enter the word to
find: "; std::cin >> searchString;
wordCount = countWordOccurrences(searchString, searchString);
std::cout << "Occurrences of '" << searchString << "': " << wordCount <<
std::endl;

return 0;
}
Experiment 4

Write a C++ program to perform following operations on a Single Linked


List data structure
a. Traversal
b. Insertion
1. Insertion after a particular node
2. Insertion before a particular node
c. Deletion
d. Reversal of a Liked List by revering the links

Code
#include <iostream>

// Define a Node structure for the


linked list struct Node {
int data;
Node*
next;
};

// Function to create a new


node Node* createNode(int
data) {
Node* newNode = new
Node; newNode->data =
data; newNode->next =
nullptr; return newNode;
}

// Function to traverse the linked list and print its


elements void traverse(Node* head) {
Node* current =
head; while (current !
= nullptr) {
std::cout << current->data << "
"; current = current->next;
}
std::cout << std::endl;
}

// Function to insert a node after a particular node


void insertAfter(Node* prevNode, int
data) { if (prevNode == nullptr) {
std::cout << "Previous node cannot be null." <<
std::endl; return;
}
Node* newNode =
createNode(data); newNode-
>next = prevNode->next;
prevNode->next = newNode;
}

// Function to insert a node before a particular node


void insertBefore(Node*& head, Node* targetNode, int
data) { if (head == nullptr || targetNode ==
nullptr) {
std::cout << "Head or target node cannot be null." <<
std::endl; return;
}

if (targetNode == head) {
Node* newNode =
createNode(data); newNode-
>next = head;
head = newNode;
return;
}

Node* current = head;


while (current->next != nullptr && current->next !=
targetNode) { current = current->next;
}

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;
}

// Function to delete a node with a specific value


void deleteNode(Node*& head, int
key) { Node* current = head;
Node* prev = nullptr;

// If the key is found at the head


if (current != nullptr && current->data ==
key) { head = current->next;
delete
current;
return;
}

while (current != nullptr && current->data !


= key) { prev = current;
current = current->next;
}

if (current == nullptr) {
std::cout << "Key not found in the list." <<
std::endl; return;
}

prev->next = current-
>next; delete current;
}

// Function to reverse the linked


list void reverseList(Node*&
head) {
Node* prev =
nullptr;
Node* current =
head;
Node* next =
nullptr;

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;

// Define a structure for a term in the


polynomial struct Term {
int
coefficient;
int
exponent;
Term* next;

Term(int coeff, int exp) : coefficient(coeff), exponent(exp), next(nullptr) {}


};

// Function to add a term to a polynomial represented as a


linked list void addTerm(Term*& poly, int coeff, int exp) {
Term* newTerm = new Term(coeff, exp);

if (poly == nullptr)
{ poly =
newTerm;
} else {
Term* current = poly;
while (current->next !=
nullptr) { current = current-
>next;
}
current->next = newTerm;
}
}

// Function to add two polynomials and store the result in a new


polynomial Term* addPolynomials(Term* poly1, Term* poly2) {
Term* result = nullptr;
Term* current1 =
poly1; Term* current2
= poly2;

while (current1 != nullptr && current2 !=


nullptr) { if (current1->exponent >
current2->exponent) {
addTerm(result, current1->coefficient, current1-
>exponent); current1 = current1->next;
} else if (current1->exponent < current2->exponent) {
addTerm(result, current2->coefficient, current2-
>exponent); current2 = current2->next;
} else {
int sum_coeff = current1->coefficient + current2-
>coefficient; if (sum_coeff != 0) {
addTerm(result, sum_coeff, current1->exponent);
}
current1 = current1-
>next; current2 =
current2->next;
}
}

// Add any remaining terms from poly1 or


poly2 while (current1 != nullptr) {
addTerm(result, current1->coefficient, current1-
>exponent); current1 = current1->next;
}

while (current2 != nullptr) {


addTerm(result, current2->coefficient, current2-
>exponent); current2 = current2->next;
}

return result;
}

// Function to display a
polynomial void
displayPolynomial(Term* poly) {
if (poly == nullptr)
{ cout << "0" <<
endl; return;
}

while (poly != nullptr) {


cout << poly-
>coefficient; if (poly-
>exponent > 0) {
cout << "x";
if (poly->exponent > 1) {
cout << "^" << poly->exponent;
} }
poly = poly-
>next; if (poly !
= nullptr) {
cout << " + ";
}
} cout << endl; }
// Function to free memory allocated for a
polynomial void freePolynomial(Term* poly) {
while (poly !=
nullptr) { Term*
temp = poly;
poly = poly-
>next; delete
temp; }}

int main() {
Term* poly1 = nullptr;
Term* poly2 = nullptr;

// Add terms to the first polynomial: 3x^2 + 2x^1


+ 1x^0 addTerm(poly1, 3, 2);
addTerm(poly1, 2, 1);
addTerm(poly1, 1, 0);

// Add terms to the second polynomial: 4x^3 +


2x^1 + 5x^0 addTerm(poly2, 4, 3);
addTerm(poly2, 2, 1);
addTerm(poly2, 5, 0);

cout << "First polynomial:


";
displayPolynomial(poly1);

cout << "Second


polynomial: ";
displayPolynomial(poly2);

Term* result = addPolynomials(poly1, poly2);

cout << "Sum of


polynomials: ";
displayPolynomial(result);

// Free memory
freePolynomial(poly1);
freePolynomial(poly2);
freePolynomial(result);

return 0; }
Experiment 6

Write a C++ program to perform following operations on a Double Linked List


a. Traversal
b. Insertion
c. Deletion

Code
#include
<iostream> using
namespace std;

// Define a structure for a node in the doubly


linked list struct Node {
int data;
Node*
prev;
Node*
next;
};

// Function to create a new


node Node* createNode(int
value) {
Node* newNode = new
Node; newNode->data =
value; newNode->prev =
nullptr; newNode->next =
nullptr; return newNode;
}

// Function to insert a node at the beginning of


the list void insertAtBeginning(Node*& head,
int value) {
Node* newNode =
createNode(value); if (head ==
nullptr) {
head = newNode;
} else {
newNode->next =
head; head->prev =
newNode; head =
newNode;
}
}
// Function to insert a node at the end of
the list void insertAtEnd(Node*& head, int
value) {
Node* newNode =
createNode(value); if (head ==
nullptr) {
head = newNode;
} else {
Node* current = head;
while (current->next !=
nullptr) { current = current-
>next;
}
current->next =
newNode; newNode-
>prev = current;
}
}

// Function to delete a node with a given value


from the list void deleteNode(Node*& head, int
value) {
if (head ==
nullptr) { return;
}

Node* current = head;


while (current !=
nullptr) {
if (current->data == value) {
if (current->prev != nullptr) {
current->prev->next = current->next;
} else {
head = current->next;
}

if (current->next != nullptr) {
current->next->prev = current->prev;
}

delete
current;
return;
}
current = current->next;
}
}

// Function to display the elements of


the list void displayList(Node* head) {
Node* current = head;
while (current !=
nullptr) {
cout << current->data
<< " "; current =
current->next;
}
cout << endl;
}

int main() {
Node* head = nullptr;

// Insert elements at the beginning


insertAtBeginning(head, 3);
insertAtBeginning(head, 2);
insertAtBeginning(head, 1);

// Display the list


cout << "List after insertions at the
beginning: "; displayList(head);

// Insert elements at the


end insertAtEnd(head, 4);
insertAtEnd(head, 5);

// Display the list


cout << "List after insertions at the
end: "; displayList(head);

// Delete an
element
deleteNode(head,
3);

// Display the list after


deletion cout << "List after
deletion of 3: ";
displayList(head);

return 0;
}
Experiment 7

Write a C++ program to perform following operations on a Circular Linked List


a. Traversal
b. Insertion
c. Deletion

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);

std::cout << "Circular Linked


List: "; myList.traverse();
myList.deleteNode(3);
myList.deleteNode(5);
std::cout << "Updated Circular Linked
List: "; myList.traverse();
return 0;
}
Experiment 8

Write a C++ program to implement stack using Array.

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: " << myStack.peek()

<< endl; myStack.pop();


myStack.pop();

cout << "Top element after popping: " << myStack.peek() << endl;

return 0;
}
Experiment 9

Write a C++ program to implement Stack using Linked List.

Code
#include <iostream>

// Define a Node structure for the


linked list struct Node {
int data;
Node*
next;
};

// Define a Stack class using a linked


list class Stack {
private:
Node* top; // Pointer to the top of the
stack public:
Stack() {
top = nullptr; // Initialize the top pointer to nullptr (empty stack)
}

// Function to push an element onto the


stack void push(int value) {
// Create a new node
Node* newNode = new
Node; newNode->data =
value;
newNode->next = top; // Set the new node's next pointer to the
current top top = newNode; // Update the top pointer to the new
node }

// Function to pop an element from the


stack void pop() {
if (isEmpty()) {
std::cout << "Stack is empty. Cannot pop." <<
std::endl; return; }

Node* temp = top; // Store the current top node in a temporary


variable top = top->next; // Update the top pointer to the next
node
delete temp; // Delete the old top node }

// Function to check if the stack is


empty bool isEmpty() {
return top == nullptr; }
// Function to get the top element of
the stack int peek() {
if (isEmpty()) {
std::cout << "Stack is empty. Cannot peek." <<
std::endl; return -1; // Return a sentinel value }
return top->data; }

// Function to display the elements of the


stack void display() {
if (isEmpty()) {
std::cout << "Stack is empty." <<
std::endl; return; }

Node* current = top;


std::cout << "Stack:
"; while (current !=
nullptr) {
std::cout << current->data
<< " "; current = current-
>next; }
std::cout << std::endl; } };

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

Write a C++ program to implement Queue using Array.

Code
#include <iostream>

const int MAX_SIZE = 100; // Maximum size of the

queue class Queue {


private:
int front; // Index of the front
element int rear; // Index of the
rear element
int arr[MAX_SIZE]; // Array to store the queue elements

public:
Queue() {
front = -1; // Initialize front to -1 (empty
queue) rear = -1; // Initialize rear to -1
(empty queue)
}

// Function to check if the queue is


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

// Function to check if the queue is


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

// Function to enqueue (insert) an element into the


queue void enqueue(int value) {
if (isFull()) {
std::cout << "Queue is full. Cannot enqueue." <<
std::endl; return;
}

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
}

// Function to dequeue (remove) an element from the


queue void dequeue() {
if (isEmpty()) {
std::cout << "Queue is empty. Cannot dequeue." <<
std::endl; return;
}

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
}
}

// Function to get the front element of the


queue int getFront() {
if (isEmpty()) {
std::cout << "Queue is empty. Cannot get front." <<
std::endl; return -1; // Return a sentinel value
}
return arr[front];
}

// Function to display the elements of the


queue void display() {
if (isEmpty()) {
std::cout << "Queue is empty." <<
std::endl; return;
}

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::cout << "Front element: " << queue.getFront() <<

std::endl; queue.dequeue();
queue.display();

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

return 0;
}
Experiment 11

Write a C++ program to implement Linked List using Queue

Code
#include
<iostream>
#include
<queue>

using namespace std;

// Structure for a node in the linked


list struct Node {
int data;
Node*
next;
};

// Linked List class


class LinkedList {
public:
LinkedList()
{ head =
nullptr;
}

// Function to add an element to the end of the


linked list void enqueue(int value) {
Node* newNode = new
Node; newNode->data =
value; newNode->next =
nullptr;

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;
}

// Function to display the linked


list void display() {
Node* temp = head;
cout << "Linked List:
"; while (temp !=
nullptr) {
cout << temp->data
<< " "; temp = temp-
>next;
}
cout << endl;
}

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

Write a C++ program for conversion of infix expression to Postfix expression.

Code
#include
<iostream>
#include
<stack>
#include
<string>

using namespace std;

// Function to check if the character is an


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

// Function to check if the character is an operand (letter


or digit) bool isOperand(char c) {
return (isalpha(c) || isdigit(c));
}

// Function to return the precedence of an


operator int getPrecedence(char c) {
if (c == '+' || c ==
'-') return 1;
else if (c == '*' || c ==
'/') return 2;
return 0;
}

// Function to convert infix expression to postfix


expression string infixToPostfix(const string& infix) {
stack<char>
operatorStack; string
postfix = "";

for (char c : infix) {


if (isOperand(c))
{ postfix +=
c;
} else if (c == '(') {
operatorStack.push(c);
} else if (c == ')') {
while (!operatorStack.empty() && operatorStack.top() !
= '(') { postfix += operatorStack.top();
operatorStack.pop();
}
operatorStack.pop(); // Remove the '('
} else if (isOperator(c)) {
while (!operatorStack.empty() && getPrecedence(operatorStack.top())
>= getPrecedence(c)) {
postfix += operatorStack.top();
operatorStack.pop();
}
operatorStack.push(c);
}
}

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

Write a C++ program for evaluation of Postfix Expression.

Code
#include
<iostream>
#include
<stack>
#include
<string>
#include
<cmath>

using namespace std;

// Function to check if the character is an


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

// Function to evaluate a postfix


expression double evaluatePostfix(const
string& postfix) {
stack<double> operandStack;

for (char c : postfix) {


if (isdigit(c) || (c == '.')) {
operandStack.push(stod(string(1, c))); // Convert the character to a double and push it
onto the
stack
} else if (isOperator(c)) {
if (operandStack.size() < 2) {
cerr << "Invalid postfix expression." <<
endl; exit(1);
}
double operand2 =
operandStack.top();
operandStack.pop();
double operand1 =
operandStack.top();
operandStack.pop();

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

Implement binary tree traversal algorithms- Inorder,preorder and postorder

Code
#include <iostream>

// Binary Tree Node


Definition struct Node {
int data;
Node*
left;
Node*
right;

Node(int value) : data(value), left(nullptr), right(nullptr) {}


};

// Inorder Traversal (Left, Root,


Right) void inorderTraversal(Node*
root) {
if (root == nullptr)
{ return;
}

inorderTraversal(root-
>left); std::cout << root-
>data << " ";
inorderTraversal(root-
>right);
}

// Preorder Traversal (Root, Left,


Right) void
preorderTraversal(Node* root) {
if (root == nullptr)
{ return;
}

std::cout << root->data


<< " ";
preorderTraversal(root-
>left);
preorderTraversal(root-
>right);
}
// Postorder Traversal (Left, Right,
Root) void postorderTraversal(Node*
root) {
if (root == nullptr)
{ return;
}
postorderTraversal(root-
>left);
postorderTraversal(root-
>right); std::cout << root-
>data << " ";
}

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);

std::cout << "Inorder Traversal: ";


inorderTraversal(root);
std::cout << std::endl;

std::cout << "Preorder Traversal: ";


preorderTraversal(root);
std::cout << std::endl;

std::cout << "Postorder Traversal: ";


postorderTraversal(root);
std::cout << std::endl;

// 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>

// Binary Search Tree Node


Definition struct Node {
int data;
Node*
left;
Node*
right;

Node(int value) : data(value), left(nullptr), right(nullptr) {}


};

class BinarySearchTree {
public:
BinarySearchTree() : root(nullptr) {}

// Search for a node with a given


value bool search(int value) {
return searchNode(root, value);
}

// Insert a new node with a given


value void insert(int value) {
root = insertNode(root, value);
}

// Delete a node with a given


value void remove(int value) {
root = deleteNode(root, value);
}

// Inorder traversal to print the


BST void inorderTraversal() {
inorder(root);
std::cout <<
std::endl;
}

private:
Node* root;

// Helper function for searching a


node bool searchNode(Node* node,
int value) {
if (node == nullptr)
{ return false;
}
if (node->data ==
value) { return true;
} else if (value < node->data) {
return searchNode(node->left, value);
} else {
return searchNode(node->right, value);
}
}

// Helper function for inserting a


node Node* insertNode(Node* node,
int value) {
if (node == nullptr) {
return new Node(value);
}

if (value < node->data) {


node->left = insertNode(node->left, value);
} else if (value > node->data) {
node->right = insertNode(node->right, value);
}

return node;
}

// Helper function for finding the minimum node in a


subtree Node* findMinNode(Node* node) {
while (node->left !=
nullptr) { node =
node->left;
}
return node;
}
// Helper function for deleting a node
Node* deleteNode(Node* node, int
value) {
if (node == nullptr)
{ return node;
}

if (value < node->data) {


node->left = deleteNode(node->left, value);
} else if (value > node->data) {
node->right = deleteNode(node->right, value);
} else {
if (node->left == nullptr)
{ Node* temp = node-
>right; delete node;
return temp;
} else if (node->right ==
nullptr) { Node* temp =
node->left; delete node;
return temp;
}

Node* temp = findMinNode(node-


>right); node->data = temp->data;
node->right = deleteNode(node->right, temp->data);
}

return node;
}

// Helper function for inorder


traversal void inorder(Node*
node) {
if (node == nullptr)
{ return;
}
inorder(node->left);
std::cout << node->data
<< " "; inorder(node-
>right);
}
};

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);

std::cout << "Inorder Traversal: ";


bst.inorderTraversal();

int valueToSearch = 40;


std::cout << "Search for value " << valueToSearch << ": " <<
(bst.search(valueToSearch) ? "Found" : "Not Found") << std::endl;

int valueToDelete = 30;


bst.remove(valueToDelete)
;
std::cout << "Inorder Traversal after deleting " << valueToDelete << ": ";
bst.inorderTraversal();

return 0;
}
Experiment 16

Write a C++ program to implement binary search

Code
#include
<iostream>
#include
<vector>

// Binary Search function


int binarySearch(const std::vector<int>& arr, int
target) { int left = 0;
int right = arr.size() - 1;

while (left <= right) {


int mid = left + (right - left) / 2;

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
}
}

return -1; // Element not found


}

int main() {
std::vector<int> sortedArray = {1, 2, 3, 4, 5, 6, 7,
8, 9, 10}; int target = 6;

int result = binarySearch(sortedArray,

target); if (result != -1) {


std::cout << "Element " << target << " found at index " << result << std::endl;
} else {
std::cout << "Element " << target << " not found in the array."

<< std::endl;

} return 0;}
Experiment 17

Write a C++ Program to implement


a. Bubble sort
b. Quick sort
c. Heap sort
d. Insertion sort
e. Merge sort

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);

for (int j = low; j <= high - 1;


j++) { if (arr[j] < pivot) {
i++;
std::swap(arr[i], arr[j]);
}
}
std::swap(arr[i + 1],
arr[high]); return (i + 1);
}

void quickSort(std::vector<int>& arr, int low,


int high) { if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}

// 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 (left < n && arr[left] >


arr[largest]) { largest = left;
}

if (right < n && arr[right] >


arr[largest]) { largest = right;
}

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);
}

for (int i = n - 1; i >= 0; i--) {


std::swap(arr[0],
arr[i]); heapify(arr,
i, 0);
}
}

// 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);

for (int i = 0; i < n1; i++)


{ leftArr[i] = arr[left +
i];
}

for (int i = 0; i < n2; i++)


{ rightArr[i] = arr[middle
+ 1 + i];
}

int i = 0, j = 0, k =

left; while (i < n1 &&

j < n2) {
if (leftArr[i] <=
rightArr[j]) { arr[k] =
leftArr[i];
i++;
} else {
arr[k] =
rightArr[j]; j++;
}
k+
+;
}

while (i < n1)


{ arr[k] =
leftArr[i]; i++;
k++;
}
while (j < n2) {
arr[k] =
rightArr[j]; j+
+;
k++;
}
}

void mergeSort(std::vector<int>& arr, int left,


int right) { if (left < right) {
int middle = left + (right - left)
/ 2; mergeSort(arr, left,
middle); mergeSort(arr,
middle + 1, right); merge(arr,
left, middle, right);
}
}

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);

std::cout << "Bubble


Sort: "; for (int num :
bubbleSorted)
{ std::cout << num << "
";
}
std::cout << std::endl;

std::cout << "Quick


Sort: "; for (int num :
quickSorted) {
std::cout << num << " ";
}
std::cout << std::endl;

std::cout << "Heap


Sort: "; for (int num :
heapSorted) {
std::cout << num << " ";
}
std::cout << std::endl;

std::cout << "Insertion


Sort: "; for (int num :
insertionSorted) {
std::cout << num << " ";
}
std::cout << std::endl;

std::cout << "Merge


Sort: "; for (int num :
mergeSorted) {
std::cout << num << " ";
}
std::cout << std::endl;

return 0;
}
Experiment 18

Implement graph traversal algorithms- BFS and DFS

Code
#include
<iostream>
#include
<vector>
#include
<queue>
#include
<stack>

class Graph {
public:
Graph(int vertices) : V(vertices)
{ adj.resize(V);
}

void addEdge(int u, int v)


{ adj[u].push_back(v);
}

void BFS(int startVertex)


{ std::vector<bool>
visited(V, false);
std::queue<int> queue;

visited[startVertex] =
true;
queue.push(startVerte
x);

while (!queue.empty()) {
int currentVertex =
queue.front(); std::cout <<
currentVertex << " ";
queue.pop();

for (int neighbor :


adj[currentVertex]) { if (!
visited[neighbor]) {
visited[neighbor] = true;
queue.push(neighbor);
}
}
}
}

void DFS(int startVertex)


{ std::vector<bool>
visited(V, false);
std::stack<int> stack;
visited[startVertex] =
true;
stack.push(startVertex);

while (!stack.empty()) {
int currentVertex =
stack.top(); std::cout <<
currentVertex << " ";
stack.pop();

for (int neighbor :


adj[currentVertex]) { if (!
visited[neighbor]) {
visited[neighbor] = true;
stack.push(neighbor);
privat } } }}
e:
int V;
std::vector<std::vector<int
>> adj;
};

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);

std::cout << "BFS starting from vertex


0: "; graph.BFS(0);
std::cout << std::endl;

std::cout << "DFS starting from vertex


0: "; graph.DFS(0);
std::cout << std::endl;

return 0;
}
Experiment 19

Write a C++ program to create a file, store information and perform following operation

a. Delete a specific line from a text file


b. Find the number of lines in a text file
c. Append the content of file at the end of another file
d. Copy file in to another file

Code
#include
<iostream>
#include
<fstream>
#include
<string>
#include
<vector>

// Function to delete a specific line from a text file


void deleteLineFromFile(const std::string& filename, int lineToDelete)
{ std::ifstream inputFile(filename);
if (!inputFile.is_open()) {
std::cerr << "Error: Cannot open file " << filename
<< std::endl; return;
}

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;
}

// Function to find the number of lines in a


text file int countLinesInFile(const
std::string& filename) {
std::ifstream
file(filename); if (!
file.is_open()) {
std::cerr << "Error: Cannot open file " << filename <<
std::endl; return -1;
}

int lineCount = 0;
std::string line;

while (std::getline(file, line)) {


lineCount++;
}

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;

while (std::getline(source, line))


{ destination << line << "\n";
}

source.close();
destination.close();

std::cout << "Content from " << sourceFile << " appended to " <<
destinationFile << std::endl;
}

// Function to copy the contents of one file into another file


void copyFile(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); if (!
destination.is_open()) {
std::cerr << "Error: Cannot open destination file " << destinationFile <<
std::endl; source.close();
return;
}

destination << source.rdbuf();

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);

// Find the number of lines in the file


int lineCount =
countLinesInFile("sample.txt"); if
(lineCount != -1) {
std::cout << "Number of lines in the file: " << lineCount << std::endl;
}

// Append the content of one file at the end of another file


appendFile("sample.txt", "append.txt");

// Copy the contents of one file into another file


copyFile("sample.txt", "copy.txt");

return 0;
}

You might also like