Oop Practicals 1-14
Oop Practicals 1-14
LIST OF EXPERIMENTS
(University Curriculum)
AIM: - Design C++ classes with static members, methods with default arguments, and
friend functions. (For example, design matrix and vector classes with static allocation, and a
friend function to do matrix-vector multiplication).
SOURCE CODE:
#include<iostream>
using namespace std;
class vector;
//Making class for matrix
class matrix{
public:
int m[3][3];
//Matrix input
void getmatrix(void){
int i,j;
cout<<"Enter element : ";
for(i=0;i<3;i++) //Loop for getting martix in m[i][j] form
{
for(j=0;j<3;j++)
{
cin>>m[i][j];
}
}
}
void dismatrix() //code to display matrix
{
int i, j;
cout<<"Show:\n";
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
cout<<m[i][j];
}
cout<<"\n";
}
}
class vector
{
public:
int v[10];
void disvector()
{
int i;
cout<<"Enter element od vector : ";
for(i=0;i<3;i++)
{
cout<<v[i]<<" ";
}
}
friend void multiply(matrix &m1, vector &v1);
};
void multiply(matrix &m1, vector &v1)
{
int ans[3], i, j;
for(i=0;i<3;i++)
ans[i]=0;
for(j=0;j<3;j++)
{
static int x,y;
x=m1.m[i][j];
y=v1.v[j];
ans[i]= x*y;
}
cout<<ans[i]<<"\t";
int main()
{
matrix m1;
vector v1;
m1.getmatrix(); //calling input method of matrix
m1.dismatrix(); //calling output method of matrix
v1.getvector(3); //calling input method of vector
v1.disvector(); //calling output method of vector
multiply(m1,v1);
return 0;
OUTPUT:
EXPERIMENT NO. 2
AIM: - Implement Matrix class with dynamic memory allocation and necessary methods. Give
proper constructor, destructor, copy constructor, and overloading of the assignment operator.
SOURCE CODE: -
#include <iostream>
using namespace std;
class Matrix {
private:
int** data;
int rows;
int cols;
public:
Matrix(int rows, int cols) : rows(rows), cols(cols) {
data = new int*[rows];
for (int i = 0; i < rows; i++) {
data[i] = new int[cols];
}
}
// Destructor
~Matrix() {
for (int i = 0; i < rows; i++) {
delete[] data[i];
}
delete[] data;
}
// Copy constructor
Matrix(const Matrix &other) : rows(other.rows), cols(other.cols) {
data = new int*[rows];
for (int i = 0; i < rows; i++) {
data[i] = new int[cols];
for (int j = 0; j < cols; j++) {
data[i][j] = other.data[i][j];
}
}
}
return *this;
}
void input() {
std::cout << "Enter matrix elements:" << std::endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
std::cin >> data[i][j];
}
}
}
void print() {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
std::cout << data[i][j] << ' ';
}
cout <<endl;
}
}
};
int main() {
int rows, cols;
cout << "Enter the number of rows and columns for Matrix 1: ";
cin >> rows >> cols;
mat2 = mat1;
return 0;
}
OUTPUT:
EXPERIMENT NO. 3
AIM: - Implement complex number class with necessary operator overloading and type
conversions such as integer to complex, double to complex, complex to double etc.
SOURCE CODE: -
#include <iostream>
using namespace std;
class Complex {
private:
double real;
double imaginary;
public:
Complex():real(0.0),imaginary(0.0) {}
Complex(double r,double i):real(r),imaginary(i) {}
void display() {
if (imaginary >= 0)
std::cout << real << " + " << imaginary << "i" << std::endl;
else
std::cout << real << " - " << -imaginary << "i" << std::endl;
}
};
int main() {
Complex a(3, 2);
Complex b(1, -1);
Complex c = a + b;
Complex d = a - b;
Complex e = a * b;
c.display();
d.display();
e.display();
int integer = 5;
Complex f = integer;
double realNumber = 2.5;
Complex g = realNumber;
double realPart = static_cast<double>(a);
f.display();
g.display();
std::cout << "Real part of a: " << realPart << std::endl;
return 0;
}
OUTPUT:
EXPERIMENT NO. 4
AIM: - Overload the new and delete operators to provide a custom dynamic allocation of
memory
SOURCE CODE: -
#include<iostream>
#include<stdlib.h>
using namespace std;
class student
{
string name;
int age;
public:
student()
{
cout<<"constructor is called"<<endl;
}
student(string name,int age)
{
this->name = name;
this->age = age;
}
void display()
{
cout<<"name: "<<name<<endl;
cout<<"age: "<<age<<endl;
}
void* operator new(size_t size)
{
void* p = ::operator new(size);
return p;
}
void operator delete(void*p)
{
cout<<"overloading delete operation"<<endl;
free(p);
}
int main()
{
student* p = new student("yash",24);
p->display();
delete p;
}
OUTPUT:
EXPERIMENT NO. 5
SOURCE CODE: -
#include <iostream>
using namespace std;
class Animal {
public:
void eat() {
cout<<"Eating..."<<endl;
}
};
class Dog: public Animal
{
public:
void bark(){
cout<<"Barking...";
}
};
class BabyDog: public Dog
{
public:
void weep() {
cout<<"Weeping...";
}
};
int main(void) {
BabyDog d1;
d1.eat();
d1.bark();
d1.weep();
return 0;
}
OUTPUT:
b. Hierarchical Inheritance
#include <iostream>
using namespace std;
class Shape // Declaration of base class.
{
public:
int a;
int b;
void get_data(int n,int m)
{
a= n;
b = m;
}
};
class Rectangle : public Shape // inheriting Shape class
{
public:
int rect_area()
{
int result = a*b;
return result;
}
};
class Triangle : public Shape // inheriting Shape class
{
public:
int triangle_area()
{
float result = 0.5*a*b;
return result;
}
};
int main()
{
Rectangle r;
Triangle t;
int length,breadth,base,height;
std::cout << "Enter the length and breadth of a rectangle: " << std::endl;
cin>>length>>breadth;
r.get_data(length,breadth);
int m = r.rect_area();
std::cout << "Area of the rectangle is : " <<m<< std::endl;
std::cout << "Enter the base and height of the triangle: " << std::endl;
cin>>base>>height;
t.get_data(base,height);
float n = t.triangle_area();
std::cout <<"Area of the triangle is : " << n<<std::endl;
return 0;
}
OUTPUT:
EXPERIMENT NO. 6
AIM: - Design a simple test application to demonstrate dynamic polymorphism and RTTI.
SOURCE CODE: -
#include<iostream>
using namespace std;
class B // Base class
{
public:
virtual void Display(void) // virtual function
{
cout << "\n The member function Display( ) " ;
cout << "of the \"Base Class B\" is invoked \n" ;
}
};
class D1 : public B // First derived class
{
public:
void Display(void)
{
cout << "\n The member function Display( ) " ;
cout << "of the \"Derived Class D1\" is invoked \n" ;
}
};
class D2 : public B // Second derived class
{
public:
void Display(void)
{
cout << "\n The member function Display() " ;
cout << "of the \"Derived Class D2\" is invoked " ;
}
};
int main()
{
B* base_ptr ; // Pointer to the object of the base class
OUTPUT:
#include <iostream>
using namespace std;
OUTPUT:
EXPERIMENT NO. 7
SOURCE CODE: -
#include <iostream>
template <typename T>
class Node {
public:
T data;
Node* next;
~LinkedList() {
// Destructor to delete all nodes when the linked list is destroyed
clear();
}
void append(const T& value) {
Node<T>* newNode = new Node<T>(value);
if (!head) {
head = newNode;
} else {
Node<T>* current = head;
while (current->next) {
current = current->next;
}
current->next = newNode;
}
}
void prepend(const T& value) {
Node<T>* newNode = new Node<T>(value);
newNode->next = head;
head = newNode;
}
void remove(const T& value) {
if (!head) {
return; // Empty list, nothing to remove
}
if (head->data == value) {
Node<T>* temp = head;
head = head->next;
delete temp;
return;
}
Node<T>* current = head;
while (current->next && current->next->data != value) {
current = current->next;
}
if (current->next) {
Node<T>* temp = current->next;
current->next = current->next->next;
delete temp;
}
}
void display() const {
Node<T>* current = head;
while (current) {
std::cout << current->data << " ";
current = current->next;
}
std::cout << std::endl;
}
void clear() {
while (head) {
Node<T>* temp = head;
head = head->next;
delete temp;
}
}
};
int main() {
// Linked List example
LinkedList<int> myList;
myList.append(10);
myList.append(20);
myList.prepend(5);
myList.append(30);
return 0;
}
OUTPUT:
EXPERIMENT NO. 8
SOURCE CODE: -
#include <iostream>
#include <vector>
}
}
// Selection Sort
selectionSort(intArr);
std::cout << "Array after Selection Sort: ";
printVector(intArr);
return 0;
}
OUTPUT:
EXPERIMENT NO. 9
AIM: - Design stack and queue classes with necessary exception handling.
SOURCE CODE: -
#include <iostream>
#include <stdexcept>
// Stack class
template <typename T>
class Stack {
private:
static const int MAX_SIZE = 100;
T data[MAX_SIZE];
int top;
public:
Stack() : top(-1) {}
T pop() {
if (isEmpty()) {
throw std::underflow_error("Stack underflow");
}
return data[top--];
}
bool isEmpty() const {
return top == -1;
}
};
// Queue class
template <typename T>
class Queue {
private:
static const int MAX_SIZE = 100;
T data[MAX_SIZE];
int front, rear;
public:
Queue() : front(-1), rear(-1) {}
if (isEmpty()) {
front = rear = 0;
} else {
rear = (rear + 1) % MAX_SIZE;
}
data[rear] = value;
}
T dequeue() {
if (isEmpty()) {
throw std::underflow_error("Queue underflow");
}
T value = data[front];
if (front == rear) {
front = rear = -1;
} else {
front = (front + 1) % MAX_SIZE;
}
return value;
}
while (!myStack.isEmpty()) {
std::cout << "Stack popped: " << myStack.pop() << std::endl;
}
// Queue example
Queue<std::string> myQueue;
myQueue.enqueue("First");
myQueue.enqueue("Second");
myQueue.enqueue("Third");
while (!myQueue.isEmpty()) {
std::cout << "Queue dequeued: " << myQueue.dequeue() << std::endl;
}
} catch (const std::exception& e) {
std::cerr << "Exception: " << e.what() << std::endl;
}
return 0;
}
OUTPUT:
EXPERIMENT NO. 10
AIM: - Write a C++ program that randomly generates complex numbers (use previously designed
Complex class) and write them two per line in a file along with an operator (+, -, *, or /). The numbers
are written to file in the format (a + ib). Write another program to read one line at a time from this file,
perform the operations, and prints the results.
SOURCE CODE: -
#include <iostream>
#include <fstream>
#include <cstdlib> // For rand() and srand()
#include <ctime> // For time()
public:
Complex() : real(0.0), imag(0.0) {}
Complex(double r, double i) : real(r), imag(i) {}
if (!outputFile.is_open()) {
std::cerr << "Error: Unable to open file for writing." << std::endl;
return EXIT_FAILURE;
}
return 0;
}
Program 2 (ReadComplexFromFile.cpp):
#include <iostream>
#include <fstream>
#include "Complex.h" // Assuming the Complex class is defined in a separate header file
int main() {
// Open file for reading
std::ifstream inputFile("complex_numbers.txt");
if (!inputFile.is_open()) {
std::cerr << "Error: Unable to open file for reading." << std::endl;
return EXIT_FAILURE;
}
Complex num1, num2, result;
char op;
return 0;
}
(BEYOND SYLLABUS)
EXPERIMENT NO. 1
AIM:- Write a C++ program to implement the stack ADT using an array
SOURCE CODE:-
#include <iostream>
class Stack {
private:
int top; // Index of the top element in the stack
int arr[MAX_SIZE]; // Array to store stack elements
public:
Stack() {
top = -1; // Initialize top to -1 indicating an empty stack
}
int main() {
Stack myStack;
myStack.push(10);
myStack.push(20);
myStack.push(30);
std::cout << "Top element of the stack: " << myStack.peek() << std::endl;
return 0;
}
OUTPUT:
EXPERIMENT NO. 2
AIM:- Write a C++ program to implement the Queue ADT using an array
SOURCE CODE:-
#include <iostream>
class Queue {
private:
int front; // Index of the front element in the queue
int rear; // Index of the rear element in the queue
int arr[MAX_SIZE]; // Array to store queue elements
public:
Queue() {
front = -1; // Initialize front and rear to -1 indicating an empty queue
rear = -1;
}
int main() {
Queue myQueue;
myQueue.enqueue(10);
myQueue.enqueue(20);
myQueue.enqueue(30);
std::cout << "Front element of the queue: " << myQueue.peek() << std::endl;
return 0;
}
OUTPUT:
EXPERIMENT NO. 3
AIM:- Write C++ programs for implementing the Quick sort method.
SOURCE CODE:-
#include <iostream>
#include <vector>
// Function to partition the array and return the index of the pivot element
int partition(std::vector<int>& arr, int low, int high) {
int pivot = arr[high]; // Choose the last element as the pivot
int i = low - 1; // Index of the smaller element
int main() {
std::vector<int> arr = {12, 8, 5, 14, 7, 3, 9};
OUTPUT:
EXPERIMENT NO. 4
AIM:- Write C++ program for implementing the Merge sort method.
SOURCE CODE:-
#include <iostream>
#include <vector>
// Merge function to merge two sorted subarrays into one sorted array
void merge(std::vector<int>& arr, int low, int mid, int high) {
int n1 = mid - low + 1; // Size of the left subarray
int n2 = high - mid; // Size of the right subarray
int main() {
std::vector<int> arr = {12, 8, 5, 14, 7, 3, 9};
return 0;
}
OUTPUT: