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

Practical oop imp

Uploaded by

sayleebandal528
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Practical oop imp

Uploaded by

sayleebandal528
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

Practical

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

#include <iostream>

using namespace std;

class Complex { // Declaring 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

};

// Default Constructor

Complex::Complex() {

real = 0;

img = 0;

// Overloading input operator

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

cout << "Enter real and imaginary parts: ";

in >> i.real >> i.img;

return in;

// Overloading output operator


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

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

return out;

// Overloading + operator

Complex Complex::operator+(Complex c1) {

Complex temp;

temp.real = real + c1.real;

temp.img = img + c1.img;

return temp;

// Overloading * operator

Complex Complex::operator*(Complex c2) {

Complex tmp;

tmp.real = real * c2.real - img * c2.img;

tmp.img = real * c2.img + img * c2.real;

return tmp;

int main() {

Complex C1, C2, C3, C4;

int flag = 1;

char b;

while (flag == 1) {

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;

int f = 1;

while (f == 1) {
cout << "Complex Number 1: " << C1 << endl;

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

cout << "**********MENU**********" << endl;

cout << "1. Addition of Complex Numbers" << endl;

cout << "2. Multiplication of Complex Numbers" << endl;

cout << "3. Exit\n";

int a;

cout << "Enter your choice from above MENU (1 to 3): ";

cin >> a;

if (a == 1) {

C3 = C1 + C2;

cout << "Addition: " << C3 << endl;

cout << "Do you want to perform another operation (y/n): ";

cin >> b;

if (b == 'y' || b == 'Y') {

f = 1;

} else {

cout << "Thanks for using this program!!\n";

flag = 0;

f = 0;

} else if (a == 2) {

C4 = C1 * C2;

cout << "Multiplication: " << C4 << endl;

cout << "Do you want to perform another operation (y/n): ";

cin >> b;

if (b == 'y' || b == 'Y') {

f = 1;

} else {

cout << "Thanks for using this program!!\n";

flag = 0;

f = 0;

}
} else {

cout << "Thanks for using this program!!\n";

flag = 0;

f = 0;

return 0;

Output:
Practical
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, Contact address, 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 as well as exception handling.

Code:

#include<iostream>

#include<string.h>

using namespace std;

class StudData;

class Student{

string name;

int roll_no;

string cls;

char* division;

string dob;

char* bloodgroup;

static int count;

public:

Student() // Default Constructor

name="";

roll_no=0;

cls="";

division=new char;

dob="dd/mm/yyyy";

bloodgroup=new char[4];

}
~Student()

delete division;

delete[] bloodgroup;

static int getCount()

return count;

void getData(StudData*);

void dispData(StudData*);

};

class StudData{

string caddress;

long int* telno;

long int* dlno;

friend class Student;

public:

StudData()

caddress="";

telno=new long;

dlno=new long;

~StudData()

delete telno;

delete dlno;
}

void getStudData()

cout<<"Enter Contact Address : ";

cin.get();

getline(cin,caddress);

cout<<"Enter Telephone Number : ";

cin>>*telno;

cout<<"Enter Driving License Number : ";

cin>>*dlno;

void dispStudData()

cout<<"Contact Address : "<<caddress<<endl;

cout<<"Telephone Number : "<<*telno<<endl;

cout<<"Driving License Number : "<<*dlno<<endl;

};

inline void Student::getData(StudData* st)

cout<<"Enter Student Name : ";

getline(cin,name);

cout<<"Enter Roll Number : ";

cin>>roll_no;

cout<<"Enter Class : ";

cin.get();

getline(cin,cls);

cout<<"Enter Division : ";

cin>>division;

cout<<"Enter Date of Birth : ";

cin.get();
getline(cin,dob);

cout<<"Enter Blood Group : ";

cin>>bloodgroup;

st->getStudData();

count++;

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;

st1->dispStudData();

int Student::count;

int main()

Student* stud1[100];

StudData* stud2[100];

int n=0;

char ch;

do

stud1[n]=new Student;

stud2[n]=new StudData;

stud1[n]->getData(stud2[n]);

n++;

cout<<"Do you want to add another student (y/n) : ";


cin>>ch;

cin.get();

} while (ch=='y' || ch=='Y');

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

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

stud1[i]->dispData(stud2[i]);

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

cout<<"Total Students : "<<Student::getCount();

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

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

delete stud1[i];

delete stud2[i];

return 0;

}
Output:
Practical
Imagine a publishing company which does marketing for book and audio cassette versions. Create a class
publication that stores the title (a string) and price (type float) of publications. 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 class, 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>

#include <stdio.h>

using namespace std;

class publication // declaring class Publication

private:

string title;

float price;

public:

void add()

cout << "\nEnter the Publication information : " << endl;

cout << "Enter Title of the Publication : ";

cin.ignore(); // To ignore any leftover newline characters

getline(cin, title);

cout << "Enter Price of Publication : ";

cin >> price;

void display()

cout << "\n--------------------------------------------------";

cout << "\nTitle of Publication : " << title;

cout << "\nPublication Price : " << price;

};

class book : public publication // declaring class book which inherits class publication in public mode.
{

private:

int page_count;

public:

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;

void display_book()

display();

cout << "\nPage Count : " << page_count;

cout << "\n--------------------------------------------------\n";

};

class tape : public publication // declaring class tape which inherits class publication in public mode

private:
float play_time;

public:

void add_tape()

try

add();

cout << "Enter Play Duration of the Tape : ";

cin >> play_time;

if (play_time <= 0)

throw play_time;

catch (...)

cout << "\nInvalid Play Time!!!";

play_time = 0;

void display_tape()

display();

cout << "\nPlay Time : " << play_time << " min";

cout << "\n--------------------------------------------------\n";

};

int main()

book b1[10]; // object of class book

tape t1[10]; // object of class tape

int ch, b_count = 0, t_count = 0;

do

{
cout << "\n* * * * * PUBLICATION DATABASE SYSTEM * * * * *";

cout << "\n--------------------MENU-----------------------";

cout << "\n1. Add Information to Books";

cout << "\n2. Add Information to Tapes";

cout << "\n3. Display Books Information";

cout << "\n4. Display Tapes Information";

cout << "\n5. Exit";

cout << "\n\nEnter your choice : ";

cin >> ch;

switch (ch)

case 1:

b1[b_count].add_book();

b_count++; // Fixed the increment syntax here

break;

case 2:

t1[t_count].add_tape();

t_count++; // Fixed the increment syntax here

break;

case 3:

cout << "\n* * * * BOOK PUBLICATION DATABASE SYSTEM * * * *";

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

b1[j].display_book();

break;

case 4:

cout << "\n* * * * TAPE PUBLICATION DATABASE SYSTEM * * * *";

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

t1[j].display_tape();

break;
case 5:

return 0; // Exits the program by returning from main

} while (ch != 5);

return 0;

Output:
* * * * * PUBLICATION DATABASE SYSTEM * * * * *
--------------------MENU-----------------------
1. Add Information to Books
2. Add Information to Tapes
3. Display Books Information
4. Display Tapes Information
5. Exit

Enter your choice : 1


Enter the Publication information :
Enter Title of the Publication : The C++ Programming Guide
Enter Price of Publication : 500
Enter Page Count of Book : 300

* * * * * PUBLICATION DATABASE SYSTEM * * * * *


--------------------MENU-----------------------
1. Add Information to Books
2. Add Information to Tapes
3. Display Books Information
4. Display Tapes Information
5. Exit

Enter your choice : 2


Enter the Publication information :
Enter Title of the Publication : Music of the World
Enter Price of Publication : 200
Enter Play Duration of the Tape : 60

* * * * * PUBLICATION DATABASE SYSTEM * * * * *


--------------------MENU-----------------------
1. Add Information to Books
2. Add Information to Tapes
3. Display Books Information
4. Display Tapes Information
5. Exit

Enter your choice : 3

* * * * BOOK PUBLICATION DATABASE SYSTEM * * * *


Title of Publication : The C++ Programming Guide
Publication Price : 500
Page Count : 300
--------------------------------------------------
* * * * * PUBLICATION DATABASE SYSTEM * * * * *
--------------------MENU-----------------------
1. Add Information to Books
2. Add Information to Tapes
3. Display Books Information
4. Display Tapes Information
5. Exit

Enter your choice : 4

* * * * TAPE PUBLICATION DATABASE SYSTEM * * * *


Title of Publication : Music of the World
Publication Price : 200
Play Time : 60 min
--------------------------------------------------
Practical
Write a C++ program that creates an output file, writes information to it, closes the file, open it again as an
input file and read the information from the file.

Code:

#include<iostream>

#include<fstream>

using namespace std;

class test

public:

void writedata();

void readdata();

};

void test::writedata()

fstream fp;

char ch;

fp.open("it.txt", ios::out);

cout << "Enter characters to write to the file (end input with a dot '.'): ";

cin >> ch;

while (ch != '.')

fp.put(ch);

cin >> ch;

fp.close();

void test::readdata()

fstream fp;
char ch;

fp.open("it.txt", ios::in);

if (!fp)

cout << "Error opening file for reading." << endl;

return;

cout << "File content: ";

// Read and display characters until the end of the file is reached

while (fp.get(ch))

cout << ch;

fp.close();

int main()

test ob;

int ch;

do

cout << "\n1. Write\n2. Read";

cout << "\nEnter your choice: ";

cin >> ch;

switch(ch)

case 1:

ob.writedata();

break;

case 2:
ob.readdata();

break;

default:

cout << "Invalid choice. Please enter 1 or 2.";

break;

} while(ch < 3);

return 0;

Output:

1.Write
2.Read
Enter your choice= 1
abcd
.

1.Write
2.Read
Enter your choice= 2
abcd
1.Write
2.Read
Enter your choice= 3
Practical
Write a function template for selection sort that inputs, sorts and outputs an integer array and a float array.

Code:

#include <iostream>

using namespace std;

// Template for selection sort

template <typename T>

void selectionSort(T arr[], int n)

// Loop through all elements in the array

for (int i = 0; i < n - 1; i++)

int minIndex = i;

// Find the minimum element in the unsorted part of the array

for (int j = i + 1; j < n; j++)

if (arr[j] < arr[minIndex])

minIndex = j;

// Swap the found minimum element with the first element

if (minIndex != i)

T temp = arr[i];

arr[i] = arr[minIndex];

arr[minIndex] = temp;

}
// Template function to display an array

template <typename T>

void displayArray(T arr[], int n)

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

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

cout << endl;

int main()

int n1, n2;

// Get the size of the integer array and input the values

cout << "Enter the number of elements in the integer array: ";

cin >> n1;

int intArray[n1];

cout << "Enter " << n1 << " integer values: ";

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

cin >> intArray[i];

// Display and sort the integer array

cout << "Original Integer Array: ";

displayArray(intArray, n1);

selectionSort(intArray, n1); // Sort the integer array

cout << "Sorted Integer Array: ";

displayArray(intArray, n1);
// Get the size of the float array and input the values

cout << "Enter the number of elements in the float array: ";

cin >> n2;

float floatArray[n2];

cout << "Enter " << n2 << " float values: ";

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

cin >> floatArray[i];

// Display and sort the float array

cout << "Original Float Array: ";

displayArray(floatArray, n2);

selectionSort(floatArray, n2); // Sort the float array

cout << "Sorted Float Array: ";

displayArray(floatArray, n2);

return 0;

Output
Practical
Write C++ program using STL for sorting and searching user defined records such as personal records
(Name, DOB, Telephone number etc) using vector container.

Code:
#include <iostream>

#include <vector>

#include <algorithm>

#include <string>

using namespace std;

// Define a struct for personal records

struct PersonalRecord {

string name;

string dob; // Date of Birth in the format "DD/MM/YYYY"

string phoneNumber;

// Constructor to easily create records

PersonalRecord(string n, string d, string p) : name(n), dob(d), phoneNumber(p) {}

};

// Function to display a personal record

void displayRecord(const PersonalRecord& record) {

cout << "Name: " << record.name << ", DOB: " << record.dob << ", Phone: " << record.phoneNumber <<
endl;

// Comparison function to sort records by name (used in sort function)

bool compareByName(const PersonalRecord& a, const PersonalRecord& b) {

return a.name < b.name; // Ascending order

// Comparison function to sort records by DOB (used in sort function)

bool compareByDOB(const PersonalRecord& a, const PersonalRecord& b) {

return a.dob < b.dob; // Ascending order


}

// Function to search for a record by name (using linear search for simplicity)

PersonalRecord* searchByName(vector<PersonalRecord>& records, const string& name) {

for (auto& record : records) {

if (record.name == name) {

return &record;

return nullptr; // Return nullptr if record is not found

int main() {

vector<PersonalRecord> records;

// Adding some sample records to the vector

records.push_back(PersonalRecord("Alice", "15/03/1990", "123-456-7890"));

records.push_back(PersonalRecord("Bob", "12/06/1985", "987-654-3210"));

records.push_back(PersonalRecord("Charlie", "22/07/2000", "555-123-4567"));

records.push_back(PersonalRecord("Diana", "01/01/1995", "444-555-6666"));

// Displaying original records

cout << "Original Records:" << endl;

for (const auto& record : records) {

displayRecord(record);

// Sorting by Name

sort(records.begin(), records.end(), compareByName);

cout << "\nSorted by Name:" << endl;

for (const auto& record : records) {

displayRecord(record);

}
// Sorting by DOB

sort(records.begin(), records.end(), compareByDOB);

cout << "\nSorted by DOB:" << endl;

for (const auto& record : records) {

displayRecord(record);

// Searching for a record by name

string searchName;

cout << "\nEnter the name to search: ";

cin >> searchName;

PersonalRecord* foundRecord = searchByName(records, searchName);

if (foundRecord != nullptr) {

cout << "\nRecord found: ";

displayRecord(*foundRecord);

} else {

cout << "\nRecord not found." << endl;

return 0;

}
Output:
Practical
Write C++ program using STL for sorting and searching user defined records such as Item records (Item
code, name, cost, quantity etc) using vector container.

Code:

#include <iostream>

#include <vector>

#include <algorithm>

#include <string>

using namespace std;

// Define a structure for Item records

struct ItemRecord {

int itemCode;

string itemName;

double itemCost;

int itemQuantity;

// Constructor for easy initialization

ItemRecord(int code, string name, double cost, int quantity)

: itemCode(code), itemName(name), itemCost(cost), itemQuantity(quantity) {}

};

// Function to display an item record

void displayItem(const ItemRecord& item) {

cout << "Item Code: " << item.itemCode

<< ", Name: " << item.itemName

<< ", Cost: $" << item.itemCost

<< ", Quantity: " << item.itemQuantity << endl;

// Comparison function to sort items by Item Code

bool compareByCode(const ItemRecord& a, const ItemRecord& b) {

return a.itemCode < b.itemCode; // Ascending order


}

// Comparison function to sort items by Item Name

bool compareByName(const ItemRecord& a, const ItemRecord& b) {

return a.itemName < b.itemName; // Ascending order

// Comparison function to sort items by Item Cost

bool compareByCost(const ItemRecord& a, const ItemRecord& b) {

return a.itemCost < b.itemCost; // Ascending order

// Function to search for an item by Item Code (using linear search)

ItemRecord* searchByCode(vector<ItemRecord>& items, int itemCode) {

for (auto& item : items) {

if (item.itemCode == itemCode) {

return &item; // Return pointer to the found item

return nullptr; // Return nullptr if item is not found

int main() {

vector<ItemRecord> items;

// Adding some sample item records to the vector

items.push_back(ItemRecord(101, "Laptop", 1200.50, 5));

items.push_back(ItemRecord(102, "Smartphone", 699.99, 10));

items.push_back(ItemRecord(103, "Tablet", 499.99, 7));

items.push_back(ItemRecord(104, "Monitor", 250.75, 3));

// Displaying original items

cout << "Original Item Records:" << endl;

for (const auto& item : items) {


displayItem(item);

// Sorting by Item Code

sort(items.begin(), items.end(), compareByCode);

cout << "\nSorted by Item Code:" << endl;

for (const auto& item : items) {

displayItem(item);

// Sorting by Item Name

sort(items.begin(), items.end(), compareByName);

cout << "\nSorted by Item Name:" << endl;

for (const auto& item : items) {

displayItem(item);

// Sorting by Item Cost

sort(items.begin(), items.end(), compareByCost);

cout << "\nSorted by Item Cost:" << endl;

for (const auto& item : items) {

displayItem(item);

// Searching for an item by Item Code

int searchCode;

cout << "\nEnter the Item Code to search for: ";

cin >> searchCode;

ItemRecord* foundItem = searchByCode(items, searchCode);

if (foundItem != nullptr) {

cout << "\nItem found: ";

displayItem(*foundItem);

} else {
cout << "\nItem with code " << searchCode << " not found." << endl;

return 0;

}
Output:
Practical
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 and returns the population of the
state.

Code:
#include <iostream>
#include <map>
#include <string>
using namespace std;

int main() {
// Create a map where key is state name (string) and value is population (int)
map<string, int> statePopulation;

// Initializing map with some states and their populations


statePopulation["California"] = 39538223;
statePopulation["Texas"] = 29145505;
statePopulation["Florida"] = 21538187;
statePopulation["New York"] = 20201249;
statePopulation["Pennsylvania"] = 13002700;
statePopulation["Illinois"] = 12812508;

// Prompt the user for a state name


string state;
cout << "Enter the name of a state: ";
getline(cin, state);

// Search for the state in the map and display the population
map<string, int>::iterator it = statePopulation.find(state);

if (it != statePopulation.end()) {
// If the state is found in the map, print the population
cout << "The population of " << state << " is: " << it->second << endl;
} else {
// If the state is not found in the map
cout << "State not found in the map." << endl;
}

return 0;
}

Output:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy