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

OOPS Lab File

Uploaded by

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

OOPS Lab File

Uploaded by

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

PANIPAT INSTITUTE OF ENGINEERING AND TECHNOLOGY

SAMALKHA

COMPUTER SCIENCE AND ENGINEERING DEPARTMENT

Object Oriented Programming Lab

Code – PC –CS –AIDS –207AL

Submitted To:

Ms. Jyoti Dahiya Submitted By:


CSE AIDS DEPARTMENT Keshav Bansal
2823373

B.Tech CSE

(Artificial Intelligence and


Machine Learning)

Affiliated to:

KURUKSHETRA UNIVERSITY KURUKSHETRA, INDIA


PRACTICAL NO: 1

Aim: Write a function called reversit ( ) that reverses a string (an array of
char). Use a for loopthat swaps the first and last characters, then the second
and next to last characters and so on. The string should be passed to reversit
( ) as an argument. Write a program to exercise reversit ( ). The program
should get a string from the user, call reversit ( ), and print out the result.

OBJECTIVE:- The way a group of characters can be stored in a character array.


Character arrays are called strings. A string constant is a one-dimensional array of
characters terminated by a null ( ‘\0’ ). Here we will use a for loop that swaps the
first and last characters, then the second and next to last characters and so on. & a
function which will reverse the input string.

SOURCE CODE:-

#include <iostream>

#include <cstring>

const int MAX = 80;

void reversit(char[]);

int main()

char str[MAX];

std::cout << "\nEnter the string: ";

std::cin.get(str, MAX);

reversit(str);

std::cout << "Reversed string is: " << str << std::endl;

return 0;

}
void reversit(char s[])

int len = strlen(s);

for (int j = 0; j < len / 2; j++)

char temp = s[j];

s[j] = s[len - j - 1];

s[len - j - 1] = temp;

OUTPUT:
PRACTICALNO: 2

AIM:- Write a program that display the menu of Dominos, receives order &
display their bill with tax using Class and objects.

OBJECTIVE:- A Menu of dominos can be made by using Class with data


member and their member Function. Classes define types of data structures and the
functions that operate on those data structures. Instances of these data types are
known as objects and can contain member variables, constants, member functions.
Here the function is defined outside the class. A tax of 12% is added on overall
bill.

SOURCE CODE:-

//Program to print menus of Dominos….


#include<iostream> //Header file…
using namespace std;
class dominos //Class declaration
{
public:
int srno;
int ch;
float price,tax,sum;
void getmenu( );
void display( );

};

void dominos::getmenu( ) //Member Function


{
sum=0;
cout<<"\n\t\t\t*****Dominos Menu*****";
cout<<"\nThe menus for the Veg items with their prices are:\n";
cout<<"\nSr no:-\tMenu items:-\t\t\tPrices:-";
cout<<"\n1.\tCheese & Tomato\t\t\tRs.200/-";
cout<<"\n2.\tDouble Cheese\t\t\tRs.220/-";
cout<<"\n3.\tMexican Green Wave\t\tRs.250/-";
cout<<"\n4.\tCheese & Barbeque Chicken\tRs.400/-";
cout<<"\n5.\tSpicy Chicken\t\t\tRs.320/-\n";

do
{ cout<<"\nEnter the serial no of an item from the menu";
cin>>srno;
switch(srno)
{
case 1: cout<<"\nYou have ordered Cheese & Tomato";
price=200;
cout<<"\nPrice is\tRs."<<price;
sum=sum+price;
break;

case 2: cout<<"\nYou have ordered Double Cheese";


price=220;
cout<<"\nPrice is\tRs."<<price;
sum=sum+price;
break;

case 3: cout<<"\nYou have ordered Mexican Green


Cave";
price=250;
cout<<"\nPrice is\tRs."<<price;
sum=sum+price;
break;

case 4: cout<<"\nYou have ordered Cheese & Barbeque


Chicken";
price=230;
cout<<"\nPrice is\tRs."<<price;
sum=sum+price;
break;
case 5: cout<<"\nYou have ordered Spicy Chicken";
price=320;
cout<<"\nPrice is\tRs."<<price;
sum=sum+price;
break;

default: cout<<"\n Enter the choice between 1-5";


}
cout<<"\nDo you want more items?\nPress 1 for YES & 0 for
NO";
cin>>ch;
} while(ch);

}
void dominos::display( ) //Member Function
{
tax=(float)(sum*12)/100;
cout<<"\n Sub Total:-\tRs."<<sum;
cout<<"\n Tax 12% \tRs."<<tax;
cout<<"\n Total Amount to be paid:-\tRs."<<sum+tax;
cout<<"\n\t\t\t ******Thanks******";

int main( )
{
dominos d; //Declaration of a class member
d.getmenu( ); // Calling of Member Function of a class using
object
d.display( ); // Calling of Member Function of a class using
object
return 0;
cin.get( );
cin.ignore( );
}
Output:
PRACTICAL NO: 3

AIM:- Write a program for Class implementation by passing arguments in


member function.

OBJECTIVE:- The C++ programming language allows programmers to separate


program-specific data types through the use of classes. Classes define types of data
structures and the functions that operate on those data structures. Instances of these
data types are known as objects and can contain member
variables, constants, member functions. An important feature of the C++ class
are member functions. Each datatype can have its own built-in functions (referred
to as methods) that have access to all
(public and private) members of the data type.

SOURCE CODE:-

//Program to create a class implementing passing arguments in member function….


#include<iostream> //Header file…..
using namespace std;
class measure //Class Declaration.
{
private:
int feet;
float inches;
public:
void get( )
{
cout<<"Enter the value of feet & inches:";
cin>>feet>>inches;
}
void display( )
{
cout<<"\nThe value of feet is:"<<feet<<"\t\t\tinches
is:"<<inches;
}
void increament(measure b)
{
feet= feet+ b.feet;
inches= inches+ b.inches;
}
};

int main( )
{
measure x,y;
x.get();
y.get();
x.increament(y);
x.display();
return 0;
cin.get( );
cin.ignore( );

Output:
PRACTICAL NO. 4

AIM:- Imagine a tollbooth with a class called toll Booth. The two data items
are a type unsigned int to hold the total number of cars, and a type double to
hold the total amount of money collected. A constructor initializes both these
to 0. A member function calledpayingCar ( ) increments the car total and adds
0.50 to the cash total. Another function, called nopayCar ( ), increments the
car total but adds nothing to the cash total. Finally, a member function called
displays the two totals.

OBJECTIVE:- The Constructor is defined to be a special member function which


helps in initializing an object while it is declared. The keyword this identifies a
special type of pointer. Every object in C++ has access to its own address through
an important pointer called this pointer. The this pointer is an implicit parameter to
all member functions. Therefore, inside a member function, this may be used to
refer to the invoking object. For exit function the header file used is process.h

SOURCE CODE:-

#include <iostream>

using namespace std;

const char ESC = 27;

const double TOLL = 0.5;

class tollbooth {

private:

unsigned int totalcars;

double totalcash;

public:

tollbooth() {

totalcars = 0;
totalcash = 0;

void payingcar() {

totalcars += 1;

totalcash += TOLL;

void nopaycar() {

totalcars += 1;

void display() {

cout << "\ncars=" << totalcars << ",cash=" << totalcash;

};

int main() {

tollbooth booth1;

char ch;

cout << "\npress 0 for each non-paying car,"

<< "\n\t1 for each paying car,"

<< "\n\tEsc to exit the program.\n";

do {

ch = getchar();

if (ch == '0')

booth1.nopaycar();
if (ch == '1')

booth1.payingcar();

while (ch != ESC);

booth1.display();

return 0;

OUTPUT:
PRACTICAL NO.5

AIM:-Make a class Employee with a name and salary. Make a class Manager
inherit from Employee. Add an instance variable, named department, of type
string. Supply a method to string that prints the manager s name, department
and salary. Make a class Executive inherit from Manager. Supply a method to
String that prints the string Executive followed by the information stored in
the Manager superclass object. Supply a test program that tests these classes
and methods.

OBJECTIVE:- Inheritance means using the Pre-defined Code. This is very Main
Feature of OOPS. With the advantage of Inheritance we can use any code that is
previously created. With the help of inheritance we uses the code that is previously
defined but always Remember, We are only using that code but not changing that
code. There are various types of inheritance & Multilevel Inheritance is one of
them. Multilevel Inheritance is a method where a derived class is derived from
another derived class.

SOURCE CODE:-

#include <iostream>

#include <string>

using namespace std;

class Employee {

protected:

string name;

unsigned int salary;

public:

Employee(const string& n, unsigned int s) : name(n), salary(s) {}

};
class Manager : public Employee {

protected:

string department;

public:

Manager(const string& n, unsigned int s, const string& d) : Employee(n, s),


department(d) {}

void toString() {

cout << "Name: " << name << endl << "Deptt: " << department << endl <<
"Salary: Rs." << salary << endl;

};

class Executive : public Manager {

public:

Executive(const string& n, unsigned int s, const string& d) : Manager(n, s, d) {}

void toString() {

cout << "Title: Executive" << endl;

Manager::toString();

};

int main() {

Manager m("Rajtilak Bhatt", 15000, "Information Technology");

Executive e("Deepak Bhatt", 21000, "Mechanical");

cout << "\n\n**************** CALL BY MANAGER OBJECT


****************\n\n";
m.toString();

cout << "\n\n**************** CALL BY EXECUTIVE OBJECT DERIVED


FROM MANAGER ****************\n\n";

e.toString();

return 0;

OUTPUT:-
PRACTICAL NO.6

AIM:- Create two classes DM and DB which store the value of distances. DM
stores distances in metres and centimeters and DB in feet and inches. Write a
program that can read values for the class objects and add one object of DM
with another object of DB. Use a friend function to carry out the addition
operation. The object that stores the results maybe a DM object or DB object,
depending on the units in which the results are required. The display should
be in the format of feet and inches or metres and cenitmetres depending on
the object on display.

OBJECTIVE:- A friend function is a function that is not a member of a class but


has access to the class's private and protected members. Friend functions are
normal external functions that are given special access privileges. Friends are not
in the class's scope, and they are not called using the member-selection operators
(. and –>) unless they are members of another class. A friend function is declared
by the class that is granting access. The friend declaration can be placed anywhere
in the class declaration. It is not affected by the access control keywords. For
converting centimeters in inches we have 1 cm = 0.393701.

SOURCE CODE:-
#include<iostream>

using namespace std;

class DB; // Forward declaration

class DM {

int metres;

float centimetres;

public:

DM() {

metres = 0;

centimetres = 0.00;
}

DM(int m, float cm) {

metres = m;

centimetres = cm;

int get_m() {

return metres;

float get_cm() {

return centimetres;

void getdata() {

cout << "enter metres: ";

cin >> metres;

cout << "enter centimetres: ";

cin >> centimetres;

void display() {

cout << metres << "m-" << centimetres << "cm";

friend DM add(DM, DB);

};

class DB {
int feet;

float inches;

public:

DB() {

feet = 0;

inches = 0.00;

DB(int f, float i) {

feet = f;

inches = i;

DB(DM dm) {

int m;

float cm, t_cm, t_in;

m = dm.get_m();

cm = dm.get_cm();

t_cm = m * 100 + cm;

t_in = t_cm / 2.54;

feet = int(t_in) / 12;

inches = t_in - feet * 12;

operator DM() {

float in = feet * 12 + inches;


float cm = in * 2.54;

int mtr = int(cm) / 100;

float cmtr = cm - mtr * 100;

return DM(mtr, cmtr);

void getdata() {

cout << "enter feet: ";

cin >> feet;

cout << "enter inches: ";

cin >> inches;

void display() {

cout << feet << "\'-" << inches << "\"";

friend DM add(DM, DB);

};

DM add(DM dm, DB db) {

DM a(db);

int m = dm.metres + a.metres;

float cm = dm.centimetres + a.centimetres;

if (int(cm) >= 100) {

cm -= 100.00;

m++;
}

return DM(m, cm);

int main() {

DB db, db1;

DM dm, dm1;

cout << "enter distance d1 (in metres & centimetres):" << endl;

dm.getdata();

cout << "enter distance d2 (in feet & inches):" << endl;

db.getdata();

dm1 = add(dm, db);

db1 = add(dm, db);

dm.display();

cout << " + ";

db.display();

cout << " = ";

dm1.display();

cout << " = ";

db1.display();

return 0;}
Output:
PRACTICAL NO.7

AIM: Create a class rational which represents a numerical value by two


double values- NUMERATOR & DENOMINATOR. Include the following
public member Functions: constructor with no arguments (default).
constructor with two arguments. void reduce( ) that reduces the rational
number by eliminating the highest common factor between the numerator
and denominator. Overload + operator to add two rational number. Overload
>> operator to enable input through cin. Overload << operator to enable
output through cout. Write a main ( ) to test all the functions in the class.

OBJECTIVE:- The Constructor is defined to be a special member function which


helps in initializing an object while it is declared. The name of the constructor is
same as that of the class name. Depending on how the member data of objects are
provided with values while declaration they are classified. A Default Constructor is
that which does not take any arguments while a Parameterized Constructor is that
which take the arguments for their member data.

SOURCE CODE:-

#include<iostream>

using namespace std;

class Rational{

float num,denom;

public:

Rational()

Rational(float num, float denom)

{
if(denom==0)

cout << "Denominator can't be zero";

exit(1);

this->num = num;

this->denom = denom;

Rational reduce()

Rational temp;

int h = hcf(num, denom);

temp.num = num/h;

temp.denom = denom/h;

return temp;

Rational operator +(Rational r)

Rational ans;

ans.denom = denom*r.denom;

ans.num = num*r.denom+r.num*denom;

return ans;

}
int hcf(int a, int b);

friend istream& operator >>(istream& s, Rational& r);

friend ostream& operator <<(ostream& s, Rational& r);

};

int Rational::hcf(int a, int b)

int r;

r = a%b;

while(r)

a=b;

b=r;

r=a%b;

return b;

istream& operator >>(istream& s,Rational& r)

int a,b;

char c;

s>>a>>c>>b;

if(c!='/')

{
cout<<"use of invalid notation";

exit(0);

if(b==0)

cout<<"denominator can't be zero.";

exit(1);

r.num=a;

r.denom=b;

return s;

ostream& operator <<(ostream& s,Rational& r)

if(r.denom==1)

s<<r.num;

else

if(r.denom==-1)

s<<-r.num;

else

s<<r.num<<'/'<<r.denom;

}
return s;

int main()

Rational r1,r2,r3;

cout<<"enter r1:";

cin>>r1;

cout<<"enter r2:";

cin>>r2;

r3=r1+r2;

cout<<r1<<" + "<<r2<<" = "<<r3<<" = ";

r3 = r3.reduce();

cout<<r3<<endl;

return 0;

Output:
PRACTICAL NO.8

AIM:- Write a program using classes to show different operator overloading


(i.e. Unary, Binary & left & right shift).

OBJECTIVE:- In C++ the overloading principle applies not only to functions, but
to operators too. A programmer can provide his or her own operator to a class by
overloading the built-in operator to perform some specific computation when the
operator is used on objects of that class. On the other hand, operator overloading,
like any advanced C++ feature, makes the language more complicated. There are
many operators which can be overloaded such as unary operator (‘+’, ‘-‘ ,’++’),
Binary operator(‘+’, ‘-‘ ,’/’) ,
Left shift & right shift (<< & >>), etc. A unary operator is one which is defined
over a single operand whereas binary operator is defined over two operand.

SOURCE CODE:-
(a) Program of Overloading Unary operator….

#include<iostream> //Header file…


using namespace std;
class integer
{
private:
int x;
public:
integer (int y=0) //Constructor…..
{
x=y;
}
integer operator-( ) //Unary operator overloading..
{
integer t;
t.x=-x;
return t;
}
void operator++( ) //Unary operator overloading..
{
x++;
}
void display( )
{
cout<<x;
}
};
int main( )
{
integer a,b(5),c(-7);
cout<<"\nb=";
b.display( );
a= -b;
cout<<"\na=";
a.display( );
cout<<"\nc=";
c.display( );
a= -c;
cout<<"\na=";
a.display( );
++c;
cout<<"\nc=";
c.display( );
return 0;
cin.get( );
cin.ignore( );
}

OUTPUT:
(b)Program of Overloading Binary operator….
#include<iostream> //Header file….
using namespace std;
class integer
{
private:
int x;
float y;
public:
integer(int s=0,float t=0.0)
{
x=s;
y=t;
}
integer operator+ (integer &m)
{
integer t;
t.x=x+m.x;
t.y=y+m.y;
return t;
}

void display( )
{
cout<<"\nx="<<x;
cout<<"\ny="<<y<<"\n";
}
};

int main( )
{
integer a(5,7.8),b(3,8.9);
integer c;
cout<<"\nFor a:";
a.display( );
cout<<"\nFor b:";
b.display( );
c=a+b;
cout<<"\nThe sum is:";
c.display( );
return 0;
}

OUTPUT:

(c) Program of Overloading Left & right shift operator….

#include<iostream> //Header file…..


using namespace std;
class date
{
private:
int d,m,y;
public:
friend istream&operator>>(istream &is, date &dt) //Left
shift overloading..
{
is>>dt.d>>dt.m>>dt.y;
return is;
}

friend ostream&operator<<(ostream &os, date &dt) //Right


shift overloading..
{
os<<dt.d<<"-"<<dt.m<<"-"<<dt.y;
return os;
}
};

int main( )
{
date dt;
cout<<"\nEnter your date:";
cin>>dt;
cout<<"\nThe date entered is:";
cout<<dt;
return 0;
cin.get( );
cin.ignore( );
}

OUTPUT:

PRACTICAL NO.9
AIM:- Consider the following class definition
class father {
protected : int age;
public:
father (int x) {age = x;}
virtual void iam ( )
{ cout < < “I AM THE FATHER, my age is : ”<< age<< end1:}
};
Derive the two classes son and daughter from the above class and for each,
define iam ( ) to write
our similar but appropriate messages. You should also define suitable
constructors for these
classes. Now, write a main ( ) that creates objects of the three classes and then
calls iam ( ) for
them. Declare pointer to father. Successively, assign addresses of objects of
the two derived
classes to this pointer and in each case, call iam ( ) through the pointer to
demonstrate
polymorphism in action.

OBJECTIVE:- Here we use the concept of Pointers to Derived Classes i.e.


Suppose A is the base class for
the class B .Any pointer to A type (base class) can be assigned the address of an
object of the class B (Derived class). In addition of an object of its own class i.e. ,
pointers to objects of base class are type compatible with pointers to objects of
derived class. We use a pointer to base type to access the public members of the
base class when it is made to point to an object of the base type, and to access the
public members of the derived class when it is made to point to an object of the
derived type by using the concept
of Virtual Functions.

SOURCE CODE:-

#include <iostream>

using namespace std;

class father {

protected:
unsigned int age;

public:

father() {

age = 60;

father(int x) {

age = x;

virtual void iam() {

cout << "I AM THE FATHER, my age is: " << age << endl;

};

class son : public father {

public:

son() {

age = 30;

son(int x) {

age = x;

void iam() override {

cout << "I AM THE SON, my age is: " << age << endl;

}
};

class daughter : public father {

public:

daughter() {

age = 24;

daughter(int x) {

age = x;

void iam() override {

cout << "I AM THE DAUGHTER, my age is: " << age << endl;

};

int main() {

father f(50), *ptrf;

son s(23);

daughter d(16);

cout << "\n\n******************************CALL BY FATHER


OBJECT*************\

****************\n\n";

f.iam();

cout << "\n\n*******************************CALL BY SON


OBJECT***************\
****************\n\n";

s.iam();

cout << "\n\n*****************************CALL BY DAUGHTER


OBJECT************\

****************\n\n";

d.iam();

ptrf = &s;

cout << "\n\n***************CALL BY POINTER TO FATHER WITH


ADDRESS OF\

SON OBJECT*************\n\n";

ptrf->iam();

cout << "\n\n************CALL BY POINTER TO FATHER WITH


ADDRESS OF DAUGHTER OBJECT***********\n\n";

ptrf = &d;

ptrf->iam();

cout << "\n\


n==========================================================
\================\n";

return 0;

Output:
PRACTICAL NO.10
Aim:- Raising a number n to a power p is the same as multiplying n by itself p
times. Write a function called power ( ) that takes a double value for n and an
int value for p, and returns the result as double value. Use a default argument
of 2 for p, so that if this argument is omitted, the number will be squared.
Write a main ( ) function that gets values from the user to test this function.

OBJECTIVE:- The nth of power 2 can be find out as:

(2*2*2……………..n times)
&
If the argument p=2 is omitted then Square of a given number n can be find
out as:

Square = number * number.

SOURCE CODE:-

#include <iostream>

#include <cmath>

double power(double n, int p = 2);

int main() {

double n, r;

int p;

char c;

std::cout << "Enter the number: ";

std::cin >> n;

do {

std::cout << "Do you want to enter power (y/n)? ";

std::cin >> c;
if (c == 'y') {

std::cout << "Enter the power to be raised: ";

std::cin >> p;

r = power(n, p);

} else if (c == 'n') {

p = 2;

r = power(n);

} else {

std::cout << "Invalid choice. Please enter 'y' or 'n'." << std::endl;

} while (c != 'y' && c != 'n');

std::cout << n << "^" << p << " (" << n << " raised to the power " << p << ") = "
<< r << std::endl;

return 0;

double power(double n, int p) {

double r = 1;

if (p < 0) {

r = 1 / pow(n, -p);

} else {

for (int i = 1; i <= p; i++) {

r *= n;

}
}

return r;

Output:

You might also like