Practice Programs CPP 2020-21

Download as pdf or txt
Download as pdf or txt
You are on page 1of 65

Practice Programs CPP 2020-21

Topic 1: classes and objects

1_1 Write a class ‘Patient’ with members name,uid,mobNum...


a) write a parameterized constructor to initialize members
b) write a static method which accepts array of ‘Patient’ and a key, mob num.
Then performs search to find patient who’s mob num matches with key mob no
and returns that patient.
c) write a test program to create array of 10 patients and demonstrate the usage of
above said method.

1_2 Consider a Customer has bank account, he is allowed to debit and credit
money to his account. The customer is allowed to transfer money from his
account to other customer account. Write a CPP program to simulate the
scenario by creating two customer objects.

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
1_3 Consider a Bank “SyndBank” has created multiple accounts and pay
interest to all the accounts periodically. Simulate the bank scenario by
printing account details before and after paying interest to all the accounts.

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
1_32 Define a class CricketPlayer(name, no_of_innings, total_runs, bat_avg). Define
appropriate constructors and perform the followge.ing

i. Initialize bat_avg with 0.


ii. Define a method UpdateBattingavg(CricketPlayer[]), which
update bat_avg of every player.
iii. Define a method DisplayPlayer(CricketPlayer[]) which display all
players .
iv. Define a method getPlayer(CricketPlayer[]), which returns a
CricketPlayer with highest batting average
v. Define method to DisplayPlayer(CricketPlayer) to print player
details
Write a main function to create 5 cricket players and test all the functions

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
1_4 Consider simple library application. library has some books and librarian can issue
the books to students. Library can list the books that are issued to the students with
their details.
1. Create a Library class with members collegeName, librarian, books. Include
methods to issue books to students and to display list of books that are
issued to students. -
2. Create a class Book with members title, publisher, student-issued to- and
display method.
3. Create a class Student with members name, srn, mobileNum and display
method.
4. Identify relationship between the classes. Include appropriate parameterized
constructors in each class.

Following code must be satisfied in your main function

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
//main
Book bookArr[100];
// initialize book array elements
Library bvbLib(“KLETU”, “Prof abc”);
Student s1(“aaa”,”18CSE098”);
bvbLib.issueBook(“datastructure”, s1);
// issue few more books
bvbLib.displayIssuedBooks( );

1_5 Consider a movie which involves many artists like actor, actress, director, singer
and musician. Intially artists are assigned to the movie one by one and error
message should be printed if same type of actors are added repeateadly. Later
there can be replacement of actor or actress. You should be able to display movie
artists and also print artists vaccant places if all artists are yet to be assigned.

//Satisfy the following code in main()


Movie KGF(.......)//create object
//add few artists
//display yet to be assigned artists
//add remaining
//replace actor

1_6 Consider Network service provider like Reliance who provide services like
Broadband and DTH connections.
I. Create a class BroadBand with memberscustomerName, id, planAmount.
II. Create a class DTH with member customerMobileNumber, string
channelList[ ], balance.
III. Create class NetworkProvider with members BroadBandbbArray[ ], DTH
dArray[ ], bbCount, dthCount. Include methods like
registerNewConnection(BroadBand b), registerNewConnection( DTH d),
displayConnetions(inttypeOfConnections)
Write a main program to create a Network service provider with few connections of
broadband and DTH. Then register new connections and display the list.

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
Topic 2: Inheritance

2_1 Scenario
Consider the Bank Account of type Savings account, current account and
money can be debited or credited to bank accounts. The number of
transactions is limited to 5 on both the accounts, if it exceeds a penalty
has to be imposed and the penalty amount has to be automatically
debited from account. The details of the bank accounts shall be printed.
Identify base class and derived classes, attributes and functions in a
class hierarchy. Write a class diagram and CPP program to simulate the
scenario.

2_2 Create a super class Car with members color, name, noOfSeats, maxSpeed,
speed, accelerate(), break().Then create two sub-classes Ferrari, BMW.
i) include a constructor in Car, Car(name, color, maxSpeed, noOfSpeed)
ii) include constructors in classes Ferrari, BMW which reuses the constructor
of CAR class
iii) over-ride methods accelerate(), break() in sub-classes
iv) write a test program to create a object of Ferrari and BMW. Race both the
cars

2-3 Create a class employee{name,salary} with method hike(percentage), display().


Then create sub classes manager{noOfStocks} and normalEmployee{}.Include
static concrete method to hike the salary of array of employees in each
subclasses.
Hike for manager is calculated as salary= salary +

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
(percentage/100*salary)+(noOfstocks*10) and for others it is salary= salary +
(percentage/100*salary) with up to 20%
a) Include only parameterized constructor to initialize members in each class.
b) Write a demo program to create an array of employee sub classes . Then
use above mentioned method to hike the salary of all objects in the array.

2_4 Consider a courier system.


Create a super class CourierItem with members such as id, fromAddress
,toAddress,weight, price with appropriate constructor. Include a method to getPrice().
● Create a subclass PaperItem of CourierItem with members typeOfDocument-like
letter, book or others. Overide getPrice() method to calculate price based on type of
document and weight.
● Materials can be packed in a box and couriered. Create another subclass
MaterialItem of type CourierItem with members boxHeight, boxWidth. Overide
getPrice() method to calculate price based on volume and weight of the box.
Write a main program to create few objects of subclasses and invoke methods to print
the prices.

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
Unit II: Chap 4

3_1 Create a super class Search and sub-classes BinarySearch and SequentialSearch.
i) members of Search class array of integer and key to be searched with following
functions int getarray(),void getkey(), virtual int searchElement()
ii) Define the virtual function SequentialSearch and binerySearch class
v) Write a test program to create objects of both the sub-classes. Then perform
sorting,searching and displaying for both objects using only one reference of
superclass

3_11 Modified version of above program 3_1


Create a super class Search and sub-classes BinarySearch and
SequentialSearch.
i) members of Search class are array integer, abstract method
searchElement(int key) and concrete method sort().
ii) override virtual method in subclass and implementation provided will as
per the algorithms indicated by subclass name.
iii) Write a test program to create objects both the sub-classes. Then perform
sorting,searching and displaying for both objects using only one reference of
superclass

3_2 Virtual function demo program

3_3 Revisiting Employees program with runtime polymorphism. Note changes


made in problem statement.
Create an abstract class employee{name,salary} with absract method
hike(percentage) and concrete method display(). Include static concrete

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
method to hike the salary of array of employees which can contains mix of
objects from its subclasses.
Then create sub classes manager{noOfStocks} and normalEmployee{}.
Hike for manager is calculated as salary= salary +
(percentage/100*salary)+(noOfstocks*10) and for others it is salary= salary +
(percentage/100*salary) with up to 20%
a) Include only parameterized constructor to initialize members in each class.
b) Write a demo program to create an array of employee sub classes . Then use
above mentioned method to hike the salary of all objects in the array.

3_4 Create an abstract class Transport{speed, virtual void moveVehicle(), void


display()}. Then create three subclasses Car, Boat, Plane.
i) include a method drive() in Car class, rowing() in Boat class, fly() in Plane class
ii) include appropriate data members and constructors in each class.
iii) You can travel by car, Boat and Plane in any combination. Include a static
method in base class, void Travel(Transport **), which will invoke the appropriate
method mentioned in (i) as per the subclass class object in the bunch. Also the
method should print longest distance traveled in a vehicle.
iii) Demonstrate usage of above functions.

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
Structure Enquire: Has-Is relationship

4_1 Consider a Customer(customerId, customerName, phoneNum, billAmount )


and the shop classifies customer as regular customer and privileged
customer. The shop offers discount of 5% on every purchase by a regular
customer and it issues a membership card to a privileged customer and
offer will be always better than regular customer. The shop prepares a list
of customers (regular and privileged randomly) visited shop and view the
bill amount of individual customer and total bill amount of all the
customers. Display count of regular customers and privileged customers.
Identify exceptions and manage.

4_2
Consider a service station for bikes, cars and Buses. The service station
can operates for 8 each day. Each vehicle being serviced goes through three
stage sparePartCheckUp, wash and oiling. At each stage of service, some
duration of time is spent for each vehicle depending the type of vehicle and
its properties as follows
i.servicing time for bikes depends on number km vehicle has run.
ii.servicing time for car depends on engine cc
iii.servicing time for bus depends number seats.
Each vehicle has its owner. Assume some vehicles are present at the start
of day. Service all the vehicle and after servicing is done customer must be
informed for delivery of bikes. Create appropriate super-sub-classes with
constructors, static and non-static members, objects and test the programs
to demonstrate above capabilities.

4_3
Consider a book shop. The shop contains a number of items like books,
DVDs, Stationaries which are sold every day. Shopkeeper maintains the total
number of each type of items sold, all items sold and the total amount
generated from the sale. Shop keeper also maintains information about
regular customers and items that are purchased by them. Shopkeeper
provides discounts based on the number of items being purchased by the
customer. Create appropriate classes with constructor, static and non-static
members, objects and test the programs to demonstrate above capabilities.

4_4 Consider online shopping website. Here items available for shopping are
electronics gadgets and books. The website lists all items available for
sale. It also maintains the total stock for each type of item and always
ensures certain number these stocks are available at the beginning of the
day. i.e it generates the order for stocks at the end of the day based on sale
happened for that day. Write a program to list the items in each category.
Then generate the list of stocks to be ordered for the next day.

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
Topic 1: classes and objects
Topic 1:classes and objects
Solutions

1_1 /**
Write a class ‘Patient’ with members name,uid,mobNum...
a) write a parameterized constructor to initialize members
b) write a static method which accepts array of ‘Patient’ and a key, mob num.
Then performs search to find patient who’s mob num matches with key mob no
and returns that patient.
c) write a test program to create array of 10 patients and demonstrate the usage
of above said method.

Date:18-01-2019
Author: Mahesh S Patil
[email protected]
*/

#include<iostream>
using namespace std;
class patient
{
public:
string name;
int uid;
long mobileNumber;
static int counter;

patient(string name, long


mobileNumber=0L):name(name),mobileNumber(mobileNumber)
{
uid=++counter;
}
void display()
{
cout<<"uid="<<uid<<" name="<<name<<" mobile
no="<<mobileNumber<<endl;
}

static int search(patient parry[], int size, long keyMobileNumber)


{
cout<<"seraching....."<<endl;
int flag=-1;
for(int i=0;i<size;i++){
cout<<"search uid:"<<parry[i].uid<<" loop:"<<i<<endl;
if(parry[i].mobileNumber==keyMobileNumber)
{
flag=i;

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
}
}
return flag;
}

};

int patient::counter=0;

int main()
{
patient parry[]={patient("ramesh"), patient("suresh"),
patient("dinesh",999999990L)};
for(int i=0; i<3; i++)
{
parry[i].display();
}
long keyMobileNumber;
cout<<"enter mobile number to search"<<endl;
cin>>keyMobileNumber;
int index=patient::search(parry,3,keyMobileNumber);
if(index==-1)
cout<<"key not found"<<endl;
else
{
cout<<"found ";
parry[index].display();
}

return 0;
}

1_2 #include <iostream>

using namespace std;

class BankAccount{
public:
int accNo;
float accbal;
BankAccount(){
accNo=0;
accbal=0;
}
BankAccount(int num,float bal){
accNo=num;
accbal=bal;

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
}
void printAccount(){
cout<<accNo<<":"<<accbal<<endl;
}
};
class Customer{
public:
int custId;
string custName;
BankAccount ba1;
Customer(){
custId=0;
custName="";
}
Customer(int id, string name,BankAccount ba){
custId=id;
custName=name;
ba1=ba;
}
void creditAmt(float amt){
ba1.accbal+=amt;
}
void debitAmt(float amt){
ba1.accbal-=amt;
}
void transferAmt(BankAccount& ba,float amt){
ba1.accbal-=amt;
ba.accbal+=amt;
}
void printCustomer(Customer c){
cout<<c.custId<<":"<<c.custName<<endl;
c.ba1.printAccount();

};
int main()
{ BankAccount acc1(1001,5000),acc2(1002,5000);
Customer c1(1,"aaa",acc1);
Customer c2(2,"bbb",acc2);
c1.printCustomer(c1);
c2.printCustomer(c2);
c1.transferAmt(c2.ba1,500);
cout<<c1.ba1.accbal<<endl;
cout<<c2.ba1.accbal<<endl;
c1.printCustomer(c1);
c2.printCustomer(c2);
c2.transferAmt(c1.ba1,500);
c1.printCustomer(c1);

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
c2.printCustomer(c2);

//cout << "Hello world!" << endl;


return 0;
}

1_3 #include <iostream>


using namespace std;

class BankAccount{
public:
int accNo;
float accBal;
BankAccount(){
accNo=0;
accBal=0;
}
BankAccount(int num, float bal){
accNo=num;
accBal=bal;
}
void printAccount(){
cout<<accNo<<":"<<accBal<<endl;
}
};
class Bank{
public:
string bankName;
string branchName;
string managerName;
string address;
BankAccount accounts[5];
Bank(){
cout<<"The accounts are"<<endl;
for(int i=0;i<10;i++)
accounts[i].printAccount();
bankName="";
branchName="";
managerName="";
address="";
}
Bank(string bankname, string branch, string manager,
string bankAddress,BankAccount bankAccounts[], int num){

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
bankName=bankname;
branchName=branch;
managerName=manager;
address=bankAddress;
for(int i=0;i<num;i++)
accounts[i]=bankAccounts[i];
}
void payInterest(int percentage){
for(int i=0;i<5;i++){

accounts[i].accBal=accounts[i].accBal+accounts[i].accBal*((float)percentage/100);
}
}
void printBankAccounts(){

cout<<bankName<<":"<<managerName<<":"<<branchName<<":"<<address<<en
dl;
for(int i=0;i<5;i++){
cout<<accounts[i].accNo<<":"<<accounts[i].accBal<<endl;

}
};
int main()
{
BankAccount acc1(1,100),
acc2(2,200),
acc3(3,300),
acc4(4,400),
acc5(5,500);
BankAccount accounts[]={acc1,acc2,acc3,acc4,acc5};
Bank bank("Synd","bvbCampus","a","Vidyanagar",accounts,5);

/*for(int i=0;i<5;i++){

bank.accounts[i].printAccount();
}*/
bank.printBankAccounts();
bank.payInterest(5);
bank.printBankAccounts();
/*

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
for(int i=0;i<5;i++){

bank.accounts[i].printAccount();
}*/

//cout << "Hello world!" << endl;


return 0;
}

1_32
#include <iostream>

using namespace std;

class CricketPlayer
{
string name;
int NoOfInnings;
int NoOfNotOuts;
int TotalRuns;
int BatAvg;
public:
CricketPlayer(){}
CricketPlayer(string n, int noi, int non, int tr,
int ba)
{
name=n;
NoOfInnings=noi;
NoOfNotOuts=non;
TotalRuns=tr;
BatAvg=ba;
}
string getName(){return name;}
int getAvg(){return BatAvg;}
void UpdateBattingavg(CricketPlayer cp[])
{
for(int i=0;i<5;i++)
cp[i].BatAvg=cp[i].TotalRuns/cp[i].NoOfInnings;
}
void Displayplayer(CricketPlayer cp[])
{
for(int i=0;i<5;i++)
{
cout<<cp[i].getName()<<":"<<cp[i].getAvg()<<endl;

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
}
}
CricketPlayer getPlayer(CricketPlayer cp[])
{
CricketPlayer temp;
for(int i=0;i<5;i++)
{
//cout<<cp[i].getName()<<endl;
if(cp[i].BatAvg>cp[i+1].BatAvg)
{
temp=cp[i];
//cout<<temp.getName()<<endl;
cp[i]=cp[i+1];
cp[i+1]=temp;

}
else {temp=cp[i];}

}
//cout<<temp.getName()<<endl;
return temp;
}
void Displayplayer(CricketPlayer cp)
{

cout<<cp.getName()<<":"<<cp.getAvg()<<endl;

}
};

int main()
{
CricketPlayer cp1;
CricketPlayer cp2("a",5,1,200,0),
cp3("b",3,2,300,0),cp5("c",3,2,100,0),
cp6("d",5,2,200,0),
cp7("e",3,2,70,0);
//CricketPlayer cp[]={cp2,cp3,cp5,cp6,cp7};
CricketPlayer cp[]={{"a",5,1,200,0},cp3,cp5,cp6,cp7};
cp1.UpdateBattingavg(cp);
cp1.Displayplayer(cp);
CricketPlayer cp4=cp1.getPlayer(cp);

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
cout<<"Highest batting avg\n";
cp1.Displayplayer(cp4);

//cout << "Hello world!" << endl;


return 0;
}

1_4 /**
Consider simple library application. library has some books and librarian can
issue the books to students. Library can list the books that are issued to the
students with their details.
Create a Library class with members collegeName, librarian, books. Include
methods to issue books to students and to display list of books that are issued
to students.
Create a class Book with members title, publisher, student-issued to- and display
method.
Create a class Student with members name, srn, mobileNum and display method.
Identify relationship between the classes. Include appropriate parameterized
constructors in each class.

Date:05-02-2019
Author: Mahesh S Patil
[email protected]
*/

#include<iostream>
#include<string>
using namespace std;
class Student
{
public:
string name;
string srn;
long mobileNum;
Student(string n, string usn):name(n), srn(usn)
{

}
void display()
{
cout<<"name="<<name<<" srn="<<srn<<" mobile
num="<<mobileNum<<endl;

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
}
};

class Book
{
public:
string title;
string publisher;
//following declaration in comment wont compile. Look at constructor for
solution
//Student issuedTo("-nil-","-nil-");
Student issuedTo;
bool issueStatus=false;

Book(string t, string pub):title(t),publisher(pub),issuedTo("-nil", "-nil")


{

}
void display()
{
cout<<"Book title="<<title<<" publisher="<<publisher<<endl;
if(issueStatus)
{
cout<<" issued to ";
issuedTo.display();
}
else
cout<<" not issued to any one"<<endl;
}
};

class Library
{
public:
string collegeName;
string librarian ;
Book *books;
int booksCount;

Library(string col, string libr):collegeName(col),librarian(libr)


{

}
void issueBook(string title, Student &toStudent)

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
{
int bookIndex=searchBooks(title);
if(bookIndex!= -1)
{
books[bookIndex].issuedTo= toStudent;
books[bookIndex].issueStatus=true;
cout<<"Book "<<title<<" issued to "<<toStudent.name<<endl;
}
else
cout<<"requested book "<<title<<" is not available in library"<<endl;
}

int searchBooks(string title)


{
for(int i=0; i<booksCount;i++)
{
if(books[i].title == title && books[i].issueStatus==false)
return i;
}
return -1;
}
void displayIssuedBooks()
{
for(int i=0; i<booksCount; i++)
{
if(books[i].issueStatus)
books[i].display();
}
}

};

int main()
{
Book b1("Data Structures","pearson");
Book b2("oops","pearson");
Book b3("DBMS","pearson");
Book b4("oops","pearson");
Book b5("Data Structures","pearson");
Book b6("DBMS","pearson");
Book b7("oops","pearson");
Book b8("Data Structures","pearson");
Book b9("DBMS","pearson");

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
Book b10("Data Structures","pearson");

Book bookArr[10]={b1,b2,b3,b4,b5,b6,b7,b8,b9,b10};

Library bvbLib("KLETU", "Prof abc");


//intialize books in library
bvbLib.books=bookArr;
bvbLib.booksCount=10;
Student s1("aaa","18CSE098");
bvbLib.issueBook("oops", s1);
// issue few more books
Student s2("bbb","srn2");
bvbLib.issueBook("DBMS",s2);
bvbLib.issueBook("DBMS",s2);
bvbLib.issueBook("DBMS",s2);
bvbLib.issueBook("DBMS",s2);

bvbLib.displayIssuedBooks( );

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
Topic 2: Inheritance
Solutions
2-1 Scenario
Consider the Bank Account of type Savings account, current account and
money can be debited or credited to bank accounts. The number of
transactions is limited to 5 on both the accounts, if it exceeds a penalty has
to be imposed and the penalty amount has to be automatically debited
from account. The details of the bank accounts shall be printed. Identify
base class and derived classes, attributes and functions in a class
hierarchy. Write a class diagram and CPP program to simulate the
scenario.

#include<iostream>
using namespace std;

class BankAccount{
public:
int accNo;
float accBal;
void printAccount(){
cout<<accNo<<":"<<accBal<<endl;
}

};
class SavingAccount:public BankAccount{
public:

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
float penaltyAmount;
static int noOfTransactions;
void debit(float amt){
accBal-=amt;
noOfTransactions++;
if(noOfTransactions>5){
penaltyAmount+=20;
accBal=accBal-20;
cout<<"penalty amount="<<penaltyAmount<<endl;

}
void credit(float amt){
accBal+=amt;
noOfTransactions++;
if(noOfTransactions>5){
penaltyAmount+=20;
accBal=accBal-20;
cout<<"penalty amount="<<penaltyAmount<<endl;
}
}
void printPenaltyAmt(){
if(penaltyAmount>0){
if(noOfTransactions>5){
penaltyAmount=20;
cout<<penaltyAmount<<endl;
}
}

}
};
int SavingAccount::noOfTransactions=0;
int main()
{
SavingAccount s1;
s1.accNo=1001;
s1.accBal=1000;
s1.penaltyAmount=0;
s1.printAccount();
s1.debit(100);
s1.credit(100);
s1.debit(100);
s1.credit(100);

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
s1.credit(100);
s1.credit(100);
s1.printAccount();
cout<<s1.noOfTransactions;
s1.debit(100);
cout<<s1.noOfTransactions;
s1.printAccount();
return 0;
}

2_2 /*Create a super class Car with members color, name, noOfSeats,
maxSpeed, speed, accelerate(), break().Then create two sub-classes
Ferrari, BMW.
i) include a constructor in Car, Car(name, color, maxSpeed, noOfSpeed)
ii) include constructors in classes Ferrari, BMW which reuses the
constructor of CAR class
iii) over-ride methods accelerate(), break() in sub-classes
iv) write a test program to create a object of Ferrari and BMW. Race both
the cars */

#include<iostream>
using namespace std;
class Car
{
public:
string color;
string name;
int noOfSeats;
int maxSpeed;
double speed=0;

Car(string clor, string nname, int seats, int mxSpeed)


{
color = clor;
name = nname;
noOfSeats = seats;
maxSpeed = mxSpeed;
}
void accelerate()
{//do nothing

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
void powerBreak()
{
//do nothing

}
};

class BMW:public Car


{
public:
BMW(string clor, string nname, int seats, int mxSpeed): Car(clor, nname,
seats, mxSpeed)
{ }
void accelerate()
{ speed=speed+2;
if(speed>=maxSpeed)
speed=maxSpeed;
}
void powerBreak()
{
speed=speed-45;
if(speed<0)
speed=0;
}
};
class Ferrari :public Car
{
public:
Ferrari(string clor, string nname, int seats, int mxSpeed):Car(clor, nname,
seats, mxSpeed)
{ }
void accelerate()
{
speed=speed+3;
if(speed>=maxSpeed)
speed=maxSpeed; }
void powerBreak()
{
speed=speed-50;
if(speed<0)
speed=0;
}
};
int main()

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
{
Ferrari f("red", "rocket", 2, 350);
BMW b("white", "king", 2, 300);
for(int i=0;i<=150;i++)
{
f.accelerate();b.accelerate();
cout<<i<<"th seconds speed\n";
cout<<"Ferrari="<<f.speed<<" BMW="<<b.speed<<endl;
}
cout<<"applying break\n";
for(int i=0;i<=7;i++)
{f.powerBreak();b.powerBreak();
cout<< i<<"th seconds speed after break apply\n";
cout<< "Ferrari="<<f.speed<<" BMW="<<b.speed<<endl;
}
return 0;
}

2_3 /*
Create a class employee{name,salary} with method hike(percentage), display().
Then create sub classes manager{noOfStocks} and
normalEmployee{}.Include static concrete method to hike the salary of array
of employees in each subclasses.
Hike for manager is calculated as salary= salary +
(percentage/100*salary)+(noOfstocks*10) and for others it is salary= salary +
(percentage/100*salary)
a) Include only parameterized constructor to initialize members in each class.
b) Write a demo program to create an array of employee sub classes . Then use
above mentioned method to hike the salary of all objects in the array.

Date:24-02-2019
Author: Mahesh S Patil
[email protected]
*/

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
#include<iostream>
using namespace std;
class Employee
{public:
string name;
float salary;
string EmployeeType;
Employee(string n, float s,string et):name(n),salary(s),EmployeeType(et)
{

}
void display()//n.display()
{
cout<<"name="<<name<<" salary="<<salary<<endl;
}
void hike(float percentage)
{
salary+=(salary*percentage/100);
}

};

class NormalEmployee: public Employee


{public:
NormalEmployee(string n, float s):Employee(n,s,"normal")
{

void hike(float percentage)


{
if(percentage<20)
Employee::hike(percentage);
else
cout<<"salary cannot be hiked since percentage is 20% and
above"<<endl;

static void hike(NormalEmployee *nArry,int size,float percentage)


{
for(int i=0; i<size; i++)
nArry[i].hike(percentage);
}

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
void display()
{
cout<<EmployeeType<<"- ";
Employee::display();
}

static void display(NormalEmployee *nArry,int size)


{
for(int i=0; i<size; i++)
//nArry[i].Employee::display();
nArry[i].display();
}

};

class Manager: public Employee


{public:
int numberOfStocks ;
Manager(int ns,string n, float
s):numberOfStocks(ns),Employee(n,s,"Manager")
{
}

void hike(float percentage)


{
salary+=((salary*percentage/100) + (numberOfStocks*10));
}

static void hike(Manager *mArry,int size,float percentage)


{
for(int i=0; i<size; i++)
mArry[i].hike(percentage);
}

void display()
{
cout<<EmployeeType<<"- "<<"number of stocks="<<numberOfStocks<<"
";
Employee::display();
}

static void display(Manager *mArry,int size)

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
{
for(int i=0; i<size; i++)
mArry[i].display();

};

int main()
{
NormalEmployee nArr[3]={NormalEmployee("aaa", 60000),
NormalEmployee("bbb", 62000),
NormalEmployee("ccc", 64000)};
NormalEmployee::display(nArr,3);

Manager mArr[3]={Manager(1000,"maa",150000),
Manager(1500,"mbb",200000),
Manager(2000,"mcc",300000)};
Manager::display(mArr,3);

cout<<endl<<"hike salaries and display**********************************"<<endl;

NormalEmployee::hike(nArr,3,10);
Manager::hike(mArr,3,10);

NormalEmployee::display(nArr,3);
Manager::display(mArr,3);

return 1;
}

Output 2_3:
normal- name=aaa salary=60000
normal- name=bbb salary=62000
normal- name=ccc salary=64000
Manager- number of stocks=1000 name=maa salary=150000
Manager- number of stocks=1500 name=mbb salary=200000
Manager- number of stocks=2000 name=mcc salary=300000

hike salaries and display**********************************


normal- name=aaa salary=66000
normal- name=bbb salary=68200
normal- name=ccc salary=70400
Manager- number of stocks=1000 name=maa salary=175000

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
Manager- number of stocks=1500 name=mbb salary=235000
Manager- number of stocks=2000 name=mcc salary=350000

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
Unit II : Chap4 : Solutions

3_1 /*Create a super class Search and sub-classes BinarySearch and SequentialSearch.
i) members of Search class array of integer and key to be searched with following
functions int getarray(),void getkey(), virtual int searchElement()
ii) Define the virtual function SequentialSearch and binerySearch class
v) Write a test program to create objects both the sub-classes. Then perform
sorting,searching and displaying for both objects using only one reference of
superclass
*/
#include<iostream>
#include <algorithm>
using namespace std;
class search1
{ public:
int a[10];
int key;
int sizeOfArray;
void getarray()
{
cout<<"Enter number of array elements required\n";
cin>>sizeOfArray;
for(int i=0;i<sizeOfArray;i++)
{
cout<<"Enter "<<i<<" th element"<<endl;
cin>>a[i];
}
}

void getkey()
{
cout<<"Enter key to be searched";
cin>>key;
}

virtual int searchElement()=0;


};

class SequentialSearch:public search1


{
public:
int searchElement()
{
cout<<"SELECTION SEARCH";

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
for(int i=0;i<sizeOfArray;i++)
{
if(key==a[i])
return 1;
}
}
};
class binerySearch:public search1
{
public:
int searchElement()
{
cout<<"BINARY SEARCH";
sort(a,a+sizeOfArray);
int l=0,r=sizeOfArray;
while (l <= r) {
int m = l + (r - l) / 2;

// Check if x is present at mid


if (a[m] == key)
return 1;

// If x greater, ignore left half


if (a[m] < key)
l = m + 1;

// If x is smaller, ignore right half


else
r = m - 1;
}

};

int main()
{
int result=0,ch;
search1 *s1;
SequentialSearch s;
binerySearch b;
for(;;)

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
{
cout<<"Do you want to go for binary search or sequential search?\n";
cout<<"Enter 1 for binary search\n";
cout<<"Enter 2 for sequential search\n";
cin>>ch;
switch(ch)
{
case 2:s1=&s;
s1->getarray();
s1->getkey();
result=s1->searchElement();
break;
case 1:s1=&b;
s1->getarray();
s1->getkey();
result=s1->searchElement();
break;
}
if(result==1)
cout<<"Element found\n"<<endl;
else
cout<<"Element not found\n"<<endl;
}

3_11 /*
Create a super class Search and sub-classes BinarySearch and
SequentialSearch.
i) members of Search class are array integer, abstract method searchElement(int
key) and concrete method sort().
ii) override virtual method in subclass and implementation provided will as per the
algorithms indicated by subclass name.
iii) Write a test program to create objects both the sub-classes. Then perform
sorting,searching and displaying for both objects using only one reference of
superclass

Date:10-03-2019
Author: Mahesh S Patil
[email protected]
*/
#include<iostream>
using namespace std;
class Search
{

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
public:
int *data, size;
Search(int *dt, int sz):data(dt), size(sz)
{

}
void sortData()
{
int temp;
for(int i=0; i<size; i++)
for(int j=0; j<(size-i-1); j++)
{
if(data[j]>data[j+1])
{
temp=data[j];
data[j]=data[j+1];
data[j+1]=temp;
}
}

}
virtual void searchData(int key)=0;
void display()
{
cout<<"data: ";
for(int i=0; i<size;i++)
cout<<data[i]<<" ";
cout<<endl;
}

};

class BinarySearch:public Search


{
public:
BinarySearch(int *dt, int sz):Search(dt,sz)
{

}
void searchData(int key)
{
int l=0,r=size, flag=-1;
sortData();
while (l <= r)
{
int m = l + (r - l) / 2;
// Check if x is present at mid
if (data[m] == key)
{

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
flag=m;
break;
}
// If x greater, ignore left half
if (data[m] < key)
l = m + 1;
// If x is smaller, ignore right half
else
r = m - 1;
}

if(flag!=-1)
{
display();
cout<<"after sorting, key="<<key<<" found at index "<<flag<<endl;

}
else
{
cout<<"key= "<<key<<" not found "<<endl;
}

}
};
class SequentialSearch:public Search
{
public:
SequentialSearch(int *dt, int sz):Search(dt,sz)
{

}
void searchData(int key)
{
int flag=-1;
sortData();
for(int i=0; i<size; i++)
{
if(key==data[i])
{
flag=i;
break;
}
}
if(flag!=-1)
{
display();
cout<<"after sorting, key="<<key<<" found at index "<<flag<<endl;

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
else
{
cout<<"key= "<<key<<" not found "<<endl;
}

}
};
int main()
{
int mydata1[10]={54,25,18,94,37,51,38,27,48,58};
int mydata2[5]={51,38,27,48,58};
BinarySearch bs(mydata1,10);
SequentialSearch ss(mydata2,5);

Search *sPtr;

cout<<"Runtime polymorphism/ Dynamic Binding/ Dynamic method dispatch


Demo"<<endl;

cout<<"BinarySearch object search:"<<endl;


sPtr=&bs;
sPtr->display();
sPtr->searchData(48);
sPtr->searchData(99);

cout<<endl;
cout<<"SequentialSearch object search:"<<endl;
sPtr=&ss;
sPtr->display();
sPtr->searchData(48);
sPtr->searchData(99);
}

/*
Runtime polymorphism/ Dynamic Binding/ Dynamic method dispatch Demo
BinarySearch object search:
data: 54 25 18 94 37 51 38 27 48 58
data: 18 25 27 37 38 48 51 54 58 94
after sorting, key=48 found at index 5
key= 99 not found

SequentialSearch object search:


data: 51 38 27 48 58
data: 27 38 48 51 58
after sorting, key=48 found at index 2
key= 99 not found
*/

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
3_2 #include<iostream>
using namespace std;
class Avir
{
public:
int x=0,y=0;
virtual void virtualFun()
{
cout<<"base virtual function"<<endl;
};
void fun()
{
cout<<"base function"<<endl;
};
void onlyBaseFun()
{
cout<<"base class implemetation for onlyBaseFun()"<<endl;
}
};

class Bvir: public Avir


{
public:
int x=1,y=1;
void virtualFun()
{
cout<<"derived virtual function"<<endl;
}
void fun()
{
cout<<"derived function"<<endl;
};
void specializedFun()
{
cout<<"derived class implementation for specializedFun()"<<endl;
}
};

int main()
{
Bvir b;
Avir *aptr=&b;
Bvir *bptr=&b;

//following line is an example of runtime binding


aptr->virtualFun();
//following line is an example of compiletime binding even though its overridden
fun
aptr->fun();

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
bptr->virtualFun();
bptr->fun();

aptr->onlyBaseFun();
//following function call doesnt compile
//aptr->specializedFun();

bptr->onlyBaseFun();
bptr->specializedFun();

cout<<"ptr accessing hidden datamembers********"<<endl;


cout<<"base pointer aptr->x="<<aptr->x<<" aptr->y="<<aptr->y<<endl;
cout<<"derived pointer bptr->x="<<bptr->x<<" bptr->y="<<bptr->y<<endl;

Bvir bArr[3];
Avir *aptr2=bArr;

cout<<"array demo virtual function call with base ptr**********"<<endl;


for(int i=0;i<3;i++)
{
aptr2[i].virtualFun();
aptr2[i].fun();
}

Bvir *bptr2=bArr;
cout<<"array demo virtual function call with derived ptr********"<<endl;
for(int i=0;i<3;i++)
{
bptr2[i].virtualFun();
bptr2[i].fun();
}

3_3 /*
Revisiting Employees program with runtime polymorphism. Note changes made in
problem statement.
Create an abstract class employee{name,salary} with absract method
hike(percentage) and concrete method display(). Include static concrete method to
hike the salary of array of employees which can contains mix of objects from its
subclasses.
Then create sub classes manager{noOfStocks} and normalEmployee{}.

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
Hike for manager is calculated as salary= salary +
(percentage/100*salary)+(noOfstocks*10) and for others it is salary= salary +
(percentage/100*salary) with up to 20%
a) Include only parameterized constructor to initialize members in each class.
b) Write a demo program to create an array of employee sub classes . Then use
above mentioned method to hike the salary of all objects in the array.

Date:10-03-2019
Author: Mahesh S Patil
[email protected]
*/
#include<iostream>
using namespace std;
class Employee
{public:
string name;
float salary;
string EmployeeType;
Employee(string n, float s,string et):name(n),salary(s),EmployeeType(et)
{

}
void virtual display()
{
cout<<"name="<<name<<" salary="<<salary<<endl;
}
void virtual hike(float percentage)=0;//abstract method

static void hike(Employee **ePtrArry,int size,float percentage)


{
for(int i=0; i<size; i++)
ePtrArry[i]->hike(percentage);//run time polymorphism
}
static void display(Employee **ePtrArry,int size)
{
for(int i=0; i<size; i++)
ePtrArry[i]->display();//run time polymorphism

};

class NormalEmployee: public Employee


{public:
NormalEmployee(string n, float s):Employee(n,s,"normal")
{

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
void hike(float percentage)
{
if(percentage<20)
{
salary+=(salary*percentage/100.0);
}
else
cout<<"salary cannot be hiked since percentage is 20% and
above"<<endl;

void display()
{
cout<<EmployeeType<<"- ";
Employee::display();
}

};

class Manager: public Employee


{public:
int numberOfStocks ;
Manager(int ns,string n, float
s):numberOfStocks(ns),Employee(n,s,"Manager")
{
}

void hike(float percentage)


{
salary+=((salary*percentage/100) + (numberOfStocks*10));
}

void display()
{
cout<<EmployeeType<<"- "<<"number of stocks="<<numberOfStocks<<" ";
Employee::display();
}

static void display(Manager *mArry,int size)


{
for(int i=0; i<size; i++)
mArry[i].display();

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
}

};

int main()
{
Employee *mixPtrArry[4]= { new NormalEmployee("aaa",55000),
new Manager(100,"mbb",150000),
new NormalEmployee("ccc",60000),
new Manager(150,"mdd",200000) };
cout<<"Employees details before salary hike**********************"<<endl;
Employee::display(mixPtrArry,4);

cout<<endl<<"hike salaries and display**********************************"<<endl;

Employee::hike(mixPtrArry,4,10);
Employee::display(mixPtrArry,4);

return 1;
}

/*
Output:
Employees details before salary hike**********************
normal- name=aaa salary=55000
Manager- number of stocks=100 name=mbb salary=150000
normal- name=ccc salary=60000
Manager- number of stocks=150 name=mdd salary=200000

hike salaries and display**********************************


normal- name=aaa salary=60500
Manager- number of stocks=100 name=mbb salary=166000
normal- name=ccc salary=66000
Manager- number of stocks=150 name=mdd salary=221500

*/

3_4 /*An online shopping provides sports item to be purchased by its customers. The
items are track suite, sports digital wear, sports bag. Customer can select and
purchase any items. Write a program for above scenario. i. Customer cannot place
multiple orders for same item. ii. Customer can only purchase upto 2 items
*/
#include<iostream>
using namespace std;
class SportItem
{
public:
string name;

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
float price;
SportItem(){}
SportItem(string n,float p):name(n),price(p){}
virtual void print()=0;
};
class customer
{
public:
string name;
int id;
static int c;
SportItem *p[2];

customer(){}
customer(string n,int i)
{
name=n;
id=i;

}
void purchase(SportItem *x)
{

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


{
if(p[i]->name==x->name)
{
cout<<"same item cannot be purchased more than once\n";
return;
}
}

p[c]=x;

//p[count]->print();
c++;

cout<<"item purchased successfully\n";

}
void display()
{
for(int i=0;i<c;i++)
{
p[i]->print();
}
}
};

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
int customer::c=0;
class suite:public SportItem
{
public:
string color;
int sz;
suite(){}
suite(string n,float p,string cl,int s ):SportItem(n,p){
color=cl;
sz=s;
}
void print()
{
cout<<"Name:"<<name<<" price:"<<price<<" color"<<color<<" size"<<
sz<<endl;

}
};
class DigitalWear:public SportItem
{
public:
string BrandName;
int sz;
DigitalWear(){}
DigitalWear(string n,float p,string b,int s ):SportItem(n,p){
BrandName=b;
sz=s;
}
void print()
{
cout<<"Hello\n";
cout<<"Name:"<<name<<" price:"<<price<<"
BrandName"<<BrandName<<" size"<< sz<<endl;

}
};
int main()
{
suite i1("teaShirt",500,"blue",10);
DigitalWear i2("Watch",5000,"Titan",20);
i2.print();
customer c("abc",1);
c.purchase(&i1);
c.purchase(&i2);
c.display();

return 0;
}

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
Solution: Structure Enquiry

4_1

/*
code contributed by a student, c div

Consider a Customer(customerId, customerName, phoneNum, billAmount ) and


the shop classifies customer as regular customer and privileged customer. The
shop offers discount of 5% on every purchase by a regular customer and it issues
a membership card to a privileged customer and offer will be always better than
regular customer. The shop prepares a list of customers (regular and privileged
randomly) visited shop and view the bill amount of individual customer and total
bill amount of all the customers. Display count of regular customers and
privileged customers. Identify exceptions and manage.

*/

#include <iostream>
using namespace std;

class Customer
{
public:
int customerId;
string customerName;
long long int phoneNum;

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
float billAmount;
static int id;
Customer()
{
billAmount=0;
customerId=-1;
}
void getDetails()
{
cout<<"Enter Name"<<endl;
cin>>customerName;
cout<<"Enter phone Number"<<endl;
cin>>phoneNum;
cout<<"Enter Bill Amount"<<endl;
cin>>billAmount;
customerId=id++;
}
virtual void printDetails()
{
cout<<"ID:"<<customerId<<endl;
cout<<"Name:"<<customerName<<endl;
cout<<"PhoneNo:"<<phoneNum<<endl;
}
virtual float generateBill()=0;
};

int Customer::id=0;

class RegularCustomer:public Customer


{
public:
static int cnt;
RegularCustomer()
{
++cnt;
}
float generateBill()
{
return billAmount-((0.05)*billAmount);
}
};

int RegularCustomer::cnt=0;

class PrivilegedCustomer:public Customer


{
public:
static int cnt;
int memCardNo;

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
PrivilegedCustomer()
{
++cnt;
memCardNo=customerId+cnt+10;
}
float generateBill()
{
return billAmount-((0.1)*billAmount);
}
void printDetails()
{
cout<<"---PRIVILEGED CUSTOMER---"<<endl;
Customer::printDetails();
cout<<"Mem Card No:"<<memCardNo<<endl;
}

};

int PrivilegedCustomer::cnt=0;

class Shop
{
public:
class StackOverflow
{

};
Customer *ptr[10];
static int pos;
~Shop()
{
cout<<"Deleting base pointer stack\n";
delete[] ptr;
}
void prepareList()
{
int x;
cout<<"Enter number of customers"<<endl;
try
{
cin>>x;
if(pos+x>10)
throw StackOverflow();
else
{
x=pos+x;
for(int i=pos;i<x;i++)
{
int y;

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
cout<<"Enter 1 for regular 2 for privileged"<<endl;
cin>>y;
if(y==1)
{
ptr[i] = new RegularCustomer;
ptr[i]->getDetails();
pos++;
}
else
{
ptr[i] = new PrivilegedCustomer;
ptr[i]->getDetails();
pos++;
}
}
}
}
catch(StackOverflow e)
{
cout<<"Customer Stack Overflow"<<endl;
}
}
void viewBill(int id)
{
int flag=0;
for(int i=0;i<pos;i++)
{
if(ptr[i]->customerId==id)
{
flag=1;
ptr[i]->printDetails();
cout<<"Bill Amount "<<ptr[i]->generateBill()<<endl;
break;
}
}
if(flag==0)
{
cout<<"Customer Id not found in list"<<endl;

}
}
void viewBill()
{
float total=0,distotal=0;
cout<<"Bill Amount\tAfter Discount"<<endl;
for(int i=0;i<pos;i++)
{
cout<<ptr[i]->billAmount<<"\t\t"<<ptr[i]->generateBill()<<endl;
total+=ptr[i]->billAmount;

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
distotal+=ptr[i]->generateBill();
}
cout<<"Total Billed Amount:"<<total<<"\tDiscount Bill:"<<distotal<<endl;
}
void displayCount()
{
cout<<"Total Regular Customers:"<<RegularCustomer::cnt<<endl;
cout<<"Total Privileged Customers:"<<PrivilegedCustomer::cnt<<endl;
}
};

int Shop::pos=0;

int main()
{
Shop s1;
int flag=1;
while(flag)
{
int c,id;
cout<<"Enter\n 1:Generate List\n 2:View Bill (id)\n 3:View Total Bill\n
4:Display Count\n 5:Exit\n";
cin>>c;
switch(c)
{
case 1:s1.prepareList();
break;
case 2:cout<<"Enter id to be searched\n";
cin>>id;
s1.viewBill(id);
break;
case 3:s1.viewBill();
break;
case 4:s1.displayCount();
break;
case 5:flag=0;
break;
default:cout<<"Enter valid input\n";
}
}
return 0;
}

4_2

4_3 /**
Consider a book shop. The shop contains a number of items like books, DVDs,

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
Stationaries which are sold every day.
Shopkeeper maintains the total number of each type of items sold, all items sold
and the total amount generated from the sale.
Shop keeper also maintains information about regular customers and items that
are purchased by them.
Shopkeeper provides discounts based on the number of items being purchased
by the customer.
Create appropriate classes with constructor, static and non-static members,
objects and test the programs to demonstrate above capabilities.

Date:23-03-2019
Author: Mahesh S Patil
[email protected]
*/

#include<iostream>
#include<string>
using namespace std;
#define MAXSIZE 100

class ShopItem
{
protected:
float soldPrice=0;
bool availability=true;
int id;
public:

virtual float getPrice(int discount)=0;


virtual void display()=0;
virtual string getType()=0;
bool getAvailability()
{
return availability;
}
void markAsSoldout()
{
availability=false;
}
bool matchItemId(int id)
{
return this->id==id?true:false;
}
float getSoldPrice()
{
return soldPrice;
}

};

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
class Book:public ShopItem
{
private:
string title;
int numberOfPages;
static float perPageValue;
static int counter;
static string type;
public:
Book(string title, int pages):title(title), numberOfPages(pages)
{
id=++counter;

}
float getPrice(int discount)
{
float price=numberOfPages*perPageValue;
soldPrice=price *(100.0-discount)/100.0;
return price;
}
void display()
{
cout<<"book title="<<title<<" id="<<id<<" sold price=Rs"<<soldPrice<<endl;
}
string getType()
{
return type;
}

};
string Book::type="book";
float Book::perPageValue=0.4;
int Book::counter=0;

class Stationary:public ShopItem


{
private:
string stationaryItem;
static int counter;
static string type;
public:
Stationary(string s):stationaryItem(s)
{
id=++counter;
}
float getPrice(int discount)
{

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
//no discount for stationary
if(stationaryItem=="sheetsBundle")
soldPrice=5;
else if(stationaryItem=="plasticBox")
soldPrice=30;
else
soldPrice=0;
return soldPrice;
}
void display()
{
cout<<"Stationary Item="<<stationaryItem<<" id="<<id<<" sold
price=Rs"<<soldPrice<<endl;
}
string getType()
{
return type;
}
};
string Stationary::type="Stationary";
int Stationary::counter=0;

class DVD:public ShopItem


{
private:
string subject;
int numberOfLessons;
static float perLessonValue;
static int counter;
static string type;
public:
DVD(string subject, int n):subject(subject),numberOfLessons(n)
{
id=++counter;
}
float getPrice(int discount)
{
float price=numberOfLessons*perLessonValue;
soldPrice=price *(100.0-discount)/100.0;
return price;
}
void display()
{
cout<<"DVD subject="<<subject<<" id="<<id<<" sold
price=Rs"<<soldPrice<<endl;
}
string getType()
{

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
return type;
}

};
string DVD::type="dvd";
float DVD::perLessonValue=50;
int DVD::counter=0;

class RegularCustomer
{
private:
string name;
long mobNum;
ShopItem *purchasedItems[MAXSIZE];
int purchaseCount=0;
public:

RegularCustomer(string name, long mobNum):name(name),


mobNum(mobNum)
{
}
void display()
{
cout<<"customer name="<<name<<" mob number="<<mobNum<<endl;
for(int i=0;i<purchaseCount;i++)
{
cout<<" purchased "; purchasedItems[i]->display();
}
}
bool matchMobileNumber(long num)
{
return num==mobNum?true:false;
}
void addPurchasedItem(ShopItem *t)
{
if(purchaseCount<MAXSIZE)
{
purchasedItems[purchaseCount]=t;
purchaseCount++;
}
}
int getPurchaseCount()
{
return purchaseCount;
}

};

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
class Shop
{
private:
string owner;
ShopItem *items[MAXSIZE];
int itemCount=0;
RegularCustomer *regularCustomers[MAXSIZE];
int regularCustomerCount=0;
public:
Shop(string owner): owner(owner)
{
}
void addItem(ShopItem *t)
{
if(itemCount<MAXSIZE)
{
items[itemCount]=t;
itemCount++;
}
}
void addRegularCustomer(RegularCustomer *r)
{
if(regularCustomerCount<MAXSIZE)
{
regularCustomers[regularCustomerCount]=r;
regularCustomerCount++;
}
}
void displayAllItems()
{
cout<<"displaying all items"<<endl;
for(int i=0;i<itemCount;i++)
{
cout<<i+1<<") ";
items[i]->display();
}
}
void displayAllRegularCustomer()
{
cout<<"displaying all regular customer"<<endl;
for(int i=0;i<regularCustomerCount;i++)
{
cout<<i+1<<") ";
regularCustomers[i]->display();
}

void sellAnItem(int itemId,string itemChoice, long customerMobile)

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
{
int itemFlag=-1, regularCustomerFlag=-1,discount=0;
//search if customer is regular based on mobile number
for(int i=0;i<regularCustomerCount;i++)
if( regularCustomers[i]->matchMobileNumber(customerMobile) )
{
regularCustomerFlag=i;
discount=10; break;
}
//search if item with given id is available
for(int i=0;i<itemCount;i++)
if(items[i]->matchItemId( itemId) && items[i]->getAvailability() &&
items[i]->getType()==itemChoice)
{
itemFlag=i; break;
}
//flag indicates if item found and not yet sold
if(itemFlag!=-1)
{
//check if it regular customer to whom item is sold
if(regularCustomerFlag!=-1)
{
if(regularCustomers[regularCustomerFlag]->getPurchaseCount()<2)
discount=10;
else
discount=15;

regularCustomers[regularCustomerFlag]->addPurchasedItem(items[itemFlag]);
}
items[itemFlag]->getPrice(discount);//this will calculate soldprice
items[itemFlag]->markAsSoldout();
cout<<"sold item with id="<<itemId<<" to customer with mob
num="<<customerMobile<<" discount"<<discount<<endl;
cout<<"sold item detail:"; items[itemFlag]->display();

}
else
{
cout<<"item with id="<<itemId<<" is either soldout or not available"<<endl;
}

void displaySaleDetails(int itemChoice)


{
float saleAmount=0;
cout<<"--displaying details of sold ";

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
if(itemChoice==1)
cout<<"books"<<endl;
else if(itemChoice==2)
cout<<"Stationary"<<endl;
else if(itemChoice==3)
cout<<"DVD"<<endl;
else
cout<<"all items"<<endl;
for(int i=0;i<itemCount;i++)
{
if(! items[i]->getAvailability())//getAvailability() returns false,then item is
soldout
{

if(itemChoice==1)
{
if(items[i]->getType()=="book")
{
items[i]->display();
saleAmount+= items[i]->getSoldPrice();
}
}
else if(itemChoice==2)
{
if(items[i]->getType()=="Stationary")
{
items[i]->display();
saleAmount+= items[i]->getSoldPrice();
}
}
else if(itemChoice==3)
{
if(items[i]->getType()=="dvd")
{
items[i]->display();
saleAmount+= items[i]->getSoldPrice();
}
}
else
{
items[i]->display();
saleAmount+= items[i]->getSoldPrice();
}

}
}
cout<<"****sale amount="<<saleAmount<<endl;
}

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
};

int main()
{
Shop *vijaya=new Shop("vijay");
vijaya->addItem(new Book("b1",300));
vijaya->addItem(new DVD("cpp",8));
vijaya->addItem(new Book("b2",300));
vijaya->addItem(new DVD("ML",6));
vijaya->addItem(new Stationary("sheetsBundle"));
vijaya->addItem(new Stationary("plasticBox"));
vijaya->addItem(new Book("b3",300));
vijaya->addItem(new Book("b4",300));
vijaya->addItem(new Book("b5",400));

vijaya->addRegularCustomer(new RegularCustomer("aaa",99990L));
vijaya->addRegularCustomer(new RegularCustomer("bbb",99991L));
vijaya->addRegularCustomer(new RegularCustomer("aaa",99993L));

cout<<"---Display all items before sale--"<<endl;


vijaya->displayAllItems();

cout<<endl<<"---Display all regular customers before sale--"<<endl;


vijaya->displayAllRegularCustomer();

cout<<endl<<"---selling some items now--"<<endl;


vijaya->sellAnItem(3, "book",99991);
vijaya->sellAnItem(3,"book", 99994);
vijaya->sellAnItem(1,"dvd", 99991);
vijaya->sellAnItem(2,"dvd", 99992);
vijaya->sellAnItem(2,"Stationary", 99992);
vijaya->sellAnItem(6, "book",99992);
vijaya->sellAnItem(1, "book",99992);
vijaya->sellAnItem(2, "book",99993);
vijaya->sellAnItem(4, "book",99993);
vijaya->sellAnItem(5, "book",99993);

cout<<endl<<"---Display sale details--"<<endl;


vijaya->displaySaleDetails(1);//1 to display only books
vijaya->displaySaleDetails(2);//2 to display only stationary
vijaya->displaySaleDetails(3);//3 to display only DVD
vijaya->displaySaleDetails(0);//any other number to display all item

cout<<endl<<"---after sale customer details--"<<endl;


vijaya->displayAllRegularCustomer();

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
}

/*
Output:
---Display all items before sale--
displaying all items
1) book title=b1 id=1 sold price=Rs0
2) DVD subject=cpp id=1 sold price=Rs0
3) book title=b2 id=2 sold price=Rs0
4) DVD subject=ML id=2 sold price=Rs0
5) Stationary Item=sheetsBundle id=1 sold price=Rs0
6) Stationary Item=plasticBox id=2 sold price=Rs0
7) book title=b3 id=3 sold price=Rs0
8) book title=b4 id=4 sold price=Rs0
9) book title=b5 id=5 sold price=Rs0

---Display all regular customers before sale--


displaying all regular customer
1) customer name=aaa mob number=99990
2) customer name=bbb mob number=99991
3) customer name=aaa mob number=99993

---selling some items now--


sold item with id=3 to customer with mob num=99991 discount10
sold item detail:book title=b3 id=3 sold price=Rs108
item with id=3 is either soldout or not available
sold item with id=1 to customer with mob num=99991 discount10
sold item detail:DVD subject=cpp id=1 sold price=Rs360
sold item with id=2 to customer with mob num=99992 discount0
sold item detail:DVD subject=ML id=2 sold price=Rs300
sold item with id=2 to customer with mob num=99992 discount0
sold item detail:Stationary Item=plasticBox id=2 sold price=Rs30
item with id=6 is either soldout or not available
sold item with id=1 to customer with mob num=99992 discount0
sold item detail:book title=b1 id=1 sold price=Rs120
sold item with id=2 to customer with mob num=99993 discount10
sold item detail:book title=b2 id=2 sold price=Rs108
sold item with id=4 to customer with mob num=99993 discount10
sold item detail:book title=b4 id=4 sold price=Rs108
sold item with id=5 to customer with mob num=99993 discount15
sold item detail:book title=b5 id=5 sold price=Rs136

---Display sale details--


--displaying details of sold books
book title=b1 id=1 sold price=Rs120
book title=b2 id=2 sold price=Rs108

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
book title=b3 id=3 sold price=Rs108
book title=b4 id=4 sold price=Rs108
book title=b5 id=5 sold price=Rs136
****sale amount=580
--displaying details of sold Stationary
Stationary Item=plasticBox id=2 sold price=Rs30
****sale amount=30
--displaying details of sold DVD
DVD subject=cpp id=1 sold price=Rs360
DVD subject=ML id=2 sold price=Rs300
****sale amount=660
--displaying details of sold all items
book title=b1 id=1 sold price=Rs120
DVD subject=cpp id=1 sold price=Rs360
book title=b2 id=2 sold price=Rs108
DVD subject=ML id=2 sold price=Rs300
Stationary Item=plasticBox id=2 sold price=Rs30
book title=b3 id=3 sold price=Rs108
book title=b4 id=4 sold price=Rs108
book title=b5 id=5 sold price=Rs136
****sale amount=1270

---after sale customer details--


displaying all regular customer
1) customer name=aaa mob number=99990
2) customer name=bbb mob number=99991
purchased book title=b3 id=3 sold price=Rs108
purchased DVD subject=cpp id=1 sold price=Rs360
3) customer name=aaa mob number=99993
purchased book title=b2 id=2 sold price=Rs108
purchased book title=b4 id=4 sold price=Rs108
purchased book title=b5 id=5 sold price=Rs136

*/

4_4 /**
Consider online shopping website. Here items available for shopping are
electronics
gadgets and books. The website lists all items available for sale. It also maintains
the total stock for each type of item and always ensures certain number these
stocks
are available at the beginning of the day. i.e it generates the order for stocks at
the end of the day based on sale happened for that day. Write a program to list
the
items in each category. Then generate the list of stocks to be ordered for the
next day.

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
Date:11-05-2020
Author: Mahesh S Patil
[email protected]
*/

#include<iostream>
using namespace std;
class Item
{
public:
int ItemId;
int stock;
int maxStock;
double price;
string itemName;

Item(int ItemId, int stock, double price, string itemName): ItemId(ItemId),


stock(stock), price(price), itemName(itemName),maxStock(100)
{

bool buy(int orderQuantity )


{
cout<<itemName<< " stock="<<stock<<" ordered
quantity="<<orderQuantity<<endl;
if( orderQuantity < stock)
{
cout<< " Your order for "<<itemName<<" is placed with quantity= "<<
orderQuantity<<endl;
stock=stock-orderQuantity;
return true;
}
else
cout<<" out of stock: "<< itemName<<", couldnt place your order"<<endl;

cout<<endl;
return false;

}
int generateStockOrder()
{
return maxStock - stock;
}

virtual void display()


{
cout<<"itemName: "<<itemName<<" price="<<price;

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
}

};

class ElectronicGadget: public Item


{
public:
string companyName;

ElectronicGadget(int ItemId, int stock, double price, string itemName, string


companyName):Item(ItemId, stock, price, itemName),
companyName(companyName)
{

void display()
{
Item::display();
cout<<" company Name- "<<companyName<<endl;
}
};

class Book: public Item


{
public:
string author;

Book(int ItemId, int stock, double price, string itemName, string


author):Item(ItemId, stock, price, itemName), author(author)
{

void display()
{
Item::display();
cout<<" Author- "<<author<<endl;
}
};

class Shop
{
public:
Item **itemArr;
int itemTypeCount;
string owner;

Shop(Item **itemArr, int size, string owner):

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
itemArr(itemArr),itemTypeCount(size), owner(owner)
{

void displayItems()
{

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


itemArr[i]->display();
}

void buyFromShop(int itemId, int quantity)


{
bool searchFlag=false;
for(int i=0; i<itemTypeCount; i++)
{
if(itemId == itemArr[i]->ItemId)
{
itemArr[i]->buy(quantity);
searchFlag=true;
}
}
if(searchFlag==false)
cout<<" item not fond"<<endl;
}

void generateAllItemStockOrder()
{
cout<<"Following are the oders for stock from shop Owner: "<<owner<<endl;
for(int i=0; i<itemTypeCount; i++)
{
int shortage= itemArr[i]->generateStockOrder();
cout<< itemArr[i]->itemName<<" Quantity required= "<<shortage<<endl;
}
}

};

int main()
{
Item *itemsArr[]={
new ElectronicGadget(1,50,555,"pendrive","HP"),
new Book(2,70,300,"C++", "abc"),
new Book(3,40,100,"vikas", "xyz"),
new ElectronicGadget(4,100,15555,"mobile","mi")
};

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
Shop myShop(itemsArr,4,"sss");
cout<<"Items in the shop**************"<<endl;
myShop.displayItems();
cout<<endl;
cout<<"Lets do some shopping************"<<endl;
myShop.buyFromShop(1,50);
myShop.buyFromShop(3,70);
myShop.buyFromShop(2,80);
myShop.buyFromShop(4,10);
cout<<endl;
cout<<"End of the day: shop owner places order for stocks************"<<endl;
myShop.generateAllItemStockOrder();

}
/* output
itemName: mobile price=15555 company Name- mi

Lets do some shopping************


pendrive stock=50 ordered quantity=50
out of stock: pendrive, couldnt place your order

vikas stock=40 ordered quantity=70


out of stock: vikas, couldnt place your order

C++ stock=70 ordered quantity=80


out of stock: C++, couldnt place your order

mobile stock=100 ordered quantity=10


Your order for mobile is placed with quantity= 10

End of the day: shop owner places order for stocks************


Following are the oders for stock from shop Owner: sss
pendrive Quantity required= 50
C++ Quantity required= 30
vikas Quantity required= 60
mobile Quantity required= 10
*/

OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20

You might also like