Rayyan
Rayyan
R MANGALAM UNIVERSITY
DR ARTI
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
#include<iostream>
int main() {
char operation;
switch (operation) {
case '+' :
case '-' :
break;
case '*' :
break;
case '/' :
break;
default :
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>
int main() {
int num;
cout << "Enter number: ";
int i = 0;
int count = 0;
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>
int i = 0, j = 0;
int temp;
temp = arr[j];
arr[j + 1] = temp;}}}
int main() {
float num;
vector<float> arr;
arr.push_back(num);
int j = 0;
bubble_sorting(arr, size);
int m = 0;
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>
int sum = 0;
sum += *ptr;
return sum;
}
double calculateAverage(int *arr, int n) {
if (n == 0) return INT_MIN;
maxVal = *ptr;
return maxVal;
int main() {
int n;
cin >> n;
if (n <= 0) {
return 1;
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
#include <iostream>
int i = 0, j = 0;
cout << "Enter elements of " << rows << " rows and " << cols << " column matrix: ";
int i = 0, j = 0;
int i = 0, j = 0;
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;
result[i][j] = 0;
int i = 0, j = 0;
int main() {
cout << "Enter number of rows and columns for matrix: ";
while (choosing != 4) {
switch (choosing) {
case 1:
break;
case 2:
break;
case 3:
break;
default:
}
}
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>
void fabonacci_seq(int n) {
int a = 0, b = 1;
int c, i = 0;
c = a + b;
a = b;
b = c;
int main() {
int n;
cout << "Enter the no. of terms for Fibonacci sequence: ";
cin >> n;
if (n <= 0) {
return 1;
fabonacci_seq(n);
return 0;
operators (+, -, *, /), and parentheses. Implement a function that parses the
parentheses. */
#include <iostream>
#include <stack>
#include <cctype>
return 1;
return 2;
}
return 0;
if (op == '+') {
return a + b;
if (op == '-') {
return a - b;
if (op == '*') {
return a * b;
if (op == '/') {
return a / b;
return 0;
stack<int> nums;
stack<char> ops;
int i = 0;
char ch = expr[i];
if (isdigit(ch)) {
int num = 0;
while (i < expr.length() && isdigit(expr[i])) {
i++;
nums.push(num);
i--;
ops.push(ch);
nums.push(calculate(a, b, op));
ops.pop();
nums.push(calculate(a, b, op));
ops.push(ch);
while (!ops.empty()) {
nums.push(calculate(a, b, op));
return nums.top();
int main() {
string expr;
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>
if (str[start] != str[end]) {
return false;
}
start++;
end--;
return true;
set<string> result;
int n = str.length();
int i = 0, j = 0;
if (Palindrome(str, i, j)) {
result.insert(sub);
return result;
int main() {
string inputStr;
return 0;
/*Create a class Rational to represent rational numbers with attributes numerator and
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>
class Rational {
private:
void reduce() {
if (denominator == 0) {
return;
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) {
denominator = 1;
reduce();
numerator = other.numerator;
denominator = other.denominator;
if (other.numerator == 0) {
if (r.denominator == 1) {
else {
return out;
char slash;
if (r.denominator == 0) {
r.denominator = 1;
r.reduce();
return in;
}
friend bool operator==(Rational a, Rational b) {
};
int main() {
cout << "\nAre they equal? " << ((num1 == num2) ? "Yes" : "No") << endl;
return 0;
}
/*Create a class Matrix that represents a 2D matrix with dynamic memory allocation,
subtract, and multiply matrices, overloading the [] operator to access matrix elements,
#include <iostream>
class Matrix {
private:
int** data;
void allocate() {
public:
Matrix(int r = 2, int c = 2) {
rows = r; cols = c;
allocate();
rows = other.rows;
cols = other.cols;
allocate();
data[i][j] = other.data[i][j];
~Matrix() {
delete[] data[i];
delete[] data;
return *this;
return result;
return *this;
if (cols != other.rows) {
return *this;
result.data[i][j] = 0;
return result;
return data[index];
void input() {
cout << "Enter " << rows << "x" << cols << " matrix values:\n";
void display() {
};
int main() {
A.input();
B.input();
(A + B).display();
(A - B).display();
(A * B).display();
return 0;
}
/*Create a class Student with attributes studentID, name, and grades (an array of
methods to calculate the average grade and display student details, using constant
member functions to display details, and implementing dynamic memory allocation for
#include <iostream>
class Student {
private:
int studentID;
string name;
int* grades;
int numGrades;
public:
Student() {
studentID = 0;
name = "Unknown";
numGrades = 0;
grades = nullptr;
studentID = id;
name = n;
numGrades = size;
grades[i] = g[i];
~Student() {
delete[] grades;
int sum = 0;
};
int main() {
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,
display the area of each shape, and an array of Shape pointers to store different shapes
#include <iostream>
#include <cmath>
class Shape {
public:
virtual ~Shape() {}
};
double radius;
public:
Circle() : radius(0) {}
Circle(double r) : radius(r) {}
cout << "Circle with radius " << radius << " has area: " << calculateArea() << endl;
};
private:
public:
};
private:
public:
cout << "Triangle with base " << base << " and height " << height << " has area: " <<
calculateArea() << endl;
};
int main() {
Shape* shapes[3];
delete shapes[i];
return 0;
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>
class Item {
private:
int id;
char* name;
int stock;
public:
name[0] = '\0';
}
Item(int itemId, const char* itemName, int itemStock) : id(itemId), stock(itemStock) {
strcpy(name, itemName);
id = other.id;
stock = other.stock;
strcpy(name, other.name);
~Item() {
delete[] name;
Item& operator++() {
stock++;
return *this;
}
Item operator++(int) {
++(*this);
return temp;
Item& operator--() {
return *this;
Item operator--(int) {
--(*this);
return temp;
cout << "ID: " << id << ", Name: " << name << ", Stock: " << stock << endl;
};
int main() {
laptop.show();
anotherLaptop.show();
laptop.add(3);
laptop.show();
laptop.remove(2);
laptop.show();
laptop++;
laptop.show();
--laptop;
laptop.show();
return 0;
operators for polynomial operations, and friend functions to input and output
polynomials.*/
#include <iostream>
class Polynomial {
private:
int degree;
int* coeffs;
public:
Polynomial() : degree(0) {
coeffs = new int[1]{0};
coeffs[i] = coef[i];
coeffs[i] = other.coeffs[i];
~Polynomial() {
delete[] coeffs;
if (poly.coeffs[i] != 0) {
return out;
}
friend istream& operator>>(istream& in, Polynomial& poly) {
in >> poly.degree;
delete[] poly.coeffs;
return in;
};
int main() {
cout << "\nP1: " << p1 << "\nP2: " << 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>
class V {
protected:
string b, m;
int y;
public:
b = b_;
m = m_;
y = y_;
cout << "Brand: " << b << ", Model: " << m << ", Year: " << y << endl;
virtual ~V() {}
};
class C : public V {
int s;
public:
C(string b_, string m_, int y_, int s_) : V(b_, m_, y_) {
s = s_;
V::d();
};
class T : public V {
float lc;
public:
T(string b_, string m_, int y_, float lc_) : V(b_, m_, y_) {
lc = lc_;
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 {
V::d();
cout << "Sidecar: " << (sc ? "Yes" : "No") << endl;
};
class G {
vector<V*> iv;
public:
void add(V* v) {
iv.push_back(v);
void list() {
v->d();
return;
~G() {
};
int main() {
G g;
g.list();
g.cmp(0, 3);
return 0;
/*Create a base class Account with methods deposit() and withdraw(). Derive classes
#include<iostream>
protected:
double b;
public:
virtual void s() { cout << "Balance: " << b << endl; }
virtual ~A() {}
};
class S : public A {
double ir;
public:
};
class C : public A {
double ol;
public:
};
int main() {
S sa(1000, 5);
C ca(2000, 500);
sa.d(500);
ca.w(2200);
sa.s();
ca.s();
return 0;
numbers. Use inheritance to extend the class with additional functionality for polar
representation. */
#include <iostream>
#include <cmath>
class C {
protected:
double r, i;
public:
C(double r_ = 0, double i_ = 0) {
r = r_;
i = i_;
}
C operator+(const C& c) {
C operator-(const C& c) {
C operator*(const C& c) {
C operator/(const C& c) {
cout << r << " + " << i << "i" << endl;
};
class P : public C {
public:
double mag() {
}
double ang() {
cout << "Polar: " << mag() << " (cos " << ang()
<< " + i sin " << ang() << ")" << endl;
};
int main() {
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
#include <iostream>
class A {
public:
virtual ~A() {}
};
class D : public A {
public:
};
class C : public A {
public:
};
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>
class P {
protected:
string n;
int a;
public:
n = n_;
a = a_;
void d() {
cout << "Name: " << n << ", Age: " << a << endl;
};
public:
};
public:
};
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.
#include <iostream>
#include <vector>
class V {
protected:
string m, mo;
public:
m = m_;
mo = mo_;
cout << m << " " << mo << " started." << endl;
cout << m << " " << mo << " stopped." << endl;
cout << "Make: " << m << ", Model: " << mo << endl;
virtual ~V() {}
};
class C : public V {
public:
};
class T : public V {
public:
};
class M : public V {
public:
};
void show(vector<V*>& v) {
for (auto i : v)
i->d();
int main() {
vector<V*> v;
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>
if (s.empty()) return s;
stringstream res;
int count = 1;
count++;
} else {
count = 1;
int main() {
string word;
cin >> word;
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
#include <iostream>
#include <vector>
#include <algorithm>
#include <ctime>
T pivot = arr[right];
int i = left - 1;
i++;
swap(arr[i], arr[j]);
}
}
return i + 1;
int main() {
srand(time(0));
return 0;
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
#include <iostream>
#include <stdexcept>
#include <string>
private:
string message;
public:
return message.c_str();
};
if (num < 0) {
int main() {
try {
int userInput;
if (cin.fail()) {
validateInput(userInput);
cout << "Valid input received: " << userInput << endl;
} catch (...) {
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>
string result;
if (isalpha(ch)) {
result += tolower(ch);
return result;
}
ifstream file(filename);
if (!file) {
cerr << "Error: Could not open file '" << filename << "'." << endl;
return;
stringstream ss(line);
if (!cleaned.empty()) {
wordCount[cleaned]++;
file.close();
cout << pair.first << " : " << pair.second << endl;
int main() {
string filename;
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>
class Stack {
T* arr;
int topIndex;
int capacity;
public:
capacity = size;
topIndex = -1;
arr[++topIndex] = item;
void pop() {
--topIndex;
T top() const {
return arr[topIndex];
};
int main() {
try {
Stack<int> s(5);
s.push(10);
s.push(20);
s.push(30);
s.pop();
cout << "Top after pop: " << s.top() << endl;
s.pop();
s.pop();
cout << "Stack empty? " << (s.isEmpty() ? "Yes" : "No") << 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>
ifstream file(filename);
stringstream buffer;
int main() {
string filename;
try {
readFile(filename);
} catch (const exception& e) {
return 0;