19CS401 C++ Question Answer Key Nov 2024
19CS401 C++ Question Answer Key Nov 2024
(PART A – 2 Marks)
UNIT - I
Knowledge
Difficulty
Q. No Questions CO Level
Level (1-5)
(Blooms)
Discuss the term Class and Objects in OOPs.
QA101* CO1 K2 1
A class is a blueprint or template for creating objects.
An object is an instance of a class.
Write an example program for constructors.
class Demo {
public:
QA102 // Constructor CO1 K2 2
Demo() {
cout << "Constructor called: Object created" << endl;
}
}
Define friend functions with an example in C++.
QA103* friend function is a function that is not a member of a class but has access to its private and CO1 K2 1
protected members. Friend functions are useful when two or more classes need to share infor-
mation. To declare a function as a friend, use the friend keyword inside the class
Describe about new operator with an example in C++.
QA104 CO1 K1 2
The new operator in C++ is used to dynamically allocate memory on the heap for a variable or
an object. Unlike automatic (stack) memory allocation, memory allocated with new persists
until it is explicitly deallocated with the delete operator.
Write down the syntax for Operator Overloading in C++.
class ClassName {
public:
QA105 // Overloading an operator as a member function CO1 K3 2
ReturnType operator OperatorSymbol (const ClassName& operand) {
// Function body
}
};
Write an example program for Destructors.
#include <iostream>
using namespace std;
class Demo {
public:
// Constructor
Demo() {
QA106* CO1 K3 2
cout << "Constructor called: Object created" << endl;
}
// Destructor
~Demo() {
cout << "Destructor called: Object destroyed" << endl;
}
}
QA107* Write a C++ program to display "Welcome to Technical Training” in first line and "at CO1 K3 2
Saveetha Engineering College" in next line in the output device
#include <iostream> // Include the iostream library for input and output
using namespace std;
int main() {
// Display the first line
cout << "Welcome to Technical Training" << endl;
// Display the second line
cout << "at Saveetha Engineering College" << endl;
return 0;
}
Write a C++ Program to read two Operands from the keyboard and display the value on the
monitor
#include <iostream>
using namespace std;
int main() {
float operand1, operand2;
return 0;
}
UNIT - II
Knowledge
Difficulty
Q. No Questions CO Level
Level (1-5)
(Blooms)
Define Inheritance. List out the types of inheritance in C++.
QA202* private members are those members (variables or methods) of a class that are accessible only CO2 K3 2
within the class itself. They are not accessible from outside the class, which provides encapsula-
tion and protects the data from unintended modification or access.
Define Composition in C++.
QA203 CO2 K1 1
Composition represents a "has-a" relationship (e.g., a Person has an Address).
Inheritance represents an "is-a" relationship (e.g., a Dog is an Animal).
Describe about ‘this’ pointer in C++.
this pointer is an implicit pointer that is passed to all non-static member functions of a class. It is
QA204 CO2 K1 1
used to refer to the current object of the class within its member functions. The this pointer
allows you to access the current instance's members and differentiate between class members and
parameters or local variables with the same name.
Describe about the virtual functions in C++.
QA205* Virtual functions are the cornerstone of runtime polymorphism in C++. They allow derived CO2 K2 2
classes to provide specific implementations for functions defined in base classes, even when
using base class pointers or references.
QA206* Write a C++ program to read regno,name & gender in one class and display the above details in CO2 K3 2
another class using inheritance
#include <iostream>
using namespace std;
// Base class
class Student {
protected:
int regno; // Registration number
string name; // Name of the student
string gender; // Gender of the student
public:
// Function to read details
void readDetails() {
cout << "Enter Registration Number: ";
cin >> regno;
cin.ignore(); // To ignore the newline character left in buffer after input
cout << "Enter Name: ";
getline(cin, name); // To read full name with spaces
cout << "Enter Gender: ";
getline(cin, gender); // To read full gender
}
};
// Derived class
class Display : public Student {
public:
// Function to display details
void showDetails() {
cout << "\nStudent Details:" << endl;
cout << "Registration Number: " << regno << endl;
cout << "Name: " << name << endl;
cout << "Gender: " << gender << endl;
}
};
QA207* Write a C++ program to initialize the members of a class and use this pointer to do it. CO2 K3 2
#include <iostream>
using namespace std;
class Student {
private:
int regNo; // Registration number
string name; // Name of the student
public:
// Constructor to initialize members using the 'this' pointer
Student(int regNo, string name) {
// Using 'this' pointer to refer to the current object's members
this->regNo = regNo; // this->regNo refers to the member variable, regNo is the parameter
this->name = name; // this->name refers to the member variable, name is the parameter
}
#include <iostream>
using namespace std;
// Base class
class Employee {
protected:
int empno; // Employee number
string empname; // Employee name
string empgender; // Employee gender
};
// Derived class
class DisplayEmployee : public Employee {
public:
// Function to display employee details
void display() {
cout << "\nEmployee Details:" << endl;
cout << "Employee Number: " << empno << endl;
cout << "Employee Name: " << empname << endl;
cout << "Employee Gender: " << empgender << endl;
}
};
UNIT - III
Knowledge
Difficulty
Q. No Questions CO Level
Level (1-5)
(Blooms)
Define Linear Data Structure in C++.
A Linear Data Structure in C++ refers to a type of data structure in which the elements are
QA301 stored and arranged sequentially, and each element is connected to its previous and next element CO3 K2 1
in a linear fashion. This structure allows for easy traversal from the first element to the last one in
a single, linear pass. The linear structure ensures that elements are processed one at a time, and
each element has a unique predecessor (except the first) and a unique successor (except the last).
Define Singly Linked List with a neat diagram in Data Structures.
A Singly Linked List is a type of linked list in which each node contains two parts:
Head --> [Data | Next] --> [Data | Next] --> [Data | Next] --> NULL
(Node1) (Node2) (Node3)
QA303* Define Doubly Linked List with a neat diagram in Data Structures. CO3 K2 1
A Doubly Linked List (DLL) is a type of linked list where each node contains three parts:
struct Node {
int data; // Data part of the node
Node* next; // Pointer to the next node
Node* prev; // Pointer to the previous node
};
NULL <--> [Data | Prev | Next] <--> [Data | Prev | Next] <--> [Data | Prev | Next] <--> NULL
(Node1) (Node2) (Node3)
Define Stack and write any two of its application in C++.
A stack is a crucial data structure that works on the LIFO principle and has various real-world
QA304 CO3 K2 1
applications, such as string reversal and parentheses matching. It is widely used in different
algorithms and systems, including managing function calls (recursion), parsing expressions, and
more.
Define Queue and write any two of its application in C++.
QA305 A Queue is a versatile data structure that operates on the FIFO principle. It is widely used in var- CO3 K2 1
ious systems, such as CPU scheduling, print job management, and more. Its applications are criti -
cal in real-time systems and process management where fairness and order are essential.
List of the differences between Postfix and Prefix Conversion
Convert the following infix expressions into its equivalent postfix expressions.
ABD⋀+EF-/G+
UNIT - IV
Knowledge
Difficulty
Q. No Questions CO Level
Level (1-5)
(Blooms)
Define Tree and Types of Trees.
A Tree is a hierarchical data structure consisting of nodes connected by edges. It is used to rep-
resent data in a way that facilitates efficient search, insertion, deletion, and traversal operations.
QA401 CO4 K1 1
Binary Tree
Binary Search Tree (BST)
AVL Tree
Red-Black Tree
List of the various operations performed on Trees
Traversal: Visiting all the nodes of a tree in a specific order. Common types of traversals:
Height: The length of the longest path from the root to a leaf node.
QA403 Compare the Binary and Full Binary Tree. CO4 K2 2
A Binary Tree is a tree where each node has at most two children, commonly referred to as the
left and right children.
A Full Binary Tree (sometimes called a proper binary tree) is a type of binary tree where ev-
ery node has either 0 or 2 children, never 1 child.
Define Level, Height and Depth in Trees
The level of a node in a tree refers to the distance from the root node to that particular node. It is
QA404* the number of edges on the path from the root node to the given node. CO4 K2 2
The height of a tree is the length of the longest path from the root node to a leaf node. It is
measured by the number of edges along the longest path from the root to the farthest leaf node.
The depth of a node is the number of edges from the root node to that node.
Compare types of Tree traversals
B-trees provide an efficient way to organize and search data, making them ideal for use in sys-
QA407* CO4 K2 1
tems where large amounts of sorted data need to be stored, such as in databases, file systems,
and indexing systems. The balanced structure ensures that operations like search, insertion, and
deletion remain efficient, even as the size of the data grows.
Write the Left-Rotation rules in Splay Trees
a Splay Tree, left rotation is an operation that is used to maintain the balanced structure of the
QA408* CO4 K2 1
tree during various operations, such as splaying (rearranging the tree so that a specific node be-
comes the root). Left rotation helps in adjusting the positions of nodes to maintain a balanced bi-
nary search tree (BST) property.
UNIT - V
Knowledge
Difficulty
Q. No Questions CO Level
Level (1-5)
(Blooms)
Define Graph with a neat diagram
A Graph is a data structure that consists of a set of vertices (or nodes) and a set of edges (or
arcs) that connect pairs of vertices. Graphs are widely used in computer science and mathematics
to represent relationships between objects, such as networks, paths, connections, and associations.
QA501 CO5 K2 2
(A) --5--> (B)
| /|
2| / |3
| / |
(C) <--4----(D)
Compare Directed and Undirected Graph
QA502* Directed graphs are suitable for scenarios where direction matters (e.g., following, CO5 K2 2
dependencies), while undirected graphs are ideal for mutual relationships or connections that
don’t have a specific direction.
List the Applications of Minimum Spanning Tree(MST)
Breadth-First Search (BFS) is an algorithm for traversing or searching through a graph (or tree)
QA504* CO5 K2 2
data structure. Starting from a given node, BFS explores all the nodes at the current depth level
before moving on to the nodes at the next depth level. It is commonly used for finding the short-
est path in an unweighted graph, among other applications.
List the Applications of Graph
Computer Networks
Social Networks
QA505 CO5 K2 1
Transportation and Navigation Systems
Search Engines
Geographic Information Systems (GIS)
Biology and Bioinformatics
Define DFS
Depth-First Search (DFS) is an algorithm used for traversing or searching through a graph (or
QA506* CO5 K2 1
tree) data structure. In DFS, we start from a selected node (often called the "source" node) and
explore as far down a branch as possible before backtracking. This "depth-first" approach means
DFS explores one possible path to its end before trying another path.
Define Undirected Graph .
A Directed Graph (or Digraph) is a type of graph in which each edge has a direction associated
with it. In a directed graph, edges point from one vertex to another, indicating a one-way
relationship. Each edge is represented as an ordered pair of vertices (u,v)(u, v)(u,v), where u is
the starting vertex (source) and v is the ending vertex (destination).
QA508* CO5 K2 1
↙ ↘
A
↘ ↙
B C
UNIT - I
Knowledge
Difficulty
Q. No Questions CO Level
Level (1-5)
(Blooms)
QB101 (a)* Write a C++ Program to generate Fibonacci series using Class and object CO1 K6 3
#include <iostream>
using namespace std;
class Fibonacci {
private:
int n; // Number of terms in the series
public:
Fibonacci(int terms) {
n = terms;
}
void generateSeries() {
int first = 0, second = 1, next;
int main() {
int terms;
cout << "Enter the number of terms: ";
cin >> terms;
Fibonacci fib(terms);
fib.generateSeries();
return 0;
}
(Or)
QB101 (b) Write a C++ program using friend function to find the minimum integer value among the CO1 K6 3
member of both the classes.
#include <iostream>
using namespace std;
class ClassB {
private:
int valueB;
public:
// Constructor to initialize valueB
ClassB(int b) : valueB(b) {}
class ClassA {
private:
int valueA;
public:
// Constructor to initialize valueA
ClassA(int a) : valueA(a) {}
return 0;
}
QB102 (a) Write a C++ program to calculate the simple interest by passing the required values of p ,n , CO1 K6 4
r as parameters (1000,2,4) respectively through constructor.
#include <iostream>
using namespace std;
public:
// Constructor to initialize principal, time, and rate
SimpleInterest(double p, double n, double r) {
principal = p;
time = n;
rate = r;
}
// Method to calculate and display simple interest
void calculateInterest() {
double interest = (principal * time * rate) / 100;
cout << "Simple Interest: " << interest << endl;
}
};
int main() {
// Create an object of SimpleInterest with p=1000, n=2, r=4
SimpleInterest si(1000, 2, 4);
return 0;
}
(Or)
QB102 (b)* Write a C++ program to calculate the area of triangle by passing the existing object as CO1 K6 4
parameters respectively through copy constructor. (Area of a triangle = 1/2 * b * h)
#include <iostream>
using namespace std;
class Triangle {
private:
double base;
double height;
public:
Triangle(double b, double h) {
base = b;
height = h;
}
Triangle(const Triangle &t) {
base = t.base;
height = t.height;
}
double calculateArea() {
return 0.5 * base * height;
}
};
int main() {
double b = 10.0, h = 5.0;
Triangle t1(b, h);
Triangle t2(t1);
cout << "Area of the triangle: " << t2.calculateArea() << endl;
return 0;
}
Write A C++ Program to allocate memory dynamically for an integer variable.
#include <iostream>
using namespace std;
int main() {
int* ptr;
ptr = new int;
if (ptr == nullptr) {
QB103 (a) CO1 K6 3
cout << "Memory allocation failed!" << endl;
return 1;
}
*ptr = 50;
cout << "The value stored in the dynamically allocated memory is: " << *ptr << endl;
delete ptr;
return 0;
}
(Or)
QB103 (b) CO1 K6 4
Write A C++ Program to create class Box and calculate the volume of the Box, make use of
static member variable and static member function in the class Box.
#include <iostream>
using namespace std;
class Box {
private:
double length, width, height; // Dimensions of the box
static int totalBoxes; // Static member variable to keep track of total boxes
public:
// Constructor to initialize dimensions and increment the total box count
Box(double l, double w, double h) {
length = l;
width = w;
height = h;
totalBoxes++; // Increment the total box count each time a new Box object is created
}
// Static member function to get the total number of boxes
static int getTotalBoxes() {
return totalBoxes;
}
// Function to calculate the volume of the box
double calculateVolume() {
return length * width * height;
}
};
// Initialize the static member variable
int Box::totalBoxes = 0;
int main() {
// Create Box objects
Box box1(3.0, 4.0, 5.0); // Box with dimensions 3x4x5
Box box2(2.0, 6.0, 8.0); // Box with dimensions 2x6x8
// Calculate the volume of the boxes
cout << "Volume of box1: " << box1.calculateVolume() << endl;
cout << "Volume of box2: " << box2.calculateVolume() << endl;
// Access the static function to get the total number of boxes
cout << "Total number of Box objects created: " << Box::getTotalBoxes() << endl;
return 0;
}
QB104 (a)* Write a C++ program to read the student details using the constructor and display them us- CO1 K6 3
ing a member function
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
string name; // Name of the student
int rollNumber; // Roll number of the student
double marks; // Marks obtained by the student
public:
// Constructor to initialize student details
Student(string n, int r, double m) {
name = n;
rollNumber = r;
marks = m;
}
// Member function to display student details
void displayDetails() {
cout << "Student Name: " << name << endl;
cout << "Roll Number: " << rollNumber << endl;
cout << "Marks: " << marks << endl;
}
};
int main() {
// Declare student details
string studentName;
int studentRollNumber;
double studentMarks;
// Input student details
cout << "Enter student name: ";
getline(cin, studentName);
cout << "Enter roll number: ";
cin >> studentRollNumber;
cout << "Enter marks: ";
cin >> studentMarks;
// Create a Student object with the provided details
Student student1(studentName, studentRollNumber, studentMarks);
// Display the student details
cout << "\nStudent Details:\n";
student1.displayDetails();
return 0;
}
(Or)
QB104 (b)* Write a C++ program to find the area of rectangle and a square using constructor overload- CO1 K6 4
ing, pass the values during compile time.
#include <iostream>
class Shape {
private:
public:
Shape(double l, double w) {
length = l;
width = w;
Shape(double s) {
side = s;
}
// Function to calculate the area of a rectangle
double calculateArea() {
};
int main() {
Shape rectangle(5.0, 3.0); // Rectangle with length 5.0 and width 3.0
return 0;
UNIT - II
Knowledge
Difficulty
Q. No Questions CO Level
Level (1-5)
(Blooms)
QB201 (a)* Write a program to do integer arithmetic operation using multiple inheritance( + and - CO2 K6 3
operation in one class,* and / in another class).
#include <iostream>
using namespace std;
class ArithmeticAddSubtract {
public:
return a + b;
return a - b;
};
class ArithmeticMultiplyDivide {
public:
return a * b;
}
// Function for division
if (b != 0) {
return a / b;
} else {
return 0;
};
public:
ArithmeticOperations() {
};
int main() {
int x, y;
ArithmeticOperations obj;
return 0;
(Or)
QB201 (b) Write a c++ program to find difference & quotient of two numbers using Hierarchical CO2 K6 3
inheritance
#include <iostream>
class Arithmetic {
protected:
public:
void input() {
};
public:
void calculateDifference() {
};
// Derived class Quotient
public:
void calculateQuotient() {
if (num2 != 0) {
} else {
};
int main() {
Difference diffObj;
Quotient quotObj;
diffObj.input();
quotObj.input();
quotObj.calculateQuotient();
return 0;
QB202 (a) Write a C++ program to get two numbers from two base classes and display the product of CO2 K6 3
two numbers in the derived class.
#include <iostream>
using namespace std;
// Base class 1
class Base1 {
protected:
int num1;
public:
// Function to take input for num1
void getNum1() {
cout << "Enter the first number: ";
cin >> num1;
}
};
// Base class 2
class Base2 {
protected:
int num2;
public:
// Function to take input for num2
void getNum2() {
cout << "Enter the second number: ";
cin >> num2;
}
};
int main() {
// Create an object of the derived class Product
Product p;
return 0;
}
(Or)
QB202 (b) Write a C++ program using the concept of virtual functions and multiple inheritance to CO2 K6 5
implement the population of Asia.
Our program should have three classes named India, China and Asia, Each class should
implement a function named population()
population() in India should print 150 crore.
population() in China should print 200 crore.
population() in Asia should print "Population of India and china amounts to 75% of the
Asia’s population".
Here the classes India and China should act as the parent classes for the class Asia
#include <iostream>
using namespace std;
// Derived class Asia that inherits from both India and China
class Asia : public India, public China {
public:
// Override the population function
void population() override {
// Since both India and China contribute to Asia's population, display the combined
message
cout << "Population of India and China amounts to 75% of the Asia’s population" <<
endl;
}
};
int main() {
// Create an object of Asia
Asia asia;
#include <iostream>
using namespace std;
public:
// Constructor to initialize data
A(int d) : data(d) {}
public:
// Constructor of class B takes an argument to initialize objA
B(int val) : objA(val) {}
int main() {
int value;
return 0;
}
(Or)
QB203 (b) Write a C++ program to pass a password (Admin@123 )to the parameterized constructor of CO2 K6 5
a base class through the derived class constructor.
#include <iostream>
#include <string>
using namespace std;
// Derived class that passes the password to the base class constructor
class Derived : public Base {
public:
// Constructor of derived class that takes password as a parameter
Derived(string password) : Base(password) {
cout << "Password passed to Base class through Derived class constructor." << endl;
}
};
int main() {
// Define the password to be passed
string password = "Admin@123";
return 0;
}
QB204 (a)* Write a C++ Program for Class conversion that can be achieved by conversion function CO1 K6 3
which is done by the use of operator overloading (use character data)
#include <iostream>
class Character {
private:
public:
Character(char c) : ch(c) {}
operator int() {
return static_cast<int>(ch); // Convert character to its ASCII value
void displayCharacter() {
};
int main() {
obj.displayCharacter();
cout << "ASCII value of the character: " << asciiValue << endl;
return 0;
}
(Or)
QB204 (b)* Write a C++ program to demonstrate the use of a virtual destructor by properly destroying CO1 K6 4
the objects of the parent and the child class.
#include <iostream>
class Base {
public:
Base() {
virtual ~Base() {
};
public:
Derived() {
~Derived() {
};
int main() {
Base* basePtr;
// The virtual destructor ensures proper destruction of both base and derived objects
delete basePtr;
return 0;
UNIT - III
Q. No Questions CO Knowledge Difficulty
Level Level (1-5)
(Blooms)
Write a C++ program to create and display a stack using STL and perform the push
operation
#include <iostream>
#include <stack> // Include the stack header
int main() {
// Create a stack of integers
stack<int> s;
return 0;
}
(Or)
QB301 (b)* Write a C++ program to create and display a Queue using STL and perform the Enqueue CO3 K6 4
operation
#include <iostream>
int main() {
queue<int> q;
q.push(10);
q.push(20);
q.push(30);
q.push(40);
q.push(50);
while (!q.empty()) {
cout << q.front() << " "; // Display the front element
return 0;
QB302 (a) Write a C++ program to implement FCFS algorithm to read no of.process p1,p2,p3 and p4 CO3 K6 4
and its burst time from the user and find out waiting time of the each process, Average
waiting time of the process
Input Result
7 8 9 Processes BT time WT
12 time
1 7 0
2 8 7
3 9 15
4 12 24
#include <iostream>
#include <vector>
using namespace std;
// Function to calculate and display waiting times and average waiting time
void FCFS(vector<int>& burstTimes, int n) {
vector<int> waitingTimes(n, 0); // Initialize waiting time for all processes to 0
int totalWaitingTime = 0;
int main() {
int n;
vector<int> burstTimes(n);
// Call FCFS function to calculate waiting times and average waiting time
FCFS(burstTimes, n);
return 0;
}
(Or)
QB302 (b)* Write a C++ program for Infix To Prefix Conversion using Stack STL. CO3 K6 4
(a+b*c-d)
#include <iostream>
#include <stack>
#include <algorithm>
#include <cctype>
return postfix;
}
int main() {
string infix = "(a+b*c-d)"; // Input infix expression
return 0;
}
QB303 (a) Write a C++ program to create and display a singly linked list and perform the delete CO3 K6 4
middle node operation.
#include <iostream>
using namespace std;
// Node structure
struct Node {
int data;
Node* next;
public:
// Constructor to initialize an empty list
SinglyLinkedList() {
head = nullptr;
}
int main() {
SinglyLinkedList list;
return 0;
}
(Or)
QB303 (b) Write a C++ program to create and display a Circularly Linked List and perform the delete CO3 K6 3
middle node operation
#include <iostream>
// Node structure
struct Node {
int data;
Node* next;
Node(int value) {
data = value;
next = nullptr;
};
class CircularLinkedList {
private:
public:
CircularLinkedList() {
head = nullptr;
if (!head) {
head = newNode;
} else {
void display() {
if (!head) {
return;
do {
temp = temp->next;
void deleteMiddle() {
if (!head || head->next == head) {
cout << "List is too short to delete middle node." << endl;
return;
fast = fast->next->next;
prev = slow;
slow = slow->next;
// Now slow is at the middle node, and prev is at the node before it
if (prev) {
head = slow->next;
}
delete slow;
~CircularLinkedList() {
if (!head) return;
Node* nextNode;
do {
nextNode = current->next;
delete current;
current = nextNode;
};
int main() {
CircularLinkedList list;
list.insert(10);
list.insert(20);
list.insert(30);
list.insert(40);
list.insert(50);
list.display();
list.deleteMiddle();
list.display();
return 0;
QB304 (a)* Write a C++ Program to insert five integer elements in to Queue ADT (use STL for Queue) CO3 K6 3
#include <iostream>
int main() {
queue<int> q;
q.push(20);
q.push(30);
q.push(40);
q.push(50);
while (!q.empty()) {
cout << q.front() << " "; // Display the front element
return 0;
}
(Or)
QB304 (b)* CO3 K6 4
Write a C++ Program to insert five special character elements in to Stack ADT (use STL
for Stack)
#include <iostream>
int main() {
stack<char> s;
s.push('@');
s.push('#');
s.push('$');
s.push('%');
s.push('^');
while (!s.empty()) {
cout << s.top() << " "; // Display the top element
return 0;
}
UNIT - IV
Knowledge
Difficulty
Q. No Questions CO Level
Level (1-5)
(Blooms)
QB401 (a) Write a C++ Program to the Right rotate module of the red black tree. CO4 K6 4
#include <iostream>
#include <memory>
struct Node {
int data;
Color color;
Node* left;
Node* right;
Node* parent;
};
private:
Node* root;
public:
RedBlackTree() : root(nullptr) {}
void rightRotate(Node* y) {
x->right = y;
y->left = T2;
if (T2 != nullptr) {
T2->parent = y;
if (y->parent == nullptr) {
root = x;
} else if (y == y->parent->left) {
y->parent->left = x;
} else {
y->parent->right = x;
y->parent = x;
if (root == nullptr) {
root = newNode;
insertHelper(root, newNode);
if (root == nullptr) {
return;
if (root->left == nullptr) {
root->left = newNode;
newNode->parent = root;
} else {
insertHelper(root->left, newNode);
} else {
if (root->right == nullptr) {
root->right = newNode;
newNode->parent = root;
} else {
insertHelper(root->right, newNode);
if (node != nullptr) {
inorderTraversal(node->left);
inorderTraversal(node->right);
void display() {
inorderTraversal(root);
cout << endl;
Node* getRoot() {
return root;
};
int main() {
RedBlackTree tree;
tree.insert(20);
tree.insert(15);
tree.insert(30);
tree.insert(10);
tree.insert(25);
tree.display();
cout << "Performing right rotation on the root node (20):" << endl;
tree.rightRotate(root);
cout << "Inorder traversal of the tree after right rotation: ";
tree.display();
return 0;
}
(Or)
QB401 (b)* Write a C++ Program to perform Postorder traversal of the below given tree CO4 K6 4
#include <iostream>
struct Node {
int data;
Node* left;
Node* right;
};
if (root == nullptr) {
return;
postorderTraversal(root->left);
postorderTraversal(root->right);
int main() {
postorderTraversal(root);
return 0;
}
QB402 (a) Write C++ program to the findParent Module of the BPlus Tree CO4 K6 4
#include <iostream>
#include <vector>
public:
BPlusTree() {
root = new BPlusNode(true); // Initialize with a leaf root
}
// Function to insert a key into the B+ Tree (simplified for this example)
void BPlusTree::insert(int key) {
if (root == nullptr) {
root = new BPlusNode(true);
}
// Base case: if the node is a leaf or if child is a direct child of node, return node
for (BPlusNode* childNode : node->children) {
if (childNode == child) {
return node;
}
}
int main() {
BPlusTree tree;
return 0;
}
(Or)
QB402 (b)* Write a C++ Program to perform Preorder traversal of the below given tree CO4 K6 4
#include <iostream>
struct Node {
int data;
Node* left;
Node* right;
if (root == nullptr) {
return;
preorderTraversal(root->left);
preorderTraversal(root->right);
int main() {
preorderTraversal(root);
return 0;
}
QB403 (a) Write a C++ Program to perform Postorder traversal of the below given tree CO4 K6 4
#include <iostream>
using namespace std;
int main() {
// Create the nodes of the 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->right = new Node(6);
return 0;
}
(Or)
QB403 (b) Write a C++ Program to the Left rotate module of the splay tree. CO4 K6 3
#include <iostream>
using namespace std;
return 0;
}
QB404 (a)* Write the search Module of B Tree in C++ CO4 K6 3
#include <iostream>
struct BTreeNode {
};
public:
// Constructor
};
this->t = t;
this->leaf = leaf;
this->n = 0;
}
// Search function that searches for a key in the given node
int i = 0;
i++;
return node;
if (node->leaf) {
return nullptr;
int main() {
BTree tree(3);
root->keys[0] = 10;
root->n = 1;
tree.root = root;
if (result) {
cout << "Key " << keyToSearch << " found in the tree." << endl;
} else {
cout << "Key " << keyToSearch << " not found in the tree." << endl;
}
return 0;
}
(Or)
QB404 (b)* Implement Binary tree in C++ and include insert function for inserting the elements CO4 K6 4
10,25,30,36,56,78
#include <iostream>
struct Node {
int data;
Node* left;
Node* right;
Node(int value) {
data = value;
left = nullptr;
right = nullptr;
};
public:
BinaryTree() {
root = nullptr;
void inorderTraversal() {
inorderRec(root);
private:
if (root == nullptr) {
} else {
if (root != nullptr) {
cout << root->data << " "; // Print the node value
}
}
};
int main() {
BinaryTree tree;
tree.insert(10);
tree.insert(25);
tree.insert(30);
tree.insert(36);
tree.insert(56);
tree.insert(78);
tree.inorderTraversal();
return 0;
}
UNIT - V
Q. No Questions CO Knowledge Difficulty
Level
Level (1-5)
(Blooms)
QB501 (a) Write A C++ Program to implement BFS using vectors and queue CO5 K6 3
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
cout << "BFS Traversal starting from vertex " << start << ": ";
while (!q.empty()) {
int node = q.front(); // Get the front element of the queue
q.pop(); // Remove the front element
cout << node << " "; // Print the visited node
int main() {
// Create a graph with 6 vertices (0 to 5)
Graph g(6);
return 0;
}
(Or)
QB501 (b) Write a C++ Program to get the elements of an Array which needs to be sorted using CO5 K6 4
insertion sort.
#include <iostream>
using namespace std;
// Function to perform Insertion Sort
void insertionSort(int arr[], int n) {
for (int i = 1; i < n; i++) {
int key = arr[i]; // The element to be inserted in the sorted part of the array
int j = i - 1;
// Move elements of arr[0..i-1] that are greater than key to one position ahead
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
// Insert the key at the correct position
arr[j + 1] = key;
}
}
int main() {
int n;
int arr[n];
return 0;
}
QB502 (a)* Write A C++ Program to implement DFS using vector STL CO5 K6 4
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
cout << "DFS Traversal starting from vertex " << start << ": ";
while (!s.empty()) {
int node = s.top(); // Get the top element of the stack
s.pop(); // Pop the top element
cout << node << " "; // Print the visited node
int main() {
// Create a graph with 6 vertices (0 to 5)
Graph g(6);
return 0;
}
(Or)
QB502 (b) Write a C++ Program to Implement the Quick Sort. CO5 K6 4
#include <iostream>
using namespace std;
// Function to partition the array into two sub-arrays based on the pivot
int partition(int arr[], int low, int high) {
int pivot = arr[high]; // Choose the last element as the pivot
int i = low - 1; // Index for the smaller element
int main() {
int n;
int arr[n];
return 0;
}
QB503 (a)* Implement a C++ Program to represent the Adjacency Matrix CO5 K6 4
#include <iostream>
#include <vector>
using namespace std;
class Graph {
public:
int vertices; // Number of vertices
vector<vector<int>> adjMatrix; // Adjacency Matrix to represent the graph
// Constructor to initialize the number of vertices and create the adjacency matrix
Graph(int v) {
vertices = v;
adjMatrix.resize(vertices, vector<int>(vertices, 0)); // Initialize all elements to 0
}
return 0;
}
(Or)
QB503 (b) Write a C++ Program to find the given element in Binary Search. CO5 K6 4
#include <iostream>
using namespace std;
// Loop until the low index is less than or equal to the high index
while (low <= high) {
int mid = low + (high - low) / 2; // Calculate mid index
int main() {
int size, target;
int arr[size];
return 0;
}
QB504 (a)* Write a C++ Program to get the elements of an Array which needs to be sorted using inser- CO5 K6 3
tion sort.
#include <iostream>
#include <vector>
int n = arr.size();
// Start from the second element, because the first element is trivially sorted
int j = i - 1;
// Move elements of arr[0..i-1], that are greater than key, to one position ahead
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
arr[j + 1] = key;
vector<int> unsortedElements;
unsortedElements.push_back(arr[i]);
return unsortedElements;
int main() {
int size;
vector<int> arr(size);
displayArray(arr);
if (!unsortedElements.empty()) {
} else {
insertionSort(arr);
return 0;
}
(Or)
QB504 (b)* CO5 K6 4
Write the quicksort module of Quick Sort in C++.
#include <iostream>
int temp = a;
a = b;
b = temp;
// Function to partition the array into two parts based on the pivot
swap(arr[i], arr[j]);
int main() {
int size;
int arr[size];
displayArray(arr, size);
// Perform QuickSort
quickSort(arr, 0, size - 1);
displayArray(arr, size);
return 0;
UNIT - I
Knowledge
Difficulty
Q. No Questions CO Level
Level (1-5)
(Blooms)
QC101 (a)* Write a C++ program using friend function to find the Armstrong number value among the CO1 K6 3
members of both the classes.
#include <iostream>
#include <cmath>
// ClassB declaration
class ClassB;
// ClassA definition
class ClassA {
int numA;
public:
};
// ClassB definition
class ClassB {
int numB;
public:
};
while (tempA != 0) {
tempA /= 10;
countA++;
while (tempB != 0) {
tempB /= 10;
countB++;
int sumA = 0;
tempA = nA;
while (tempA != 0) {
tempA /= 10;
int sumB = 0;
tempB = nB;
while (tempB != 0) {
tempB /= 10;
// Display results
if (sumA == nA)
else
cout << nA << " in ClassA is NOT an Armstrong number." << endl;
if (sumB == nB)
else
cout << nB << " in ClassB is NOT an Armstrong number." << endl;
int main() {
ClassA objA(numA);
ClassB objB(numB);
checkArmstrong(objA, objB);
return 0;
}
(Or)
QC101 (b)* CO1 K6 4
Write a C++ program using friend function to find the minimum integer value among the
members of both the classes.
#include <iostream>
class ClassB;
// ClassA definition
class ClassA {
private:
int numA;
public:
};
// ClassB definition
class ClassB {
private:
int numB;
public:
int minVal;
// Compare the values of numA and numB and find the minimum
minVal = objA.numA;
} else {
minVal = objB.numB;
cout << "The minimum value among " << objA.numA << " (ClassA) and "
<< objB.numB << " (ClassB) is: " << minVal << endl;
int main() {
ClassA objA(numA);
ClassB objB(numB);
findMin(objA, objB);
return 0;
UNIT - II
Knowledge
Difficulty
Q. No Questions CO Level
Level (1-5)
(Blooms)
QC201 (a)* To develop a C++ program for Electricity Bill calculation using Hybrid inheritance (use CO2 K6 5
service no ,name, previous reading, current reading, unit consumption & amount as data
members)( units<=100 per unit Rs.2.00 ,units>100 and unit<=300 rs=3.00,above 300 units
rs.5.00)
#include <iostream>
using namespace std;
// Base Class 1: For storing basic details
class Customer {
protected:
int serviceNo;
string name;
float previousReading, currentReading;
public:
// Constructor to initialize customer details
Customer(int sNo, string n, float prevReading, float currReading)
: serviceNo(sNo), name(n), previousReading(prevReading),
currentReading(currReading) {}
public:
// Function to calculate unit consumption
void calculateConsumption() {
unitConsumption = currentReading - previousReading;
}
public:
// Constructor to initialize and calculate bill
Bill(int sNo, string n, float prevReading, float currReading)
: Customer(sNo, n, prevReading, currReading) {
calculateConsumption(); // Calculate unit consumption
calculateBill(); // Calculate the bill amount
}
int main() {
int serviceNo;
string name;
float previousReading, currentReading;
// Input customer details and readings
cout << "Enter Service Number: ";
cin >> serviceNo;
cout << "Enter Customer Name: ";
cin.ignore(); // To clear the newline character from the input buffer
getline(cin, name);
cout << "Enter Previous Reading: ";
cin >> previousReading;
cout << "Enter Current Reading: ";
cin >> currentReading;
return 0;
}
(Or)
QC201 (b) i)Write a C++ program to initialize the members of a class and use this pointer to do it. (6) CO2 K6 4
#include <iostream>
using namespace std;
class MyClass {
private:
int num1;
float num2;
public:
// Constructor to initialize class members using 'this' pointer
MyClass(int num1, float num2) {
this->num1 = num1; // Using this pointer to access member variable 'num1'
this->num2 = num2; // Using this pointer to access member variable 'num2'
}
int main() {
MyClass obj(5, 3.14); // Creating an object and passing values to the constructor
obj.display(); // Displaying the values using the display function
return 0;
}
ii) Write a C++ program to demonstrate the use of a virtual destructor by properly
destroying the objects of the parent and the child class. (9)
#include <iostream>
using namespace std;
// Base Class
class Base {
public:
// Virtual destructor in the base class
virtual ~Base() {
cout << "Base class destructor called." << endl;
}
};
// Derived Class
class Derived : public Base {
public:
// Destructor of derived class
~Derived() {
cout << "Derived class destructor called." << endl;
}
};
int main() {
// Creating a pointer of base class type but pointing to derived class object
Base *basePtr = new Derived();
UNIT - III
Knowledge
Difficulty
Q. No Questions CO Level
Level (1-5)
(Blooms)
QC301 (a)* Write a C++ program to create and display Doubly Linked List and delete the first node. CO3 K6 4
#include <iostream>
using namespace std;
public:
// Constructor to initialize an empty list
DoublyLinkedList() {
head = nullptr;
}
// Function to add a node at the end of the list
void insertAtEnd(int data) {
Node* newNode = new Node(data); // Create a new node
if (head == nullptr) {
head = newNode; // If the list is empty, make the new node as head
} else {
Node* temp = head;
while (temp->next != nullptr) {
temp = temp->next; // Traverse to the last node
}
temp->next = newNode; // Link last node's next to the new node
newNode->prev = temp; // Set the new node's prev to the last node
}
}
if (head != nullptr) {
head->prev = nullptr; // Set the previous pointer of the new head to null
}
int main() {
DoublyLinkedList list;
return 0;
}
(Or)
QC301 (b) Write a C++ program to create and display 2 Polynomial Equations Using Linked List and add the same and CO3 K6 4
display the result.
#include <iostream>
using namespace std;
public:
// Constructor to initialize the polynomial to an empty list
Polynomial() {
head = nullptr;
}
int main() {
Polynomial poly1, poly2, result;
UNIT - IV
Q. No Questions CO Knowledge Difficulty
Level Level (1-5)
(Blooms)
QC401 (a) Implement the search module of B Tree and find out if the given char is present in the tree CO4 K6 5
or not.
#include <iostream>
#include <vector>
using namespace std;
// Constructor
BTreeNode(bool leaf = true) {
this->leaf = leaf;
this->numKeys = 0;
}
};
public:
// Constructor
BTree(int degree) {
this->degree = degree;
root = new BTreeNode(true);
}
// Constructor
BTreeNode(bool leaf = true) {
this->leaf = leaf;
this->numKeys = 0;
}
};
public:
// Constructor
BTree(int degree) {
this->degree = degree;
root = new BTreeNode(true);
}
newChild->numKeys = degree - 1;
fullChild->numKeys = degree - 1;
// Copy the second half of the keys from the fullChild to the newChild
for (int i = 0; i < degree - 1; i++) {
newChild->keys.push_back(fullChild->keys[i + degree]);
}
if (!node->leaf) {
for (auto child : node->children) {
display(child, level + 1);
}
}
}
};
int main() {
// Create a B-Tree of degree 3
BTree tree(3);
return 0;
}
UNIT - V
Knowledge
Difficulty
Q. No Questions CO Level
Level (1-5)
(Blooms)
QC501 (a) Given a weighted, undirected and connected graph of V vertices and E edges. Implement a CO5 K6 5
C++ Program to find the sum of weights of the edges of the Minimum Spanning Tree.
public:
DisjointSet(int n) {
parent.resize(n);
rank.resize(n, 0);
for (int i = 0; i < n; ++i) {
parent[i] = i; // Initially, each vertex is its own parent
}
}
// Find the root of the set that contains x with path compression
int find(int x) {
if (parent[x] != x) {
parent[x] = find(parent[x]); // Path compression
}
return parent[x];
}
if (rootX != rootY) {
// Union by rank
if (rank[rootX] > rank[rootY]) {
parent[rootY] = rootX;
} else if (rank[rootX] < rank[rootY]) {
parent[rootX] = rootY;
} else {
parent[rootY] = rootX;
rank[rootX]++;
}
}
}
};
// Function to perform Kruskal’s algorithm and return the sum of the MST weights
int kruskalMST(int V, vector<Edge>& edges) {
// Step 1: Sort all the edges in increasing order of weight
sort(edges.begin(), edges.end());
// Step 2: Iterate over sorted edges and add to MST if no cycle is formed
for (const auto& edge : edges) {
int u = edge.u;
int v = edge.v;
int weight = edge.weight;
int main() {
int V, E;
vector<Edge> edges(E);
// Calculate the sum of the weights of the MST using Kruskal’s Algorithm
int mstWeight = kruskalMST(V, edges);
cout << "The sum of the weights of the edges in the Minimum Spanning Tree is: " <<
mstWeight << endl;
return 0;
}
(Or)
There is an undirected weighted connected graph. You are given a positive integer n which
denotes that the graph has n nodes labeled from 1 to n, and an array edges where
QC501 (b)* CO5 K6 5
each edges[i] = [ui, vi, weighti] denotes that there is an edge between nodes ui and vi with
weight equal to weighti.
Write a C++ Program to find the dijkstra'a shortest path from every node to all other nodes
in the given graph.
#include <iostream>
#include <vector>
#include <queue>
#include <climits>
typedef pair<int, int> pii; // A pair to store the node and the distance
// Dijkstra's Algorithm to find the shortest path from a source node to all other nodes
vector<int> dijkstra(int n, int src, const vector<vector<pii>>& graph) {
// Distance vector to store the shortest distance from src to all other nodes
vector<int> dist(n + 1, INT_MAX);
dist[src] = 0;
// Min-heap priority queue to get the node with the minimum distance
priority_queue<pii, vector<pii>, greater<pii>> pq;
pq.push({0, src}); // {distance, node}
while (!pq.empty()) {
int u = pq.top().second;
int d = pq.top().first;
pq.pop();
return dist;
}
int main() {
int n, e;
cout << "Enter number of nodes (n) and edges (e): ";
cin >> n >> e;
// Input edges
cout << "Enter the edges (u, v, weight):" << endl;
for (int i = 0; i < e; ++i) {
int u, v, weight;
cin >> u >> v >> weight;
graph[u].push_back({v, weight});
graph[v].push_back({u, weight}); // As the graph is undirected
}
// For each node, calculate the shortest paths to all other nodes using Dijkstra's algorithm
for (int i = 1; i <= n; ++i) {
vector<int> dist = dijkstra(n, i, graph);
return 0;
}
Applying
K1 Remembering (Knowledge) K2 Understanding (Comprehension) K3
(Application of Knowledge)