0% found this document useful (0 votes)
13 views77 pages

Rayyan

This document contains a C++ lab manual with various programming tasks, including implementing a simple calculator, checking for prime numbers, sorting arrays, performing matrix operations, generating Fibonacci sequences, evaluating string expressions, finding unique palindromic substrings, and creating a Rational class. Each task includes a description and corresponding C++ code to accomplish the objectives. The manual serves as a practical guide for students to practice and enhance their programming skills in C++.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views77 pages

Rayyan

This document contains a C++ lab manual with various programming tasks, including implementing a simple calculator, checking for prime numbers, sorting arrays, performing matrix operations, generating Fibonacci sequences, evaluating string expressions, finding unique palindromic substrings, and creating a Rational class. Each task includes a description and corresponding C++ code to accomplish the objectives. The manual serves as a practical guide for students to practice and enhance their programming skills in C++.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 77

K.

R MANGALAM UNIVERSITY

C++ LAB MANUAL


Submitted to :-

DR ARTI

Student name :- RAYYAN KHAN

Roll no :-2401420046
*Implement a simple calculator in C++ that can perform basic arithmetic operations such as addition,
subtraction, multiplication, and division.

The program should prompt the user to enter two numbers and an operator, then display the result.
Use appropriate data types and control structures

to handle the calculations and validate user input*/

#include<iostream>

using namespace std;

int main() {

int n1, n2;

char operation;

cout << "Enter first number: ";

cin >> n1;

cout << "Enter operation(eg. +, /, -, *): ";

cin >> operation;

cout << "Enter second number: ";

cin >> n2;

if (n1 > 0 && n2 > 0 ) {

switch (operation) {

case '+' :

cout << "Addition: " << n1 + n2 << endl;


break;

case '-' :

cout << "Subtraction: " << n1 - n2 << endl;

break;

case '*' :

cout << "Multiplication: " << n1 * n2 << endl;

break;

case '/' :

cout << "Division: " << n1 / n2 << endl;

break;

default :

cout << "Invalid operation" << endl;

break;

return 0;

/*Create a C++ program that checks if a given number is a prime number. The program should
prompt the user to enter a number,then use control

structures and functions to determine if the number is prime. Display an appropriate message
indicating the result. */

#include<iostream>

using namespace std;

int main() {

int num;
cout << "Enter number: ";

cin >> num;

int i = 0;

int count = 0;

for (i = 2; i < num; i++) {

if (num%i == 0) {

count++;

break;

if (count > 0) {

cout << "Number " << num << " is not a prime" << endl;

else {

cout << "Number " << num << " is a prime" << endl;

return 0;

/*Implement a C++ program that sorts an array of integers using the bubble sort algorithm. The
program should allow the user to input

the array elements, then use a function to sort the array in ascending order. Display the sorted array
as the output. */

#include<iostream>
#include<vector>

using namespace std;

void bubble_sorting(vector<float>& arr, int size) {

int i = 0, j = 0;

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

int temp;

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

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

temp = arr[j];

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

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

int main() {

float num;

vector<float> arr;

cout << "Enter array elements and press -1 to break: ";

while (cin >> num && num != -1) {

arr.push_back(num);

int size = arr.size();

cout << "Unsorted array: ";

int j = 0;

for (j = 0; j < size; j++) {


cout << arr[j] << " ";

}cout << endl;

bubble_sorting(arr, size);

cout << "Sorted array: ";

int m = 0;

for (m = 0; m < size; m++) {

cout << arr[m] << " ";

}cout << endl;

return 0;

/*Write a C++ program to demonstrate pointer arithmetic by creating an array of integers and using
pointers to traverse and manipulate the array elements.

Implement functions to calculate the sum, average, and maximum value of the array using pointer
arithmetic?*/

#include <iostream>

using namespace std;

int calculateSum(int *arr, int n) {

int sum = 0;

for (int *ptr = arr; ptr < arr + n; ptr++) {

sum += *ptr;

return sum;

}
double calculateAverage(int *arr, int n) {

return (n == 0) ? 0 : static_cast<double>(calculateSum(arr, n)) / n;

int findMax(int *arr, int n) {

if (n == 0) return INT_MIN;

int maxVal = *arr;

for (int *ptr = arr + 1; ptr < arr + n; ptr++) {

if (*ptr > maxVal) {

maxVal = *ptr;

return maxVal;

int main() {

int n;

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

cin >> n;

if (n <= 0) {

cout << "Invalid array size!" << endl;

return 1;

int *arr = new int[n];

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

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

cin >> arr[i];


}

cout << "Sum: " << calculateSum(arr, n) << endl;

cout << "Average: " << calculateAverage(arr, n) << endl;

cout << "Maximum Value: " << findMax(arr, n) << endl;

delete[] arr;

return 0;

/*Write a C++ program to perform basic matrix operations such as addition, subtraction,and
multiplication. Use two-dimensional arrays to represent

the matrices and implement functions for each operation. Ensure the program handles matrices of
appropriate sizes and displays

the results accurately.*/

#include <iostream>

using namespace std;

const int max_s = 10;

void input(int matrix[max_s][max_s], int rows, int cols) {

int i = 0, j = 0;

cout << "Enter elements of " << rows << " rows and " << cols << " column matrix: ";

for (i = 0; i < rows; i++) {

for (j = 0; j < cols; j++) {

cin >> matrix[i][j];


}

void add(int matrix1[max_s][max_s], int matrix2[max_s][max_s], int result[max_s][max_s], int rows,


int cols) {

int i = 0, j = 0;

for (i = 0; i < rows; i++) {

for (j = 0; j < cols; j++) {

result[i][j] = matrix1[i][j] + matrix2[i][j];

void subtract(int matrix1[max_s][max_s], int matrix2[max_s][max_s], int result[max_s][max_s], int


rows, int cols) {

int i = 0, j = 0;

for (i = 0; i < rows; i++) {

for (j = 0; j < cols; j++) {

result[i][j] = matrix1[i][j] - matrix2[i][j];

void multiplication(int matrix1[max_s][max_s], int matrix2[max_s][max_s], int result[max_s][max_s],

int matrix1_r, int matrix1_c, int matrix2_r, int matrix2_c) {

if (matrix1_c != matrix2_r) {

cout << "Matrix multiplication not possible (Columns of matrix1 not equal to Rows of matrix2)"
<< endl;

return;

}
int i = 0, j = 0, k = 0;

for (i = 0; i < matrix1_r; i++) {

for (j = 0; j < matrix2_c; j++) {

result[i][j] = 0;

for (k = 0; k < matrix1_c; k++) {

result[i][j] += matrix1[i][k] * matrix2[k][j];

void display(int matrix[max_s][max_s], int rows, int cols) {

int i = 0, j = 0;

for (i = 0; i < rows; i++) {

cout << "{ ";

for (j = 0; j < cols; j++) {

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

cout << " }" << endl;

int main() {

int matrix1[max_s][max_s], matrix2[max_s][max_s], result[max_s][max_s];

int rows, cols, choosing;

cout << "Enter number of rows and columns for matrix: ";

cin >> rows >> cols;

cout << "Matrix 1: " << endl;


input(matrix1, rows, cols);

cout << "Matrix 2: " << endl;

input(matrix2, rows, cols);

while (choosing != 4) {

cout << "======Choose operation=========" << endl;

cout << "1. Addition\n2. Subtraction\n3. Multiplication\n4. Exit" << endl;

cout << "Enter choice: ";

cin >> choosing;

switch (choosing) {

case 1:

add(matrix1, matrix2, result, rows, cols);

cout << "Result of Addition:" << endl;

display(result, rows, cols);

break;

case 2:

subtract(matrix1, matrix2, result, rows, cols);

cout << "Result of Subtraction:" << endl;

display(result, rows, cols);

break;

case 3:

multiplication(matrix1, matrix2, result, rows, cols, rows, cols);

cout << "Result of Multiplication:" << endl;

display(result, rows, cols);

break;

default:

cout << "Invalid choice!" << endl;

}
}

cout << "Exiting" << endl;

return 0;

/*Create a C++ program that generates the Fibonacci sequence up to a specified number of terms.
Use a loop and control structures to generate

the sequence and store the terms in an array. Display the generated sequence as the output. */

#include <iostream>

using namespace std;

void fabonacci_seq(int n) {

int a = 0, b = 1;

if (n >= 1) cout << a << " ";

if (n >= 2) cout << b << " ";

int c, i = 0;

for (i = 3; i <= n; i++) {

c = a + b;

cout << c << " ";

a = b;

b = c;

int main() {

int n;

cout << "Enter the no. of terms for Fibonacci sequence: ";

cin >> n;
if (n <= 0) {

cout << "Enter a positive integer" << endl;

return 1;

cout << "Fibonacci Sequence: ";

fabonacci_seq(n);

return 0;

/*Write a C++ program to evaluate a string expression containing numbers, arithmetic

operators (+, -, *, /), and parentheses. Implement a function that parses the

expression and computes the result, considering operator precedence and

parentheses. */

#include <iostream>

#include <stack>

#include <cctype>

using namespace std;

int prefer(char op) {

if (op == '+' || op == '-') {

return 1;

if (op == '*' || op == '/') {

return 2;

}
return 0;

int calculate(int a, int b, char op) {

if (op == '+') {

return a + b;

if (op == '-') {

return a - b;

if (op == '*') {

return a * b;

if (op == '/') {

return a / b;

return 0;

int solve(string expr) {

stack<int> nums;

stack<char> ops;

int i = 0;

for (i = 0; i < expr.length(); i++) {

char ch = expr[i];

if (isdigit(ch)) {

int num = 0;
while (i < expr.length() && isdigit(expr[i])) {

num = num * 10 + (expr[i] - '0');

i++;

nums.push(num);

i--;

else if (ch == '(') {

ops.push(ch);

else if (ch == ')') {

while (!ops.empty() && ops.top() != '(') {

int b = nums.top(); nums.pop();

int a = nums.top(); nums.pop();

char op = ops.top(); ops.pop();

nums.push(calculate(a, b, op));

ops.pop();

else if (ch == '+' || ch == '-' || ch == '*' || ch == '/') {

while (!ops.empty() && prefer(ops.top()) >= prefer(ch)) {

int b = nums.top(); nums.pop();

int a = nums.top(); nums.pop();

char op = ops.top(); ops.pop();

nums.push(calculate(a, b, op));

ops.push(ch);

while (!ops.empty()) {

int b = nums.top(); nums.pop();


int a = nums.top(); nums.pop();

char op = ops.top(); ops.pop();

nums.push(calculate(a, b, op));

return nums.top();

int main() {

string expr;

cout << "Enter expression: ";

cin >> expr;

int result = solve(expr);

cout << "Result: " << result << endl;

return 0;

/*Write a C++ program to find all unique palindromic substrings in a given string. The

function should take a string as input and return a set of strings containing all unique

palindromic substrings.*/

#include <iostream>

#include <set>

using namespace std;

bool Palindrome(string str, int start, int end) {

while (start < end) {

if (str[start] != str[end]) {

return false;
}

start++;

end--;

return true;

set<string> finding_Pal(string str) {

set<string> result;

int n = str.length();

int i = 0, j = 0;

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

for (j = i; j < n; j++) {

if (Palindrome(str, i, j)) {

string sub = str.substr(i, j - i + 1);

result.insert(sub);

return result;

int main() {

string inputStr;

cout << "Enter a string: ";

cin >> inputStr;

set<string> palindromes = finding_Pal(inputStr);

cout << "Palindromic Substrings: " << endl;

for (string p : palindromes) {


cout << p << endl;

return 0;

/*Create a class Rational to represent rational numbers with attributes numerator and

denominator, implementing default, parameterized, and copy constructors, methods

to add, subtract, multiply, and divide rational numbers, overloading the << and >>

operators for input and output, and a friend function to compare two rational numbers.*/

#include <iostream>

using namespace std;

class Rational {

private:

int numerator, denominator;

void reduce() {

if (denominator == 0) {

return;

int a = abs(numerator), b = abs(denominator);

while (a != b) {

if (a > b) a -= b;

else b -= a;

numerator /= a;

denominator /= a;

if (denominator < 0) {

numerator = -numerator;

denominator = -denominator;

}
}

public:

Rational() {

numerator = 0;

denominator = 1;

Rational(int n, int d) {

numerator = n;

denominator = d;

if (d == 0) {

cout << "Error: Denominator cannot be zero! Defaulting to 1.\n";

denominator = 1;

reduce();

Rational(const Rational &other) {

numerator = other.numerator;

denominator = other.denominator;

Rational operator+(Rational other) {

return Rational(numerator * other.denominator + other.numerator

* denominator, denominator * other.denominator);

Rational operator-(Rational other) {

return Rational(numerator * other.denominator - other.numerator

* denominator, denominator * other.denominator);

Rational operator*(Rational other) {


return Rational(numerator * other.numerator, denominator * other.denominator);

Rational operator/(Rational other) {

if (other.numerator == 0) {

cout << "Oops! Division by zero is undefined.\n";

return Rational(0, 1);

return Rational(numerator * other.denominator, denominator * other.numerator);

friend ostream& operator<<(ostream &out, Rational r) {

if (r.denominator == 1) {

out << r.numerator;

else {

out << r.numerator << "/" << r.denominator;

return out;

friend istream& operator>>(istream &in, Rational &r) {

char slash;

in >> r.numerator >> slash >> r.denominator;

if (r.denominator == 0) {

cout << "Invalid input! Setting denominator to 1.\n";

r.denominator = 1;

r.reduce();

return in;

}
friend bool operator==(Rational a, Rational b) {

return (a.numerator * b.denominator) == (b.numerator * a.denominator);

};

int main() {

Rational num1, num2;

cout << "Enter a fraction (a/b): ";

cin >> num1;

cout << "Enter another fraction: ";

cin >> num2;

cout << "\nSum: " << num1 + num2;

cout << "\nDifference: " << num1 - num2;

cout << "\nProduct: " << num1 * num2;

cout << "\nQuotient: " << num1 / num2;

cout << "\nAre they equal? " << ((num1 == num2) ? "Yes" : "No") << endl;

return 0;

}
/*Create a class Matrix that represents a 2D matrix with dynamic memory allocation,

implementing default, parameterized constructors, and a destructor, methods to add,

subtract, and multiply matrices, overloading the [] operator to access matrix elements,

and inline functions for basic matrix operations.*/

#include <iostream>

using namespace std;

class Matrix {

private:

int rows, cols;

int** data;

void allocate() {

data = new int*[rows];

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

data[i] = new int[cols];

public:

Matrix(int r = 2, int c = 2) {

rows = r; cols = c;

allocate();

Matrix(const Matrix& other) {

rows = other.rows;

cols = other.cols;

allocate();

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


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

data[i][j] = other.data[i][j];

~Matrix() {

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

delete[] data[i];

delete[] data;

Matrix operator+(const Matrix& other) {

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

cout << "Matrix sizes don't match for addition.\n";

return *this;

Matrix result(rows, cols);

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

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

result.data[i][j] = data[i][j] + other.data[i][j];

return result;

Matrix operator-(const Matrix& other) {

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

cout << "Matrix sizes don't match for subtraction.\n";

return *this;

Matrix result(rows, cols);

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

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

result.data[i][j] = data[i][j] - other.data[i][j];


return result;

Matrix operator*(const Matrix& other) {

if (cols != other.rows) {

cout << "Matrix multiplication not possible.\n";

return *this;

Matrix result(rows, other.cols);

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

for (int j = 0; j < other.cols; j++) {

result.data[i][j] = 0;

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

result.data[i][j] += data[i][k] * other.data[k][j];

return result;

int* operator[](int index) {

return data[index];

void input() {

cout << "Enter " << rows << "x" << cols << " matrix values:\n";

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

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

cin >> data[i][j];

void display() {

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


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

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

cout << endl;

};

int main() {

Matrix A(2, 2), B(2, 2);

cout << "Matrix A:\n";

A.input();

cout << "Matrix B:\n";

B.input();

cout << "\nA + B = \n";

(A + B).display();

cout << "\nA - B = \n";

(A - B).display();

cout << "\nA * B = \n";

(A * B).display();

return 0;

}
/*Create a class Student with attributes studentID, name, and grades (an array of

integers), implementing default, parameterized constructors, and a destructor,

methods to calculate the average grade and display student details, using constant

member functions to display details, and implementing dynamic memory allocation for

the grades array. */

#include <iostream>

using namespace std;

class Student {

private:

int studentID;

string name;

int* grades;

int numGrades;

public:

Student() {

studentID = 0;

name = "Unknown";

numGrades = 0;

grades = nullptr;

Student(int id, string n, int* g, int size) {

studentID = id;

name = n;

numGrades = size;

grades = new int[numGrades];


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

grades[i] = g[i];

~Student() {

delete[] grades;

double getAverage() const {

if (numGrades == 0) return 0.0;

int sum = 0;

for (int i = 0; i < numGrades; i++) sum += grades[i];

return (double) sum / numGrades;

void display() const {

cout << "Student ID: " << studentID << endl;

cout << "Name: " << name << endl;

cout << "Grades: ";

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

cout << grades[i] << " ";

cout << endl;

cout << "Average Grade: " << getAverage() << endl;

};
int main() {

int marks[] = {87, 99, 73, 91, 84};

Student s1(47, "Aman", marks, 3);

cout << "Student Details:" << endl;

s1.display();

return 0;

/*Create an abstract class Shape with a pure virtual function calculateArea(), deriving

classes Circle, Rectangle, and Triangle each with attributes relevant to their shapes,

implementing default and parameterized constructors, methods to calculate and

display the area of each shape, and an array of Shape pointers to store different shapes

and calculate their areas. */

#include <iostream>

#include <cmath>

using namespace std;

class Shape {

public:

virtual double calculateArea() const = 0;

virtual void display() const = 0;

virtual ~Shape() {}

};

class Circle : public Shape {


private:

double radius;

public:

Circle() : radius(0) {}

Circle(double r) : radius(r) {}

double calculateArea() const override {

return M_PI * radius * radius;

void display() const override {

cout << "Circle with radius " << radius << " has area: " << calculateArea() << endl;

};

class Rectangle : public Shape {

private:

double length, width;

public:

Rectangle() : length(0), width(0) {}

Rectangle(double l, double w) : length(l), width(w) {}

double calculateArea() const override {

return length * width;

void display() const override {


cout << "Rectangle with length " << length << " and width " << width << " has area: " <<
calculateArea() << endl;

};

class Triangle : public Shape {

private:

double base, height;

public:

Triangle() : base(0), height(0) {}

Triangle(double b, double h) : base(b), height(h) {}

double calculateArea() const override {

return 0.5 * base * height;

void display() const override {

cout << "Triangle with base " << base << " and height " << height << " has area: " <<
calculateArea() << endl;

};

int main() {

Shape* shapes[3];

shapes[0] = new Circle(7);

shapes[1] = new Rectangle(3, 5);

shapes[2] = new Triangle(3, 7);

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


shapes[i]->display();

delete shapes[i];

return 0;

/*Create a class InventoryItem with attributes itemID, itemName, and quantity,

implementing default, parameterized, and copy constructors, methods to add, remove,

and display inventory items, overloading the ++ and -- operators to increase and

decrease item quantity, and implementing dynamic memory allocation for inventory

items. */

#include <iostream>

#include <cstring>

using namespace std;

class Item {

private:

int id;

char* name;

int stock;

public:

Item() : id(0), stock(0) {

name = new char[1];

name[0] = '\0';

}
Item(int itemId, const char* itemName, int itemStock) : id(itemId), stock(itemStock) {

name = new char[strlen(itemName) + 1];

strcpy(name, itemName);

Item(const Item& other) {

id = other.id;

stock = other.stock;

name = new char[strlen(other.name) + 1];

strcpy(name, other.name);

~Item() {

delete[] name;

void add(int amount) {

if (amount > 0) stock += amount;

void remove(int amount) {

if (amount > 0 && stock >= amount) stock -= amount;

else cout << "Not enough stock!" << endl;

Item& operator++() {

stock++;

return *this;

}
Item operator++(int) {

Item temp = *this;

++(*this);

return temp;

Item& operator--() {

if (stock > 0) stock--;

return *this;

Item operator--(int) {

Item temp = *this;

--(*this);

return temp;

void show() const {

cout << "ID: " << id << ", Name: " << name << ", Stock: " << stock << endl;

};

int main() {

Item laptop(101, "Laptop", 5);

Item anotherLaptop = laptop;

laptop.show();

anotherLaptop.show();

laptop.add(3);

laptop.show();
laptop.remove(2);

laptop.show();

laptop++;

laptop.show();

--laptop;

laptop.show();

return 0;

/*Create a class Polynomial to represent a polynomial with dynamic memory allocation

for coefficients, implementing default, parameterized constructors, and a destructor,

methods to add, subtract, and multiply polynomials, overloading the +, -, and *

operators for polynomial operations, and friend functions to input and output

polynomials.*/

#include <iostream>

using namespace std;

class Polynomial {

private:

int degree;

int* coeffs;

public:

Polynomial() : degree(0) {
coeffs = new int[1]{0};

Polynomial(int deg, const int* coef) : degree(deg) {

coeffs = new int[degree + 1];

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

coeffs[i] = coef[i];

Polynomial(const Polynomial& other) : degree(other.degree) {

coeffs = new int[degree + 1];

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

coeffs[i] = other.coeffs[i];

~Polynomial() {

delete[] coeffs;

Polynomial operator+(const Polynomial& other) const {

int maxDeg = max(degree, other.degree);

int* sumCoeffs = new int[maxDeg + 1]{0};

for (int i = 0; i <= degree; i++) sumCoeffs[i] += coeffs[i];

for (int i = 0; i <= other.degree; i++) sumCoeffs[i] += other.coeffs[i];

return Polynomial(maxDeg, sumCoeffs);

Polynomial operator-(const Polynomial& other) const {

int maxDeg = max(degree, other.degree);


int* subCoeffs = new int[maxDeg + 1]{0};

for (int i = 0; i <= degree; i++) subCoeffs[i] += coeffs[i];

for (int i = 0; i <= other.degree; i++) subCoeffs[i] -= other.coeffs[i];

return Polynomial(maxDeg, subCoeffs);

Polynomial operator*(const Polynomial& other) const {

int newDeg = degree + other.degree;

int* mulCoeffs = new int[newDeg + 1]{0};

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

for (int j = 0; j <= other.degree; j++)

mulCoeffs[i + j] += coeffs[i] * other.coeffs[j];

return Polynomial(newDeg, mulCoeffs);

friend ostream& operator<<(ostream& out, const Polynomial& poly) {

for (int i = poly.degree; i >= 0; i--) {

if (poly.coeffs[i] != 0) {

if (i != poly.degree && poly.coeffs[i] > 0) out << " + ";

if (poly.coeffs[i] < 0) out << " - ";

out << abs(poly.coeffs[i]);

if (i > 0) out << "x";

if (i > 1) out << "^" << i;

return out;

}
friend istream& operator>>(istream& in, Polynomial& poly) {

cout << "Enter degree: ";

in >> poly.degree;

delete[] poly.coeffs;

poly.coeffs = new int[poly.degree + 1];

cout << "Enter coefficients (highest to lowest degree): ";

for (int i = poly.degree; i >= 0; i--) in >> poly.coeffs[i];

return in;

};

int main() {

Polynomial p1, p2;

cout << "Enter first polynomial:\n";

cin >> p1;

cout << "Enter second polynomial:\n";

cin >> p2;

cout << "\nP1: " << p1 << "\nP2: " << p2 << endl;

cout << "P1 + P2 = " << (p1 + p2) << endl;

cout << "P1 - P2 = " << (p1 - p2) << endl;

cout << "P1 * P2 = " << (p1 * p2) << endl;

return 0;

}
/*Develop a Vehicle Management System that demonstrates different types of

inheritance and polymorphism in C++. The system should manage various types of

vehicles, including cars, trucks, and motorcycles, and should be able to perform

operations such as adding new vehicles, displaying vehicle details, and comparing

vehicles. */

#include <iostream>

#include <vector>

using namespace std;

class V {

protected:

string b, m;

int y;

public:

V(string b_, string m_, int y_) {

b = b_;

m = m_;

y = y_;

virtual void d() {

cout << "Brand: " << b << ", Model: " << m << ", Year: " << y << endl;

bool operator==(const V& v) {

return (b == v.b && m == v.m && y == v.y);

virtual ~V() {}

};

class C : public V {
int s;

public:

C(string b_, string m_, int y_, int s_) : V(b_, m_, y_) {

s = s_;

void d() override {

cout << "[Car] ";

V::d();

cout << "Seats: " << s << endl;

};

class T : public V {

float lc;

public:

T(string b_, string m_, int y_, float lc_) : V(b_, m_, y_) {

lc = lc_;

void d() override {

cout << "[Truck] ";

V::d();

cout << "Load Capacity: " << lc << " tons" << endl;

};

class M : public V {

bool sc;

public:

M(string b_, string m_, int y_, bool sc_) : V(b_, m_, y_) {

sc = sc_;

}
void d() override {

cout << "[Motorcycle] ";

V::d();

cout << "Sidecar: " << (sc ? "Yes" : "No") << endl;

};

class G {

vector<V*> iv;

public:

void add(V* v) {

iv.push_back(v);

void list() {

cout << "\n== Garage Inventory ==" << endl;

for (auto v : iv) {

v->d();

cout << "----------------------" << endl;

void cmp(int a, int b) {

if (a < 0 || b < 0 || a >= iv.size() || b >= iv.size()) {

cout << "Invalid!" << endl;

return;

if (*iv[a] == *iv[b]) cout << "Same.\n";

else cout << "Different.\n";


}

~G() {

for (auto v : iv) delete v;

};

int main() {

G g;

g.add(new C("Toyota", "Corolla", 2022, 5));

g.add(new T("Ford", "F-150", 2020, 1.5));

g.add(new M("Harley", "Street 750", 2019, true));

g.add(new C("Honda", "Civic", 2023, 5));

g.list();

g.cmp(0, 3);

return 0;

/*Create a base class Account with methods deposit() and withdraw(). Derive classes

SavingsAccount and CurrentAccount from Account. Overload the deposit() and

withdraw() methods in the derived classes to include additional parameters like

interest rate for SavingsAccount and overdraft limit for CurrentAccount. */

#include<iostream>

using namespace std;


class A {

protected:

double b;

public:

A(double b_) { b = b_; }

virtual void d(double x) { b += x; }

virtual void w(double x) { if (x <= b) b -= x; }

virtual void s() { cout << "Balance: " << b << endl; }

virtual ~A() {}

};

class S : public A {

double ir;

public:

S(double b_, double ir_) : A(b_) { ir = ir_; }

void d(double x, double extra = 0) { b += x + (x * ir / 100); }

void w(double x) { if (x <= b) b -= x; }

};

class C : public A {

double ol;

public:

C(double b_, double ol_) : A(b_) { ol = ol_; }

void d(double x, double extra = 0) { b += x; }

void w(double x) { if (x <= b + ol) b -= x; }

};
int main() {

S sa(1000, 5);

C ca(2000, 500);

sa.d(500);

ca.w(2200);

sa.s();

ca.s();

return 0;

/*Create a class ComplexNumber to represent complex numbers. Implement operator

overloading for +, -, *, and / operators to perform arithmetic operations on complex

numbers. Use inheritance to extend the class with additional functionality for polar

representation. */

#include <iostream>

#include <cmath>

using namespace std;

class C {

protected:

double r, i;

public:

C(double r_ = 0, double i_ = 0) {

r = r_;

i = i_;
}

C operator+(const C& c) {

return C(r + c.r, i + c.i);

C operator-(const C& c) {

return C(r - c.r, i - c.i);

C operator*(const C& c) {

return C(r * c.r - i * c.i, r * c.i + i * c.r);

C operator/(const C& c) {

double d = c.r * c.r + c.i * c.i;

return C((r * c.r + i * c.i) / d, (i * c.r - r * c.i) / d);

virtual void d() {

cout << r << " + " << i << "i" << endl;

};

class P : public C {

public:

P(double r_, double i_) : C(r_, i_) {}

double mag() {

return sqrt(r * r + i * i);

}
double ang() {

return atan2(i, r);

void d() override {

cout << "Polar: " << mag() << " (cos " << ang()

<< " + i sin " << ang() << ")" << endl;

};

int main() {

C c1(3, 4), c2(1, -2);

P p1(5, 12);

C sum = c1 + c2;

C diff = c1 - c2;

C prod = c1 * c2;

C quot = c1 / c2;

sum.d();

diff.d();

prod.d();

quot.d();

p1.d();

return 0;

}
/*Create a base class Animal with a virtual function makeSound(). Derive classes Dog

and Cat from Animal, each implementing makeSound(). Write a function

playWithAnimal() that takes a pointer to Animal and calls makeSound(). Demonstrate

polymorphism by calling playWithAnimal() with pointers to Dog and Cat. */

#include <iostream>

using namespace std;

class A {

public:

virtual void s() {

cout << "Some sound" << endl;

virtual ~A() {}

};

class D : public A {

public:

void s() override {

cout << "Woof" << endl;

};

class C : public A {

public:

void s() override {

cout << "Meow" << endl;

};

void p(A* a) {
a->s();

int main() {

A* d = new D();

A* c = new C();

p(d);

p(c);

delete d;

delete c;

return 0;

/*Create a base class Person with attributes name and age. Derive classes Student and

Teacher from Person. Further derive a class TeachingAssistant from both Student and

Teacher. Use a virtual base class to avoid ambiguity in accessing attributes of Person. */

#include <iostream>

using namespace std;

class P {

protected:

string n;

int a;
public:

P(string n_, int a_) {

n = n_;

a = a_;

void d() {

cout << "Name: " << n << ", Age: " << a << endl;

};

class r : virtual public P {

public:

r (string n_, int a_) : P(n_, a_) {}

};

class T : virtual public P {

public:

T(string n_, int a_) : P(n_, a_) {}

};

class TA : public r, public T {

public:

TA(string n_, int a_) : P(n_, a_), r (n_, a_), T(n_, a_) {}

};

int main() {

TA ta("VIKASH", 21);

ta.d();

return 0;

}
/*Create a base class Vehicle with attributes make and model, and methods start() and

stop(). Derive classes Car, Truck, and Motorcycle from Vehicle. Use dynamic memory

allocation (new and delete operators) to create and manage objects of these classes.

Implement a function to display details of all vehicles. */

#include <iostream>

#include <vector>

using namespace std;

class V {

protected:

string m, mo;

public:

V(string m_, string mo_) {

m = m_;

mo = mo_;

virtual void s() {

cout << m << " " << mo << " started." << endl;

virtual void st() {

cout << m << " " << mo << " stopped." << endl;

virtual void d() {

cout << "Make: " << m << ", Model: " << mo << endl;

virtual ~V() {}

};

class C : public V {
public:

C(string m_, string mo_) : V(m_, mo_) {}

};

class T : public V {

public:

T(string m_, string mo_) : V(m_, mo_) {}

};

class M : public V {

public:

M(string m_, string mo_) : V(m_, mo_) {}

};

void show(vector<V*>& v) {

for (auto i : v)

i->d();

int main() {

vector<V*> v;

v.push_back(new C("TOYOTA", "Camry"));

v.push_back(new T("TATA", "Curv"));

v.push_back(new M("MAHINDRA", "Scorpion"));

show(v);

for (auto i : v)

delete i;

return 0;

}
/*Write a C++ program that compresses a string using the counts of repeated

characters. For example, the string "aabcccccaaa" would become "a2b1c5a3". If the

"compressed" string would not become smaller than the original string, the function

should return the original string. Use streams for efficient string manipulation. */

#include <iostream>

#include <sstream>

#include <string>

using namespace std;

string compress(const string& s) {

if (s.empty()) return s;

stringstream res;

int count = 1;

for (size_t i = 1; i <= s.length(); i++) {

if (i < s.length() && s[i] == s[i - 1]) {

count++;

} else {

res << s[i - 1] << count;

count = 1;

string finalStr = res.str();

return (finalStr.length() < s.length()) ? finalStr : s;

int main() {

string word;
cin >> word;

cout << compress(word) << endl;

return 0;

/*Write a template-based function in C++ to sort an array of any data type using the

quicksort algorithm. Ensure the function works with different data types such as

integers, floating-point numbers, and strings.*/

#include <iostream>

#include <vector>

#include <algorithm>

#include <ctime>

using namespace std;

template <typename T>

int partition(T arr[], int left, int right) {

swap(arr[right], arr[left + rand() % (right - left + 1)]);

T pivot = arr[right];

int i = left - 1;

for (int j = left; j < right; j++) {

if (arr[j] <= pivot) {

i++;

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

}
}

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

return i + 1;

template <typename T>

void quicksort(T arr[], int left, int right) {

if (left >= right) return;

int pivotIndex = partition(arr, left, right);

quicksort(arr, left, pivotIndex - 1);

quicksort(arr, pivotIndex + 1, right);

template <typename T>

void printArray(T arr[], int size) {

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

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

cout << endl;

int main() {

srand(time(0));

int nums[] = {7, 3, 8, 5, 2, 1, 9};

float decimals[] = {4.3, 2.1, 5.8, 1.7, 0.9};

string words[] = {"zebra", "apple", "mango", "banana", "cherry"};


int size1 = sizeof(nums) / sizeof(nums[0]);

int size2 = sizeof(decimals) / sizeof(decimals[0]);

int size3 = sizeof(words) / sizeof(words[0]);

quicksort(nums, 0, size1 - 1);

quicksort(decimals, 0, size2 - 1);

quicksort(words, 0, size3 - 1);

cout << "Sorted Integers: "; printArray(nums, size1);

cout << "Sorted Floats: "; printArray(decimals, size2);

cout << "Sorted Strings: "; printArray(words, size3);

return 0;

/*Create a custom exception class InvalidInputException in C++ to handle invalid inputs.

Implement a function that takes user input and throws an InvalidInputException if the

input is not valid. Use try, catch, and throw blocks to handle the exception and display

an appropriate error message. */

#include <iostream>

#include <stdexcept>

#include <string>

using namespace std;

class InvalidInputException : public exception {

private:

string message;
public:

InvalidInputException(const string& msg) : message(msg) {}

const char* what() const noexcept override {

return message.c_str();

};

void validateInput(int num) {

if (num < 0) {

throw InvalidInputException("Error: Negative numbers are not allowed!");

if (num > 100) {

throw InvalidInputException("Error: Number exceeds allowed limit (100)!");

int main() {

try {

int userInput;

cout << "Enter a number (0-100): ";

cin >> userInput;

if (cin.fail()) {

throw InvalidInputException("Error: Invalid input! Please enter a number.");

validateInput(userInput);

cout << "Valid input received: " << userInput << endl;

} catch (const InvalidInputException& e) {


cerr << e.what() << endl;

} catch (...) {

cerr << "An unknown error occurred!" << endl;

return 0;

/*Write a C++ program that reads a text file, processes the text to remove punctuation,

convert to lowercase, and count the frequency of each word. Use string streams for

text manipulation and file streams for reading and writing files. */

#include <iostream>

#include <fstream>

#include <sstream>

#include <unordered_map>

#include <cctype>

using namespace std;

string cleanWord(const string& word) {

string result;

for (char ch : word) {

if (isalpha(ch)) {

result += tolower(ch);

return result;
}

void countWordsInFile(const string& filename) {

ifstream file(filename);

if (!file) {

cerr << "Error: Could not open file '" << filename << "'." << endl;

return;

unordered_map<string, int> wordCount;

string line, word;

while (getline(file, line)) {

stringstream ss(line);

while (ss >> word) {

string cleaned = cleanWord(word);

if (!cleaned.empty()) {

wordCount[cleaned]++;

file.close();

cout << "\nWord Frequency Count:\n";

for (const auto& pair : wordCount) {

cout << pair.first << " : " << pair.second << endl;

int main() {
string filename;

cout << "Enter the filename: ";

cin >> filename;

cout << "\nProcessing file '" << filename << "'...\n";

countWordsInFile(filename);

return 0;

/*Implement a template-based stack class in C++ that supports basic stack operations

such as push, pop, top, and isEmpty. Ensure the class works with different data types

and includes appropriate exception handling for stack underflow and overflow. */

#include <iostream>

#include <stdexcept>

using namespace std;

template <typename T>

class Stack {

T* arr;

int topIndex;

int capacity;

public:

Stack(int size = 10) {


if (size <= 0) throw invalid_argument("Stack size must be positive.");

capacity = size;

arr = new T[capacity];

topIndex = -1;

~Stack() { delete[] arr; }

void push(const T& item) {

if (topIndex == capacity - 1) throw overflow_error("Stack overflow! Cannot push more


elements.");

arr[++topIndex] = item;

void pop() {

if (isEmpty()) throw underflow_error("Stack underflow! Cannot pop from an empty stack.");

--topIndex;

T top() const {

if (isEmpty()) throw underflow_error("Stack is empty! No top element.");

return arr[topIndex];

bool isEmpty() const { return topIndex == -1; }

int size() const { return topIndex + 1; }

};

int main() {

try {
Stack<int> s(5);

s.push(10);

s.push(20);

s.push(30);

cout << "Top element: " << s.top() << endl;

s.pop();

cout << "Top after pop: " << s.top() << endl;

s.pop();

s.pop();

cout << "Stack empty? " << (s.isEmpty() ? "Yes" : "No") << endl;

} catch (const exception& e) {

cout << "Error: " << e.what() << endl;

return 0;

}
/*Write a C++ program that reads data from a file and processes it. Implement error

handling to catch exceptions if the file does not exist, is empty, or cannot be read. Use

exception specifications to define the exceptions that the functions might throw. */

#include <iostream>

#include <fstream>

#include <sstream>

#include <stdexcept>

using namespace std;

void readFile(const string& filename) {

ifstream file(filename);

if (!file) throw runtime_error("Error: Could not open file.");

stringstream buffer;

buffer << file.rdbuf();

string content = buffer.str();

if (content.empty()) throw invalid_argument("Warning: File is empty.");

cout << content << endl;

int main() {

string filename;

cout << "Enter filename: ";

cin >> filename;

try {

readFile(filename);
} catch (const exception& e) {

cerr << e.what() << endl;

return 0;

You might also like