Practice Programs CPP 2020-21
Practice Programs CPP 2020-21
Practice Programs CPP 2020-21
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
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.
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.
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
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.
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
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.
OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
Structure Enquire: Has-Is relationship
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;
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;
}
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);
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();
}*/
1_32
#include <iostream>
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);
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;
}
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;
}
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 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};
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;
OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
void powerBreak()
{
//do nothing
}
};
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);
}
};
OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
void display()
{
cout<<EmployeeType<<"- ";
Employee::display();
}
};
void display()
{
cout<<EmployeeType<<"- "<<"number of stocks="<<numberOfStocks<<"
";
Employee::display();
}
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);
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
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;
}
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;
};
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;
}
};
}
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<<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
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;
}
};
int main()
{
Bvir b;
Avir *aptr=&b;
Bvir *bptr=&b;
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();
Bvir bArr[3];
Avir *aptr2=bArr;
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
};
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();
}
};
void display()
{
cout<<EmployeeType<<"- "<<"number of stocks="<<numberOfStocks<<" ";
Employee::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);
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
*/
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)
{
p[c]=x;
//p[count]->print();
c++;
}
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
*/
#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;
int RegularCustomer::cnt=0;
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:
};
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;
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;
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:
};
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();
}
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;
}
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));
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
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
*/
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;
cout<<endl;
return false;
}
int generateStockOrder()
{
return maxStock - stock;
}
OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
}
};
void display()
{
Item::display();
cout<<" company Name- "<<companyName<<endl;
}
};
void display()
{
Item::display();
cout<<" Author- "<<author<<endl;
}
};
class Shop
{
public:
Item **itemArr;
int itemTypeCount;
string owner;
OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20
itemArr(itemArr),itemTypeCount(size), owner(owner)
{
void displayItems()
{
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
OOP student drive folder link Links OOP 19-20 Practice Programs OOP 19-20