Intermediate OOP Applications
Intermediate OOP Applications
1. Fraction Operations: Create a class to represent fractions with methods for addition,
subtraction, multiplication, and division.
#include <iostream>
#include <numeric> // for std::gcd in C++17 or later
using namespace std;
class Fraction {
private:
int numerator;
int denominator;
public:
// Constructor
Fraction(int num = 0, int denom = 1) {
if (denom == 0) {
throw invalid_argument("Denominator cannot be zero.");
}
numerator = num;
denominator = denom;
simplify();
}
// Display function
void display() const {
if (denominator == 1) {
cout << numerator << endl;
} else {
cout << numerator << "/" << denominator << endl;
}
}
// Addition
Fraction operator+(const Fraction &other) const {
int num = numerator * other.denominator + other.numerator *
denominator;
int denom = denominator * other.denominator;
return Fraction(num, denom);
}
// Subtraction
Fraction operator-(const Fraction &other) const {
int num = numerator * other.denominator - other.numerator *
denominator;
int denom = denominator * other.denominator;
return Fraction(num, denom);
}
// Multiplication
Fraction operator*(const Fraction &other) const {
int num = numerator * other.numerator;
int denom = denominator * other.denominator;
return Fraction(num, denom);
}
// Division
Fraction operator/(const Fraction &other) const {
if (other.numerator == 0) {
throw invalid_argument("Division by zero.");
}
int num = numerator * other.denominator;
int denom = denominator * other.numerator;
return Fraction(num, denom);
}
};
int main() {
try {
Fraction f1(3, 4); // 3/4
Fraction f2(2, 5); // 2/5
return 0;
}
2. Matrix Calculator: Develop a class to handle matrix operations such as addition, subtraction,
multiplication, and transpose.
#include <iostream>
#include <vector>
class Matrix {
public:
std::vector<std::vector<int>> mat;
int rows, cols;
// Display matrix
void display() {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++)
std::cout << mat[i][j] << " ";
std::cout << std::endl;
}
}
// Matrix addition
Matrix add(const Matrix& m) {
Matrix result(rows, cols);
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
result.mat[i][j] = mat[i][j] + m.mat[i][j];
return result;
}
// Matrix subtraction
Matrix subtract(const Matrix& m) {
Matrix result(rows, cols);
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
result.mat[i][j] = mat[i][j] - m.mat[i][j];
return result;
}
// Matrix multiplication
Matrix multiply(const Matrix& m) {
Matrix result(rows, m.cols);
for (int i = 0; i < rows; i++)
for (int j = 0; j < m.cols; j++)
for (int k = 0; k < cols; k++)
result.mat[i][j] += mat[i][k] * m.mat[k][j];
return result;
}
// Matrix transpose
Matrix transpose() {
Matrix result(cols, rows);
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
result.mat[j][i] = mat[i][j];
return result;
}
};
int main() {
int r, c;
std::cout << "Enter number of rows and columns: ";
std::cin >> r >> c;
// Operations
std::cout << "\nAddition:" << std::endl;
Matrix result = m1.add(m2);
result.display();
return 0;
}
3. Complex Number Calculator: Implement a class for complex numbers with methods for
arithmetic operations.
#include <iostream>
using namespace std;
class Complex {
private:
double real;
double imag;
public:
// Constructor
Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}
int main() {
Complex c1(3.0, 4.0); // Represents 3 + 4i
Complex c2(2.0, -1.0); // Represents 2 - 1i
// Displaying results
cout << "Sum: ";
sum.display();
cout << "Difference: ";
diff.display();
cout << "Product: ";
prod.display();
return 0;
}
#include <iostream>
#include <vector>
using namespace std;
class Polynomial {
private:
vector<double> coefficients; // Stores the coefficients of the polynomial
public:
// Constructor to create a polynomial with given coefficients
Polynomial(const vector<double>& coeffs) : coefficients(coeffs) {}
return Polynomial(resultCoeff);
}
return Polynomial(resultCoeff);
}
};
int main() {
// Create polynomials
Polynomial p1({3, 2, 1}); // Represents 3 + 2x + x^2
Polynomial p2({1, 0, -1}); // Represents 1 - x^2
// Display polynomials
cout << "Polynomial 1: ";
p1.display();
cout << "Polynomial 2: ";
p2.display();
// Polynomial addition
Polynomial sum = p1 + p2;
cout << "Sum: ";
sum.display();
// Polynomial multiplication
Polynomial product = p1 * p2;
cout << "Product: ";
product.display();
// Evaluate polynomial at x = 2
double evalResult = p1.evaluate(2);
cout << "Evaluation of p1 at x = 2: " << evalResult << endl;
// Differentiate polynomial
Polynomial derivative = p1.differentiate();
cout << "Derivative of p1: ";
derivative.display();
return 0;
}
5. Vector Algebra: Implement a class to handle 3D vector operations such as dot product, cross
product, and magnitude calculation.
#include <iostream>
#include <cmath> // For sqrt
using namespace std;
class Vector3D {
private:
double x, y, z; // Coordinates of the 3D vector
public:
// Constructor to initialize the vector
Vector3D(double x = 0.0, double y = 0.0, double z = 0.0) : x(x), y(y), z(z) {}
int main() {
// Create two vectors
Vector3D v1(3.0, -2.0, 5.0); // Represents vector (3, -2, 5)
Vector3D v2(1.0, 4.0, -3.0); // Represents vector (1, 4, -3)
// Display vectors
cout << "Vector v1: ";
v1.display();
cout << "Vector v2: ";
v2.display();
// Dot product
double dotProduct = v1.dot(v2);
cout << "Dot product of v1 and v2: " << dotProduct << endl;
// Cross product
Vector3D crossProduct = v1.cross(v2);
cout << "Cross product of v1 and v2: ";
crossProduct.display();
// Magnitude of vectors
cout << "Magnitude of v1: " << v1.magnitude() << endl;
cout << "Magnitude of v2: " << v2.magnitude() << endl;
return 0;
}
6. Statistics Calculator: Develop a class to compute mean, median, mode, variance, and standard
deviation for a dataset.
#include <iostream>
#include <vector>
#include <algorithm>
#include <unordered_map>
#include <cmath>
using namespace std;
class Statistics {
private:
vector<double> data;
public:
// Constructor to initialize the dataset
Statistics(const vector<double>& dataset) : data(dataset) {}
int maxFreq = 0;
for (const auto& pair : frequency) {
maxFreq = max(maxFreq, pair.second);
}
vector<double> modes;
for (const auto& pair : frequency) {
if (pair.second == maxFreq) {
modes.push_back(pair.first);
}
}
return modes;
}
return 0;
}
7. Prime Number Generator: Create a class that generates prime numbers and checks for the
primality of given integers.
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
class PrimeNumberGenerator {
public:
// Function to check if a given number is prime
bool isPrime(int num) {
if (num <= 1) return false; // 0 and 1 are not prime numbers
if (num == 2) return true; // 2 is the only even prime number
if (num % 2 == 0) return false; // Other even numbers are not prime
int limit = sqrt(num);
for (int i = 3; i <= limit; i += 2) {
if (num % i == 0) return false;
}
return true;
}
int main() {
// Create a PrimeNumberGenerator object
PrimeNumberGenerator primeGen;
cout << "Prime numbers up to " << limit << ": ";
for (int prime : primes) {
cout << prime << " ";
}
cout << endl;
return 0;
}
8. Root Finding Tool: Implement the Newton-Raphson and bisection methods for finding the roots
of functions.
#include <iostream>
#include <cmath>
#include <functional>
#include <limits>
using namespace std;
class RootFinder {
public:
// Newton-Raphson method to find the root of a function
double newtonRaphson(function<double(double)> f, function<double(double)> df, double
initialGuess, double tolerance = 1e-6, int maxIterations = 100) {
double x = initialGuess;
int iterations = 0;
while (iterations < maxIterations) {
double fx = f(x);
double dfx = df(x);
x = x - fx / dfx;
iterations++;
}
cout << "Newton-Raphson method did not converge within the maximum iterations." << endl;
return x; // return the current estimate if it didn't converge
}
double c = a;
int iterations = 0;
while ((b - a) / 2 > tolerance && iterations < maxIterations) {
c = (a + b) / 2;
if (f(c) == 0.0) {
break; // Found exact root
}
iterations++;
}
cout << "Bisection method converged in " << iterations << " iterations." << endl;
return c; // return the root estimate
}
};
int main() {
// Define a function and its derivative for Newton-Raphson
auto f = [](double x) { return x*x - 4; }; // Example function f(x) = x^2 - 4
auto df = [](double x) { return 2*x; }; // Derivative f'(x) = 2x
return 0;
}
9. Linear Regression Model: Build a class to fit and evaluate a linear regression model on input
data points.
#include <iostream>
#include <vector>
#include <cmath>
#include <limits>
using namespace std;
class LinearRegression {
private:
double slope; // The slope (m) of the regression line
double intercept; // The intercept (b) of the regression line
public:
// Constructor initializes slope and intercept to zero
LinearRegression() : slope(0), intercept(0) {}
// Fit the linear regression model to the data (using the least squares method)
void fit(const vector<double>& x, const vector<double>& y) {
if (x.size() != y.size() || x.empty()) {
cerr << "Error: x and y vectors must have the same size and cannot be empty." << endl;
return;
}
int main() {
// Example data: x (independent variable), y (dependent variable)
vector<double> x = {1, 2, 3, 4, 5};
vector<double> y = {1, 2, 1.9, 4.1, 5.2};
cout << "Mean Squared Error (MSE): " << mse << endl;
cout << "R-squared: " << r2 << endl;
return 0;
}
10. Numerical Integration: Create a class to compute definite integrals using methods like
Trapezoidal and Simpson’s rule.
#include <iostream>
#include <cmath>
#include <functional>
class NumericalIntegration {
public:
// Trapezoidal Rule Method
static double trapezoidalRule(std::function<double(double)> f, double a, double b, int n) {
double h = (b - a) / n;
double sum = (f(a) + f(b)) / 2.0;
return sum * h;
}
double h = (b - a) / n;
double sum = f(a) + f(b);
return 0;
}