Oop.pdf

  • Uploaded by: akanksha singh
  • 0
  • 0
  • November 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Oop.pdf as PDF for free.

More details

  • Words: 4,032
  • Pages: 38
DELHI TECHNOLOGICAL UNIVERSITY

OBJECT ORIENTED PROGRAMMING LAB

SUBMITTED BY:

Abhishek Shakya 2K17/SE/008

S.NO

TOPIC

SUBMISSION DATE

SIGNATURE

S.NO

TOPIC

SUBMISSION DATE

SIGNATURE

PROGRAM – 1 Objective: Raising a number n to a power p is 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 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 the values from user to test the function.

Description: A default argument is a value provided in function declaration that is automatically assigned by the compiler if caller of the function doesn’t provide a value for the argument with default value.

Code: #include #include <stdio.h> using namespace std;

class power{ public: double pwr(double a,int b = 2){ double ans = 1; for(int I = 1; I <= b; i++) { ans = ans * a; } return ans; } }p;

int main() { cout<<"Enter a & n"<<endl; int a; cin>>a; char ch; ch = getchar(); if(ch=='\n'){ cout<<"default n = 2 :"<<endl;

cout<<"a^n : "<>n; cout<<"a^n : "<
Output:

Learning and Finding: We have learnt to define the default argument for a function.

PROGRAM – 2 Objective: A point on the 2-d can be representated by two numbers : an x co-ordinate and a y coordiante. The sum of two points can be defined as a new point whose x co-ordinate is the sum of x coordinates of both points and same for y. Write a program that uses structure called point to model a point. Define three points, and have user input values of then. Then set the third point equal to the sum of the other two and display the new point.

Description: Structure is a collection of variables of different data types under a single name. It is similar to a class in that, both holds a collection of data of different data types.

Code: #include using namespace std;

struct point { int x; int y; };

int main(){ point a; cout<<"Enter x & y cordinates of point A :"<<endl; cin>>a.x>>a.y;

point b; cout<<"Enter x & y cordinates of point B :"<<endl; cin>>b.x>>b.y;

point c; c.x=a.x+b.x; c.y=a.y+b.y;

cout<<"Enter x & y cordinates of resultant point C :"<<endl; cout<
Output:

Learning and Finding: We have made a program with using the structures, so we’ve learnt that how to build structures in c++.

PROGRAM – 3 Objective: Create a equivalent four function calculator. The program should request the user to enter a number. It should than carry out specified arithmatical operation: adding, mutiplying , division. The program should ask if the user wants to do another calculations in response ‘Y’ ans ‘N’.

Description:

Switch case statements are a substitute for long if statements that compare a variable to several integral values ▪ ▪

The switch statement is a multiway branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression. Switch is a control statement that allows a value to change control of execution.

Code: #include using namespace std;

int main(){ float a,b; char ch; x: cin>>a; cin>>ch;

switch(ch){ case '+' : cin>>b; cout<
case '-': cin rel="nofollow">>b; cout<
case '*':

cin rel="nofollow">>b; cout<
case '/': cin rel="nofollow">>b; cout<
} cout<<"\nDo you want to another calculation...?(y/n)\n"; char choice; cin rel="nofollow">>choice; if(choice=='y'||choice=='Y') goto x; return 0; }

Output:

Learning and Finding: We have learnt to implement the goto statement and the switch statement.

PROGRAM – 4 Objective: A phone number, such as (212) 767-8900, can be thought of as having three parts: the area code (212), the exchange (767) and the number (8900). Write a program that uses a class to store these three parts of a phone number seperately. Call the class phone. Create two class objects of type phone of type phone. Initialize one, and have the user input a number for the other one. Display both the numbers.

Description: Initializer List is used to initialize data members of a class. The list of members to be initialized is indicated with constructor as a comma separated list followed by a colon.

Code: #include #include using namespace std;

class phone{ string areacode; string exchange; string number;

public: phone(string a="212",string e="767",string n="100"):areacode(a),exchange(e),number(n){} void display(){ cout<<"("<<areacode<<")"<<exchange<<"-"<
int main(){ cout<<"default phonenumber\n(y/n)\n"; char ch; cin>>ch; if(ch=='y'||ch=='Y'){ phone p1;

p1.display(); }else{ cout<<"new phone number..\n"; string a,e,n; cout<<"Enter the areacode\n"; cin>>a; cout<<"Enter the exchangecode\n"; cin>>e; cout<<"Enter the number\n"; cin>>n;

phone p2(a,e,n); p2.display();

} return 0; }

Output:

Learning and Finding: This program demonstrates that how to define an initializer list using constructor.

PROGRAM – 5 OBJECTIVE: Create two classes DM and DB which store the value of distances. DM stores distances in meters and centimeters and DB in feets and inches. Write a program that can read values for the classes 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 mey be a DM object or DB object, depending on the units in which results are required.

Description: A friend function of a class is defined outside that class' scope but it has the right to access all private and protected members of the class. Even though the prototypes for friend functions appear in the class definition, friends are not member functions. A friend can be a function, function template, or member function, or a class or class template, in which case the entire class and all of its members are friends. In C++, we can make operators to work for user defined classes. This means C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator overloading.

Code: #include using namespace std;

class DB; class DM{ private: double meters; double centimeters; public: DM(double m=0,double c=0){ meters = m; centimeters = c; } friend DM operator+(DM o1, DB o2); friend DB operator+(DB o1, DM o2); void display(){ cout<<"IN METERS : "<<meters<<endl; cout<<"IN CENTIMETERS : "<
};

class DB{ private: double inches; double feets; public: DB(double i=0,double f=0){ inches = i; feets = f; } friend DM operator+(DM o1, DB o2); friend DB operator+(DB o1, DM o2); void display(){ cout<<"IN INCHES : "<
DM operator+(DM a, DB b){ DM res; res.meters = a.meters + b.inches*0.0254; res.centimeters = a.centimeters + b.feets*30.48; return res; }

DB operator+(DB a, DM b){ DB res; res.inches = a.inches + b.meters*39.3701; res.feets = a.feets + b.centimeters*0.032808398950131; return res; }

int main(){ double m,c,i,f; cout<<"Put distance '1' in meters"<<endl; cin>>m; c=100*m; cout<<"Put another distance '2' in inches"<<endl; cin>>i; f=12*i; DB a(m,c); DM b(i,f); cout<<"distance '1' + '2' in DM' unit :"<<endl; DM r1 = b+a; r1.display(); cout<<endl;

cout<<"distance '1' + '2' in DB' unit :"<<endl; DB r2 = a+b; r2.display();

return 0; }

Output:

Learning and Finding: We’ve learnt the definition and declaration of the friend function and operator overloading using friend function.

PROGRAM - 6 Objective: Create a class rational which represents a numerical value by two double valuesNUMERATOR and DENOMENATOR. Include the following public member functions: • • • • • •

Constructor with no parameters . Constructors with two parameters. Overload + operator to enable addition of two rational numbers. Reduce() function to reduce the rational numbers. Overload >> operator to enable input through in Overload << operator to enable output through in.

Write main() to test all the functions in the class.

Description: In C++, we can make operators to work for user defined classes. This means C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator overloading. For example, we can overload an operator ‘+’ in a class like String so that we can concatenate two strings by just using +. Other example classes where arithmetic operators may be overloaded are Complex Number, Fractional Number, Big Integer, etc.

Code: #include using namespace std;

class rational{ double NUMERATOR; double DENOMINATOR; public: rational(){ NUMERATOR = 1; DENOMINATOR = 1; } rational(double a,double b){ NUMERATOR = a; DENOMINATOR = b; } rational operator+(rational b){

rational res; res.NUMERATOR = (NUMERATOR*b.DENOMINATOR)+(b.NUMERATOR*DENOMINATOR); res.DENOMINATOR = DENOMINATOR*b.DENOMINATOR; return res; } void reduce(){ int g = gcd(NUMERATOR,DENOMINATOR); while(g!=1){ NUMERATOR=NUMERATOR/g; DENOMINATOR=DENOMINATOR/g; g = gcd(NUMERATOR,DENOMINATOR); } } friend ostream & operator << (ostream &out, const rational &c); friend istream & operator >> (istream &in, rational &c); private : int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } }; ostream & operator << (ostream &out, const rational &c) { out<<" ( "<> (istream &in, rational &c) { cout<<"Enter NUMERATOR: "; in>>c.NUMERATOR; cout<<"Enter DENOMINATOR: "; in>>c.DENOMINATOR; return in; } int main(){ rational a;

cout<<"Default rational no. :"; cout<>a; cout<<"a+b : "; rational c = a+b; cout<
Output:

Learning and Finding: We’ve learnt the operator overloading and found that sizeof can’t be overloaded.

. (dot), ::, ?: and

PROGRAM - 7 Objective: Write a program that creates a binary file by reading the data for the students from the terminal. The data of each student consist of roll no., name and marks.

Description: In C++, files are mainly dealt by using three classes fstream, ifstream, ofstream availaible in fstream headerfile. ofstream: Stream class to write files. ifstream: Stream class to read from files. fstream: Stream class to both read and write from/to files. We can open file by 1. passing file name in constructor at the time of object creation 2. using the open method

Code: #include #include #include using namespace std;

int main(){ ofstream fout; fout.open("student.doc",ios::out|ios::binary|ios::app); int roll_no,marks; string name; cout<<"Roll No : "; fout<<"Roll No : "; cin>>roll_no; fout<>name; fout<>marks; fout<<marks<<"\n\n";

fout.close(); }

Output:

Learning and Finding: We’ve learnt the file handling and about different modes of file handling like: ios::app, ,ios::ate, ios::in, ios::out, ios::trunc

PROGRAM – 8 Objective: 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 that prints the manager’s name, department and salary. Make a class Executive inherit from Manager. Supply a method that prints the string “Executive” followed by information stored in Manager class object.

Description: The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object-Oriented Programming.

• •

Sub Class: The class that inherits properties from another class is called Sub class or Derived Class. Super Class: The class whose properties are inherited by sub class is called Base Class or Super class.

Code: #include using namespace std;

class Employee{ public: string name; int salary; };

class Manager : public Employee{ public: string department; void info(){ cout<<"Manager's name : "<
class Executive :public Manager{ public: string a = "Executive "; void info1(){

cout<
int main(){ Manager m; m.name="Abhishek"; m.department="Promotion & Adv."; m.salary=40000; m.info();

cout<<endl;

Executive e; e.name="Aman"; e.department="Social Media"; e.salary=30000; e.info1();

return 0; }

Output:

Finding and Learning: We’ve learnt the implementation of Inheritance and got to know about modes like Public, Private and Protected.

PROGRAM – 9 Objective: Imagine a tollbooth with a class called tollbooth. The two data items are: a toe unsigned int to hold the total number of cars, and a type double to hold the total amount of money collected. A constructor initializesbotoh these to 0. A member function called paying cars() increments the car total and adds 0.50 to the cash total. Another function, called nonpay car(), increments the car total but adds nothing to the cash total. Finally a member function called displays the two totals. Include a program to test thid class. This program should allow the user to push one key to count a nonpaying car. Pushing the ESC key shoulf cause the program to print out the totals cars and the total cash and then exit.

Description: getch() is a nonstandard function and is present in conio.h header file which is mostly used by MS-DOS compilers like Turbo C. It is not part of the C standard library or ISO C, nor is it defined by POSIX . Like above functions, it reads also a single character from keyboard. But it does not use any buffer, so the entered character is immediately returned without waiting for the enter key. conio.h header used in C programming contains functions for console input/output. Some of the most commonly used functions of conio.h are clrscr, getch, getche, kbhit etc. Functions of conio.h can be used to clear screen, change color of text and background, move text, check whether a key is pressed or not and many more. conio.h file is provided by Borland Turbo C compiler and GCC compiler doesn't support it. Beginner C/C++ programmers and some books use this file but it isn't recommended to use it in your software/application.

Code: #include #include using namespace std;

class tollbooth{ public: unsigned int cars; double amount; tollbooth(unsigned int c = 0 , double a = 0){ cars = c; amount = a; } void paying(){ cars++;

amount=amount+.50; } void nonpaying(){ cars++; } void display(){ cout<<"Total no. of cars : "<
int main(){ tollbooth t; int key; char key_press; while(true){ key_press=getch(); key = key_press;

if(key==75){// (<-) key t.paying(); cout<<"paying.."<<endl; } else if(key==77){// (- rel="nofollow">) key t.nonpaying(); cout<<"non-paying.."<<endl; } else if(key==27)// (esc) key break; } t.display(); return 0; }

Output:

Learning and Finding: We’ve successfully developed a program that uses two user input keys to operate and ESC key to exit the program.

PROGRAM – 10 Objective: Write a function reverseit() which passes a string as a parameter and reverses the string using the procedure: First swap the first and the last character of the string, then the second and the second last character and so-on. Write a program to exercise reverseit(). The program should get a string from user. Call reverseit() and print out the result. Use input method that allows embedded blanks. Test the program with Napolean’s famous phrase, “Able was I ere saw Ebla”.

Description: Pass-by-reference means to pass the reference of an argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the argument by using its reference passed in. Pass-by-references is more efficient than pass-by-value, because it does not copy the arguments. The formal parameter is an alias for the argument. When the called function read or write the formal parameter, it is actually read or write the argument itself.

Code: #include #include

using namespace std;

void reverseit(string &s){ int l = s.length(); int i=0; while(i
}

int main(){ string s;

getline(cin,s); reverseit(s); cout<<s; }

Output:

Learning and Finding: The difference between pass-by-reference and pass-by-value is that modifications made to arguments passed in by reference in the called function have effect in the calling function, whereas modifications made to arguments passed in by value in the called function cannot affect the calling function. Pass-by-reference is used when we want to modify the argument value in the calling function. Otherwise, pass-by-value is used to pass arguments.

PROGRAM – 11 Objective: Create a class complex with two integer data members as real and imaginary. Design a method to input the complex number, design a function to perform adddition operation between the two complex numbers by operator overloading. Finally display the result.

Description: C++ allows you to specify more than one definition for a function name or an operator in the same scope, which is called function overloading and operator overloading respectively. An overloaded declaration is a declaration that is declared with the same name as a previously declared declaration in the same scope, except that both declarations have different arguments and obviously different definition (implementation). When you call an overloaded function or operator, the compiler determines the most appropriate definition to use, by comparing the argument types you have used to call the function or operator with the parameter types specified in the definitions. The process of selecting the most appropriate overloaded function or operator is called overload resolution.

Code: #include using namespace std;

class complex{ public: int real=0; int img=0;

complex operator+(complex c2){ complex res; res.real = real + c2.real; res.img = img + c2.img; return res; }

void display(){ cout<
int main(){

complex c1; cout<<"Real : "; cin>>c1.real; cout<<"Imaginary : "; cin>>c1.img; complex c2; cout<<"Real : "; cin>>c2.real; cout<<"Imaginary : "; cin>>c2.img; complex c3 = c1 + c2; c3.display();

return 0; }

Output:

Learning and Finding: We’ve learnt about operator overloading with and without using friend function.

PROGRAM – 12 Objective: Declare a class “cont” with a integer static data member cnt to store the number of objects active, a constructor function to increment cnt, a destructor function to increment cnt, and a static function showcnt() to display the value of cnt at that instance.

Description: A constructor is a member function of a class which initializes objects of a class. In C++, Constructor is automatically called when object (instance of class) create. It is special member function of the class. A constructor is different from normal functions in following ways: ▪ ▪ ▪ ▪

Constructor has same name as the class itself Constructors don’t have return type A constructor is automatically called when an object is created. If we do not specify a constructor, C++ compiler generates a default constructor for us (expects no parameters and has an empty body).

Destructor is a member function which destructs or deletes an object. Destructors have same name as the class preceded by a tilde (~). Destructors don’t take any argument and don’t return anything

Code: #include using namespace std; static int cnt; class cont{ public: cont(){ cnt++; } ~cont(){ cnt--; } }; static void showcnt(){ cout<<"No. of object/s at this instance is/are : "<
cont *bptr,b; bptr = &b;

showcnt();

cont *cptr,c; cptr = &c;

cont *dptr,d; cptr = &d;

showcnt();

delete dptr; delete cptr;

showcnt();

return 0; }

Output:

Learning and Finding: From this program we have learnt about the working and definition of the constructor and the destructor.

PROGRAM – 13 Objective: Consider the following class definition class father{ protected: int age; public: father(int x=0){ age=x;} virtual void iam() {cout<<"I am the father, my age is : "<
Description: The word polymorphism means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. Real life example of polymorphism, a person at a same time can have different characteristic. Like a man at a same time is a father, a husband, a employee. So a same person possess have different behaviour in different situations. This is called polymorphism. Polymorphism is considered as one of the important features of Object-Oriented Programming. A virtual function a member function which is declared within base class and is re-defined (Overridden) by derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class’s version of the function. ▪ ▪ ▪ ▪

Virtual functions ensure that the correct function is called for an object, regardless of the type of reference (or pointer) used for function call. They are mainly used to achieve Runtime polymorphism Functions are declared with a virtual keyword in base class. The resolving of function call is done at Run-time

Code: #include using namespace std;

class father{ protected: int age;

public: father(int x=0){ age=x; } virtual void iam(){ cout<<"I am the father, my age is : "<
class son :public father{ protected: int age; public: son(int x){ age = x; } void iam(){ cout<<"I am the son, my age is : "<
class daughter:public father{ protected: int age; public: daughter(int x){ age = x; } void iam(){ cout<<"I am the daughter, my age is : "<
int main(){

father *ptr,f(45); son s(20); daughter d(11);

ptr = &f; ptr- rel="nofollow">iam();

ptr=&s; ptr->iam();

ptr = &d; ptr->iam();

return 0; }

Output:

Learning and Finding: Runtime polymorphism is achieved only through a pointer (or reference) of base class type. Also, a base class pointer can point to the objects of base class as well as to the objects of derived class. In above code, base class pointer ‘bptr’ contains the address of object ‘d’ of derived class.

PROGRAM – 14 Objective: Write a program to develop a generic type linked list using templates. Description: Template is simple and yet very powerful tool in C++. The simple idea is to pass data type as a parameter so that we don’t need to write same code for different data types. For example a software company may need sort() for different data types. Rather than writing and maintaining the multiple codes, we can write one sort() and pass data type as a parameter. C++ adds two new keywords to support templates: ‘template’ and ‘typename’. The second keyword can always be replaced by keyword ‘class’.

Code: #include using namespace std;

template class node{ public: T data; node* nxt; };

template class LinkedList{ private: node *head; node *temp; public: LinkedList(){ head=NULL; temp=NULL;

} void add(U a){ if(head==NULL){ head = new node; head->data = a; temp = head; }else{ node *temp1 = new node; temp1->data = a; temp->nxt = temp1; temp=temp->nxt; } } void display(){ node *temp1 = head; while(temp1!=NULL){ cout<data<<" "; temp1 = temp1->nxt; } } };

int main(){ cout<<"Enter LinkedList :"<<endl; LinkedList l1; for(int i = 0; i<8; i++){ char data;

cin>>data; l1.add(data); } cout<<"Enter LinkedList<double> :"<<endl; LinkedList<double> l2; for(int i = 0; i<8; i++){ double data; cin>>data; l2.add(data); } cout<<"LinkedLists are..."<<endl; l1.display(); cout<<endl; l2.display(); return 0; }

Output:

Learning and Finding: We’ve learnt to implement a generic data structure by using the concepts of templates in c++.

PROGRAM – 15 Objective: Write a program in which there is a division of two user input numbers, and the exception in which denominator is zero should be handled separately by using exception handling.

Description:

One of the advantages of C++ over C is Exception Handling. C++ provides following specialized keywords for this purpose. try: represents a block of code that can throw an exception. catch: represents a block of code that is executed when a particular exception is thrown. throw: Used to throw an exception. Also used to list the exceptions that a function throws, but doesn’t handle itself.

Code: #include using namespace std;

int main(){ int a,b; cout<<"Enter A :"<<endl; cin>>a; cout<<"Enter B :"<<endl; cin>>b; cout<<"A/(A-B) = "; try{ int r = a-b; if(r! = 0) cout<
catch(int r){ cout<<"div by zero is not allowed!"; } return 0;

}

Output:

Learning and Finding:

a block will raise an exception, a method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Exception handling is used to catch the expected exception without terminating the whole program.

More Documents from "akanksha singh"

08_chapter 2 (1).pdf
August 2019 21
Akhilesh Kumar.docx
November 2019 14
Oop.pdf
November 2019 14
Report.docx
November 2019 13