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

OOP Corrected Practicals

Uploaded by

yogirain216
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

OOP Corrected Practicals

Uploaded by

yogirain216
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Experiment No : 1

Implement a class Complex which represents the Complex Number data type. Implement the following
Constructor (including a default constructor which creates the complex number 0+0i).
Overload operator+ to add two complex numbers.
Overload operator* to multiply two complex numbers.
Overload operators << and >> to print and read Complex Numbers

CODE:

#include <iostream>
using namespace std;

class Complex {
double real;
double img;

public:
Complex(); // Default Constructor
friend istream& operator >> (istream&, Complex&); // Input
friend ostream& operator << (ostream&, const Complex&); // Output
Complex operator + (Complex); // Addition
Complex operator * (Complex); // Multiplication
};

Complex::Complex() {
real = 0;
img = 0;
}

istream& operator >> (istream& in, Complex& i) {


in >> i.real >> i.img;
return in;
}

ostream& operator << (ostream& out, const Complex& d) {


out << d.real << " + " << d.img << "i";
return out;
}

Complex Complex::operator + (Complex c1) {


Complex temp;
temp.real = real + c1.real;
temp.img = img + c1.img;
return temp;
}

Complex Complex::operator * (Complex c2) {


Complex temp;
temp.real = real * c2.real - img * c2.img;
temp.img = real * c2.img + img * c2.real;
return temp;
}
int main() {
Complex C1, C2, C3, C4;
cout << "Enter Real and Imaginary part of the Complex Number 1: \n";
cin >> C1;
cout << "Enter Real and Imaginary part of the Complex Number 2: \n";
cin >> C2;

cout << "Complex Number 1: " << C1 << endl;


cout << "Complex Number 2: " << C2 << endl;

C3 = C1 + C2;
cout << "Addition: " << C3 << endl;

C4 = C1 * C2;
cout << "Multiplication: " << C4 << endl;

return 0;
}

Experiment No : 1
Output :
Experiment No : 2
/*
Experiment Number 2 : Develop a program in C++ to create a database of student’s information
system containing the following information: Name, Roll number, Class, Division, Date of Birth, Blood
group, Contactaddress, Telephone number, Driving license no. and other. Construct the database with
suitable member functions. Make use of constructor, default constructor, copy constructor, destructor,
static member functions, friend class, this pointer, inline code and dynamic memory allocation
operators-new and delete aswell as exception handling.
*/

CODE:

#include<iostream>
#include<string>
using namespace std;

class StudData; // Forward declaration

class Student {
string name;
int roll_no;
string cls;
char* division;
string dob;
char* bloodgroup;
static int count;

public:
// Default Constructor
Student() {
name = "";
roll_no = 0;
cls = "";
division = new char[10]; // Allocate memory for division
dob = "dd/mm/yyyy";
bloodgroup = new char[4]; // Allocate memory for blood group
}

// Destructor
~Student() {
delete[] division; // Deallocate memory for division
delete[] bloodgroup; // Deallocate memory for blood group
}

// Static function to get the count of students


static int getCount() {
return count;
}
void getData(StudData*);
void dispData(StudData*);
};
// Initializing static member
int Student::count = 0;

class StudData {
string caddress;
long int* telno;
long int* dlno;

// Declare Student as a friend class to allow access to private members


friend class Student;

public:
// Default Constructor
StudData() {
caddress = "";
telno = new long; // Allocate memory for telephone number
dlno = new long; // Allocate memory for driving license number
}

// Destructor
~StudData() {
delete telno; // Deallocate memory for telephone number
delete dlno; // Deallocate memory for driving license number
}

// Function to input student data


void getStudData() {
cout << "Enter Contact Address: ";
cin.ignore(); // To avoid any issues with getline() after cin
getline(cin, caddress);
cout << "Enter Telephone Number: ";
cin >> *telno;
cout << "Enter Driving License Number: ";
cin >> *dlno;
}

// Function to display student data


void dispStudData() {
cout << "Contact Address: " << caddress << endl;
cout << "Telephone Number: " << *telno << endl;
cout << "Driving License Number: " << *dlno << endl;
}
};
// Inline function to get student data
inline void Student::getData(StudData* st) {
cout << "Enter Student Name: ";
cin.ignore(); // To avoid any issues with getline() after cin
getline(cin, name);
cout << "Enter Roll Number: ";
cin >> roll_no;
cout << "Enter Class: ";
cin.ignore(); // Clear input buffer before getline
getline(cin, cls);
cout << "Enter Division: ";
cin >> division;
cout << "Enter Date of Birth: ";
cin.ignore(); // Clear input buffer before getline
getline(cin, dob);
cout << "Enter Blood Group: ";
cin >> bloodgroup;
// Get additional student data
st->getStudData();
count++; // Increment student count
}

// Inline function to display student data


inline void Student::dispData(StudData* st1) {
cout << "Student Name: " << name << endl;
cout << "Roll Number: " << roll_no << endl;
cout << "Class: " << cls << endl;
cout << "Division: " << division << endl;
cout << "Date of Birth: " << dob << endl;
cout << "Blood Group: " << bloodgroup << endl;

// Display additional student data


st1->dispStudData();
}

int main() {
Student* stud1;
StudData* stud2;

// Dynamic memory allocation for student and data


stud1 = new Student;
stud2 = new StudData;

// Get and display data


stud1->getData(stud2);
cout << endl;
stud1->dispData(stud2);
cout << endl;

// Free allocated memory


delete stud1;
delete stud2;

return 0;
}
Experiment No : 2
Output :
Experiment No : 3
/*
Imagine a publishing company which does marketing for book and audiocassette versions. Create a
class publication that stores the title (a string) and price (type float) of a publication. From this class
derive two classes: book, which adds a page count(type int), and tape, which adds a playing time in
minutes(type float). Write a program that instantiates the book and tape classes, allows user to enter
data and displays the data members.If an exception is caught, replace all the data member values with
zero values.
*/

CODE

#include<iostream>
using namespace std;

// Declaring class Publication


class publication {
private:
string title;
float price;

public:
// Function to add publication details
void add() {
cout << "\nEnter the Publication information: " << endl;
cout << "Enter Title of the Publication: ";
cin >> title;
cout << "Enter Price of Publication: ";
cin >> price;
}
// Function to display publication details
void display() {
cout << "\nTitle of Publication: " << title;
cout << "\nPublication Price: " << price;
}
};
// Declaring class book which inherits class publication in public mode.
class book : public publication {
private:
int page_count;
public:
// Function to add book details
void add_book() {
try {
add();
cout << "Enter Page Count of Book: ";
cin >> page_count;
if (page_count <= 0) {
throw page_count;
}
}
catch (...) {
cout << "\nInvalid Page Count!!!";
page_count = 0;
}
}

// Function to display book details


void display_book() {
display();
cout << "\nPage Count: " << page_count;
cout << "\n";
}
};

// Declaring class tape which inherits class publication in public mode


class tape : public publication {
private:
float play_time;

public:
// Function to add tape details
void add_tape() {
try {
add();
cout << "Enter Play Duration of the Tape (in minutes): ";
cin >> play_time;
if (play_time <= 0) {
throw play_time;
}
}
catch (...) {
cout << "\nInvalid Play Time!!!";
play_time = 0;
}
}

// Function to display tape details


void display_tape() {
display();
cout << "\nPlay Time: " << play_time << " minutes";
cout << "\n";
}
};

int main() {
book b1; // Object of class book
tape t1; // Object of class tape

b1.add_book(); // Adding book details


t1.add_tape(); // Adding tape details

// Displaying book details


cout << "\n* * * * BOOK PUBLICATION DATABASE SYSTEM * * * *";
b1.display_book();

// Displaying tape details


cout << "\n* * * * TAPE PUBLICATION DATABASE SYSTEM * * * *";
t1.display_tape();

return 0;
}
Experiment No : 3
Output :
Experiment No : 4
/*
Write a C++ program that creates an output file, writes information to it, closes the file, open it again
as aninput file and read the information from the file.
*/

CODE:-

#include <iostream>
#include <fstream>
using namespace std;

class Employee {
string Name;
int ID;
double salary;

public:
// Function to accept employee details
void accept() {
cout << "\nName: ";
cin >> Name;
cout << "Id: ";
cin >> ID;
cout << "Salary: ";
cin >> salary;
}

// Function to display employee details


void display() const {
cout << "\nName: " << Name;
cout << "\nId: " << ID;
cout << "\nSalary: " << salary << endl;
}

// Function to write employee details to a file


void writeToFile(ofstream &f) const {
f << Name << endl;
f << ID << endl;
f << salary << endl;
}

// Function to read employee details from a file


void readFromFile(ifstream &f) {
f >> Name;
f >> ID;
f >> salary;
}
};

int main() {
Employee o[5];
fstream file;
int i, n;

// Open the file for writing


file.open("aaa.txt", ios::out);
if (!file) {
cout << "Error opening file for writing!" << endl;
return 1;
}

// Get the number of employees to store


cout << "\nEnter the number of employees you want to store: ";
cin >> n;

// Accept and write employee details to the file


for (i = 0; i < n; i++) {
cout << "\nEnter information of Employee " << i + 1 << "\n";
o[i].accept();
o[i].writeToFile(file);
}

file.close(); // Close the file after writing

// Open the file for reading


file.open("aaa.txt", ios::in);
if (!file) {
cout << "Error opening file for reading!" << endl;
return 1;
}

// Read and display employee details from the file


cout << "\nInformation of Employees is as follows: \n";
for (i = 0; i < n; i++) {
cout << "\nEmployee " << i + 1 << "\n";
o[i].readFromFile(file);
o[i].display();
}

file.close(); // Close the file after reading

return 0;
}
Experiment No : 4

Output :
Experiment No : 5
/*

Write a function template for selection sort that inputs, sorts and outputs an integer array anda
float array.
*/

CODE:

#include<iostream>
using namespace std;

#define SIZE 10 // Macro for array size


int n; // Global variable for number of elements

// Template function for selection sort


template<class T>
void sel(T A[SIZE]) {
int i, j, min;
T temp;

// Selection sort algorithm


for(i = 0; i < n - 1; i++) {
min = i;
for(j = i + 1; j < n; j++) {
if(A[j] < A[min])
min = j;
}

// Swap the elements


temp = A[i];
A[i] = A[min];
A[min] = temp;
}

// Display sorted array


cout << "\nSorted array:";
for(i = 0; i < n; i++) {
cout << " " << A[i];
}
cout << endl;
}

int main() {
int A[SIZE]; // Array to hold integers
float B[SIZE]; // Array to hold floats
int i;

// Input and sort integers


cout << "\nEnter total number of integer elements: ";
cin >> n;
cout << "\nEnter integer elements:\n";
for(i = 0; i < n; i++) {
cin >> A[i];
}
sel(A); // Sort integer array
// Input and sort floats
cout << "\nEnter total number of float elements: ";
cin >> n;
cout << "\nEnter float elements:\n";
for(i = 0; i < n; i++) {
cin >> B[i];
}

sel(B); // Sort float array

return 0;
}

Experiment No : 5
Output :
Experiment No : 6
/*

Write C++ Program using STL for sorting and searching user defined records such as item records
using vector container.
*/

CODE:-

#include <iostream> // Standard input-output stream header file


#include <algorithm> // To use algorithms like sort, find, and for_each
#include <vector> // The header file for the STL vector library

using namespace std;

class Item { // Creating class Item


public:
char name[10]; // Item name
int quantity; // Item quantity
int cost; // Item cost
int code; // Item code

// Overloading '==' operator for comparison based on 'code'


bool operator==(const Item& i1) const {
return code == i1.code;
}

// Overloading '<' operator for sorting based on 'code'


bool operator<(const Item& i1) const {
return code < i1.code;
}
};

// Global vector to store 'Item' objects


vector<Item> o1;

// Function declarations
void print(Item &i1);
void display();
void insert();
void search();
void dlt();
bool compare(const Item &i1, const Item &i2);

int main() {
int ch;
do {
// Displaying menu
cout << "\n* * * * * Menu * * * * *";
cout << "\n1. Insert";
cout << "\n2. Display";
cout << "\n3. Search";
cout << "\n4. Sort";
cout << "\n5. Delete";
cout << "\n6. Exit";
cout << "\nEnter your choice: ";
cin >> ch;
switch (ch) {
case 1:
insert();
break;
case 2:
display();
break;
case 3:
search();
break;
case 4:
sort(o1.begin(), o1.end(), compare); // Sorting based on cost
cout << "\n\n Sorted on Cost: ";
display();
break;
case 5:
dlt();
break;
case 6:
exit(0);
}
} while (ch != 6);

return 0;
}

// Function to insert an item


void insert() {
Item i1;
cout << "\nEnter Item Name: ";
cin >> i1.name;
cout << "\nEnter Item Quantity: ";
cin >> i1.quantity;
cout << "\nEnter Item Cost: ";
cin >> i1.cost;
cout << "\nEnter Item Code: ";
cin >> i1.code;

o1.push_back(i1); // Add item to the vector


}

// Function to display all items


void display() {
for_each(o1.begin(), o1.end(), print); // Display all items
}

// Function to print a single item


void print(Item &i1) {
cout << "\n";
cout << "Item Name: " << i1.name << "\n";
cout << "Item Quantity: " << i1.quantity << "\n";
cout << "Item Cost: " << i1.cost << "\n";
cout << "Item Code: " << i1.code << "\n\n";
}
// Function to search for an item by code
void search() {
vector<Item>::iterator p;
Item i1;
cout << "\nEnter Item Code to search: ";
cin >> i1.code;
p = find(o1.begin(), o1.end(), i1); // Search for the item by code
if (p == o1.end()) {
cout << "\nNot found!!!\n";
} else {
cout << "\nFound!!!\n";
print(*p); // Display found item
}
}

// Function to delete an item by code


void dlt() {
vector<Item>::iterator p;
Item i1;
cout << "\nEnter Item Code to delete: ";
cin >> i1.code;

p = find(o1.begin(), o1.end(), i1); // Search for the item by code


if (p == o1.end()) {
cout << "\nNot found!!!\n";
} else {
o1.erase(p); // Delete the item from the vector
cout << "\nDeleted!!!\n";
}
}

// Function to compare items based on cost (used in sorting)


bool compare(const Item &i1, const Item &i2) {
return i1.cost < i2.cost; // Sort in ascending order of cost
}
Experiment No : 6
Output :
Experiment No : 7
/*
Write a program in C++ to use map associative container. The keys will be the names of states, and the
values will be the populations of the states. When the program runs, the user is prompted to type the
name of a state. The program then looks in the map, using the state name as an index andreturns the
population of the state.
*/

CODE:-

#include <iostream>
#include <map>
#include <string>

using namespace std;

int main() {
// Using float for population values
typedef map<string, float> mapType;
mapType populationMap;
// Correcting the insertions
populationMap.insert(make_pair("Maharashtra", 125));
populationMap.insert(make_pair("Uttar Pradesh", 225));
populationMap.insert(make_pair("Bihar", 120));
populationMap.insert(make_pair("West Bengal", 100));
populationMap.insert(make_pair("Madhya Pradesh", 90));
populationMap.insert(make_pair("Tamil Nadu", 80));
populationMap.insert(make_pair("Rajasthan", 78));
populationMap.insert(make_pair("Andhra Pradesh", 53));
populationMap.insert(make_pair("Odisha", 47));
populationMap.insert(make_pair("Kerala", 38));
populationMap.insert(make_pair("Telangana", 37));
populationMap.insert(make_pair("Assam", 35));
populationMap.insert(make_pair("Jharkhand", 38));
populationMap.insert(make_pair("Karnataka", 68));
populationMap.insert(make_pair("Gujarat", 70));
populationMap.insert(make_pair("Punjab", 31));
populationMap.insert(make_pair("Chhattisgarh", 30));
populationMap.insert(make_pair("Haryana", 29));
populationMap.insert(make_pair("UT Delhi", 19));
populationMap.insert(make_pair("UT Jammu and Kashmir", 14));
populationMap.insert(make_pair("Uttarakhand", 12));
populationMap.insert(make_pair("Himachal Pradesh", 8));
populationMap.insert(make_pair("Tripura", 4));
populationMap.insert(make_pair("Meghalaya", 4));
populationMap.insert(make_pair("Manipur", 3));
populationMap.insert(make_pair("Nagaland", 2));
populationMap.insert(make_pair("Goa", 2));
populationMap.insert(make_pair("Arunachal Pradesh", 2));
populationMap.insert(make_pair("UT Puducherry", 2));
populationMap.insert(make_pair("Mizoram", 1));
populationMap.insert(make_pair("UT Chandigarh", 1));
populationMap.insert(make_pair("Sikkim", 1));
populationMap.insert(make_pair("UT Dadra and Nagar Haveli and Daman and Diu", 1));
populationMap.insert(make_pair("UT Andaman and Nicobar Islands", 1));
populationMap.insert(make_pair("UT Lakshadweep", 0.0003));
populationMap.insert(make_pair("UT Ladakh", 0.00006));

// Display total number of states and population details


cout << "Total state and UT of India with Size of populationMap: " << populationMap.size() << '\n';

// Iterating through the map and displaying each state's population


for (mapType::iterator iter = populationMap.begin(); iter != populationMap.end(); ++iter) {
cout << iter->first << ": " << iter->second << " million\n";
}

// Searching for population of a specific state


char c;
do {
string state;
cout << "\nEnter the state you want to know the population of: ";
cin >> state;
mapType::iterator iter = populationMap.find(state);

if (iter != populationMap.end()) {
cout << state << "'s population is " << iter->second << " million\n";
} else {
cout << "State is not in the populationMap\n";
}

cout << "Do you wish to continue? (y/n): ";


cin >> c;
} while (c == 'y' || c == 'Y');

// Clear the map at the end


populationMap.clear();
return 0;
}
Experiment No : 7
Output :

You might also like