Daa Lab Manual
Daa Lab Manual
1. a) Create a CPP class called Student with the following details as variables within it.
(i) Register_number
(ii) Student_name
(iii) Programme_name
#include <iostream>
#include <vector>
#include <string>
class Student {
private:
int register_number;
std::string student_name;
std::string programme_name;
std::string phone_number;
public:
// Constructor
Student(int reg_num, const std::string& name, const std::string& program, const std::string&
phone)
: register_number(reg_num), student_name(name), programme_name(program),
phone_number(phone) {}
int main() {
int n;
std::cout << "Enter the number of students: ";
std::cin >> n;
std::vector<Student> students;
std::cout << "\nEnter details for student " << i + 1 << ":\n";
std::cout << "Register Number: ";
std::cin >> reg_num;
std::cin.ignore(); // Ignore newline character in buffer
std::cout << "Student Name: ";
std::getline(std::cin, name);
std::cout << "Programme Name: ";
std::getline(std::cin, program);
std::cout << "Phone Number: ";
std::getline(std::cin, phone);
return 0;
}
b). Write a program to implement the Stack using arrays. Write Push (), Pop(), and
Display() methods to demonstrate its working.
#include <iostream>
#define MAX_SIZE 100
class Stack {
private:
int top;
int arr[MAX_SIZE];
public:
Stack() {
top = -1; // Initializing top to -1 indicates an empty stack
}
bool isEmpty() {
return top == -1;
}
bool isFull() {
return top == MAX_SIZE - 1;
}
void pop() {
if (isEmpty()) {
std::cout << "Stack Underflow! Cannot pop from an empty stack.\n";
return;
}
std::cout << arr[top--] << " popped from stack.\n";
}
void display() {
if (isEmpty()) {
std::cout << "Stack is empty.\n";
return;
}
std::cout << "Stack elements: ";
for (int i = 0; i <= top; ++i) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
}
};
int main() {
Stack stack;
return 0;
}
2. a). Design a superclass called Staff with details as StaffId, Name, Phone, Salary. Extend
this class by writing three subclasses namely Teaching (domain, publications), Technical
(skills), and Contract (period). Write a CPP program to read and display at least 3 staff
objects of all three categories.
#include <iostream>
#include <string>
class Staff {
protected:
int staffId;
std::string name;
std::string phone;
double salary;
public:
Staff(int id, const std::string& n, const std::string& p, double sal)
: staffId(id), name(n), phone(p), salary(sal) {}
public:
Teaching(int id, const std::string& n, const std::string& p, double sal, const std::string& dom,
int pub)
: Staff(id, n, p, sal), domain(dom), publications(pub) {}
public:
Technical(int id, const std::string& n, const std::string& p, double sal, const std::string& sk)
: Staff(id, n, p, sal), skills(sk) {}
public:
Contract(int id, const std::string& n, const std::string& p, double sal, int per)
: Staff(id, n, p, sal), period(per) {}
int main() {
// Creating teaching staff objects
Teaching teacher1(101, "John Doe", "123-456-7890", 50000, "Computer Science", 5);
Teaching teacher2(102, "Jane Smith", "987-654-3210", 55000, "Physics", 3);
Teaching teacher3(103, "Alice Johnson", "111-222-3333", 48000, "Mathematics", 7);
return 0;
}
b). Write a class called Customer to store their name and date_of_birth. The date_of_birth
format should be dd/mm/yyyy. Write methods to read customer data as and display as
using StringTokenizer class considering the delimiter character as “/”.
#include <iostream>
#include <string>
#include <sstream>
class Customer {
private:
std::string name;
int day, month, year;
public:
// Constructor
Customer(const std::string& n, int d, int m, int y)
: name(n), day(d), month(m), year(y) {}
int main() {
Customer customer1("", 0, 0, 0);
Customer customer2("", 0, 0, 0);
return 0;
}
3. a). Write a program to read two integers a andb. Compute a/b and print, when b is not
zero. Raise an exception when b is equal to zero.
#include <iostream>
#include <stdexcept>
int main() {
int a, b;
try {
// Check if b is zero
if (b == 0) {
throw std::runtime_error("Error: Division by zero!");
}
return 0;
}
b). Write a program that implements a multi-thread application that has three threads.
First thread generates a random integer for every 1 second; second thread computes the
square of the number and prints; third thread will print the value of cube of the number.
#include <iostream>
#include <thread>
#include <chrono>
#include <random>
#include <mutex>
void generateRandomNumber() {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, 100);
while (true) {
int randomNumber = dis(gen);
{
std::lock_guard<std::mutex> lock(mtx);
std::cout << "Generated number: " << randomNumber << std::endl;
}
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
void computeSquare() {
while (true) {
std::this_thread::sleep_for(std::chrono::seconds(1));
int randomNumber = std::rand() % 100 + 1;
{
std::lock_guard<std::mutex> lock(mtx);
std::cout << "Square: " << randomNumber * randomNumber << std::endl;
}
}
}
void computeCube() {
while (true) {
std::this_thread::sleep_for(std::chrono::seconds(1));
int randomNumber = std::rand() % 100 + 1;
{
std::lock_guard<std::mutex> lock(mtx);
std::cout << "Cube: " << randomNumber * randomNumber * randomNumber <<
std::endl;
}
}
}
int main() {
std::thread t1(generateRandomNumber);
std::thread t2(computeSquare);
std::thread t3(computeCube);
t1.join();
t2.join();
t3.join();
return 0;
}
4. Sort a given set of n integer elements using Quick Sort method and compute its time
complexity. Run the program for varied values of n> 5000 and record the time taken to
sort. Plot a graph of the time taken versus non graph sheet. The elements can be read from
a file or can be generated using the random number generator. Demonstrate using CPP
how the divide-and-conquer method works along with its time complexity analysis: worst
case, average case and best case.
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <chrono>
int main() {
// Initialize random number generator
std::srand(std::time(0));
// Generate random input
int n;
std::cout << "Enter the number of elements: ";
std::cin >> n;
std::vector<int> arr(n);
for (int i = 0; i < n; i++) {
arr[i] = std::rand() % 10000; // Random integers between 0 and 9999
}
return 0;
}
5. Sort a given set of n integer elements using Merge Sort method and compute its time
complexity. Run the program for varied values of n> 5000, and record the time taken to
sort. Plot a graph of the time taken versus non graph sheet. The elements can be read from
a file or can be generated using the random number generator. Demonstrate using CPP
how the divide-and-conquer method works along with its time complexity analysis: worst
case, average case and best case.
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <chrono>
int main() {
// Initialize random number generator
std::srand(std::time(0));
std::vector<int> arr(n);
for (int i = 0; i < n; i++) {
arr[i] = std::rand() % 10000; // Random integers between 0 and 9999
}
return 0;
}
6. Implement the Knapsack problem using
#include <iostream>
#include <vector>
return K[n][W];
}
int main() {
int n; // Number of items
std::cout << "Enter the number of items: ";
std::cin >> n;
return 0;
}
(b) Greedy method.
#include <iostream>
#include <vector>
#include <algorithm>
// Comparator function to sort items in non-increasing order of value per unit weight
bool cmp(const Item& a, const Item& b) {
double valuePerUnitWeightA = (double)a.value / a.weight;
double valuePerUnitWeightB = (double)b.value / b.weight;
return valuePerUnitWeightA > valuePerUnitWeightB;
}
return totalValue;
}
int main() {
int capacity;
std::cout << "Enter the capacity of the knapsack: ";
std::cin >> capacity;
int n;
std::cout << "Enter the number of items: ";
std::cin >> n;
std::vector<Item> items(n);
std::cout << "Enter the value and weight of each item:\n";
for (int i = 0; i < n; ++i) {
std::cin >> items[i].value >> items[i].weight;
}
return 0;
}
7. Write a program-from a given vertex in a weighted connected graph, find shortest paths
to other vertices using Dijkstra's algorithm..
#include <iostream>
#include <vector>
#include <queue>
#include <limits>
// Function to find shortest paths from a given source vertex to all other vertices using Dijkstra's
algorithm
std::vector<int> dijkstra(const std::vector<Vertex>& graph, int source) {
int n = graph.size(); // Number of vertices in the graph
std::vector<int> distance(n, std::numeric_limits<int>::max()); // Initialize distances to infinity
distance[source] = 0; // Distance from source to itself is 0
// Priority queue to store vertices based on their distances from the source
std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int>>,
std::greater<std::pair<int, int>>> pq;
pq.push({0, source}); // Push the source vertex into the priority queue
// Dijkstra's algorithm
while (!pq.empty()) {
int u = pq.top().second; // Extract the vertex with the minimum distance
pq.pop();
int main() {
// Example graph represented as an adjacency list
std::vector<Vertex> graph = {
{{ {1, 4}, {2, 1} }}, // Vertex 0
{{ {0, 4}, {2, 2}, {3, 5} }}, // Vertex 1
{{ {0, 1}, {1, 2}, {3, 2} }}, // Vertex 2
{{ {1, 5}, {2, 2} }} // Vertex 3
};
int source;
std::cout << "Enter the source vertex: ";
std::cin >> source;
return 0;
}
8. Find Minimum Cost Spanning Tree of a given connected undirected graph using
Kruskal's algorithm. Use Union-Find algorithms in your program.
#include <iostream>
#include <vector>
#include <algorithm>
// Function to find Minimum Cost Spanning Tree (MST) using Kruskal's algorithm
std::vector<Edge> kruskalMST(std::vector<Edge>& edges, int V) {
std::vector<Edge> MST;
std::vector<Subset> subsets(V);
// Initialize subsets
for (int i = 0; i < V; i++) {
subsets[i].parent = i;
subsets[i].rank = 0;
}
int edgeCount = 0, i = 0;
while (edgeCount < V - 1 && i < edges.size()) {
Edge nextEdge = edges[i++];
if (x != y) {
MST.push_back(nextEdge);
Union(subsets, x, y);
edgeCount++;
}
}
return MST;
}
int main() {
int V, E;
std::cout << "Enter the number of vertices and edges: ";
std::cin >> V >> E;
std::vector<Edge> edges(E);
std::cout << "Enter source, destination, and weight of each edge:\n";
for (int i = 0; i < E; i++) {
std::cin >> edges[i].src >> edges[i].dest >> edges[i].weight;
}
return 0;
}
9. Find Minimum Cost Spanning Tree of a given connected undirected graph using Prim's
algorithm.
#include <iostream>
#include <vector>
#include <queue>
#include <climits>
// Function to find the Minimum Cost Spanning Tree (MST) using Prim's algorithm
std::vector<Edge> primMST(const std::vector<Vertex>& graph, int start) {
int n = graph.size();
std::vector<Edge> MST;
std::vector<bool> visited(n, false);
std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int>>,
std::greater<std::pair<int, int>>> pq;
visited[start] = true;
for (const Edge& edge : graph[start].neighbors) {
pq.push({edge.weight, edge.to});
}
while (!pq.empty()) {
int weight = pq.top().first;
int u = pq.top().second;
pq.pop();
if (visited[u]) continue;
visited[u] = true;
MST.push_back({start, u, weight});
return MST;
}
int main() {
// Example graph represented as an adjacency list
std::vector<Vertex> graph = {
{{ {1, 2}, {2, 3} }}, // Vertex 0
{{ {0, 2}, {2, 2}, {3, 4} }}, // Vertex 1
{{ {0, 3}, {1, 2}, {3, 1} }}, // Vertex 2
{{ {1, 4}, {2, 1} }} // Vertex 3
};
int start;
std::cout << "Enter the starting vertex: ";
std::cin >> start;
return 0;
}
10. Write programs to
#include <iostream>
#include <vector>
#include <limits>
return dist;
}
int main() {
// Example usage
vector<vector<int>> graph = {
{0, 5, INF, 10},
{INF, 0, 3, INF},
{INF, INF, 0, 1},
{INF, INF, INF, 0}
};
return 0;
}
(b) Implement Travelling Sales Person problem using Dynamic programming.
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <limits>
return minCost;
}
int main() {
int n;
std::cout << "Enter the number of cities: ";
std::cin >> n;
return 0;
}
11. Design and implement in CPP, to find a subset of a given set S = {Sl, S2,.....,Sn} of n
positive integers whose SUM is equal to a given positive integer d. For example, if S ={1, 2,
5, 6, 8} and d= 9, there are two solutions {1,2,6}and {1,8}. Display a suitable message, if the
given problem instance doesn't have a solution
#include <iostream>
#include <vector>
// Function to find a subset of a given set whose sum is equal to a given positive integer
void findSubset(const std::vector<int>& set, int n, int targetSum) {
std::vector<std::vector<bool>> dp(n + 1, std::vector<bool>(targetSum + 1, false));
return 0;
}
12. Design and implement in CPP to find all Hamiltonian Cycles in a connected undirected
Graph G of n vertices using backtracking principle.
#include <iostream>
#include <vector>
#include <algorithm>
class Graph {
private:
int V; // Number of vertices
std::vector<std::vector<int>> adj; // Adjacency list
// Function to check if vertex v can be added at index 'pos' in the Hamiltonian cycle
bool isSafe(int v, const std::vector<int>& path, int pos) {
// Check if vertex v is adjacent to the previously added vertex in the path
if (!adj[path[pos - 1]][v])
return false;
return true;
}
// Function to recursively find Hamiltonian cycle starting from the vertex 'pos'
bool hamiltonianCycleUtil(std::vector<int>& path, int pos) {
// If all vertices are included in the path, and the last vertex is adjacent to the first vertex,
then it's a Hamiltonian cycle
if (pos == V) {
if (adj[path[pos - 1]][path[0]] == 1)
return true;
else
return false;
}
return false;
}
public:
Graph(int vertices) : V(vertices), adj(vertices, std::vector<int>(vertices, 0)) {}
if (!hamiltonianCycleUtil(path, 1)) {
std::cout << "No Hamiltonian cycle exists in the graph\n";
return;
}
int main() {
Graph g(5); // Create a graph with 5 vertices
return 0;
}