0% found this document useful (0 votes)
2 views42 pages

DS File Layout

The document outlines a practical assignment for BCA-II students at Shri Shankaracharya Institute of Professional Studies, focusing on data structures using C++. It includes a series of programming tasks such as matrix operations, linked list manipulations, stack and queue implementations, and tree traversals, each accompanied by example code. The assignment aims to enhance students' understanding of data structures through hands-on coding experience.

Uploaded by

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

DS File Layout

The document outlines a practical assignment for BCA-II students at Shri Shankaracharya Institute of Professional Studies, focusing on data structures using C++. It includes a series of programming tasks such as matrix operations, linked list manipulations, stack and queue implementations, and tree traversals, each accompanied by example code. The assignment aims to enhance students' understanding of data structures through hands-on coding experience.

Uploaded by

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

SHRI SHANKARACHARYA INSTITUTE

OF PROFESSIONAL STUDIES,
RAIPUR

ACADEMIC YEAR 2025-26


A

PRACTICAL ON

“ DATA STRUCTURE USING C++ ”

(CASC-06T)

BCA-II

GUIDED BY: SUBMITTED BY:


[Link] Verma
H.O.D OF BCA BCA 2th Semester
SSIPS, RAIPUR (C.G)
INDEX
PAGE REMARKS /
S NO. EXPERIMENTS
NO. SIGNATURE
Write a program to create a square matrix, fill the data inside and print the
1
diagonal elements.
2 Write a program to perform addition and subtraction on two matrices.
3 Write a program to perform multiplication on two matrices.
Write a program to perform insertion, deletion of nodes from the end in
4
singly linked list.
Write a program to perform insertion and deletion of nodes from the end
5
in circular doubly linked list.
Write a program to perform push and pop operations in stack, where stack
6
should be created using array.
Write a program to perform push and pop operation in stack, where stack
7
should be created linked list.
8 Write a program to calculate factorial of given number using stack.
Write a program to perform insertion and deletion of data items in queue.
9
Queue should be implemented by using a linked list.
Write a program to perform insertion and deletion of data items in queue,
10
queue should be implemented by using arrays.
11 Write a program to demonstrate functioning of a double ended queue.
Write a program to read the postfix arithmetic expression and evaluate its
12
value using the stack.
Write a program to show how to handle the overflow and underflow
13
situation in stack.
Write a program to convert infix notation-based expression into the postfix
14
notation-based expression using the stack.
Write a program to implement the concept of priority-based element
15
Traversing using priority queue.
Write a program to create binary search tree using the concept of linked
16
list and array, suppose data set will be given at the run time.
Write a program to create a binary tree with any data set and traverse the
17
data items in pre-order, in-order and post-order manner using recursion.
Write a program to perform deletion of any data item from the binary
18
search tree.
19 Write a program to find the height of any tree.
Write a program to create any given undirected graph using the adjacency
20
matrix, and print each node/element with list of its adjacent elements.
Write a program to traverse the element of given graph according BFS and
21
DFS.
22 Write a program to find the minimum spanning tree of any given graph.
Write a program to search any run time given element from the array of 10
23
Elements in the array are unsorted.
24 Write a program to demonstrate the binary search.
25 Write a program to find the smallest and largest element in any array.
26 Write a program to arrange the data items of any array in ascending order.
Write a program to arrange the data items of any array in descending order
27
using quick sort.
Programs
[Link] a program to create the square a matrix , fill the data inside and print the diagonal elements.

#include <iostream>

using namespace std;

int main() {

int n;

// Prompt user for the size of the matrix

cout << "Enter the size of the square matrix: ";

cin >> n;

// Declare a 2D array (matrix)

int matrix[n][n];

// Fill the matrix with data

cout << "Enter the elements of the matrix:" << endl;

for (int i = 0; i < n; ++i) {

for (int j = 0; j < n; ++j) {

cin >> matrix[i][j];

} }

// Print the diagonal elements

cout << “The diagonal elements are: “;

for (int i = 0; i < n; ++i) {

cout << matrix[i][i] << “ “; }

cout << endl;

return 0;

Output
Programs
Q2. Write a program to perform addition and subtraction on two matrices.

#include<iostream>

using namespace std;

int main()

int i,j,a[10][10],b[10][10],c[10][10],d[10][10],n,m;

cout<<"\nEnter the Number of Rows and Columns of Matrix A and B:";

cin>>n>>m;

cout<<"Enter the Elements of Matrix A: ";

for(i=0; i<n;i++)

for(j=0;j<m;j++)

cin>>a[i][j];

cout<<"Enter the Elements of Matrix B: ";

for(i=0; i<n; i++)

for(j=0;j<m;j++ )

cin>>b[i][j];

for(i=0; i<n; i++)

for(j=0;j<m ;j++)

c[i][j]=a[i][j]+b[i][j];

d[i][j]=a[i][j]-b[i][j];

cout<<"\nThe Resultant Matrix C=A+B is :\n";

for(i=0; i<n; i++)

{
Programs
for(j=0; j<m; j++ )

cout<<c[i][j]<<" ";

cout<<"\n";

cout<<"\n The Resultant Matrix D=A-B is : \n";

for(i=0; i<n; i++)

for (j=0; j<m; j++ )

cout<<d[i][j]<<" ";

cout<<"\n";

return 0;

Output
Programs
Q3. Write a program to perform multiplication on two matrices.

#include <iostream>

using namespace std;

int main() {

int r1, c1, r2, c2;

cout << "Enter size of matrix A (rows cols): ";

cin >> r1 >> c1;

cout << "Enter size of matrix B (rows cols): ";

cin >> r2 >> c2;

if (c1 != r2) {

cout << "Matrix multiplication not possible!";

return 0; }

int A[r1][c1], B[r2][c2], C[r1][c2] = {};

cout << "Enter elements of matrix A:\n";

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

for (int j = 0; j < c1; cin >> A[i][j++]);

cout << "Enter elements of matrix B:\n";

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

for (int j = 0; j < c2; cin >> B[i][j++]);

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

for (int j = 0; j < c2; j++)

for (int k = 0; k < c1; k++)

C[i][j] += A[i][k] * B[k][j];

cout << "Result matrix:\n";

for (int i = 0; i < r1; i++, cout << endl)

for (int j = 0; j < c2; cout << C[i][j++] << " ");

return 0;

} Output
Programs
Q4. Write a program to perform insertion , deletion of nodes from the end in singly linked list.

#include <iostream>

using namespace std;

struct Node {

int data;

Node* next;

};

Node* head = nullptr;

// Insert at end

void insertEnd(int value) {

Node* newNode = new Node{value, nullptr};

if (!head)

head = newNode;

else {

Node* temp = head;

while (temp->next)

temp = temp->next;

temp->next = newNode;

// Delete from end

void deleteEnd() {

if (!head) {

cout << “List is empty.\n”;

return;

if (!head->next) {

delete head;

head = nullptr

return;

Node* temp = head;

while (temp->next->next)

temp = temp->next;

delete temp->next;
Programs
temp->next = nullptr;

// Display list

void display() {

Node* temp = head;

while (temp) {

cout << temp->data << “ -> “;

temp = temp->next;

cout << “NULL\n”;

int main() {

insertEnd(5);

insertEnd(10);

insertEnd(15);

display();

deleteEnd();

display();

return 0;

Output
Programs
Q5. Write a program to perform insertion and deletion of nodes from the end in circular doubly linked list.

#include <iostream>

using namespace std;

struct Node {

int data;

Node* next;

Node* prev; };

class CircularDoublyLinkedList {

public:

CircularDoublyLinkedList() : head(nullptr) {}

void insertAtEnd(int value) {

Node* newNode = new Node();

newNode->data = value;

if (!head) {

head = newNode;

head->next = head;

head->prev = head;

} else {

Node* tail = head->prev;

tail->next = newNode;

newNode->prev = tail;

newNode->next = head;

head->prev = newNode;

} }

void deleteFromEnd() {

if (!head) {

std::cout << “List is empty.\n”;

return; }

Node* tail = head->prev;

if (head == tail) {

delete head;

head = nullptr;

} else {

Node* newTail = tail->prev;


Programs
newTail->next = head;

head->prev = newTail;

delete tail;

} }

void display() {

if (!head) {

std::cout << “List is empty.\n”;

return; }

Node* temp = head;

do {

std::cout << temp->data << “ “;

temp = temp->next;

} while (temp != head);

std::cout << “\n”; }

private:

Node* head;

}; int main() {

CircularDoublyLinkedList list;

[Link](10);

[Link](20);

[Link](30);

[Link]();

[Link]();

[Link]();

[Link]();

[Link]();

[Link]();

[Link]();

return 0;

Output
Programs
Q6. Write a program to perform push and pop operations in stack, where stack should be created using array.

#include <iostream>

using namespace std;

int stack[100], n=100, top=-1;

void push(int val) {

if(top>=n-1)

cout<<"Stack Overflow"<<endl;

else {

top++;

stack[top]=val;

} }

void pop() {

if(top<=-1)

cout<<"Stack Underflow"<<endl;

else {

cout<<"The popped element is "<< stack[top] <<endl;

top--;

} }

void display() {

if(top>=0) {

cout<<"Stack elements are:";

for(int i=top; i>=0; i--)

cout<<stack[i]<<" ";

cout<<endl;

} else

cout<<"Stack is empty"; }

int main() {

int ch, val;

cout<<"1) Push in stack"<<endl;

cout<<"2) Pop from stack"<<endl;

cout<<"3) Display stack"<<endl;

cout<<"4) Exit"<<endl;

do {

cout<<"Enter choice: ";

cin>>ch;
Programs
switch(ch) {

case 1: {

cout<<"Enter value to be pushed:";

cin>>val;

push(val);

break; }

case 2: {

pop();

break; }

case 3: {

display();

break; }

case 4: {

cout<<"Exit"<<endl;

break; }

default: {

cout<<"Invalid Choice"<<endl; } }

} while(ch!=4);

return 0;

Output
Programs
Q7. Write a program to perform push and pop operations in stack, where stack should be created using linked list.

#include <iostream>

using namespace std;

struct Node {

int data;

struct Node *next; };

struct Node* top = NULL;

void push(int val) {

struct Node* newnode = (struct Node*) malloc(sizeof(struct Node));

newnode->data = val;

newnode->next = top;

top = newnode; }

void pop() {

if(top==NULL)

cout<<"Stack Underflow"<<endl;

else {

cout<<"The popped element is "<< top->data <<endl;

top = top->next; } }

void display() {

struct Node* ptr;

if(top==NULL)

cout<<"stack is empty";

else {

ptr = top;

cout<<"Stack elements are: ";

while (ptr != NULL) {

cout<< ptr->data <<" ";

ptr = ptr->next; } }

cout<<endl; }

int main() {

int ch, val;

cout<<"1) Push in stack"<<endl;

cout<<"2) Pop from stack"<<endl;

cout<<"3) Display stack"<<endl;

cout<<"4) Exit"<<endl;
Programs
do {

cout<<"Enter choice: ";

cin>>ch;

switch(ch) {

case 1: {

cout<<"Enter value to be pushed:";

cin>>val;

push(val);

break; }

case 2: {

pop();

break; }

case 3: {

display();

break; }

case 4: {

cout<<"Exit"<<endl;

break; }

default: {

cout<<"Invalid Choice"<<endl; } }

} while(ch!=4);

return 0;

Output
Programs
Q8. Write a program to calculate factorial of a given number using stack.

#include <iostream>

#include <stack>

using namespace std;

int factorialUsingStack(int n) {

stack<int> s;

// Push all numbers from n to 1 onto the stack

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

[Link](i); }

int result = 1;

// Pop each number and multiply

while (![Link]()) {

result *= [Link]();

[Link](); }

return result; }

int main() {

int number;

cout << "Enter a number to calculate its factorial: ";

cin >> number;

if (number < 0) {

cout << "Factorial is not defined for negative numbers." << endl;

} else {

int result = factorialUsingStack(number);

cout << "Factorial of " << number << " is: " << result << endl; }

return 0;

Output
Programs
Q9. Write a program to perform insertion and deletion of data items in queue should be implemented by using a linked list.

#include <iostream>

using namespace std;

// Node structure

struct Node {

int data;

Node* next; };

// Queue class

class Queue {

private:

Node* front;

Node* rear;

public:

Queue() {

front = nullptr;

rear = nullptr; }

// Function to add an element to the queue

void enqueue(int value) {

Node* newNode = new Node();

newNode->data = value;

newNode->next = nullptr;

if (rear == nullptr) {

front = rear = newNode;

} else {

rear->next = newNode;

rear = newNode; }

cout << "Enqueued: " << value << endl; }

// Function to remove an element from the queue

void dequeue() {

if (front == nullptr) {

cout << "Queue is empty, cannot dequeue." << endl;

return; }

Node* temp = front;

front = front->next;
Programs

if (front == nullptr) {

rear = nullptr; }

cout << "Dequeued: " << temp->data << endl;

delete temp; }

// Function to display the queue

void display() {

if (front == nullptr) {

cout << "Queue is empty." << endl;

return; }

Node* temp = front;

while (temp != nullptr) {

cout << temp->data << " ";

temp = temp->next; }

cout << endl; } };

int main() {

Queue q;

[Link](10);

[Link](20);

[Link](30);

[Link]();

[Link]();

[Link]();

[Link]();

[Link]();

[Link]();

// Attempt to dequeue from an empty queue

return 0; }

Output
Programs
Q10. Write a program to perform insertion and deletion of data items in queue should be implemented by using arrays.

#include <iostream>

using namespace std;

int queue[100], n = 100, front = - 1, rear = - 1;

void Insert() {

int val;

if (rear == n - 1)

cout<<"Queue Overflow"<<endl;

else {

if (front == - 1)

front = 0;

cout<<"Insert the element in queue : ";

cin>>val;

rear++;

queue[rear] = val; } }

void Delete() {

if (front == - 1 || front > rear) {

cout<<"Queue Underflow ";

return ;

} else {

cout<<"Element deleted from queue is : "<< queue[front] <<endl;

front++;; } }

void Display() {

if (front == - 1)

cout<<"Queue is empty"<<endl;

else {

cout<<"Queue elements are : ";

for (int i = front; i <= rear; i++)

cout<<queue[i]<<" ";

cout<<endl; } }

int main() {

int ch;

cout<<"1) Insert element to queue"<<endl;

cout<<"2) Delete element from queue"<<endl;

cout<<"3) Display all the elements of queue"<<endl;


Programs
cout<<"4) Exit"<<endl;

do {

cout<<"Enter your choice : ";

cin>>ch;

switch (ch) {

case 1: Insert();

break;

case 2: Delete();

break;

case 3: Display();

break;

case 4: cout<<"Exit"<<endl;

break;

default: cout<<"Invalid choice"<<endl; }

} while(ch!=4);

return 0;

Output
Programs
Q11. Write a program to demonstrate functioning of a double ended queue.

#include <iostream>

#include <deque>

using namespace std;

int main() {

// Create a deque of integers

std::deque<int> deq;

// Insert elements at the front

deq.push_front(10);

deq.push_front(20);

deq.push_front(30);

// Insert elements at the back

deq.push_back(40);

deq.push_back(50);

deq.push_back(60);

// Display the elements of the deque

std::cout << "Deque elements: ";

for (int elem : deq) {

std::cout << elem << " "; }

std::cout << std::endl;

// Remove elements from the front

deq.pop_front();

deq.pop_front();

// Remove elements from the back

deq.pop_back();

deq.pop_back();

// Display the elements of the deque after removal

std::cout << "Deque elements after removal: ";

for (int elem : deq) {

std::cout << elem << " "; }

std::cout << std::endl;

return 0; } Output
Programs
Q12. Write a program to read the postfix arithmetic expression and evaluate its value using the stack.

#include <iostream>

#include <stack>

#include <string>

using namespace std;

// Function to perform an operation based on the operator

// and return the result

int performOperation(int operand1, int operand2,

char operation)

switch (operation) {

case '+':

return operand1 + operand2;

case '-':

return operand1 - operand2;

case '*':

return operand1 * operand2;

case '/':

return operand1 / operand2;

default:

return 0;

// Function to evaluate the postfix expression

int evaluatePostfixExpression(const string& expression)

stack<int> stack;

for (char c : expression) {

if (isdigit(c)) {

// Convert char digit to int and push onto the

// stack

[Link](c - '0');
Programs
}

else {

// Pop the top two elements for the operation

int operand2 = [Link]();

[Link]();

int operand1 = [Link]();

[Link]();

// Perform operation and push the result back

// onto the stack

int result

= performOperation(operand1, operand2, c);

[Link](result);

// The final result should be the only item left in the

// stack

return [Link]();

int main()

string expression2 = "73*4+";

int result = evaluatePostfixExpression(expression2);

cout << "Result of Postfix Expression \"" << expression2

<< "\" is: " << result << endl;

return 0;

Output
Programs
Q13. Write a program to show how to handle the overflow and underflow situation in stack.

#include <iostream>

using namespace std;

#define MAX 5 // Maximum size of the stack

class Stack {

private:

int arr[MAX];

int top;

public:

Stack() {

top = -1; }

// Function to add an element to the stack

void push(int value) {

if (top >= MAX - 1) {

cout << "Stack Overflow! Cannot push " << value << endl;

} else {

arr[++top] = value;

cout << "Pushed " << value << " to stack." << endl; } }

// Function to remove the top element from the stack

void pop() {

if (top < 0) {

cout << "Stack Underflow! Cannot pop." << endl;

} else {

cout << "Popped " << arr[top--] << " from stack." << endl; } }

// Function to display the current stack

void display() {

if (top < 0) {

cout << "Stack is empty." << endl;

} else {

cout << "Stack elements are: ";

for (int i = 0; i <= top; i++) {

cout << arr[i] << " "; }

cout << endl; }

};
Programs
int main() {

Stack s;

// Testing overflow

[Link](10);

[Link](20);

[Link](30);

[Link](40);

[Link](50);

[Link](60); // Should trigger overflow

[Link]();

// Testing underflow

[Link]();

[Link]();

[Link]();

[Link]();

[Link]();

[Link](); // Should trigger underflow

[Link]();

return 0;

Output
Programs
Q14. Write a program to convert infix notation-based expression into the postfix notation-based expression using the stack.

#include <iostream>

#include <stack>

#include <cctype>

using namespace std;

int prec(char op) {

if (op == '^') return 3;

if (op == '*' || op == '/') return 2;

if (op == '+' || op == '-') return 1;

return 0; }

string infixToPostfix(string exp) {

stack<char> st;

string res;

for (char c : exp) {

if (isalnum(c)) res += c;

else if (c == '(') [Link](c);

else if (c == ')') {

while (![Link]() && [Link]() != '(') res += [Link](), [Link]();

[Link](); // pop '('

} else {

while (![Link]() && prec([Link]()) >= prec(c)) res += [Link](), [Link]();

[Link](c); } }

while (![Link]()) res += [Link](), [Link]();

return res; }

int main() {

string exp;

cout << "Enter infix: "; cin >> exp;

cout << "Postfix: " << infixToPostfix(exp);

return 0;

Output
Programs
Q15. write a program to implement the concept of priority based element traversing using priority queue.

#include <iostream>

#include <queue>

#include <vector>

using namespace std;

// Structure for elements with value and priority

struct Element {

int value;

int priority;

// Constructor

Element(int v, int p) : value(v), priority(p) {} };

// Custom comparator for the priority queue (higher priority comes first)

struct ComparePriority {

bool operator()(Element const& e1, Element const& e2) {

// Return true if e1 has lower priority than e2

return [Link] < [Link]; } };

int main() {

// Create a priority queue using the custom comparator

priority_queue<Element, vector<Element>, ComparePriority> pq;

// Inserting elements into the priority queue

[Link](Element(10, 2));

[Link](Element(20, 4));

[Link](Element(30, 1));

[Link](Element(40, 3));

cout << "Traversing elements based on priority:" << endl;

// Traversing and removing elements from the priority queue

while (![Link]()) {

Element e = [Link]();

cout << "Value: " << [Link] << ", Priority: " << [Link] << endl;

[Link](); }

return 0; } Output
Programs
Q16. Write a program to create binary search tree using the concept of linked list and array , suppose data set will be given
at the run time.

#include <iostream>

using namespace std;

// Define a node for the BST (Linked List Node)

struct Node {

int data;

Node* left;

Node* right; };

// Function to create a new node

Node* createNode(int value) {

Node* newNode = new Node();

newNode->data = value;

newNode->left = newNode->right = nullptr;

return newNode; }

// Function to insert a node in BST

Node* insert(Node* root, int value) {

if (root == nullptr) {

return createNode(value); }

if (value < root->data) {

root->left = insert(root->left, value);

} else if (value > root->data) {

root->right = insert(root->right, value); }

return root;}

// In-order traversal (prints in ascending order)

void inorderTraversal(Node* root) {

if (root != nullptr) {

inorderTraversal(root->left);

cout << root->data << " ";

inorderTraversal(root->right);

int main() {
Programs
int n;

cout << "Enter number of elements: ";

cin >> n;

int* arr = new int[n];

cout << "Enter " << n << " elements:\n";

for (int i = 0; i < n; ++i) {

cin >> arr[i];

Node* root = nullptr;

// Insert elements into BST

for (int i = 0; i < n; ++i) {

root = insert(root, arr[i]);

// Print BST in sorted order

cout << "In-order Traversal (Sorted Output): ";

inorderTraversal(root);

cout << endl;

delete[] arr;

return 0;

Output
Programs
Q17. Write a program to create a binary search tree with any data set and traverse the data items in pre-order ,in -order
and post-order manner using recursion.

#include <iostream>

using namespace std;

struct Node {

int data;

Node* left, *right;

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

};

Node* insert(Node* root, int val) {

if (!root) return new Node(val);

if (val < root->data) root->left = insert(root->left, val);

else if (val > root->data) root->right = insert(root->right, val);

return root;

void inorder(Node* r) { if (r) { inorder(r->left); cout << r->data << " "; inorder(r->right); } }

void preorder(Node* r) { if (r) { cout << r->data << " "; preorder(r->left); preorder(r->right); } }

void postorder(Node* r) { if (r) { postorder(r->left); postorder(r->right); cout << r->data << " "; } }

int main() {

Node* root = nullptr;

int data[] = {50, 30, 70, 20, 40, 60, 80};

for (int val : data) root = insert(root, val);

cout << "In-order: "; inorder(root); cout << endl;

cout << "Pre-order: "; preorder(root); cout << endl;

cout << "Post-order: "; postorder(root); cout << endl;

return 0;

Output
Programs
Q18. Write a program to perform deletion of any data item from the binary search tree.

#include <iostream>

using namespace std;

struct Node {

int data;

Node *left, *right;

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

};

Node* insert(Node* root, int val) {

if (!root) return new Node(val);

if (val < root->data) root->left = insert(root->left, val);

else root->right = insert(root->right, val);

return root;

Node* findMin(Node* root) {

while (root && root->left) root = root->left;

return root;

Node* deleteNode(Node* root, int key) {

if (!root) return nullptr;

if (key < root->data) root->left = deleteNode(root->left, key);

else if (key > root->data) root->right = deleteNode(root->right, key);

else {

if (!root->left) return root->right;

if (!root->right) return root->left;

Node* temp = findMin(root->right);

root->data = temp->data;

root->right = deleteNode(root->right, temp->data);

return root;

}
Programs
void inorder(Node* root) {

if (root) {

inorder(root->left);

cout << root->data << " ";

inorder(root->right);

int main() {

Node* root = nullptr;

root = insert(root, 50);

insert(root, 30); insert(root, 70);

insert(root, 20); insert(root, 40);

insert(root, 60); insert(root, 80);

cout << "Inorder before deletion: ";

inorder(root);

root = deleteNode(root, 50);

cout << "\nInorder after deletion: ";

inorder(root);

return 0;

Output
Programs
Q19. Write a program to find the height of any tree.

#include <iostream>

using namespace std;

struct Node {

int data;

Node *left, *right;

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

};

int height(Node* root) {

if (!root) return -1;

return 1 + max(height(root->left), height(root->right));

int main() {

Node* root = new Node(1);

root->left = new Node(2);

root->right = new Node(3);

cout << "Height: " << height(root);

return 0;

Output
Programs
Q20. Write a program to create any given undirected graph using the adjacency matrix, and print each node/element with
list of its adjacent elements.

#include <iostream>

#include <vector>

using namespace std;

int main() {

int v, e;

cout << "Enter vertices and edges: ";

cin >> v >> e;

vector<vector<int>> adj(v, vector<int>(v, 0));

cout << "Enter " << e << " edges (u v):\n";

while (e--) {

int u, w;

cin >> u >> w;

adj[u][w] = adj[w][u] = 1;

cout << "\nAdjacency List:\n";

for (int i = 0; i < v; ++i) {

cout << "Node " << i << ": ";

for (int j = 0; j < v; ++j)

if (adj[i][j]) cout << j << " ";

cout << "\n";

return 0;

Output
Programs
Q21. Write a program to traverse the element of given graph according BFS and DFS.

#include <iostream>

#include <vector>

#include <queue>

using namespace std;

void dfs(int v, vector<vector<int>> &g, vector<bool> &vis) {

cout << v << " "; vis[v] = true;

for (int u : g[v]) if (!vis[u]) dfs(u, g, vis);

void bfs(int s, vector<vector<int>> &g, vector<bool> &vis) {

queue<int> q; [Link](s); vis[s] = true;

while (![Link]()) {

int v = [Link](); [Link](); cout << v << " ";

for (int u : g[v]) if (!vis[u]) vis[u] = true, [Link](u);

int main() {

int n = 5; // nodes from 0 to 4

vector<vector<int>> g(n);

g[0] = {1, 2}; g[1] = {0, 3}; g[2] = {0, 4}; g[3] = {1}; g[4] = {2};

vector<bool> vis(n, false);

cout << "DFS: "; dfs(0, g, vis); cout << endl;

fill([Link](), [Link](), false);

cout << "BFS: "; bfs(0, g, vis); cout << endl;

return 0;

Output
Programs
Q22. Write a program to find the minimum spanning tree of any given graph.

#include <iostream> // using Prim’s method

#include <vector>

#include <climits>

using namespace std;

int minKey(const vector<int>& key, const vector<bool>& mstSet, int V) {

int min = INT_MAX, idx = -1;

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

if (!mstSet[i] && key[i] < min)

min = key[i], idx = i;

return idx;

void primMST(const vector<vector<int>>& graph, int V) {

vector<int> parent(V), key(V, INT_MAX);

vector<bool> mstSet(V, false);

key[0] = 0, parent[0] = -1;

for (int count = 0; count < V - 1; ++count) {

int u = minKey(key, mstSet, V);

mstSet[u] = true;

for (int v = 0; v < V; ++v)

if (graph[u][v] && !mstSet[v] && graph[u][v] < key[v])

parent[v] = u, key[v] = graph[u][v];

cout << "Edge\tWeight\n";

for (int i = 1; i < V; ++i)

cout << parent[i] << " - " << i << "\t" << graph[i][parent[i]] << "\n";

int main() {
Programs
int V;

cin >> V;

vector<vector<int>> graph(V, vector<int>(V));

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

for (int j = 0; j < V; ++j)

cin >> graph[i][j];

primMST(graph, V);

return 0;

Output
Programs
Q23. Write a program to search any run time given element from the array of 10 elements in the array are unsorted.

#include <iostream>

using namespace std;

int main() {

int arr[10];

int key, found = 0;

// Input: array elements

cout << "Enter 10 elements for the array (unsorted):" << endl;

for(int i = 0; i < 10; i++) {

cin >> arr[i];

// Input: element to search

cout << "Enter the element to search: ";

cin >> key;

// Linear search

for(int i = 0; i < 10; i++) {

if(arr[i] == key) {

cout << "Element found at index " << i << endl;

found = 1;

break;

if(!found) {

cout << "Element not found in the array." << endl;

return 0;

Output
Programs
Q24. Write a program to demonstrate the binary search.

#include <iostream>

using namespace std;

// Function to perform binary search

int binarySearch(int arr[], int size, int key) {

int low = 0;

int high = size - 1;

while (low <= high) {

int mid = (low + high) / 2;

if (arr[mid] == key)

return mid; // Element found

else if (arr[mid] < key)

low = mid + 1; // Search in right half

else

high = mid - 1; // Search in left half }

return -1; // Element not found }

int main() {

int arr[] = {10, 20, 30, 40, 50, 60, 70};

int size = sizeof(arr) / sizeof(arr[0]);

int key;

cout << "Enter the element to search: ";

cin >> key;

int result = binarySearch(arr, size, key);

if (result != -1)

cout << "Element found at index " << result << endl;

else

cout << "Element not found in the array." << endl;

return 0;

} Output
Programs
Q25. Write a program to find the smallest and largest element in any array.

#include <iostream>

using namespace std;

int main() {

int n;

// Input size of the array

cout << "Enter the number of elements in the array: ";

cin >> n;

// Declare the array

int arr[n];

// Input array elements

cout << "Enter " << n << " elements:\n";

for(int i = 0; i < n; i++) {

cin >> arr[i]; }

// Initialize smallest and largest with the first element

int smallest = arr[0];

int largest = arr[0];

// Traverse the array to find smallest and largest

for(int i = 1; i < n; i++) {

if(arr[i] < smallest)

smallest = arr[i];

if(arr[i] > largest)

largest = arr[i]; }

// Output the results

cout << "Smallest element: " << smallest << endl;

cout << "Largest element: " << largest << endl;

return 0;

Output
Programs
Q26. Write a program to arrange the data items of any array in ascending order.

#include <iostream>

using namespace std;

int main() {

int n, temp;

// Input array size

cout << "Enter the number of elements in the array: ";

cin >> n;

int arr[n];

// Input array elements

cout << "Enter " << n << " elements:" << endl;

for (int i = 0; i < n; i++) {

cin >> arr[i]; }

// Bubble Sort for ascending order

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

for (int j = 0; j < n - i - 1; j++) {

if (arr[j] > arr[j + 1]) {

// Swap

temp = arr[j];

arr[j] = arr[j + 1];

arr[j + 1] = temp;

// Output sorted array

cout << "Array in ascending order:" << endl;

for (int i = 0; i < n; i++) {

cout << arr[i] << " "; }

return 0;

} Output
Programs
Q27. Write a program to arrange the data items of any array in descending order using quick sort.

#include <iostream>

using namespace std;

void swap(int &a, int &b) { int t = a; a = b; b = t; }

int partition(int arr[], int low, int high) {

int pivot = arr[high], i = low - 1;

for (int j = low; j < high; j++)

if (arr[j] > pivot) swap(arr[++i], arr[j]);

swap(arr[i + 1], arr[high]);

return i + 1;

void quickSort(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);

void print(int arr[], int n) {

for (int i = 0; i < n; i++) cout << arr[i] << " ";

cout << endl;

int main() {

int arr[] = {34, 7, 23, 32, 5, 62}, n = sizeof(arr) / sizeof(arr[0]);tha

cout << "Original: "; print(arr, n);

quickSort(arr, 0, n - 1);

cout << "Descending: "; print(arr, n);

return 0;

Output
Programs

You might also like