0% found this document useful (0 votes)
13 views

19CS401 C++ Question Answer Key Nov 2024

1

Uploaded by

sanjays66869
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

19CS401 C++ Question Answer Key Nov 2024

1

Uploaded by

sanjays66869
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 126

Question Repository for Nov 2024 Examinations

DATA STRUCTURES AND OBJECT Common To


Subject Code 19CS401 Subject Name ORIENTED PROGRAMMING
USING C++
Mention the
Faculty Name Mr. TENALI RAVI KUMAR Department CSE Branches here

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

// Prompt user for input


cout << "Enter the first operand: ";
QA108* cin >> operand1; CO1 K3 2

cout << "Enter the second operand: ";


cin >> operand2;

// Display the values entered


cout << "You entered:" << endl;
cout << "First operand: " << operand1 << endl;
cout << "Second operand: " << operand2 << endl;

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++.

Inheritance is a fundamental concept in Object-Oriented Programming (OOP) that allows a class


QA201 CO2 K1 1
to inherit attributes and methods from another class.
Types of Inheritance: Single Inheritance, Multiple Inheritance, Multilevel Inheritance, Hierarchi-
cal Inheritance and Hybrid (or Virtual) Inheritance
Describe about private members with an example.

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
}

// Function to display the student details


void display() {
cout << "Registration Number: " << this->regNo << endl;
cout << "Name: " << this->name << endl;
}
};
QA208* Write a C++ program to read empno,empname & empgender in one class and display the above CO2 K3 2
details in another class using inheritance

#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:

1. Data: The actual value or information that the node stores.


2. Next: A pointer or reference to the next node in the list (or NULL if it is the last node).
QA302* CO3 K2 1
struct Node {
int data; // Data part of the node
Node* next; // Pointer to the next node
};

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:

1. Data: The actual data or value stored in the node.


2. Previous: A pointer or reference to the previous node in the list.
3. Next: A pointer or reference to the next node in the list.

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

 Postfix: The operator is placed after the operands.


QA306* CO3 K2 1
 Prefix: The operator is placed before the operands.
 Both notations avoid the need for parentheses or complex precedence rules, making them
easier to evaluate using stacks.

Convert the following Infix expression to Postfix form using a stack.


X + Y * Z + (P * Q + R) * S
QA307* CO3 K2 1
XYZ*+PQ*R+S*+

Convert the following infix expressions into its equivalent postfix expressions.

QA308* (A + B ⋀D)/(E – F)+G CO3 K2 1

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:

 Pre-order (Root, Left, Right)


 In-order (Left, Root, Right)
 Post-order (Left, Right, Root)
QA402*  Level-order (Breadth-first traversal) CO4 K2 1

 Search: Finding a node with a given value in the tree.

 Insertion: Adding a new node to the tree.

 Deletion: Removing a node from the tree.

 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

 Pre-order: Root node first, then left and right subtrees.


QA405 CO4 K2 1
 In-order: Left subtree first, then root, then right subtree.
 Post-order: Left and right subtrees first, then root node.
 Level-order: Nodes are visited in levels, from top to bottom.
List the Properties of B Trees

Balanced Tree Structure


Multiple Keys in Each Node
QA406* CO4 K2 1
Degree of a B-Tree
Number of Keys in a Node
All Leaves at the Same Level
Efficient Search, Insertion, and Deletion
List the applications of B Trees

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)

Network Design (Computer Networks, Telecommunication, Power Grids)


Transportation Networks
QA503 CO5 K2 1
Cluster Analysis in Data Mining
Image Processing and Computer Vision
Approximation Algorithms for NP-Hard Problems
Broadcasting in Networks
Define BFS

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 .

An Undirected Graph is a type of graph in which edges have no direction. In an undirected


QA507* CO5 K2 1
graph, edges connect pairs of vertices in both directions. If there is an edge between vertices A
and B, it implies that A is connected to B and B is also connected to A. There is no distinction
between the start and end vertices, making it bidirectional.
Define Directed Graph with example.

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

(PART B – 13 Marks - Either Or Type)

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;

cout << "Fibonacci Series: ";


for (int i = 0; i < n; i++) {
if (i <= 1) {
next = i; // First two terms are 0 and 1
} else {
next = first + second;
first = second;
second = next;
}
cout << next << " ";
}
cout << endl;
}
};

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 ClassA; // Forward declaration

class ClassB {
private:
int valueB;

public:
// Constructor to initialize valueB
ClassB(int b) : valueB(b) {}

// Friend function declaration


friend int findMin(ClassA, ClassB);
};

class ClassA {
private:
int valueA;

public:
// Constructor to initialize valueA
ClassA(int a) : valueA(a) {}

// Friend function declaration


friend int findMin(ClassA, ClassB);
};

// Friend function to find the minimum of valueA and valueB


int findMin(ClassA objA, ClassB objB) {
return (objA.valueA < objB.valueB) ? objA.valueA : objB.valueB;
}
int main() {
int a, b;

// Input values for both classes


cout << "Enter an integer for ClassA: ";
cin >> a;
cout << "Enter an integer for ClassB: ";
cin >> b;

// Create objects of ClassA and ClassB


ClassA objA(a);
ClassB objB(b);

// Call the friend function to find the minimum


int minValue = findMin(objA, objB);
cout << "The minimum value is: " << minValue << endl;

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;

// Class to calculate Simple Interest


class SimpleInterest {
private:
double principal; // Principal amount
double time; // Time period in years
double rate; // Rate of interest per year

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

// Call method to calculate and display simple interest


si.calculateInterest();

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>

using namespace std;

class Shape {

private:

double length, width, side;

public:

// Constructor for rectangle (length and width)

Shape(double l, double w) {

length = l;

width = w;

cout << "Rectangle area: " << calculateArea() << endl;

// Constructor for square (side)

Shape(double s) {

side = s;

cout << "Square area: " << calculateArea() << endl;

}
// Function to calculate the area of a rectangle

double calculateArea() {

if (length != 0 && width != 0) {

return length * width; // Area of rectangle

return side * side; // Area of square

};

int main() {

// Creating objects with compile-time initialization

Shape rectangle(5.0, 3.0); // Rectangle with length 5.0 and width 3.0

Shape square(4.0); // Square with side 4.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;

// Base class for addition and subtraction

class ArithmeticAddSubtract {

public:

// Function for addition

int add(int a, int b) {

return a + b;

// Function for subtraction

int subtract(int a, int b) {

return a - b;

};

// Base class for multiplication and division

class ArithmeticMultiplyDivide {

public:

// Function for multiplication

int multiply(int a, int b) {

return a * b;

}
// Function for division

int divide(int a, int b) {

if (b != 0) {

return a / b;

} else {

cout << "Error! Division by zero." << endl;

return 0;

};

// Derived class that inherits from both ArithmeticAddSubtract and


ArithmeticMultiplyDivide

class ArithmeticOperations : public ArithmeticAddSubtract, public


ArithmeticMultiplyDivide {

public:

// Constructor to display a message (optional)

ArithmeticOperations() {

cout << "Arithmetic Operations Initialized!" << endl;

};
int main() {

int x, y;

// Get input values for x and y

cout << "Enter two integers: ";

cin >> x >> y;

// Create an object of ArithmeticOperations (derived class)

ArithmeticOperations obj;

// Perform arithmetic operations using the object of the derived class

cout << "Addition: " << obj.add(x, y) << endl;

cout << "Subtraction: " << obj.subtract(x, y) << endl;

cout << "Multiplication: " << obj.multiply(x, y) << endl;

cout << "Division: " << obj.divide(x, y) << endl;

return 0;

(Or)
QB201 (b) Write a c++ program to find difference & quotient of two numbers using Hierarchical CO2 K6 3
inheritance

#include <iostream>

using namespace std;


// Base class Arithmetic

class Arithmetic {

protected:

int num1, num2;

public:

// Function to take input

void input() {

cout << "Enter two integers: ";

cin >> num1 >> num2;

};

// Derived class Difference

class Difference : public Arithmetic {

public:

// Function to calculate the difference

void calculateDifference() {

int diff = num1 - num2;

cout << "Difference: " << diff << endl;

};
// Derived class Quotient

class Quotient : public Arithmetic {

public:

// Function to calculate the quotient

void calculateQuotient() {

if (num2 != 0) {

double quotient = static_cast<double>(num1) / num2; // Handle division

cout << "Quotient: " << quotient << endl;

} else {

cout << "Error! Division by zero." << endl;

};

int main() {

// Create objects of derived classes

Difference diffObj;

Quotient quotObj;

// Input the values for num1 and num2

diffObj.input();

quotObj.input();

// Calculate and display the difference


diffObj.calculateDifference();

// Calculate and display the quotient

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

// Derived class that calculates the product


class Product : public Base1, public Base2 {
public:
// Function to calculate and display the product
void calculateProduct() {
int product = num1 * num2;
cout << "The product of " << num1 << " and " << num2 << " is: " << product << endl;
}
};

int main() {
// Create an object of the derived class Product
Product p;

// Get the numbers from the base classes


p.getNum1();
p.getNum2();

// Calculate and display the product of the two numbers


p.calculateProduct();

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;

// Base class India


class India {
public:
// Virtual function to be overridden by derived classes
virtual void population() {
cout << "Population of India: 150 crore" << endl;
}
};

// Base class China


class China {
public:
// Virtual function to be overridden by derived classes
virtual void population() {
cout << "Population of China: 200 crore" << endl;
}
};

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

// Call the population function of Asia


asia.population();
return 0;
}
QB203 (a)* Write a C++ program to demonstrate on the object composition (use int data) CO2 K6 3
class A{
// body of a class
};
class B{
A objA;
public:
B(arg-list) : objA(arg-list1);
};

#include <iostream>
using namespace std;

// Class A with an integer data member


class A {
int data; // private data member of class A

public:
// Constructor to initialize data
A(int d) : data(d) {}

// Member function to display the value of data


void displayData() {
cout << "Value of data in class A: " << data << endl;
}
};

// Class B contains an object of class A


class B {
A objA; // Composition: object of class A inside class B

public:
// Constructor of class B takes an argument to initialize objA
B(int val) : objA(val) {}

// Member function to display data of objA (from class A)


void display() {
objA.displayData();
}
};

int main() {
int value;

// Get an integer value from the user


cout << "Enter an integer value: ";
cin >> value;

// Create an object of class B, which will create an object of A inside it


B objB(value);

// Call display function of class B to display the data from class A


objB.display();

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;

// Base class with a constructor that takes a password as a parameter


class Base {
public:
// Constructor to accept the password
Base(string password) {
cout << "Password received in Base class: " << password << endl;
}
};

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

// Create an object of Derived class and pass the password


Derived obj(password);

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>

using namespace std;

class Character {

private:

char ch; // Character data member

public:

// Constructor to initialize the character

Character(char c) : ch(c) {}

// Conversion function to convert character to int (ASCII value)

operator int() {
return static_cast<int>(ch); // Convert character to its ASCII value

// Display the character

void displayCharacter() {

cout << "Character: " << ch << endl;

};

int main() {

// Create an object of class Character

Character obj('A'); // 'A' is a character

// Display the character

obj.displayCharacter();

// Convert Character object to int using the conversion function

int asciiValue = obj; // This calls the conversion operator

// Display the ASCII value of the character

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>

using namespace std;

// Base class with a virtual destructor

class Base {

public:

// Constructor of Base class

Base() {

cout << "Base class constructor called." << endl;

// Virtual destructor to ensure proper cleanup

virtual ~Base() {

cout << "Base class destructor called." << endl;

};

// Derived class inheriting from Base

class Derived : public Base {

public:

// Constructor of Derived class

Derived() {

cout << "Derived class constructor called." << endl;


}

// Destructor of Derived class

~Derived() {

cout << "Derived class destructor called." << endl;

};

int main() {

// Create a pointer of Base class type

Base* basePtr;

// Create an object of Derived class

basePtr = new Derived();

// Deleting the derived class object through base class pointer

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

using namespace std;

int main() {
// Create a stack of integers
stack<int> s;

// Push elements onto the stack


s.push(10);
s.push(20);
s.push(30);
QB301 (a)* s.push(40); CO3 K6 3
s.push(50);

// Display the elements in the stack (top to bottom)


cout << "Stack elements (top to bottom):" << endl;

// Since STL stack does not allow direct access to elements,


// we have to pop the elements to display them (from top to bottom).
while (!s.empty()) {
cout << s.top() << " "; // Display the top element
s.pop(); // Remove the top element from the stack
}

cout << endl;

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>

#include <queue> // Include the queue header

using namespace std;

int main() {

// Create a queue of integers

queue<int> q;

// Enqueue elements into the queue (using push operation)

q.push(10);

q.push(20);

q.push(30);

q.push(40);

q.push(50);

// Display the elements in the queue (front to back)

cout << "Queue elements (front to back):" << endl;

// Since we can't directly access elements in a queue,

// we use a loop to display the front element and remove it.

while (!q.empty()) {

cout << q.front() << " "; // Display the front element

q.pop(); // Remove the front element from the queue


}

cout << endl;

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;

// Calculate waiting times


for (int i = 1; i < n; ++i) {
waitingTimes[i] = burstTimes[i - 1] + waitingTimes[i - 1];
}

// Display individual waiting times for each process


cout << "\nProcess\tBurst Time\tWaiting Time\n";
for (int i = 0; i < n; ++i) {
cout << "P" << i + 1 << "\t" << burstTimes[i] << "\t\t" << waitingTimes[i] << endl;
totalWaitingTime += waitingTimes[i];
}
// Calculate and display average waiting time
double avgWaitingTime = (double)totalWaitingTime / n;
cout << "\nAverage Waiting Time: " << avgWaitingTime << endl;
}

int main() {
int n;

// Input number of processes


cout << "Enter number of processes: ";
cin >> n;

vector<int> burstTimes(n);

// Input burst times for each process


cout << "Enter the burst time for each process: \n";
for (int i = 0; i < n; ++i) {
cout << "Burst time for P" << i + 1 << ": ";
cin >> burstTimes[i];
}

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

using namespace std;


// Function to check if the character is an operator
bool isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/');
}

// Function to check precedence of operators


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

// Function to reverse the string


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

// Function to convert infix to postfix


string infixToPostfix(const string& infix) {
stack<char> s;
string postfix;

for (char c : infix) {


// If the character is an operand, append it to the postfix expression
if (isalnum(c)) {
postfix += c;
}
// If the character is '(', push it to the stack
else if (c == '(') {
s.push(c);
}
// If the character is ')', pop until '(' is found
else if (c == ')') {
while (!s.empty() && s.top() != '(') {
postfix += s.top();
s.pop();
}
s.pop(); // Pop the '('
}
// If the character is an operator, pop operators with higher or equal precedence
else if (isOperator(c)) {
while (!s.empty() && precedence(s.top()) >= precedence(c)) {
postfix += s.top();
s.pop();
}
s.push(c);
}
}

// Pop all remaining operators in the stack


while (!s.empty()) {
postfix += s.top();
s.pop();
}

return postfix;
}

// Function to convert infix to prefix


string infixToPrefix(const string& infix) {
// Reverse the infix expression
string reversedInfix = reverseString(infix);

// Replace '(' with ')' and vice versa


for (int i = 0; i < reversedInfix.length(); i++) {
if (reversedInfix[i] == '(') {
reversedInfix[i] = ')';
} else if (reversedInfix[i] == ')') {
reversedInfix[i] = '(';
}
}

// Convert the reversed infix to postfix


string postfix = infixToPostfix(reversedInfix);

// Reverse the postfix to get the prefix


return reverseString(postfix);
}

int main() {
string infix = "(a+b*c-d)"; // Input infix expression

// Convert the infix expression to prefix


string prefix = infixToPrefix(infix);

cout << "Infix Expression: " << infix << endl;


cout << "Prefix Expression: " << prefix << endl;

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;

// Constructor to initialize the node with a value


Node(int value) {
data = value;
next = nullptr;
}
};

// Class for Singly Linked List


class SinglyLinkedList {
private:
Node* head; // Head of the list

public:
// Constructor to initialize an empty list
SinglyLinkedList() {
head = nullptr;
}

// Function to insert a new node at the end of the list


void insert(int value) {
Node* newNode = new Node(value);
if (!head) {
head = newNode;
} else {
Node* temp = head;
while (temp->next) {
temp = temp->next;
}
temp->next = newNode;
}
}

// Function to display the linked list


void display() {
if (!head) {
cout << "List is empty." << endl;
return;
}
Node* temp = head;
while (temp) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}

// Function to delete the middle node of the linked list


void deleteMiddle() {
if (!head || !head->next) {
cout << "List is too short to delete middle node." << endl;
return;
}
// Initialize two pointers (slow and fast)
Node* slow = head;
Node* fast = head;
Node* prev = nullptr;

// Traverse the list with fast and slow pointers


while (fast && fast->next) {
fast = fast->next->next;
prev = slow;
slow = slow->next;
}

// Delete the middle node (slow pointer)


if (prev) {
prev->next = slow->next;
}
delete slow;
cout << "Middle node deleted." << endl;
}

// Destructor to free allocated memory


~SinglyLinkedList() {
Node* current = head;
Node* nextNode;
while (current) {
nextNode = current->next;
delete current;
current = nextNode;
}
}
};

int main() {
SinglyLinkedList list;

// Insert elements into the list


list.insert(10);
list.insert(20);
list.insert(30);
list.insert(40);
list.insert(50);

// Display the original list


cout << "Original List: ";
list.display();

// Delete the middle node


list.deleteMiddle();

// Display the list after deleting the middle node


cout << "List after deleting the middle node: ";
list.display();

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>

using namespace std;

// Node structure

struct Node {

int data;

Node* next;

// Constructor to initialize the node with a value

Node(int value) {

data = value;
next = nullptr;

};

// Class for Circular Linked List

class CircularLinkedList {

private:

Node* head; // Head of the list

public:

// Constructor to initialize an empty list

CircularLinkedList() {

head = nullptr;

// Function to insert a new node at the end of the list

void insert(int value) {

Node* newNode = new Node(value);

if (!head) {

head = newNode;

newNode->next = head; // Point to itself, as it is circular

} else {

Node* temp = head;

while (temp->next != head) { // Traverse till the last node


temp = temp->next;

temp->next = newNode; // Link the last node to the new node

newNode->next = head; // Make the new node point to head

// Function to display the circular linked list

void display() {

if (!head) {

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

return;

Node* temp = head;

do {

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

temp = temp->next;

} while (temp != head); // Stop when we reach the head again

cout << endl;

// Function to delete the middle node of the circular linked list

void deleteMiddle() {
if (!head || head->next == head) {

cout << "List is too short to delete middle node." << endl;

return;

// Initialize two pointers (slow and fast)

Node* slow = head;

Node* fast = head;

Node* prev = nullptr;

// Traverse the list with fast and slow pointers

while (fast != head && fast->next != head) {

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

prev->next = slow->next; // Bypass the middle node

if (slow == head) { // Special case: if the middle node is the head

head = slow->next;

}
delete slow;

cout << "Middle node deleted." << endl;

// Destructor to free allocated memory

~CircularLinkedList() {

if (!head) return;

Node* current = head;

Node* nextNode;

// Loop to free the nodes

do {

nextNode = current->next;

delete current;

current = nextNode;

} while (current != head); // Stop when we reach back to head

};

int main() {

CircularLinkedList list;

// Insert elements into the list

list.insert(10);

list.insert(20);
list.insert(30);

list.insert(40);

list.insert(50);

// Display the original list

cout << "Original List: ";

list.display();

// Delete the middle node

list.deleteMiddle();

// Display the list after deleting the middle node

cout << "List after deleting the middle node: ";

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>

#include <queue> // Include the queue header from STL

using namespace std;

int main() {

// Create a queue of integers

queue<int> q;

// Insert five integer elements into the queue


q.push(10);

q.push(20);

q.push(30);

q.push(40);

q.push(50);

// Display the elements of the queue

cout << "Elements in the queue: ";

while (!q.empty()) {

cout << q.front() << " "; // Display the front element

q.pop(); // Remove the front element from the queue

cout << endl;

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>

#include <stack> // Include the stack header from STL


using namespace std;

int main() {

// Create a stack of characters

stack<char> s;

// Insert five special characters into the stack

s.push('@');

s.push('#');

s.push('$');

s.push('%');

s.push('^');

// Display and remove elements from the stack

cout << "Elements in the stack (in LIFO order): ";

while (!s.empty()) {

cout << s.top() << " "; // Display the top element

s.pop(); // Remove the top element from the stack

cout << endl;

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>

using namespace std;

// Define the color constants for Red and Black

enum Color { RED, BLACK };

// Define a structure for Red-Black Tree Node

struct Node {

int data;

Color color;

Node* left;

Node* right;

Node* parent;

// Constructor to initialize a new node

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

};

// Red-Black Tree class


class RedBlackTree {

private:

Node* root;

public:

// Constructor to initialize an empty tree

RedBlackTree() : root(nullptr) {}

// Right Rotation function

void rightRotate(Node* y) {

// Perform a right rotation on node y

Node* x = y->left; // Left child of y becomes the new root

Node* T2 = x->right; // Right subtree of x becomes the left subtree of y

// Perform the rotation

x->right = y;

y->left = T2;

// Update the parent pointers

if (T2 != nullptr) {

T2->parent = y;

// Update the parent of x


x->parent = y->parent;

// If y was the root, update the root pointer

if (y->parent == nullptr) {

root = x;

} else if (y == y->parent->left) {

y->parent->left = x;

} else {

y->parent->right = x;

// Update the parent of y

y->parent = x;

// Utility function to insert a node into the Red-Black Tree

void insert(int value) {

Node* newNode = new Node(value);

if (root == nullptr) {

root = newNode;

root->color = BLACK; // The root is always black


} else {

insertHelper(root, newNode);

// Helper function for insertion

void insertHelper(Node* root, Node* newNode) {

if (root == nullptr) {

return;

if (newNode->data < root->data) {

if (root->left == nullptr) {

root->left = newNode;

newNode->parent = root;

rightRotate(root); // Perform right rotation after insertion

} else {

insertHelper(root->left, newNode);

} else {

if (root->right == nullptr) {
root->right = newNode;

newNode->parent = root;

rightRotate(root); // Perform right rotation after insertion

} else {

insertHelper(root->right, newNode);

// Function to display the tree structure (inorder traversal)

void inorderTraversal(Node* node) {

if (node != nullptr) {

inorderTraversal(node->left);

cout << node->data << " ";

inorderTraversal(node->right);

// Public function to display the tree

void display() {

inorderTraversal(root);
cout << endl;

// Function to return the root of the tree

Node* getRoot() {

return root;

};

int main() {

RedBlackTree tree;

// Insert elements into the Red-Black Tree

tree.insert(20);

tree.insert(15);

tree.insert(30);

tree.insert(10);

tree.insert(25);

// Display the tree after insertion

cout << "Inorder traversal of the tree after insertion: ";

tree.display();

// Perform a right rotation


Node* root = tree.getRoot();

cout << "Performing right rotation on the root node (20):" << endl;

tree.rightRotate(root);

// Display the tree after right rotation

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>

using namespace std;

// Define the structure for a binary tree node

struct Node {

int data;

Node* left;
Node* right;

// Constructor to create a new node

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

};

// Function for Postorder Traversal

void postorderTraversal(Node* root) {

if (root == nullptr) {

return;

// Traverse the left subtree

postorderTraversal(root->left);

// Traverse the right subtree

postorderTraversal(root->right);

// Visit the node

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

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

// Perform the Postorder traversal and display the output

cout << "Postorder Traversal of the Tree: ";

postorderTraversal(root);

cout << endl;

return 0;

}
QB402 (a) Write C++ program to the findParent Module of the BPlus Tree CO4 K6 4

#include <iostream>
#include <vector>

using namespace std;

// Define the BPlus Tree Node structure


struct BPlusNode {
bool isLeaf;
vector<int> keys; // Holds the keys
vector<BPlusNode*> children; // Points to child nodes (or data in case of leaf nodes)

BPlusNode(bool leaf = false) : isLeaf(leaf) {}


};

// BPlusTree class definition


class BPlusTree {
private:
BPlusNode* root;

public:
BPlusTree() {
root = new BPlusNode(true); // Initialize with a leaf root
}

// Function to insert a key into the B+ Tree


void insert(int key);

// Function to find the parent of a given node


BPlusNode* findParent(BPlusNode* child, BPlusNode* node = nullptr);

// Function to display the tree in a simple manner


void display(BPlusNode* node, int level = 0);

// Getter for root


BPlusNode* getRoot() {
return 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);
}

BPlusNode* node = root;


while (!node->isLeaf) {
// Traverse to the correct child node
bool found = false;
for (int i = 0; i < node->keys.size(); ++i) {
if (key < node->keys[i]) {
node = node->children[i];
found = true;
break;
}
}
if (!found) {
node = node->children[node->keys.size()];
}
}

// Insert into the leaf node


node->keys.push_back(key);
sort(node->keys.begin(), node->keys.end());
}

// Function to find the parent of a given node


BPlusNode* BPlusTree::findParent(BPlusNode* child, BPlusNode* node) {
if (node == nullptr) {
node = root;
}

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

// Recursively search in internal nodes


for (BPlusNode* childNode : node->children) {
if (!childNode->isLeaf) {
BPlusNode* parent = findParent(child, childNode);
if (parent != nullptr) {
return parent;
}
}
}

// Return nullptr if no parent is found


return nullptr;
}
// Function to display the tree (used for debugging)
void BPlusTree::display(BPlusNode* node, int level) {
if (node == nullptr) return;

// Print the current node keys


cout << "Level " << level << ": ";
for (int key : node->keys) {
cout << key << " ";
}
cout << endl;

// Recursively display the children if the node is not a leaf


if (!node->isLeaf) {
for (BPlusNode* child : node->children) {
display(child, level + 1);
}
}
}

int main() {
BPlusTree tree;

// Insert some keys into the B+ Tree


tree.insert(10);
tree.insert(20);
tree.insert(30);
tree.insert(40);
tree.insert(50);
tree.insert(60);
tree.insert(70);

// Display the tree


cout << "BPlus Tree Structure:" << endl;
tree.display(tree.getRoot());

// Assuming we want to find the parent of node containing 40


BPlusNode* parent = tree.findParent(tree.getRoot()->children[0]); // Example child node
if (parent != nullptr) {
cout << "Parent node found. Parent keys: ";
for (int key : parent->keys) {
cout << key << " ";
}
cout << endl;
} else {
cout << "Parent not found." << endl;
}

return 0;
}
(Or)
QB402 (b)* Write a C++ Program to perform Preorder traversal of the below given tree CO4 K6 4

#include <iostream>

using namespace std;

// Define the structure for a binary tree node

struct Node {

int data;

Node* left;

Node* right;

// Constructor to create a new node

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


};

// Function for Preorder Traversal

void preorderTraversal(Node* root) {

if (root == nullptr) {

return;

// Visit the node

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

// Traverse the left subtree

preorderTraversal(root->left);

// Traverse the right subtree

preorderTraversal(root->right);

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

// Perform the Preorder traversal and display the output

cout << "Preorder Traversal of the Tree: ";

preorderTraversal(root);

cout << endl;

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;

// Define the structure for a binary tree node


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

// Constructor to create a new node


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

// Function for Postorder Traversal


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

// Traverse the left subtree


postorderTraversal(root->left);

// Traverse the right subtree


postorderTraversal(root->right);

// Visit the node


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

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

// Perform the Postorder traversal and display the output


cout << "Postorder Traversal of the Tree: ";
postorderTraversal(root);
cout << endl;

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;

// Define the structure for a node of Splay Tree


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

// Constructor to initialize the node


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

// Function to perform left rotation


Node* leftRotate(Node* root) {
if (root == nullptr || root->right == nullptr) {
return root; // No rotation is possible if the node has no right child
}

Node* newRoot = root->right; // New root after left rotation


root->right = newRoot->left; // Move the left subtree of the new root to the right of
the old root
newRoot->left = root; // Move the old root to the left of the new root

return newRoot; // Return the new root of the subtree


}

// Function to perform Preorder traversal


void preorderTraversal(Node* root) {
if (root == nullptr) return;
cout << root->data << " ";
preorderTraversal(root->left);
preorderTraversal(root->right);
}

// Main function to demonstrate the left rotation


int main() {
// Create a simple splay tree manually
Node* root = new Node(10);
root->right = new Node(20);
root->right->right = new Node(30);

cout << "Tree before Left Rotation (Preorder): ";


preorderTraversal(root);
cout << endl;
// Perform the Left rotation on the root
root = leftRotate(root);

cout << "Tree after Left Rotation (Preorder): ";


preorderTraversal(root);
cout << endl;

return 0;
}
QB404 (a)* Write the search Module of B Tree in C++ CO4 K6 3

#include <iostream>

using namespace std;

// Define a structure for B-tree node

struct BTreeNode {

int *keys; // Array of keys in the node

int t; // Minimum degree (defines the range for number of keys)

BTreeNode **children; // Array of child pointers

int n; // Current number of keys in the node

bool leaf; // True if the node is a leaf, false otherwise

// Constructor to create a B-tree node

BTreeNode(int t, bool leaf);

};

// Define the structure for B-tree itself


class BTree {

public:

BTreeNode *root; // Root node of the B-tree

int t; // Minimum degree of B-tree

// Constructor

BTree(int t) : root(nullptr), t(t) {}

// Search function in B-tree

BTreeNode* search(BTreeNode *node, int key);

// Helper function to start search from the root

BTreeNode* search(int key);

};

// Constructor for BTreeNode

BTreeNode::BTreeNode(int t, bool leaf) {

this->t = t;

this->leaf = leaf;

this->keys = new int[2*t - 1];

this->children = new BTreeNode*[2*t];

this->n = 0;

}
// Search function that searches for a key in the given node

BTreeNode* BTree::search(BTreeNode *node, int key) {

int i = 0;

// Find the first key greater than or equal to the key

while (i < node->n && key > node->keys[i]) {

i++;

// If the key is found, return this node

if (i < node->n && node->keys[i] == key) {

return node;

// If the node is a leaf, the key is not present

if (node->leaf) {

return nullptr;

// Move to the next child to continue searching

return search(node->children[i], key);

// Helper function to start search from the root


BTreeNode* BTree::search(int key) {

return search(root, key);

int main() {

// Create a B-tree of minimum degree 3

BTree tree(3);

// Example B-tree nodes (manually created for demonstration purposes)

// In a complete implementation, you would insert keys here.

BTreeNode *root = new BTreeNode(3, true);

root->keys[0] = 10;

root->n = 1;

// The tree initially has only the root node

tree.root = root;

int keyToSearch = 10;

BTreeNode *result = tree.search(keyToSearch);

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>

using namespace std;

// Define a structure for a Binary Tree Node

struct Node {

int data;

Node* left;

Node* right;

// Constructor to create a new node

Node(int value) {

data = value;

left = nullptr;

right = nullptr;

};

// Define a class for Binary Tree


class BinaryTree {

public:

Node* root; // Root node of the tree

// Constructor to initialize an empty tree

BinaryTree() {

root = nullptr;

// Insert function to insert elements into the tree

void insert(int value) {

root = insertRec(root, value);

// Inorder Traversal to display the tree

void inorderTraversal() {

inorderRec(root);

cout << endl;

private:

// Recursive insert function to add elements to the tree

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


// If the tree is empty, return a new node

if (root == nullptr) {

return new Node(value);

// Otherwise, recur down the tree

if (value < root->data) {

root->left = insertRec(root->left, value); // Insert in the left subtree

} else {

root->right = insertRec(root->right, value); // Insert in the right subtree

return root; // Return the (unchanged) node pointer

// Recursive inorder traversal to print the tree

void inorderRec(Node* root) {

if (root != nullptr) {

inorderRec(root->left); // Visit the left subtree

cout << root->data << " "; // Print the node value

inorderRec(root->right); // Visit the right subtree

}
}

};

int main() {

// Create a Binary Tree object

BinaryTree tree;

// Insert elements into the binary tree

tree.insert(10);

tree.insert(25);

tree.insert(30);

tree.insert(36);

tree.insert(56);

tree.insert(78);

// Display the tree using Inorder Traversal

cout << "Inorder Traversal of the Binary Tree: ";

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;

// Class to represent a graph


class Graph {
public:
int vertices; // Number of vertices in the graph
vector<vector<int>> adjList; // Adjacency list representation of the graph

// Constructor to initialize the graph with a given number of vertices


Graph(int v) {
vertices = v;
adjList.resize(v);
}

// Function to add an edge in an undirected graph


void addEdge(int u, int v) {
adjList[u].push_back(v); // Add v to u’s list
adjList[v].push_back(u); // Add u to v’s list (since it's undirected)
}

// Function to perform BFS starting from a given source vertex


void BFS(int start) {
vector<bool> visited(vertices, false); // Visited array to mark visited nodes
queue<int> q; // Queue to hold vertices for BFS

// Start BFS from the given start vertex


visited[start] = true;
q.push(start);

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

// Visit all the adjacent nodes of the current node


for (int neighbor : adjList[node]) {
if (!visited[neighbor]) { // If the neighbor hasn't been visited
visited[neighbor] = true; // Mark it visited
q.push(neighbor); // Push it into the queue
}
}
}
cout << endl;
}
};

int main() {
// Create a graph with 6 vertices (0 to 5)
Graph g(6);

// Add edges to the graph


g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 3);
g.addEdge(1, 4);
g.addEdge(2, 5);

// Perform BFS starting from vertex 0


g.BFS(0);

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

// Function to print the array elements


void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
}

int main() {
int n;

// Read the size of the array


cout << "Enter the number of elements: ";
cin >> n;

int arr[n];

// Read the elements of the array


cout << "Enter the elements of the array: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
// Print the original array
cout << "Original Array: ";
printArray(arr, n);

// Perform Insertion Sort


insertionSort(arr, n);

// Print the sorted array


cout << "Sorted Array: ";
printArray(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;

// Class to represent a graph


class Graph {
public:
int vertices; // Number of vertices in the graph
vector<vector<int>> adjList; // Adjacency list representation of the graph

// Constructor to initialize the graph with a given number of vertices


Graph(int v) {
vertices = v;
adjList.resize(v);
}

// Function to add an edge in an undirected graph


void addEdge(int u, int v) {
adjList[u].push_back(v); // Add v to u’s list
adjList[v].push_back(u); // Add u to v’s list (since it's undirected)
}

// Function to perform DFS starting from a given source vertex


void DFS(int start) {
vector<bool> visited(vertices, false); // Visited array to mark visited nodes
stack<int> s; // Stack to hold vertices for DFS

// Start DFS from the given start vertex


visited[start] = true;
s.push(start);

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

// Visit all the adjacent nodes of the current node


for (int neighbor : adjList[node]) {
if (!visited[neighbor]) { // If the neighbor hasn't been visited
visited[neighbor] = true; // Mark it visited
s.push(neighbor); // Push it into the stack
}
}
}
cout << endl;
}
};

int main() {
// Create a graph with 6 vertices (0 to 5)
Graph g(6);

// Add edges to the graph


g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 3);
g.addEdge(1, 4);
g.addEdge(2, 5);

// Perform DFS starting from vertex 0


g.DFS(0);

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

// Iterate through the array and swap elements as needed


for (int j = low; j < high; j++) {
if (arr[j] < pivot) {
i++; // Increment the index of the smaller element
swap(arr[i], arr[j]); // Swap elements
}
}

// Swap the pivot element to its correct position


swap(arr[i + 1], arr[high]);
return i + 1; // Return the index of the pivot
}

// Function to implement Quick Sort algorithm


void quickSort(int arr[], int low, int high) {
if (low < high) {
// Find the pivot index where the array is partitioned
int pi = partition(arr, low, high);

// Recursively sort the two sub-arrays


quickSort(arr, low, pi - 1); // Sort the left sub-array
quickSort(arr, pi + 1, high); // Sort the right sub-array
}
}
// Function to print the array
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
}

int main() {
int n;

// Read the size of the array


cout << "Enter the number of elements: ";
cin >> n;

int arr[n];

// Read the elements of the array


cout << "Enter the elements: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}

// Print the original array


cout << "Original Array: ";
printArray(arr, n);

// Perform Quick Sort


quickSort(arr, 0, n - 1);

// Print the sorted array


cout << "Sorted Array: ";
printArray(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
}

// Function to add an edge between two vertices (for an undirected graph)


void addEdge(int u, int v) {
adjMatrix[u][v] = 1; // Set the edge from u to v
adjMatrix[v][u] = 1; // Since it's an undirected graph, set the edge from v to u as well
}

// Function to display the adjacency matrix


void displayMatrix() {
cout << "Adjacency Matrix:" << endl;
for (int i = 0; i < vertices; i++) {
for (int j = 0; j < vertices; j++) {
cout << adjMatrix[i][j] << " "; // Print each element of the matrix
}
cout << endl;
}
}

// Function to check if there's an edge between two vertices


bool isEdge(int u, int v) {
return adjMatrix[u][v] == 1; // Returns true if there's an edge, false otherwise
}
};
int main() {
int v, e;

// Read the number of vertices


cout << "Enter the number of vertices: ";
cin >> v;

// Create a graph with 'v' vertices


Graph g(v);

// Read the number of edges


cout << "Enter the number of edges: ";
cin >> e;

// Read each edge and add to the graph


cout << "Enter the edges (pair of vertices): " << endl;
for (int i = 0; i < e; i++) {
int u, v;
cout << "Edge " << i+1 << ": ";
cin >> u >> v; // Read the two vertices of the edge
g.addEdge(u, v); // Add edge to the graph
}

// Display the adjacency matrix


g.displayMatrix();

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;

// Function to perform binary search


int binarySearch(int arr[], int size, int target) {
int low = 0;
int high = size - 1;

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

// Check if target is at mid


if (arr[mid] == target) {
return mid; // Element found, return its index
}
// If target is smaller than mid, search in the left half
else if (arr[mid] > target) {
high = mid - 1;
}
// If target is greater than mid, search in the right half
else {
low = mid + 1;
}
}

return -1; // Element not found


}

int main() {
int size, target;

// Read the size of the array


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

int arr[size];

// Read the elements of the array


cout << "Enter the elements of the array (sorted order): ";
for (int i = 0; i < size; i++) {
cin >> arr[i];
}

// Read the element to be searched


cout << "Enter the element to search for: ";
cin >> target;

// Call binarySearch function


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

// Output the result


if (result == -1) {
cout << "Element not found in the array." << endl;
} else {
cout << "Element found at index " << result << endl;
}

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>

using namespace std;

// Function to perform insertion sort

void insertionSort(vector<int>& arr) {

int n = arr.size();

// Start from the second element, because the first element is trivially sorted

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

int key = arr[i]; // The current element to be inserted

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

// Insert the key into its correct position

arr[j + 1] = key;

// Function to display the array

void displayArray(const vector<int>& arr) {

for (int i = 0; i < arr.size(); i++) {

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

cout << endl;

// Function to get the elements that need to be sorted

vector<int> getUnsortedElements(const vector<int>& arr) {

vector<int> unsortedElements;

// Check for elements that are out of order


for (int i = 1; i < arr.size(); i++) {

if (arr[i] < arr[i - 1]) {

unsortedElements.push_back(arr[i]);

return unsortedElements;

int main() {

int size;

// Read the size of the array

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

cin >> size;

vector<int> arr(size);

// Read the elements of the array

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

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

cin >> arr[i];

// Display the array before sorting


cout << "Original array: ";

displayArray(arr);

// Get the elements that need to be sorted

vector<int> unsortedElements = getUnsortedElements(arr);

// Display the elements that need to be sorted

if (!unsortedElements.empty()) {

cout << "Elements that need to be sorted: ";

for (int i = 0; i < unsortedElements.size(); i++) {

cout << unsortedElements[i] << " ";

cout << endl;

} else {

cout << "The array is already sorted!" << endl;

// Apply insertion sort to the array

insertionSort(arr);

// Display the array after sorting

cout << "Sorted array: ";


displayArray(arr);

return 0;
}
(Or)
QB504 (b)* CO5 K6 4
Write the quicksort module of Quick Sort in C++.

#include <iostream>

using namespace std;

// Function to swap two elements

void swap(int& a, int& b) {

int temp = a;

a = b;

b = temp;

// Function to partition the array into two parts based on the pivot

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

// Pivot is the last element in the array

int pivot = arr[high];

int i = (low - 1); // Index of the smaller element

// Traverse through all elements in the array

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


// If current element is smaller than or equal to the pivot

if (arr[j] <= pivot) {

i++; // Increment index of smaller element

swap(arr[i], arr[j]);

// Swap the pivot element with the element at index i + 1

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

return (i + 1); // Return the index of the pivot element

// QuickSort function (recursive)

void quickSort(int arr[], int low, int high) {

if (low < high) {

// Partition the array and get the pivot index

int pivotIndex = partition(arr, low, high);

// Recursively apply quicksort to the left and right sub-arrays

quickSort(arr, low, pivotIndex - 1); // Left part

quickSort(arr, pivotIndex + 1, high); // Right part

// Function to display the array


void displayArray(int arr[], int size) {

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

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

cout << endl;

int main() {

int size;

// Read the size of the array

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

cin >> size;

int arr[size];

// Read the elements of the array

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

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

cin >> arr[i];

// Display the array before sorting

cout << "Original array: ";

displayArray(arr, size);

// Perform QuickSort
quickSort(arr, 0, size - 1);

// Display the sorted array

cout << "Sorted array: ";

displayArray(arr, size);

return 0;

(PART C – 15 Marks - Either Or Type)

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>

using namespace std;

// ClassB declaration

class ClassB;

// ClassA definition

class ClassA {
int numA;

public:

ClassA(int num) : numA(num) {} // Parameterized constructor to initialize numA

// Declaring ClassB's function as a friend to access numB

friend void checkArmstrong(ClassA, ClassB);

};

// ClassB definition

class ClassB {

int numB;

public:

ClassB(int num) : numB(num) {} // Parameterized constructor to initialize numB

// Declaring ClassA's function as a friend to access numA

friend void checkArmstrong(ClassA, ClassB);

};

// Friend function to check if numbers in both classes are Armstrong numbers

void checkArmstrong(ClassA objA, ClassB objB) {

int nA = objA.numA, nB = objB.numB;

int tempA = nA, tempB = nB;

// Calculate the number of digits in nA and nB


int countA = 0, countB = 0;

while (tempA != 0) {

tempA /= 10;

countA++;

while (tempB != 0) {

tempB /= 10;

countB++;

// Check for Armstrong number in ClassA's numA

int sumA = 0;

tempA = nA;

while (tempA != 0) {

int digit = tempA % 10;

sumA += pow(digit, countA);

tempA /= 10;

// Check for Armstrong number in ClassB's numB

int sumB = 0;
tempB = nB;

while (tempB != 0) {

int digit = tempB % 10;

sumB += pow(digit, countB);

tempB /= 10;

// Display results

if (sumA == nA)

cout << nA << " in ClassA is an Armstrong number." << endl;

else

cout << nA << " in ClassA is NOT an Armstrong number." << endl;

if (sumB == nB)

cout << nB << " in ClassB is an Armstrong number." << endl;

else

cout << nB << " in ClassB is NOT an Armstrong number." << endl;

int main() {

int numA, numB;


// Read numbers for both classes

cout << "Enter a number for ClassA: ";

cin >> numA;

cout << "Enter a number for ClassB: ";

cin >> numB;

// Create objects for both classes

ClassA objA(numA);

ClassB objB(numB);

// Check Armstrong numbers for both objects using friend function

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>

using namespace std;

// Forward declaration of ClassB

class ClassB;
// ClassA definition

class ClassA {

private:

int numA;

public:

// Constructor to initialize numA

ClassA(int num) : numA(num) {}

// Friend function declaration to access private members of both classes

friend void findMin(ClassA, ClassB);

};

// ClassB definition

class ClassB {

private:

int numB;

public:

// Constructor to initialize numB

ClassB(int num) : numB(num) {}

// Friend function declaration to access private members of both classes

friend void findMin(ClassA, ClassB);


};

// Friend function to find the minimum of both numbers

void findMin(ClassA objA, ClassB objB) {

int minVal;

// Compare the values of numA and numB and find the minimum

if (objA.numA < objB.numB) {

minVal = objA.numA;

} else {

minVal = objB.numB;

// Display the minimum value

cout << "The minimum value among " << objA.numA << " (ClassA) and "

<< objB.numB << " (ClassB) is: " << minVal << endl;

int main() {

int numA, numB;

// Take input for both numbers

cout << "Enter an integer for ClassA: ";

cin >> numA;


cout << "Enter an integer for ClassB: ";

cin >> numB;

// Create objects of ClassA and ClassB

ClassA objA(numA);

ClassB objB(numB);

// Call the friend function to find the minimum value

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

// Function to display customer details


void displayDetails() {
cout << "Service Number: " << serviceNo << endl;
cout << "Customer Name: " << name << endl;
cout << "Previous Reading: " << previousReading << endl;
cout << "Current Reading: " << currentReading << endl;
}
};

// Base Class 2: To compute unit consumption


class UnitConsumption {
protected:
float unitConsumption;

public:
// Function to calculate unit consumption
void calculateConsumption() {
unitConsumption = currentReading - previousReading;
}

// Function to display unit consumption


void displayConsumption() {
cout << "Unit Consumption: " << unitConsumption << " units" << endl;
}
};
// Derived Class: To calculate the bill based on consumption
class Bill : public Customer, public UnitConsumption {
private:
float amount;

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
}

// Function to calculate the bill based on unit consumption


void calculateBill() {
if (unitConsumption <= 100) {
amount = unitConsumption * 2.00; // Rs. 2 per unit for <= 100 units
} else if (unitConsumption <= 300) {
amount = (100 * 2.00) + ((unitConsumption - 100) * 3.00); // Rs. 3 per unit for 101-
300 units
} else {
amount = (100 * 2.00) + (200 * 3.00) + ((unitConsumption - 300) * 5.00); // Rs. 5
per unit for > 300 units
}
}

// Function to display the bill


void displayBill() {
displayDetails(); // Display customer details
displayConsumption(); // Display unit consumption
cout << "Amount to be Paid: Rs. " << amount << endl; // Display 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;

// Create an object of Bill class to calculate and display the bill


Bill customerBill(serviceNo, name, previousReading, currentReading);

// Display the calculated bill


customerBill.displayBill();

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

// Function to display the values of the data members


void display() {
cout << "num1: " << num1 << ", num2: " << num2 << endl;
}
};

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

// Deleting the object using base class pointer


// This will invoke the virtual destructor and destroy both base and derived class objects
delete basePtr;
return 0;
}

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;

// Node structure for doubly linked list


struct Node {
int data;
Node* next;
Node* prev;

// Constructor to initialize node with data


Node(int val) {
data = val;
next = nullptr;
prev = nullptr;
}
};

// Doubly Linked List class


class DoublyLinkedList {
private:
Node* head; // Head pointer to the first node in the list

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

// Function to display the list


void display() {
if (head == nullptr) {
cout << "List is empty!" << endl;
return;
}

Node* temp = head;


cout << "Doubly Linked List: ";
while (temp != nullptr) {
cout << temp->data << " ";
temp = temp->next; // Move to the next node
}
cout << endl;
}

// Function to delete the first node


void deleteFirstNode() {
if (head == nullptr) {
cout << "List is empty! Cannot delete." << endl;
return;
}
Node* temp = head;
head = head->next; // Move the head pointer to the next node

if (head != nullptr) {
head->prev = nullptr; // Set the previous pointer of the new head to null
}

delete temp; // Delete the old head node


cout << "First node deleted." << endl;
}
};

int main() {
DoublyLinkedList list;

// Inserting nodes at the end


list.insertAtEnd(10);
list.insertAtEnd(20);
list.insertAtEnd(30);
list.insertAtEnd(40);

// Displaying the list


list.display();

// Deleting the first node


list.deleteFirstNode();

// Displaying the list again


list.display();

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;

// Node structure for polynomial linked list


struct Node {
int coef; // Coefficient
int exp; // Exponent
Node* next; // Pointer to the next term in the polynomial

// Constructor to initialize the node with coefficient and exponent


Node(int c, int e) {
coef = c;
exp = e;
next = nullptr;
}
};

// Class to represent a polynomial


class Polynomial {
private:
Node* head; // Head pointer to the polynomial list

public:
// Constructor to initialize the polynomial to an empty list
Polynomial() {
head = nullptr;
}

// Function to insert a term into the polynomial


void insertTerm(int coef, int exp) {
Node* newNode = new Node(coef, exp);

if (head == nullptr || head->exp < exp) {


newNode->next = head;
head = newNode;
} else {
Node* temp = head;
while (temp->next != nullptr && temp->next->exp > exp) {
temp = temp->next;
}
if (temp->next != nullptr && temp->next->exp == exp) {
temp->next->coef += coef; // If exponent is same, add the coefficients
delete newNode;
} else {
newNode->next = temp->next;
temp->next = newNode;
}
}
}

// Function to display the polynomial


void display() {
if (head == nullptr) {
cout << "0";
return;
}

Node* temp = head;


while (temp != nullptr) {
cout << temp->coef;
if (temp->exp != 0) {
cout << "x^" << temp->exp;
}
if (temp->next != nullptr && temp->next->coef > 0) {
cout << " + ";
}
temp = temp->next;
}
cout << endl;
}

// Function to add two polynomials and return the result


Polynomial add(Polynomial& p2) {
Polynomial result;
Node* temp1 = this->head;
Node* temp2 = p2.head;

while (temp1 != nullptr || temp2 != nullptr) {


if (temp1 == nullptr) {
result.insertTerm(temp2->coef, temp2->exp);
temp2 = temp2->next;
} else if (temp2 == nullptr) {
result.insertTerm(temp1->coef, temp1->exp);
temp1 = temp1->next;
} else {
if (temp1->exp > temp2->exp) {
result.insertTerm(temp1->coef, temp1->exp);
temp1 = temp1->next;
} else if (temp1->exp < temp2->exp) {
result.insertTerm(temp2->coef, temp2->exp);
temp2 = temp2->next;
} else {
result.insertTerm(temp1->coef + temp2->coef, temp1->exp);
temp1 = temp1->next;
temp2 = temp2->next;
}
}
}
return result;
}
};

int main() {
Polynomial poly1, poly2, result;

// Creating first polynomial: 5x^3 + 4x^2 + 2x + 1


poly1.insertTerm(5, 3);
poly1.insertTerm(4, 2);
poly1.insertTerm(2, 1);
poly1.insertTerm(1, 0);

// Creating second polynomial: 3x^3 + 6x^2 + 7x + 8


poly2.insertTerm(3, 3);
poly2.insertTerm(6,

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;

// Define the BTreeNode structure


struct BTreeNode {
vector<char> keys; // Keys stored in the node
vector<BTreeNode*> children; // Pointers to child nodes
bool leaf; // True if the node is a leaf, false otherwise
int numKeys; // Number of keys currently in the node

// Constructor
BTreeNode(bool leaf = true) {
this->leaf = leaf;
this->numKeys = 0;
}
};

// BTree class to encapsulate the B-tree functionality


class BTree {
private:
BTreeNode* root; // Pointer to the root node
int degree; // Minimum degree (defines the range for number of keys in nodes)

public:
// Constructor
BTree(int degree) {
this->degree = degree;
root = new BTreeNode(true);
}

// Function to search the key in the BTree


bool search(BTreeNode* node, char key) {
int i = 0;

// Find the first key greater than or equal to key


while (i < node->numKeys && key > node->keys[i]) {
i++;
}

// If the key is found, return true


if (i < node->numKeys && node->keys[i] == key) {
return true;
}

// If the node is a leaf, return false as key is not present


if (node->leaf) {
return false;
}

// Otherwise, search in the appropriate child


return search(node->children[i], key);
}

// Function to start the search from the root node


bool search(char key) {
return search(root, key);
}

// Function to insert a key into the B-Tree (used for testing)


void insert(char key) {
if (root->numKeys == 2 * degree - 1) {
// If the root is full, split it
BTreeNode* newRoot = new BTreeNode(false);
newRoot->children.push_back(root);
splitChild(newRoot, 0);
root = newRoot;
}
(Or)
QC401 (b)* Develop the Red Black Tree construction module in C++. CO4 K6 5
#include <iostream>
#include <vector>
using namespace std;

// Define the BTreeNode structure


struct BTreeNode {
vector<char> keys; // Keys stored in the node
vector<BTreeNode*> children; // Pointers to child nodes
bool leaf; // True if the node is a leaf, false otherwise
int numKeys; // Number of keys currently in the node

// Constructor
BTreeNode(bool leaf = true) {
this->leaf = leaf;
this->numKeys = 0;
}
};

// BTree class to encapsulate the B-tree functionality


class BTree {
private:
BTreeNode* root; // Pointer to the root node
int degree; // Minimum degree (defines the range for number of keys in nodes)

public:
// Constructor
BTree(int degree) {
this->degree = degree;
root = new BTreeNode(true);
}

// Function to search the key in the BTree


bool search(BTreeNode* node, char key) {
int i = 0;

// Find the first key greater than or equal to key


while (i < node->numKeys && key > node->keys[i]) {
i++;
}

// If the key is found, return true


if (i < node->numKeys && node->keys[i] == key) {
return true;
}
// If the node is a leaf, return false as key is not present
if (node->leaf) {
return false;
}

// Otherwise, search in the appropriate child


return search(node->children[i], key);
}

// Function to start the search from the root node


bool search(char key) {
return search(root, key);
}

// Function to insert a key into the B-Tree (used for testing)


void insert(char key) {
if (root->numKeys == 2 * degree - 1) {
// If the root is full, split it
BTreeNode* newRoot = new BTreeNode(false);
newRoot->children.push_back(root);
splitChild(newRoot, 0);
root = newRoot;
}
insertNonFull(root, key);
}

// Function to split a full child node during insertion


void splitChild(BTreeNode* parent, int index) {
BTreeNode* fullChild = parent->children[index];
BTreeNode* newChild = new BTreeNode(fullChild->leaf);

parent->children.insert(parent->children.begin() + index + 1, newChild);


parent->keys.insert(parent->keys.begin() + index, fullChild->keys[degree - 1]);

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 the child is not a leaf, move the children


if (!fullChild->leaf) {
for (int i = 0; i < degree; i++) {
newChild->children.push_back(fullChild->children[i + degree]);
}
}

// Remove the moved keys and children from the fullChild


fullChild->keys.resize(degree - 1);
fullChild->children.resize(degree);
}

// Function to insert a key into a non-full node


void insertNonFull(BTreeNode* node, char key) {
int i = node->numKeys - 1;

// If the node is a leaf, insert the key


if (node->leaf) {
while (i >= 0 && key < node->keys[i]) {
i--;
}
node->keys.insert(node->keys.begin() + i + 1, key);
node->numKeys++;
} else {
// If the node is not a leaf, find the child to insert the key
while (i >= 0 && key < node->keys[i]) {
i--;
}
i++;
if (node->children[i]->numKeys == 2 * degree - 1) {
splitChild(node, i);
if (key > node->keys[i]) {
i++;
}
}
insertNonFull(node->children[i], key);
}
}

// Function to display the tree (for debugging)


void display(BTreeNode* node, int level = 0) {
if (node == nullptr) {
return;
}

cout << "Level " << level << ": ";


for (int i = 0; i < node->numKeys; i++) {
cout << node->keys[i] << " ";
}
cout << endl;

if (!node->leaf) {
for (auto child : node->children) {
display(child, level + 1);
}
}
}
};

int main() {
// Create a B-Tree of degree 3
BTree tree(3);

// Insert elements into the tree


tree.insert('A');
tree.insert('C');
tree.insert('B');
tree.insert('D');
tree.insert('E');
tree.insert('F');
tree.insert('G');

// Display the tree (for visualization)


cout << "BTree structure:" << endl;
tree.display(tree.search('A'));

// Search for a character in the B-Tree


char key = 'B';
if (tree.search(key)) {
cout << "The key '" << key << "' was found in the B-Tree." << endl;
} else {
cout << "The key '" << key << "' was not found in the B-Tree." << endl;
}

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.

Output: MST cost is 4


#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

// Structure to represent an edge


struct Edge {
int u, v, weight;

// Comparator to sort edges by weight


bool operator<(const Edge& other) {
return weight < other.weight;
}
};

// Disjoint Set (Union-Find) data structure


class DisjointSet {
private:
vector<int> parent, rank;

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

// Union of two sets using union by rank


void unionSets(int x, int y) {
int rootX = find(x);
int rootY = find(y);

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

DisjointSet ds(V); // Initialize the Disjoint Set for V vertices


int mstWeight = 0; // Variable to store the sum of the MST weights
int edgeCount = 0; // Counter for the number of edges added to the MST

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

// Check if adding this edge forms a cycle


if (ds.find(u) != ds.find(v)) {
ds.unionSets(u, v);
mstWeight += weight;
edgeCount++;

// If we have added V-1 edges, we can stop


if (edgeCount == V - 1) {
break;
}
}
}

// Return the sum of the weights of the MST


return mstWeight;
}

int main() {
int V, E;

// Input number of vertices and edges


cout << "Enter number of vertices (V) and edges (E): ";
cin >> V >> E;

vector<Edge> edges(E);

// Input the edges (u, v, weight)


cout << "Enter the edges (u, v, weight):" << endl;
for (int i = 0; i < E; ++i) {
cin >> edges[i].u >> edges[i].v >> edges[i].weight;
}

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

using namespace std;

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

// If the current distance is not up-to-date, continue


if (d > dist[u]) {
continue;
}
// Explore all adjacent nodes
for (const auto& edge : graph[u]) {
int v = edge.first;
int weight = edge.second;

// If a shorter path to node v is found


if (dist[u] + weight < dist[v]) {
dist[v] = dist[u] + weight;
pq.push({dist[v], v});
}
}
}

return dist;
}

int main() {
int n, e;
cout << "Enter number of nodes (n) and edges (e): ";
cin >> n >> e;

// Graph represented as an adjacency list


vector<vector<pii>> graph(n + 1);

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

// Print the shortest distance from node i to all other nodes


cout << "Shortest path from node " << i << " to all other nodes:" << endl;
for (int j = 1; j <= n; ++j) {
if (dist[j] == INT_MAX) {
cout << "Node " << j << " is unreachable from " << i << endl;
} else {
cout << "Distance to node " << j << " is " << dist[j] << endl;
}
}
cout << endl;
}

return 0;
}

Knowledge Level (Blooms Taxonomy)

Applying
K1 Remembering (Knowledge) K2 Understanding (Comprehension) K3
(Application of Knowledge)

K4 Analysing (Analysis) K5 Evaluating (Evaluation) K6 Creating (Synthesis)


Note: For each Question, mention as follows
(i) K1 or K2 etc. for Knowledge Level
(ii) CO1, CO2 etc. for Course Outcomes
(iii) Any number from 1 to 5 for Difficulty Level (With 1 as Most Easy & 5 as Most Difficult)

You might also like