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

CPP_Practical

Uploaded by

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

CPP_Practical

Uploaded by

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

GROUP A

Assignment NO 1

Implement a class Complex which represents the Complex Number data type.

Implement the following operations:

1. Constructor (including a default constructor which creates the complex number 0+0i).

2. Overloaded operator+ to add two complex numbers.

3. Overloaded operator* to multiply two complex numbers

4. Overloaded << and >> to print and read Complex Numbers.

#include<iostream>

using namespace std;

class complex
{
float x;
float y;
public:
complex()
{
x=0;
y=0;
}
complex operator+(complex);
complex operator*(complex);
friend istream &operator >>(istream &input,complex &t)
{
cout<<"Enter the real part";
input>>t.x;
cout<<"Enter the imaginary part";
input>>t.y;
}
friend ostream &operator <<(ostream &output,complex &t)
{

output<<t.x<<"+"<<t.y<<"i\n";

}
};
complex complex::operator+(complex c)
{
complex temp;
temp.x=x+c.x;
temp.y=y+c.y;
return(temp);
}
complex complex::operator*(complex c)
{
complex temp2;
temp2.x=(x*c.x)-(y*c.y);
temp2.y=(y*c.x)+(x*c.y);
return (temp2);
}
int main()
{
complex c1,c2,c3,c4;
cout<<"Default constructor value=\n";
cout<<c1;
cout<<"\nEnter the 1st number\n";
cin>>c1;
cout<<"\nEnter the 2nd number\n";

cin>>c2;
c3=c1+c2;
c4=c1*c2;
cout<<"\nThe first number is ";
cout<<c1;
cout<<"\nThe second number is ";
cout<<c2;
cout<<"\nThe addition is ";
cout<<c3;
cout<<"\nThe multiplication is ";
cout<<c4;
return 0;
}

[4] Write a C++ program create a calculator for an arithmetic operator (+, -, *, /).
The program should take two operands from user and performs the operation on those
two operands depending upon the operator entered by user. Use a switch statement to
select the operation. Finally, display the result.
Some sample interaction with the program might look like this:
Enter first number, operator, second number: 10 / 3 Answer = 3.333333 Do another (y/n)?
y
Enter first number, operator, second number: 12 + 100 Answer = 112 Do another (y/n)? n

#include <iostream>
using namespace std;

int main() {
char choice;
do {
double num1, num2, result;
char op;

// Input: two numbers and an operator


cout << "Enter first number:";
cin >> num1;
cout << "Enter operator: ";
cin >> op;
cout << "Enter second number: ";
cin >> num2;

// Perform the operation based on the operator


switch (op) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
} else {
cout << "Error: Division by zero is undefined.\n";
continue; // Skip the result output and prompt again
}
break;
default:
cout << "Error: Invalid operator entered.\n";
continue; // Skip the result output and prompt again
}

// Output the result


cout << "Answer = " << result << endl;

// Ask the user if they want to perform another operation


cout << "Do another (y/n)? ";
cin >> choice;

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

cout << "Calculator closed." << endl;

return 0;
}
Assignment No 3

Implement a class Cpp Array which is identical to a one-dimensional C++ array (i.e., the index set is
a set of consecutive integers starting at 0) except for the following: 1. It performs range checking.
2. It allows one to be assigned to another array through the use of the assignment operator (e.g.
cp1= cp2) 3. It supports a function that returns the size of the array. 4. It allows the reading or
printing of array through the use of cout and cin

#include <iostream>

#include <stdexcept> // For std::out_of_range and std::invalid_argument

class CppArray {

private:

int* arr; // Pointer to dynamically allocate memory for the array

int size; // Size of the array

public:

// Constructor: Initialize the array with a given size

CppArray(int s) {

if (s <= 0) {

throw std::invalid_argument("Array size must be greater than 0");

size = s;

arr = new int[size](); // Allocate memory and initialize to zero

// Destructor: Clean up the dynamically allocated memory

~CppArray() {

delete[] arr;

// Copy constructor: To create a deep copy of another CppArray


CppArray(const CppArray& other) {

size = other.size;

arr = new int[size];

for (int i = 0; i < size; ++i) {

arr[i] = other.arr[i];

// Assignment operator overload

CppArray& operator=(const CppArray& other) {

if (this == &other) {

return *this; // Self-assignment check

// Delete existing array

delete[] arr;

// Allocate new memory and copy values

size = other.size;

arr = new int[size];

for (int i = 0; i < size; ++i) {

arr[i] = other.arr[i];

return *this;

// Overload subscript operator for range-checked element access

int& operator[](int index) {

if (index < 0 || index >= size) {

throw std::out_of_range("Index out of bounds");


}

return arr[index];

// Function to get the size of the array

int getSize() const {

return size;

// Overload >> operator for input (cin)

friend std::istream& operator>>(std::istream& input, CppArray& array) {

for (int i = 0; i < array.size; ++i) {

input >> array.arr[i];

return input;

// Overload << operator for output (cout)

friend std::ostream& operator<<(std::ostream& output, const CppArray& array) {

for (int i = 0; i < array.size; ++i) {

output << array.arr[i] << " ";

return output;

};

int main() {

int n;

// User input for size of the array

std::cout << "Enter size of the array: ";


std::cin >> n;

// Create an array of size n

CppArray arr1(n);

// Input array elements

std::cout << "Enter array elements: ";

std::cin >> arr1;

// Print the array

std::cout << "Array elements: " << arr1 << std::endl;

// Test assignment operator

CppArray arr2 = arr1; // Copy arr1 to arr2

std::cout << "Copied array: " << arr2 << std::endl;

// Test element access

try {

std::cout << "Element at index 2: " << arr1[2] << std::endl;

} catch (const std::out_of_range& e) {

std::cerr << e.what() << std::endl;

// Test size function

std::cout << "Size of the array: " << arr1.getSize() << std::endl;

return 0;

}
Assignment No 5

Develop an object oriented program in C++ to create a database of student information system
containing the following information: Name, Roll number, Class, division, Date of Birth, Blood
group, Contact address, telephone number, driving licence no. etc Construct the database with
suitable member functions for initializing and destroying the data viz constructor, default
constructor, Copy constructor, destructor, static member functions, friend class, this pointer, inline
code and dynamic memory allocation operators-new and delete.

#include <iostream>

#include <string>

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;
}

Assignment No 8

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 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

#include <iostream>

#include <string>

#include <stdexcept>

class Publication {

protected:

std::string title;

float price;

public:

// Default constructor

Publication() : title(""), price(0.0f) {}

// Method to get data for Publication

virtual void getData() {

std::cout << "Enter title: ";

std::getline(std::cin, title);

std::cout << "Enter price: ";

std::cin >> price;

if (price < 0) {

throw std::invalid_argument("Price cannot be negative.");


}

// Method to display data of Publication

virtual void displayData() const {

std::cout << "Title: " << title << "\nPrice: $" << price << std::endl;

// Method to reset the values to zero or empty

virtual void reset() {

title = "";

price = 0.0f;

// Virtual destructor to allow derived classes to clean up properly

virtual ~Publication() = default;

};

class Book : public Publication {

private:

int pageCount;

public:

// Default constructor

Book() : Publication(), pageCount(0) {}

// Overriding the getData method for Book-specific input

void getData() override {

Publication::getData(); // Call the base class method to get title and price

std::cout << "Enter page count: ";

std::cin >> pageCount;


if (pageCount < 0) {

throw std::invalid_argument("Page count cannot be negative.");

// Overriding the displayData method to show Book-specific data

void displayData() const override {

Publication::displayData(); // Call the base class display method

std::cout << "Page Count: " << pageCount << std::endl;

// Overriding the reset method to reset page count as well

void reset() override {

Publication::reset(); // Call the base class reset method

pageCount = 0;

};

class Tape : public Publication {

private:

float playTime;

public:

// Default constructor

Tape() : Publication(), playTime(0.0f) {}

// Overriding the getData method for Tape-specific input

void getData() override {

Publication::getData(); // Call the base class method to get title and price

std::cout << "Enter playing time (in minutes): ";


std::cin >> playTime;

if (playTime < 0) {

throw std::invalid_argument("Playing time cannot be negative.");

// Overriding the displayData method to show Tape-specific data

void displayData() const override {

Publication::displayData(); // Call the base class display method

std::cout << "Playing Time: " << playTime << " minutes" << std::endl;

// Overriding the reset method to reset playing time as well

void reset() override {

Publication::reset(); // Call the base class reset method

playTime = 0.0f;

};

int main() {

Book myBook;

Tape myTape;

std::cout << "Enter data for a Book:\n";

try {

myBook.getData();

} catch (const std::exception& e) {

std::cerr << "Error: " << e.what() << "\nResetting values to zero...\n";

myBook.reset();

}
std::cin.ignore(); // To clear the newline character from the input buffer

std::cout << "\nEnter data for a Tape:\n";

try {

myTape.getData();

} catch (const std::exception& e) {

std::cerr << "Error: " << e.what() << "\nResetting values to zero...\n";

myTape.reset();

std::cout << "\nDisplaying data for Book:\n";

myBook.displayData();

std::cout << "\nDisplaying data for Tape:\n";

myTape.displayData();

return 0;

Assignment no 11:

A book shop maintains the inventory of books that are being sold at the shop. The list includes

details such as author, title, price, publisher and stock position. Whenever a customer wants a

book, the sales person inputs the title and author and the system searches the list and displays

whether it is available or not. If it is not, an appropriate message is displayed. If it is, then the

system displays the book details and requests for the number of copies required. If the

requested copies book details and requests for the number of copies required. If the requested

copies are available, the total cost of the requested copies is displayed; otherwise the message

Required copies not in stock‖ is displayed. Design a system using a class called books with

suitable member functions and Constructors. Use new operator in constructors to allocate
memory space required. Implement C++ program for the system

#include<iostream>

#include<string.h>

#include<stdlib.h>

using namespace std;

class book

char author[20];

char title[20];

char publisher[20];

double price;

int stock;

public:

book();

void insertdata();

void display();

int search(char[],char[]);

void nocopies(int);

};

book::book()

char *author=new char[50];

char * title=new char[50];

char *publisher=new char[50];

price=0;

stock=0;

void book::insertdata()
{

cout<<"\n Enter the name of Book:";

cin>>title;

cout<<"\n Enter The Name Of Author:";

cin>>author;

cout<<"\n Enter The name of Publisher:";

cin>>publisher;

cout<<"\n Enter the Price of book:";

cin>>price;

cout<<"\n Enter Stock of book:";

cin>>stock;

void book::display()

cout<<"\n "<<title<<"\t\t "<<author<<"\t\t "<<publisher<<" \t\t\t "<<price<<"\t "<<stock;

int book::search(char t[],char a[])

if(strcmp(title,t)&&(strcmp(author,a)))

return 0;

else

return 1;

void book::nocopies(int num)


{

if(stock>=num)

cout<<"\n Title is avilable";

cout<<"\n Cost of"<<num<<"Books is Rs."<<(price*num);

else

cout<<"\n Required copies not in stock";

int main()

int ch,n,i,flag=0,copies,key=0;

book b[100];

char bname[50];

char key_title[50],key_author[50];

do

cout<<"\n*****Book Store******";

cout<<"\n 1.Insert Details of book \n 2.Display \n 3.search \n 4.exit";

cout<<"\n Enter Your Choice:";

cin>>ch;

switch(ch)

case 1:

cout<<"\n How many books data u want to enter";

cin>>n;

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

b[i].insertdata();
}

break;

case 2:

cout<<"\n"<<"TITLE"<<"\t \t "<<"AUTHOR"<<"\t\t"<<"PUBLISHER"<<"\t\
t"<<"PRICE"<<"\t "<<"STOCK";

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

cout<<"\n";

b[i].display();

break;

case 3:

cout<<"\n Enter title of required book";

cin>>key_title;

cout<<"\n Enter author of required book";

cin>>key_author;

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

if(b[i].search(key_title,key_author))

flag=1;

cout<<"\n"<<"TITLE"<<"\t \t "<<"AUTHOR"<<"\t\t"<<"PUBLISHER"<<"\t\t"<<"PRICE"<<"\t
"<<"STOCK";

b[i].display();

//break;

key=i;

}
if(flag==1)

cout<<"\n Book is available";

else

cout<<"\n book is Not available";

break;

if(flag==1)

cout<<"\n Please enter the required number of copies of the book";

cin>>copies;

b[key].nocopies(copies);

break;

case 4: exit(EXIT_SUCCESS);

break;

default :

cout<<"\n Wrong Choice";

break;

}while(ch!=5);

return 0;

Assignment no:12

Create employee biodata using following classes

i) Personal record ii)Professional record iii) Academic record

Assume appropriate data members and member function to accept required data & print bio data.
Create biodata using multiple inheritance using C++.

*/
#include<iostream>

using namespace std;

class personal

public:

char name[20];

int age;

int date,month,year;

char gender;

personal()

cout<<" Enter name :";

cin>>name;

cout<<" \n Enter age :";

cin>>age;

cout<<" \n Enter date of birth";

cin>>date>>month>>year;

cout<<"\n Enter gender(F/M)";

cin>>gender;

};

class professional

public:
int id;

int d,m,y;

professional()

cout<<"\n Enter ID number";

cin>>id;

cout<<"\n Enter date of joining";

cin>>d>>m>>y;

};

class academic

public:

char edu[20];

char branch[20];

academic()

cout<<"\n Enter education";

cin>>edu;

cout<<"\n Enter branch";

cin>>branch;

};

class all:public personal,public professional,public academic


{

public:

all()

cout<<"\n\tBIO DATA\n";

cout<<"Personal data:";

cout<<"\nname is "<<name<<"\n age is "<<age<<"\n Date of birth


"<<date<<"/"<<month<<"/"<<year;

cout<<"\n\nprofessional data:\n";

cout<<"ID is "<<id<<"\n date of joining "<<d<<"/"<<m<<"/"<<y;

cout<<"\n\nacademic data:\n";

cout<<"Education is "<<edu<<"\n branch is "<<branch;

};

int main()

all obj;

return 0;

}
GROUP B

Assignment No 13

Crete User defined exception to check the following conditions and throw the exception if the
criterion does not meet. a. User has age between 18 and 55 b. User stays has income between Rs.
50,000 – Rs. 1,00,000 per month c. User stays in Pune/ Mumbai/ Bangalore / Chennai d. User has
4-wheeler Accept age, Income, City, Vehicle from the user and check for the conditions mentioned
above. If any of the condition not met then throw the exception

#include <iostream>

#include <string>

#include <stdexcept>

// User-defined exception class for Age validation

class AgeException : public std::exception {

public:

const char* what() const noexcept override {

return "Age must be between 18 and 55.";

};

// User-defined exception class for Income validation

class IncomeException : public std::exception {

public:

const char* what() const noexcept override {

return "Income must be between Rs. 50,000 and Rs. 1,00,000.";

};

// User-defined exception class for City validation

class CityException : public std::exception {


public:

const char* what() const noexcept override {

return "User must stay in Pune, Mumbai, Bangalore, or Chennai.";

};

// User-defined exception class for Vehicle validation

class VehicleException : public std::exception {

public:

const char* what() const noexcept override {

return "User must have a 4-wheeler.";

};

// Class for validating user input based on criteria

class User {

private:

int age;

double income;

std::string city;

bool hasFourWheeler;

public:

// Method to get user data

void getData() {

// Input user age

std::cout << "Enter age: ";

std::cin >> age;

// Input user income

std::cout << "Enter income (Rs.): ";


std::cin >> income;

// Input user city

std::cout << "Enter city: ";

std::cin.ignore(); // To ignore the newline character from the buffer

std::getline(std::cin, city);

// Input whether the user has a 4-wheeler

std::cout << "Do you have a 4-wheeler (1 for Yes, 0 for No): ";

std::cin >> hasFourWheeler;

// Method to validate user data

void validate() {

// Check age condition

if (age < 18 || age > 55) {

throw AgeException();

// Check income condition

if (income < 50000 || income > 100000) {

throw IncomeException();

// Check city condition

if (city != "Pune" && city != "Mumbai" && city != "Bangalore" && city != "Chennai") {

throw CityException();

// Check 4-wheeler condition

if (!hasFourWheeler) {
throw VehicleException();

};

int main() {

User user;

try {

user.getData(); // Get user data from input

user.validate(); // Validate user input

std::cout << "User data is valid and meets all criteria." << std::endl;

} catch (const AgeException& e) {

std::cerr << "Age Error: " << e.what() << std::endl;

} catch (const IncomeException& e) {

std::cerr << "Income Error: " << e.what() << std::endl;

} catch (const CityException& e) {

std::cerr << "City Error: " << e.what() << std::endl;

} catch (const VehicleException& e) {

std::cerr << "Vehicle Error: " << e.what() << std::endl;

return 0;

You might also like