pvg’s college of engineering nashik department of computer ... · 3 write a c++ program create a...

88
PVG’s College of Engineering Nashik Department of Computer Engineering LABORATORY MANUAL 2017-2018 OBJECT ORIENTED PROGRAMMING LABORATORY SE-COMPUTER ENGINEERING SEMESTER-I TEACHING SCHEME Lectures: 4 Hrs/Week Practical: 2 Hrs/Week Subject Code: 210245 EXAMINATION SCHEME Theory:50 Marks On-Line:50 Marks Practical:50 Marks Term Work: 25 Marks -: Name of Faculty :- Prof. A.R.Jain Asst. Professor, Department of Computer Engineering,

Upload: others

Post on 24-Mar-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

PVG’s College of Engineering

Nashik

Department of Computer Engineering

LABORATORY MANUAL

2017-2018

OBJECT ORIENTED PROGRAMMINGLABORATORY

SE-COMPUTER ENGINEERING

SEMESTER-I

TEACHING SCHEMELectures: 4 Hrs/WeekPractical: 2 Hrs/Week

Subject Code: 210245

EXAMINATION SCHEME

Theory:50 Marks

On-Line:50 Marks

Practical:50 Marks

Term Work: 25 Marks

-: Name of Faculty :-

Prof. A.R.JainAsst. Professor, Department of Computer Engineering,

Page 2: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

PUNE VIDYARTHI GRIHA’S

COLLEGE OF ENGINEERING, NASHIK. INDEX

Sr.No

Title Page No

Date of Conduction

Date of Submission

Sign

1 Install, Configure 64 bit Linux OperatingSystems, study basic architecture, memorysystem, and learn basic administration.

2 Implement a class Complex whichrepresents the Complex Number datatype. Implement thefollowing operations:1. Constructor (including a defaultconstructor which creates the complexnumber 0+0i).2.2. Overloaded operator+ to add twocomplex numbers.3. Overloaded operator* to multiply twocomplex numbers.4. Overloaded << and >> to print andread Complex Numbers.

3 Write a C++ program create a calculator foran arithmetic operator (+, -, *, /). Theprogram should take two operands fromuser and performs the operation on thosetwo operands depending upon the operatorentered by user. Use a switch statement toselect the operation. Finally, display theresult. Some sample interaction with the programmight look like this: Enter first number, operator, secondnumber: 10 / 3 Answer = 3.333333 Do another (y/n)? y Enter first number, operator, secondnumber: 12 + 100 Answer = 112 Do another (y/n)? n

4 Create a class template to represent ageneric vector. Include following memberfunctions:

To create the vector. To modify the value of a given element To multiply by a scalar value To display the vector in the form

(10,20,30,…)

Page 3: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

PUNE VIDYARTHI GRIHA’S

COLLEGE OF ENGINEERING, NASHIK. INDEX

.

5 Develop an object oriented program in C++to create a database of student informationsystem containing the followinginformation: Name, Roll number, Class,division, Date of Birth, Blood group,Contact address, telephone number, drivinglicence no. etc Construct the database withsuitable member functions for initializingand destroying the data viz constructor,default constructor, Copy constructor,destructor, static member functions, friendclass, this pointer, inline code and dynamicmemory allocation operators-new anddelete.

6 Write C++ Program with base class convertdeclares two variables, val1 and val2, whichhold the initial and converted values,respectively. It also defines the functionsgetinit( ) and getconv( ), which return theinitial value and the converted value. Theseelements of convert are fixed and applicableto all derived classes that will inheritconvert. However, the function that willactually perform the conversion,compute( ), is a pure virtual function thatmust be defined by the classes derived fromconvert. The specific nature of compute( )will be determined by what type ofconversion is taking place.

7 Create employee bio-data using followingclasses i) Personal record ii))Professionalrecord iii) Academic record Assumeappropriate data members and memberfunction to accept required data & print bio-data. Create bio-data using multipleinheritance using C++.

8Crete User defined exception to check thefollowing conditions and throw theexception if the criterion does not meet. a. User has age between 18 and 55 b. User stays has income between Rs.50,000 – Rs. 1,00,000 per month c. User stays in Pune/ Mumbai/ Bangalore /Chennai d. User has 4-wheeler

Accept age, Income, City, Vehicle from theuser and check for the conditions mentionedabove. If any of the condition not met thenthrow the exception.

Page 4: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

PUNE VIDYARTHI GRIHA’S

COLLEGE OF ENGINEERING, NASHIK. INDEX 9 Write a menu driven program that will

create a data file containing the list oftelephone numbers in the following form John 23456 Ahmed 9876 ……….. ……… Use a class object to store each set of data,access the file created and implement thefollowing tasks I. Determine the telephone number ofspecified person II. Determine the name if telephone numberis known III. Update the telephone number, wheneverthere is a change.

10 Write a C++ program that creates an outputfile, writes information to it, closes the fileand open it again as an input file and readthe information from the file.

11Write a function template selection Sort.Write a program that inputs, sorts andoutputs an integer array and a float array.

12 Write C++ program using STL forimplementation of stack & queue using SLL

13 Write C++ program using STL to addbinary numbers (assume one bit as onenumber); use STL stack.

14 Write C++ program using STL for Dqueue(Double ended queue)

15 Mini-projects

`

Page 5: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

COMPULSORY ASSIGNMENTS

Page 6: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Assignment No. 1

Title Install, Configure 64 bit Linux Operating Systems.

Subject Object Oriented Programming

Class S.E. (C.E.)

Roll No.

Date

Signature

Page 7: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Assignment Number 1

Title: Install, Configure 64 bit Linux Operating Systems.

Aim: Install, Configure 64 bit Linux Operating Systems, study basic architecture, memory

system, and learn basic administration.

Prerequisites:

Knowledge of Any Operating System

Objectives:

1.To learn how to Install,Configure 64 bit Linux Operating Systems.

2. study basic architecture, memory system, and basic administration of OS.

Theory :

Architecture:

Page 8: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

At the top is the user space. Below the user space is the kernel space. Here, the Linux kernel

exists.

User Space: This is where the user applications are executed. There is also the GNU C Library

(glibc). This provides the system call interface that connects to the kernel and provides the

mechanism to transition between the user-space application and the kernel.

Kernel Space:Here, the Linux Kernel exists which can be further divided into three levels. At the

top is the system call interface, which implements the basic functions such as readand write.

Below the system call interface is the kernel code, which can be more accurately defined as the

architecture-independent kernel code. This code is common to all of the processor architectures

supported by Linux. Below this is the architecture-dependent code, which forms what is more

commonly called a BSP (Board Support Package). This code serves as the processor and

platform-specific code for the given architecture.

Properties of the Linux Kernel

The kernel is layered into a number of distinct subsystems. Linux can also be considered

monolithic because it lumps all of the basic services into the kernel. This differs from a

microkernel architecture where the kernel provides basic services such as communication, I/O,

and memory and process management, and more specific services are plugged in to the

microkernel layer.

Functions of the Kernel

Now let’s look at some of the functions of the Linux kernel.

System Call Interface

The SCI is a thin layer that provides the means to perform function calls from user space into the

kernel. As discussed previously, this interface can be architecture dependent, even within the same

processor family. You can find the SCI implementation in ./linux/kernel, as well as architecture-

dependent portions in ./linux/arch.

Process Management

Page 9: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

The kernel is in charge of creating and destroying processes and handling their connection to the

outside world (input and output). Communication among different processes (through signals,

pipes, or interprocess communication primitives) is basic to the overall system functionality and is

also handled by the kernel. In addition, the scheduler, which controls how processes share the

CPU, is part of process management.

Memory management

Another important resource that’s managed by the kernel is memory. For efficiency, given the way

that the hardware manages virtual memory, memory is managed in what are called pages (4KB in

size for most architectures). Linux includes the means to manage the available memory, as well as

the hardware mechanisms for physical and virtual mappings.

File Systems

Linux is heavily based on the filesystem concept; almost everything in Linux can be treated as a

file. The kernel builds a structured filesystem on top of unstructured hardware, and the resulting

file abstraction is heavily used throughout the whole system. In addition, Linux supports multiple

filesystem types, that is, different ways of organizing data on the physical medium. For example,

disks may be formatted with the Linux- standard ext3 filesystem, the commonly used FAT

filesystem or several others.

Device control

Almost every system operation eventually maps to a physical device. With the exception of the

processor,memory, and a very few other entities, any and all device control operations are

performed by code that is specific to the device being addressed. That code is called a device

driver. The kernel must have embedded in it a device driver for every peripheral present on a

system, from the hard drive to the keyboard and the tape drive.

Networking

Networking must be managed by the operating system, because most network operations are not

specific to a process: incoming packets are asynchronous events. The packets must be collected,

identified, and dispatched before a process takes care of them. The system is in charge of

delivering data packets across program and network interfaces, and it must control the execution

of programs according to their network activity. Additionally, all the routing and address

resolution issues are implemented within the kernel.

Page 10: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Algorithm:

1. Download the Fedora live CD image file

2. Burn the image file to CD

3. Boot your computer from the CD

4. Fedora Live Desktop

5. Language Selection

6. The Installation Summary Menu

7. Keyboard Configuration

8. Date and time

9. Network Configuration

10. Storage and partitioning

11. Software Selection

12. Begin installation

13. The Configuration Menu and Progress Screen

14. Set the Root Password

15. User Creation

16. Reboot your system

17. Your installation is complete

Conclusion: Hence We studied how to install and configure Linux Operating Systems.

Page 11: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

GROUP A

(5 ASSIGNMENTS)

Page 12: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Assignment No. Group A(2)

Title Complex Number

Subject Object Oriented Programming

Class S.E. (C.E.)

Roll No.

Date

Signature

Page 13: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Assignment No. Group A(2)

Title: Complex Number

Objectives: To understand operator overloading, constructor and data hiding.

Problem Statement:

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

following operations:

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

2. Overloaded operator+ to add two complex numbers.

3. Overloaded operator* to multiply two complex numbers.

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

Outcomes: To understand operator overloading concept.

Software Requirements: ubuntu Operating system, Eclipse and Gedit.

Hardware Requirements: P4 System.

Prerequisite: Object oriented concepts.

2.1 Theory:

A complex number is a number that can be expressed in the form a + bi, where a and b are real

numbers and i is the imaginary unit, that satisfies the equation i2 = −1. In this expression, a is the

real part and b is the imaginary part of the complex number.

Operations on Complex number:

1. Addition of Complex Numbers Addition of two complex numbers a + b i and c + d i is

Page 14: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

defined asfollows.

(a + b i) + (c + d i) = (a + c) + (b + d) i

This is similar to grouping like terms: real parts are added to real parts and imaginary parts are

added to imaginary parts.

2. Subtraction of Complex Numbers

The subtraction of two complex numbers a + b i and c + d i is defined as follows.

(a + b i) - (c + d i) = (a - b) + (b - d) i

3. Mulyiply Complex Numbers

The multiplication of two complex numbers a + b i and c + d i is defined as follows.

(a + b i)(c + d i) = (a c - b d) + (a d + bc) i

However you do not need to memorize the above definition as the multiplication can be carried

out using properties similar to those of the real numbers and the added property i 2 = -1. (see the

examplebelow)

2.2 OOP Features & Concepts used in this practical :

Operator Overloading: You can redefine or overload most of the built-in operators available in

C++. Thus a programmer can use operators with user-defined types as well.

Overloaded operators are functions with special names the keyword operator followed by the

symbol for the operator being defined. Like any other function, an overloaded operator has a

return type and a parameter list.

Box operator+(const Box&);

declares the addition operator that can be used to add two Box objects and returns final Box

object.

Overloadable/Non-overloadableOperators:

Following is the list of operators which can be overloaded:

+ - * / % ^

& | ~ ! , =

< > <= >= ++ --

<< >> == != && ||

+= -= /= %= ^= &=

Page 15: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

|= *= <<= >>= [ ] ( )

-> ->* new new [ ] delete delete [ ]

Operator that are not overloaded are follows

scope operator - ::

sizeof

member selector - .

member pointer selector - *

ternary operator - ?:

Syntax of operator overloading:

For calling function:

resultant = Object operatorsymbol Object;

resultant will vary depending upon operation done and return type of function.

2.3 Conclusions: Complex number operations are implemented with the operator overloading

concept.

Page 16: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Assignment No. Group A(5)

Title Calculator

Subject Object Oriented Programming

Class S.E. (C.E.)

Roll No.

Date

Signature

Page 17: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Assignment No. Group A(5)

Title: Calculator

Objectives: To understand basic object oriented concepts such as constructor, data hiding, class

object, etc

Problem Statement: Write a C++ program create a calculator for an arithmetic

operator (+, -, *, /). The program should take two operands from user and performs

the operation on those two operands depending upon the operator entered by user.

Use a switch statement to select the operation. Finally, display the result. Some

sample interaction with the program might look like this:

Enter first number, operator, second number: 10 / 3

Answer = 3.333333

Do another (y/n)? y

Enter first number, operator, second number: 12 + 100

Answer = 112

Do another (y/n)? n

3.1 Theory:

Constructors

Constructors are special class functions which performs initialization of every object. The

Compiler calls the Constructor whenever an object is created. Constructors initialize values to

object members after storage is allocated to the object.

class A

{

int x;

public:

A(); //Constructor

};

Page 18: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

While defining a contructor you must remeber that the name of constructor will be same as the

name of the class, and contructors never have return type.

Constructors can be defined either inside the class definition or outside class definition using class

name and scope resolution :: operator.

class A

{

int i;

public:

A(); //Constructor declared

};

A::A() // Constructor definition

{

i=1;

}

Types of Constructors

Constructors are of three types :

1. Default Constructor

2. Parameterized Constructor

3. Copy Constructor

Default Constructor

Default constructor is the constructor which doesn't take any argument. It has no parameter.

Syntax : class Cube

{

int side;

public:

Cube()

{

Page 19: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

side=10;

}

};

int main()

{

Cube c;

cout << c.side;

}

Output : 10

In this case, as soon as the object is created the constructor is called which initializes its data

members.

A default constructor is so important for initialization of object members, that even if we do not

define a constructor explicitly, the compiler will provide a default constructor implicitly.

Parameterized Constructor

These are the constructors with parameter. Using this Constructor you can provide different values

to data members of different objects, by passing the appropriate values as argument.

Example :

class Cube

{

int side;

public:

Cube(int x)

{

side=x;

}

};

int main()

{

Cube c1(10);

Cube c2(20);

Page 20: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Cube c3(30);

cout << c1.side;

cout << c2.side;

cout << c3.side;

}

OUTPUT : 10 20 30

By using parameterized construcor in above case, we have initialized 3 objects with user defined

values. We can have any number of parameters in a constructor.

Copy Constructor

These are special type of Constructors which takes an object as argument, and is used to copy

values of data members of one object into other object. We will study copy constructors in detail

later.

Constructor Overloading

Just like other member functions, constructors can also be overloaded. Infact when you have both

default and parameterized constructors defined in your class you are having Overloaded

Constructors, one with no parameter and other with parameter.

You can have any number of Constructors in a class that differ in parameter list.

class Student

{

int rollno;

string name;

public:

Student(int x)

{

rollno=x;

name="None";

}

Student(int x, string str)

{

rollno=x ;

Page 21: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

name=str ;

}

};

int main()

{

Student A(10);

+Student B(11,"Ram");

}

In above case we have defined two constructors with different parameters, hence overloading the

constructors.

One more important thing, if you define any constructor explicitly, then the compiler will

not provide default constructor and you will have to define it yourself.

Destructors

Destructor is a special class function which destroys the object as soon as the scope of object

ends. The destructor is called automatically by the compiler when the object goes out of scope.

The syntax for destructor is same as that for the constructor, the class name is used for the name

of destructor, with a tilde ~ sign as prefix to it.

class A

{

public:

~A();

};

Destructors will never have any arguments.

3.2 OOP Features & Concepts used in this practical : Constructor , Destructors, class and

object, Data encapsulation.

Page 22: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

3.3 Conclusions: Calculator application is implemented using object oriented concepts such as

constructor , Destructors, class and object, Data encapsulation.

Page 23: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Assignment No. Group A(6)Title Student Information

System

Subject Object Oriented Programming

Class S.E. (C.E.)

Roll No.

Date

Signature

Page 24: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Assignment No. Group A(6)

Title: Personal information system using constructor, destructor, static member functions, friend

class, this pointer, inline code and dynamic memory allocation.

Objectives: To learn the concept of constructor, default constructor, copy, destructor, static

member functions, friend class, this pointer, inline code and dynamic memory allocation

operators-new and delete.

Problem Statement: : Develop an object oriented program in C++ to create a database of student

information system containing the following information: Name, Roll number, Class, division,

Date of Birth, Blood group, Contact address, telephone number, driving licence no. etc Construct

the database with suitable member functions for initializing and destroying the data viz

constructor, default constructor, Copy constructor, destructor, static member functions, friend

class, this pointer, inline code and dynamic memory allocation operators-new and delete.

Outcomes:

Software Requirements: 32-bit Open source Linux or its derivative, Open Source C++

Programming tool like G++/GCC.

Hardware Requirements: Pentium IV, 512 RAM.

New Concepts:

6.1 Theory: A special method of the class that will be automatically invoked when an instance of

the class is created is called as constructor. Following are the most useful features of constructor.

1) Constructor is used for Initializing the values to the data members of the Class.

2) Constructor is that whose name is same as name of class.

3) Constructor gets Automatically called when an object of class is created.

4) Constructors never have a Return Type even void.

5) Constructor is of Default, Parameterized and Copy Constructors.

Page 25: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

The various types of Constructor are as follows:-

Constructors can be classified into 3 types

1. Default Constructor

2. Parameterized Constructor

3. Copy Constructor

1. Default Constructor:- Default Constructor is also called as Empty Constructor which has

no arguments and It is Automatically called when we creates the object of class but

Remember name of Constructor is same as name of class and Constructor never declared

with the help of Return Type.

2. Parameterized Constructor: - This is another type constructor which has some

Arguments and same name as class name but it uses some Arguments So For this We have

to create object of Class by passing some Arguments at the time of creating object with the

name of class. When we pass some Arguments to the Constructor then this will

automatically pass the Arguments to the Constructor and the values will retrieve by the

Respective Data Members of the Class.

3. Copy Constructor: - This is also another type of Constructor. In this Constructor we pass

the object of class into the Another Object of Same Class. As name Suggests you Copy,

means Copy the values of one Object into the another Object of Class .This is used for

Copying the values of class object into an another object of class So we call them as Copy

Constructor and For Copying the values We have to pass the name of object whose values

we wants to Copying and When we are using or passing an Object to a Constructor then

we must have to use the & Ampersand or Address Operator.

Destructor: As we know that Constructor is that which is used for Assigning Some Values to data

Members and for Assigning Some Values this May also used Some Memory so that to free up the

Memory which is Allocated by Constructor, destructor is used which gets Automatically Called at

the End of Program and we doesn’t have to Explicitly Call a Destructor and Destructor Cant be

Parameterized or a Copy This can be only one Means Default Destructor which Have no

Arguments. For Declaring a destructor we have to use ~tiled Symbol in front of Destructor.

Static members

Page 26: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

A class can contain static members, either data or functions.

A static member variable has following properties:

It is initialized to zero when the first object of its class is created. No other initialization is

permitted.

Only one copy of that member is created for the entire class and is shared by all the

objects of that class.

It is the visible only within the class but its lifetime is the entire program.

Static data members of a class are also known as "class variables", because there is only one

unique value for all the objects of that same class. Their content is not different from one object

static members have the same properties as global variables but they enjoy class scope. For that

reason, and to avoid them to be declared several times, we can only include the prototype (its

declaration) in the class declaration but not its definition (its initialization). In order to initialize a

static data-member we must include a formal definition outside the class, in the global scope of

this class to another. Because it is a unique variable value for all the objects of the same class, it

can be referred to as a member of any object of that class or even directly by the class name (of

course this is only valid for static members.

A static member function has following properties :

4. A static function can have access to only other static members (fun or var) declared in the

same class

5. A static function can be called using the class name instead of its object name

Class_name :: function_name;

Static member functions are considered to have class scope. In contrast to non static member

functions, these functions have no implicit this argument; therefore, they can use only static data

members, enumerators, or nested types directly. Static member functions can be accessed without

using an object of the corresponding class type.

The following restrictions apply to such static functions:

They cannot access non static class member data using the member-selection operators

(. or –>).

Page 27: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

They cannot be declared as virtual.

They cannot have the same name as a non static function that has the same argument

types.

Ex. Shall we give the example………………………

Friend functions:

In principle, private and protected members of a class cannot be accessed from outside the same

class in which they are declared. However, this rule does not affect friends. Friends are functions

or classes declared as such. If we want to declare an external function as friend of a class, thus

allowing this function to have access to the private and protected members of this class, we do it

by declaring a prototype of this external function within the class, and preceding it with the

keyword friend.

Properties of friend function:

It is not in the scope of the class to which it has been declared as friend.

Since it is not in the scope of the class , it cannot be called using the object of that class

It can be invoked like a normal function w/o the help of any object.

It can be declared in private or in the public part of the class.

Unlike member functions, it cannot access the member names directly and has to use an

object name and dot operator with each member name.

Friend classes

Just as we have the possibility to define a friend function, we can also define a class as friend of

another one, granting that second class access to the protected and private members of the first

one.

Pointers:

A pointer is a derived data type that refers to another data variable by storing the variables

memory address rather than data.

Declaration of pointer variable is in the following form:

Data_type * ptr_var;

Eg. int * ptr;

Page 28: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Here ptr is a pointer variable and points to an integer data type.

We can initialize pointer variable as follows

int p, * ptr ; // declaration

ptr = & a ; // initialization

Pointers to objects:

Consider the following example

item P ; // where item is class & P is object

Similarly, we can define a pointer item_ptr of type item as follows

item *it_ptr ;

Object pointers are useful in creating objects at runtime. We can also

access public members of the class using pointers.

Ex. item X;

item *ptr = &X;

the pointer „ptr „is initialized with address of X.

we can access the member functions and data using pointers as

follows

ptr getdata();

ptr show();

this pointer:

C++ uses a unique keyword called this to represent an object that invokes a member function. this

is a pointer that points to the object for which this function was called. This unique pointer is

automatically passed to a member function when it is called.

Important notes on this pointer:

this pointer stores the address of the class instance, to enable pointer access of the

members to the member functions of the class.

this pointer is not counted for calculating the size of the object.

this pointers are not accessible for static member functions.

Page 29: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

this pointers are not modifiable.

6.2 Algorithm:

1. Start

2. Read personnel information such as Name, Roll number, Class, division, Date of Birth, Blood

group, Contact address, telephone number, driving licence no. etc

3. Print all information from database.

4. Stop

6.3 Input : Personnel information such as Name, Roll number, Class, division, Date of Birth,

Blood group, Contact address, telephone number, driving licence no. Etc

Output :Display personnel information from database.

6.4 Conclusions:

Hence, we have successfully studied concept of constructor, default constructor, copy constructor,

destructor, static member functions, friend class, this pointer, inline code and dynamic memory

allocation operators-new and delete.

Page 30: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Assignment No. Group A(7)

Title

Study of Generic types

using Vector Template.

Subject Object Oriented Programming

Class S.E. (C.E.)

Roll No.

Date

Signature

Page 31: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Assignment No. Group A(7)

Title : Study of Generic types using Vector Template.

Aim: Create a class template to represent a generic vector. Include following member functions:

Prerequisites:

C Programming Language

Objectives:

To learn concept of Templates & STL.

Theory :

C++ templates provide a way to re-use source code. C++ provides two kinds of templates:

1. Class templates

2. Function templates.

Use function templates to write generic functions that can be used with arbitrary types. For

example, one can write searching and sorting routines which can be used with any arbitrary

type.C++ Function templates are those functions which can handle different data types without

separate code for each of them. For a similar operation on several kinds of data types, a

programmer need not write different versions by overloading a function. It is enough if he writes a

C++ template based function. This will take care of all the data types.

Class Templates

A class template definition looks like a regular class definition, except it is prefixed by the

keyword template. Once code is written as a C++ class template, it can support all data

types.Declaration of C++ class template should start with the keyword template. A parameter

should be included inside angular brackets. The parameter inside the angular brackets, can be

Page 32: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

either the keyword class or typename. This is followed by the class body declaration with the

member data and member functions.

template <class T>

class class_name

{

. // class member specification

// with anonymous type T wherever appropriate

};

T is a type parameter and it can be any type. Defining member functions - C++ Class Templates:

If the functions are defined outside the template class body, they should always be defined with

the full template definition. Other conventions of writing the function in C++ class templates are

the same as writing normal c++ functions.

Advantages of C++ Class Templates:

• One C++ Class Template can handle different types of parameters.

• Compiler generates classes for only the used types. If the template is instantiated for int

type, compiler generates only an int version for the c++ template class.

• Templates reduce the effort on coding for different data types to a single set of code.

• Testing and debugging efforts are reduced.

Function templates

There are lot of occasions, where we might need to write the same functions for different

data types. A favorite example can be addition of two variables. The variable can be integer, float

or double. The requirement will be to return the corresponding return type based on the input type.

If we start writing one function for each of the data type, then we will end up with 4 to 5 different

functions, which can be a night mare for maintenance.C++ templates come to our rescue in such

situations. When we use C++ function templates, only one function signature needs to be created.

The C++ compiler will automatically generate the required functions for handling the individual

Page 33: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

data types.

Eg: Add function.

Template <class T>

T Add(T a, T b)

{

return a+b;

}

This c++ function template definition will be enough. Now when the integer version of the

function, the compiler generates an Add function compatible for integer data type and if float is

called it generates float type and so on. Here T is the typename. This is dynamically determined

by the compiler according to the parameter passed. The keyword class means, the parameter can

be of any type. It can even be a class.

STL

Containers and algorithms

Like many class libraries, the STL includes container classes: classes whose purpose is to contain

other objects. The STL includes the classes vector, list, deque, set, multiset, map, multimap,

hash_set, hash_multiset, hash_map, and hash_multimap. Each of these classes is a template, and

can be instantiated to contain any type of object. You can, for example, use a vector<int> in much

the same way as you would use an ordinary C array, except that vector eliminates the chore of

managing dynamic memory allocation by hand.

vector<int> v(3); // Declare a vector of 3 elements.

v[0] = 7;

v[1] = v[0] + 3;

v[2] = v[0] + v[1]; // v[0] == 7, v[1] == 10, v[2] == 17

The STL also includes a large collection of algorithms that manipulate the data stored in

containers. You can reverse the order of elements in a vector, for example, by using the reverse

algorithm.

reverse(v.begin(), v.end()); // v[0] == 17, v[1] == 10, v[2] == 7

Page 34: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

There are two important points to notice about this call to reverse. First, it is a global function,

not a member function. Second, it takes two arguments rather than one: it operates on a range of

elements, rather than on a container. In this particular case the range happens to be the entire

container v.The reason for both of these facts is the same: reverse, like other STL algorithms, is

decoupled from the STL container classes. This means that reverse can be used not only to reverse

elements in vectors, but also to reverse elements in lists, and even elements in C arrays. The

following program is also valid.

double A[6] = { 1.2, 1.3, 1.4, 1.5, 1.6, 1.7 };

reverse(A, A + 6);

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

cout << "A[" << i << "] = " << A[i];

This example uses a range, just like the example of reversing a vector: the first argument to

reverse is a pointer to the beginning of the range, and the second argument points one element

past the end of the range. This range is denoted [A, A + 6); the asymmetrical notation is a

reminder that the two endpoints are different, that the first is the beginning of the range and the

second is one past the end of the range.

Iterators

In the example of reversing a C array, the arguments to reverse are clearly of type double*. What

are the arguments to reverse if you are reversing a vector, though, or a list? That is, what exactly

does reverse declare its arguments to be, and what exactly do v.begin() and v.end() return?

The answer is that the arguments to reverse are iterators, which are a generalization of pointers.

Pointers themselves are iterators, which is why it is possible to reverse the elements of a C array.

Similarly, vector declares the nested types iterator and const_iterator. In the example above, the

type returned by v.begin() and v.end() is vector<int>::iterator. There are also some iterators, such

as istream_iterator and ostream_iterator, that aren't associated with containers at all.

Iterators are the mechanism that makes it possible to decouple algorithms from containers:

algorithms are templates, and are parameterized by the type of iterator, so they are not restricted to

a single type of container. Consider, for example, how to write an algorithm that performs linear

search through a range. This is the STL's find algorithm.

Page 35: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

template <class InputIterator, class T>

InputIterator find(InputIterator first, InputIterator last, const T& value) {

while (first != last && *first != value) ++first;

return first;

}

Find takes three arguments: two iterators that define a range, and a value to search for in that

range. It examines each iterator in the range [first, last), proceeding from the beginning to the end,

and stops either when it finds an iterator that points to value or when it reaches the end of the

range.

First and last are declared to be of type InputIterator, and InputIterator is a template parameter.

That is, there isn't actually any type called InputIterator: when you call find, the compiler

substitutes the actual type of the arguments for the formal type parameters InputIterator and T. If

the first two arguments to find are of type int* and the third is of type int, then it is as if you had

called the following function.

int* find(int* first, int* last, const int& value) {

while (first != last && *first != value) ++first;

return first;

}

Facilities:

Linux Operating Systems, GCC, Eclipse framework, VC++.

Algorithm:

1. Start

2. create vector variable v by declaration

3. check initial size of vector.

4. insert elements using push_back() method

5. insert element in between vector using iterator

6. remove element from vector using Erase() method .

Page 36: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

7. Display all elements of Vector

8. Stop

Input:

Vector v & values for each corresponding Index of that Vector.

Output:

1. Display all elements of vector.

Conclusion:

Hence, we have successfully studied concept of Templates & STL through the study of Vectors.

Page 37: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Assignment No. Group A(11)

TitleVirtual Function(Polymorphism)

Subject Object Oriented Programming

Class S.E. (C.E.)

Roll No.

Date

Signature

Page 38: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Assignment No. Group A(11)

Title: Virtual Function (Polymorphism)

Objectives: To understand concept of pure virtual function , constructor in inheritance.

Problem Statement:

Write C++ Program with base class convert declares two variables, val1 and val2, which hold

the initial and converted values, respectively. It also defines the functions getinit( ) and getconv( ),

which return the initial value and the converted value. These elements of convert are fixed and

applicable to all derived classes that will inherit convert. However, the function that will actually

perform the conversion, compute( ), is a pure virtual function that must be defined by the classes

derived from convert. The specific nature of compute( ) will be determined by what type of

conversion is taking place..

Outcomes: To understand concept of pure virtual function , constructor in inheritance.

Software Requirements: ubuntu Operating system, Eclipse and Gedit.

Hardware Requirements: P4 System.

Prerequisite: Object oriented concepts. .

11.1 Theory:

Polymorphism in C++

The word polymorphism means having many forms. Typically, polymorphism occurs when there

is a hierarchy of classes and they are related by inheritance.

C++ polymorphism means that a call to a member function will cause a different function to be

executed depending on the type of object that invokes the function.

Virtual Function:

A virtual function is a function in a base class that is declared using the keyword virtual.

Page 39: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Defining in a base class a virtual function, with another version in a derived class, signals to the

compiler that we don't want static linkage for this function.

Late Binding

In Late Binding function call is resolved at runtime. Hence, now compiler determines the type of

object at runtime, and then binds the function call. Late Binding is also called Dynamic Binding

or Runtime Binding.

What we do want is the selection of the function to be called at any given point in the program to

be based on the kind of object for which it is called. This sort of operation is referred to as

dynamic linkage, or late binding.

Problem without Virtual Keyword

class Base

{

public:

void show()

{

cout << "Base class";

}

};

class Derived:public Base

{

public:

void show()

{

cout << "Derived Class";

}

}

int main()

{

Base* b; //Base class pointer

Derived d; //Derived class object

b = &d;

Page 40: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

b->show(); //Early Binding Ocuurs

}

Output : Base class

When we use Base class's pointer to hold Derived class's object, base class pointer or reference

will always call the base version of the function

Using Virtual Keyword

We can make base class's methods virtual by using virtual keyword while declaring them. Virtual

keyword will lead to Late Binding of that method.

class Base

{

public:

virtual void show()

{

cout << "Base class";

}

};

class Derived:public Base

{

public:

void show()

{

cout << "Derived Class";

}

}

int main()

{

Base* b; //Base class pointer

Derived d; //Derived class object

b = &d;

b->show(); //Late Binding Ocuurs

}

Page 41: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Output : Derived class

On using Virtual keyword with Base class's function, Late Binding takes place and the derived

version of function will be called, because base class pointer pointes to Derived class object.

Pure Virtual Functions:

It's possible that you'd want to include a virtual function in a base class so that it may be redefined

in a derived class to suit the objects of that class, but that there is no meaningful definition you

could give for the function in the base class.

class Shape

{

protected:

int width, height;

public:

Shape( int a=0, int b=0)

{

width = a;

height = b;

}

// pure virtual function

virtual int area() = 0;

};

The = 0 tells the compiler that the function has no body and above virtual function will be called

pure virtual function.

11.2 OOP Features & Concepts used in this practical :

Polymorphism, late binding, virtual function, pure virtual function,constructor.

11.3 Conclusions:

Implemented statement using pure virtual function thus applying runtime polymorphism.

11.4 Assignment Questions:

1. What is polymorphism?

2. What is pure virtual function?

3. What is late and early binging?

Page 42: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Assignment No. Group A(13)

TitleImplemented employeedatabase, bio-data

Subject Object Oriented Programming

Class S.E. (C.E.)

Roll No.

Date

Signature

Page 43: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Assignment No. Group A(13)

Title: Implemented employee database, bio-data

Objectives: To implement multiple inheritance using C++.

Problem Statement: Create employee biodata using following classes i) Personal record

ii))Professional record iii) Academic record Assume appropriate data members and member

function to accept required data & print biodata. Create biodata using multiple inheritance

using C++.

Outcomes: To understand the inheritance concept and implement it.

Software Requirements: Ubuntu operating system, eclipse and gedit.

Hardware Requirements: P4 computer system.

Prerequisite: Object oriented concepts.

13.1 Theory:

Inherit Definition :

Derive quality and characteristics from parents or ancestors. Like you inherit features of

your parents. Inheritance in Object Oriented Programming can be described as a process of

creating new classes from existing classes. New classes inherit some of the properties and

behavior of the existing classes. An existing class that is "parent" of a new class is called a base

class. New class that inherits properties of the base class is called a derived class.

Inheritance is a technique of code reuse. It also provides possibility to extend existing classes by

creating derived classes.

Inheritance Syntax

The basic syntax of inheritance is:

class DerivedClass : accessSpecifier BaseClass

Page 44: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Public Inheritance: This inheritance mode is used mostly. In this the protected member of Base

class becomes protected members of Derived class and public becomes public.

class DerivedClass : public BaseClass

Accessing Base class members public protected private

From Base class Yes Yes Yes

From object of a Base class Yes No No

From Derived classes Yes (As Public) Yes (As Protected) No

From object of a Derived class Yes No No

From Derived class of Derived Classes Yes (As Public) Yes (As Protected) No

Protected Inheritance: In protected mode, the public and protected members of Base class

becomes protected members of Derived class.

class DerivedClass : protected BaseClass

Accessing Base class members public protected private

From Base class Yes Yes Yes

From object of a Base class Yes No No

From Derived classes Yes (As Protected) Yes (As Protected) No

From object of a Derived class No No No

From Derived class of Derived Classes Yes (As Protected) Yes (As Protected) No

Private Inheritance: In private mode the public and protected members of Base class become

private members of Derived class.

class DerivedClass : private BaseClass

class DerivedClass : BaseClass // By default inheritance is p

Accessing Base class members public protected private

From Base class Yes Yes Yes

From object of a Base class Yes No No

From Derived classes Yes (As Private) Yes (As Private) No

From object of a Derived class No No No

From Derived class of Derived Classes No No No

Types of Inheritance: There are different types of inheritance:

1. Single Inheritance

2. Multiple Inheritance

Page 45: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

3. Multilevel Inheritance

4. Hierarchical Inheritance

5. Hybrid (Virtual) Inheritance

1. Single Inheritance

Single inheritance represents a form of inheritance when there is only one base class and one

derived class. For example, a class describes a Person:

2. Multiple Inheritance

Multiple inheritance represents a kind of inheritance when a derived class inherits properties of

multiple classes. For example, there are three classes A, B and C and derived class is D as shown

below:

3. Multilevel Inheritance

Multilevel inheritance represents a type of inheritance when a Derived class is a base class for

another class. In other words, deriving a class from a derived class is known as multi-level

inheritance. Simple multi-level inheritance is shown in below image where Class A is a parent of

Class B and Class B is a parent of Class C

Page 46: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Hierarchical Inheritance

4. Hierarchical Inheritance

When there is a need to create multiple Derived classes that inherit properties of the same Base

class is known as Hierarchical inheritance

5. Hybrid Inheritance (also known as Virtual Inheritance)

Combination of Multi-level and Hierarchical inheritance will give you Hybrid inheritance.

Page 47: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Diamond Problem

When you have a hybrid inheritance then a Diamond problem may arise. In this problem a

Derived class will have multiple paths to a Base class. This will result in duplicate inherited

members of the Base class. This kind of problem is known as Diamond problem

Virtual Inheritance

We can avoid Diamond problem easily with Virtual Inheritance. Child classes in this case

should inherit Grandparent class by using virtual inheritance:

class Grandparent

{

//content of grandparent class

};

class Child1 :public virtual Grandparent

{

//content of Child1 class

};

class Child2 :public virtual Grandparent

{

//content of Child2 class

};

class grandson :public Child1, public Child2

{

//content of grandson class

};

Now grandson class will have only one copy of data members of the Grandparent class.

Order of Constructor Call

When a default or parameterized constructor of a derived class is called, the default constructor of

a base class is called automatically. As you create an object of a derived class, first the default

constructor of a base class is called after that constructor of a derived class is called.

Page 48: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

13.2 OOP Features & Concepts used in this practical : Inheritance, Class, Objects, data

hiding,etc.

13.3 Conclusions: Implemented employee database, bio-data using multiple inheritance using

C++.

13.4 Assignment Questions

Page 49: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Group B

7 Assignment

Page 50: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Assignment No. Group B(14)

Title Exception Handling

Subject Object Oriented Programming

Class S.E. (C.E.)

Roll No.

Date

Signature

Page 51: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Assignment No. Group B(14)

Title: Exception Handling

Objectives: To understand the concept of Exception handling

Problem Statement:

Crete User defined exception to check the following conditions and throw the exception if the

criterion does not met.

a. User has age between 18 and 55

b. User stays has income between Rs. 50,000 – Rs. 1,00,000 per month

c. User stays in Pune/ Mumbai/ Bangalore / Chennai

d. User has 4-wheeler

Accept age, Income, City, Vehicle from the user and check for the conditions mentioned

above. If any of the condition not met then throw the exception.

Outcomes: To To understand the concept of Exception handling

Software Requirements: ubuntu Operating system, Eclipse and Gedit.

Hardware Requirements: P4 System,512 RAM.

Prerequisite: Object oriented concepts..

14.1 Theory:

One benefit of C++ over C is its exception handling system. An exception is a situation in which a

program has an unexpected circumstance that the section of code containing the problem is not

explicitly designed to handle. In C++, exception handling is useful because it makes it easy to

separate the error handling code from the code written to handle the chores of the program. Doing

so makes reading and writing the code easier. Furthermore, exception handling in C++ propagates

the exceptions up the stack; therefore, if there are several functions called, but only one function

that needs to reliably deal with errors, the method C++ uses to handle exceptions means that it can

easily handle those exceptions without any code in the intermediate functions. One consequence

is that functions don't need to return error codes,freeing their return values for program logic.

Page 52: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

// …..

double divide(double x, double y)

{

if(y==0)

{

throw DivideByZero;

}

return x/y;

}

The function will throw DivideByZero as an exception that can then be caught by an exception-

handling catch statement that catches exceptions of type int. The necessary construction for

catching exceptions is a try catch system. If you wish to have your program check for exceptions,

you must enclose the code that may have exceptions thrown in a try block. For example:

try

{

divide(10, 0);

}

catch(int i)

{

if(i==DivideByZero)

{

cerr<<"Divide by zero error";

}

}

The catch statement catches exceptions that are of the proper type. You can, for example, throw

objects of a class to differentiate between several different exceptions. It is often more useful for

you to create a class that stores information on exceptions as they occur. For example, it would be

more useful if you had a class to handle exceptions.

class DivideByZero

{

Page 53: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

public:

double divisor;

DivideByZero(double x);

};

DivideByZero::DivideByZero(double x) : divisor(x) {}

int divide(int x, int y)

{

if(y==0)

{

throw DivideByZero(x);

}

}

try

{

divide (12, 0);

}

catch (DivideByZero divZero)

{

cerr<<"Attempted to divide "<<divZero.divisor<<" by zero";

}

If you wish to catch more than one possible exception, you can specify separate catch blocks for

each type of exception. It's also possible to have a general exception handler that will respond to

any thrown exception. To use it, simply use catch (...) for the catch statement and print a general

warning of some kind.The handy thing to remember about exception handling is that the errors

can be handled outside of the regular code. This means that it is easier to structure the program

code, and it makes dealing with errors more centralized.

Input:

Class Data members: age, Income, City, IsVehicle,etc Member functions: getdata(),Display() Overloaded Insertion and Extraction operators. Get data, Display data.

Output:

Page 54: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

If exception is caught display error message.

14.2 Conclusions: Hence, we have successfully studied concept of exception handling.

14.3 Assignment Questions:

1. What is difference between exception and Error?

2. Which languages help for exception handling?

3. What will happen if exception in not handeled?

Page 55: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Assignment No. Group B(15)

Title File handing

Subject Object Oriented Programming

Class S.E. (C.E.)

Roll No.

Date

Signature

Page 56: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Assignment No. Group B(15)

Title: File handing

Problem Statement: Write a menu driven program that will create a data file containing the list

of

telephone numbers in the following form

John 23456

Ahmed 9876

……….. ………

Use a class object to store each set of data, access the file created and implement the

following tasks

I. Determine the telephone number of specified person II.

Determine the name if telephone number is known

III. Update the telephone number, whenever there is a change.

Prerequisites: Object Oriented Programming

Objectives: To learn the concept of File handing.

Theory: Stream:

A stream is a sequence of bytes. It acts as source from which the input data can be

obtained or as a destination to which the output data can be sent.

Page 57: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

1. Input Stream

Input Streams are used to hold input from a data producer, such as a keyboard, a

file, or a network. The source stream that provides data to the program is called

the input stream. A program extracts the bytes from the input stream. In most

cases the standard input device is the keyboard. With the cin and “extraction”

operator ( >>) it is possible to read input from the keyboard.

2. Output Stream

Output Streams are used to hold output for a particular data consumer, such as a

monitor, a file, or a printer. The destination stream that receives data from the

program is called the output stream. A program inserts the bytes into an output

stream. By default, the standard output of a program points at the screen. So

with the cout operator and the “insertion” operator (<<) you can print a message

onto the screen.

iostream standard library provides cin and cout methods for reading from standard

input and writing to standard output respectively.

file handling provides three new data types:

Data Type Description

Page 58: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

ofstream This data type represents the output file stream and is used to

create files and to write information to files.

ifstream This data type represents the input file stream and is used to read

information from files.

fstream This data type represents the file stream generally, and has the

capabilities of both ofstream and ifstream which means it can

create files, write information to files, and read information from

files.

To perform file processing in C++, header file

<iostream> and <fstream> must be included in your C++ source file.

Opening a File

A file must be opened before you can read from it or write to it.

Either the ofstream or fstream object may be used to open a file for writing and

ifstream object is used to open a file for reading purpose only.

Following is the standard syntax for open() function which is a member of fstream,

ifstream and ofstream objects.

void open(const char *filename, ios::openmode mode);

Here, the first argument specifies the name and location of the file to be opened and

the second argument of the open() member function defines the mode in which the

file should be opened.

Mode Flag Description

ios::app Append mode. In this All output to that file to be appended to the

end.

ios::ate Open a file for output and move the read/write control to the end

Page 59: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

of the file.

ios::in Open a file for reading.

ios::out Open a file for writing.

ios::trunk If the file already exists, its contents will be truncated before

opening the file.

You can combine two or more of these values by ORing them together.

For example, if you want to open a file in write mode and want to truncate it in case

it already exists, following will be the syntax:

ofstream outfile;

outfile.open("file.dat", ios::out | ios::trunc );

Similar way, you can open a file for reading and

writing purpose as follows: fstream afile;

afile.open("file.dat", ios::out | ios::in );

Closing a File

When a C++ program terminates it automatically closes flushes all the streams,

release all the allocated memory and close all the opened files.

It is always a good practice that a programmer should close all the opened files

before program termination.

Following is the standard syntax for close() function, which is a member of fstream,

Page 60: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

ifstream, and ofstream objects.

void close();

Writing to a File

While doing C++ programming, you write information to a file from your program

using the stream insertion operator (<<) just as you use that operator to output

information to the screen.

The only difference is that you use an ofstream or fstream object instead of the cout

object.

Reading from a File

You read information from a file into your program using the stream extraction

operator (>>) just as you use that operator to input information from the keyboard.

The only difference is that you use an ifstream or fstream object instead of the cin

object.

Example

file . read ((char *)&V , sizeof (V));

file . Write ((char *)&V , sizeof (V));

These function take two arguments. The first is the address of the variable V , and the second

is the length of that variable in bytes . The address of variable must be cast to type char * (i.e

pointer to character type) .

File Pointer

Each file have two associated pointers known as the file pointers. One of them is called

the input pointer (or get pointer) and the other is called the output pointer (or put

pointer). The input pointer is used for reading the contents of a given file location and

the output pointer is used for writing to a given file location.

Functions for Manipulating File Pointers

Page 61: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

When we want to move file pointer to desired position then use these function to

manage the file pointers.

Seekg () = moves get pointer (input) to a specified location

Seekp () = moves put pointer (output) to a specified location

tellg () = gives the current position of the get pointer

tellp () = gives the current position of the put pointer

fout . seekg(0, ios :: beg) = go to start

fout . seekg(0, ios :: cur) = stay at current position

fout . seekg(0, ios :: end) = go to the end of file

fout . seekg(m, ios :: beg) = move to m+1 byte in the file

fout . seekg(m, ios :: cur) = go forward by m bytes from the current position

fout . seekg(-m, ios :: cur) = go backward by m bytes from the current position

fout . seekg(-m, ios :: end) = go backward by m bytes from the end

Facilities:

Linux Operating Systems, G++

Algorithm:

1. Start

2. Create a class

3. Define data members name and number

4.Define accept() to take name and number from user.

4. Define display() to display the record.

5.Define searchnumber() to search the number from exising list

6. .Define searchname() to search the name from exising list.

7.In main() create the object of class and fstream class.

Page 62: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

8.Take a limit from user in n variable.

9.Design menu driven program using switch case, in that take a choice from user.

10.In case 1: Open the file in out mode ,call accept() to take record from user,then

write that record into the file and at the end close that file.

In case 2: Open the file in in mode , read the record from the file ,call display()

function to display the record and at the end close that file.

11. In case 3: Open the file in in mode , read the record from the file ,take a new number from

user for search , call searchnumber() to search the record and display the message

occordingly and at the end close that file.

12. In case 4: Open the file in in mode , read the record from the file ,take a

new name from user for search , call searchname() to search the record and

display the message occordingly and at the end close that file.

13. In case 5:Open the file in out mode ,read the content from the file, take

new name from user to search, read the file line by line and accordingly

increament the value of count by 1,when record found then relocate the out file

pointer to specific location using seekp(), then call accept function to take new

record, then call write() to update that record into the file and at the end close that

file.

14. Stop

Conclusion:

Hence, we have studied concept of File handling.

Questions:

1. What is file handling?

2. What are the different modes of open()?

Page 63: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

3. What is ofstream class?

4. What is ifstream class?

5. What is fstream class?

6. What is Seekp()?

Page 64: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Assignment No. Group B(16)

Title File Handling In C++

Subject Object Oriented Programming

Class S.E. (C.E.)

Roll No.

Date

Signature

Page 65: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Assignment No. Group B(16)

Title: File Handling In C++

Objectives: To understand File Handling in C++ like opening the file,reading and writing the

file,closing the file

Problem Statement:

Implement a program to open, read, write and to close the file in c++. Implement the following

operations:

1. Open a file.

2. Read data from file.

3. Write data into file.

4. Close the file.

Outcomes: To understand The Concept Of File Handling.

Software Requirements: ubuntu Operating system, Eclipse and Gedit.

Hardware Requirements: P4 System.

Prerequisite: Object oriented concepts.

16.1 Theory:

So far, we have been using the iostream standard library, which provides cin and cout methods

for reading from standard input and writing to standard output respectively.

Operations :

Creating a file and output some data

In order to create files we have to learn about File I/O i.e. how to write data into a file and how

to read data from a file. We will start this section with an example of writing data to a file. We

begin as before with the include statement for stdio.h, then define some variables for use in the

example including a rather strange looking new type.

#include <stdio.h>

Page 66: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

#include <stdio.h>

main( )

{

FILE *fp;

char stuff[25];

int index;

fp = fopen("TENLINES.TXT","w"); /* open for writing */

strcpy(stuff,"This is an example line.");

for (index = 1; index <= 10; index++)

fprintf(fp,"%s Line number %d\n", stuff, index);

fclose(fp); /* close the file before ending program */

}

2. Reading from File

When an r is used, the file is opened for reading, a w is used to indicate a file to be used for

writing, and an a indicates that you desire to append additional data to the data already in an

existing file. Most C compilers have other file attributes available; check your Reference Manual

for details. Using the r indicates that the file is assumed to be a text file. Opening a file for

reading requires that the file already exist. If it does not exist, the file pointer will be set to NULL

and can be checked by the program.

#include <stdio.h>

void main()

{

FILE *fopen(), *fp;

int c;

fp = fopen("prog.c","r");

c = getc(fp) ;

while (c!= EOF)

{

putchar(c);

c = getc(fp);

}

fclose(fp);

}

Page 67: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Write In File

When a file is opened for writing, it will be created if it does not already exist and it will be

reset if it does, resulting in the deletion of any data already there. Using the w indicates that the

file is assumed to be a text file.

#include <stdio.h>

int main()

{

FILE *fp;

file = fopen("file.txt","w");

/*Create a file and add text*/

fprintf(fp,"%s","This is just an example :)"); /*writes

data to the file*/

fclose(fp); /*done!*/

return 0;

}

4. Close the File

To close a file you simply use the function fclose with the file pointer in the parentheses. Actually,

in this simple program, it is not necessary to close the file because the system will close all open

files before returning to DOS, but it is good programming practice for you to close all files in

spite of the fact that they will be closed automatically, because that would act as a reminder to you

of what files are open at the end of each program.

fclose(fp);

16.3 Conclusions:

File operation is implemented using object oriented programming language features.

16.4 Assignment Questions:

1) what is file?

2) What is database?

3) What is file descriptor?

Page 68: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Assignment No. Group B(18)

TitleSelection sort usingfunction template.

Subject Object Oriented Programming

Class S.E. (C.E.)

Roll No.

Date

Signature

Page 69: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Assignment No. Group B(18)

Title: Selection sort using function template.

Aim: Implement C++ program for Selection sort using function template

Objectives: To understand the concept of function template.

Theory:

Function templates

Function templates are special functions that can operate with generic types. This allows us to

create a function template whose functionality can be adapted to more than one type or class

without repeating the entire code for each type. In C++ this can be achieved using template

parameters. A template parameter is a special kind of parameter that can be used to pass a type as

argument: just like regular function parameters can be used to pass values to a function, template

parameters allow to pass also types to a function. These function templates can use these

parameters as if they were any other regular type. The format for declaring function templates

with type parameters is:

template<classidentifier>function_declaration;

template<typenameidentifier>function_declaration

For example, to create a template function that returns the greater one of two objects we could

use:

template <class myType>

myType GetMax (myType a, myType b)

{

return (a>b?a:b);

}

Here we have created a template function with myType as its template parameter. This template

parameter represents a type that has not yet been specified, but that can be used in the template

function as if it were a regular type. As you can see, the function template GetMax returns the

greater of two parameters of this still-undefined type.

Page 70: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Here in this program we have written a function for Selection sort and we have added a template

tag before the function so that, the parameter will be of the data type Name. Everything is same

except some variable data types. Take a look at the below program, you‟ll get a clear idea.

In the main function we are passing some predefined values into the Selection function by calling

the function Selection(a,6) where a is the array containing integers and 6 is the size of array. After

passing the values into the function we are displaying the sorted order. You can also rewrite the

main function in a way that the user will enter the data and size of the array.

Selection sort

The algorithm divides the input list into two parts: the sublist of items already sorted, which is

built up from left to right at the front (left) of the list, and the sublist of items remaining to be

sorted that occupy the rest of the list. Initially, the sorted sublist is empty and the unsorted sublist

is the entire input list. The algorithm proceeds by finding the smallest (or largest, depending on

sorting order) element in the unsorted sublist, exchanging (swapping) it with the leftmost unsorted

element (putting it in sorted order), and moving the sublist boundaries one element to the right.

int i,j;

for (j = 0; j < n-1; j++)

{

int iMin = j;

for ( i = j+1; i < n; i++)

{

if (a[i] < a[iMin])

{

iMin = i;

}

}

if(iMin != j)

{

swap(a[j], a[iMin]);

}

}

Page 71: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Selection sort is not difficult to analyze compared to other sorting algorithms since none of the

loops depend on the data in the array. Selecting the lowest element requires scanning all n

elements (this takes n − 1 comparisons) and then swapping it into the first position. Finding the

next lowest element requires scanning the remaining n − 1 elements and so on, for (n − 1) + (n −

2) + ... + 2 + 1 = n(n - 1) / 2 Θ(∈ n2) comparisons. Each of these scans requires one swap for n −

1 elements (the final element is already in place).

Algorithm Selection Sort:

Selection(A, N)

Step 1 − Set MIN to location 0

Step 2 − Search the minimum element in the list

Step 3 − Swap with value at location MIN

Step 4 − Increment MIN to point to next element

Step 5 − Repeat until list is sorted

Algorithm:

1. Start

2. Read the numbers as integers or characters.

3. Sort them according to ascending order.

4. Print values as output.

5. Stop

Input:

Integer values, Float values.

Output:

Sorted order of integers as well as floats.

Conclusion:

Hence, we have successfully implemented Selection sort using function template.

Page 72: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Assignment No. Group B(21)

Title STL using Stack

Subject Object Oriented Programming

Class S.E. (C.E.)

Roll No.

Date

Signature

Page 73: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Assignment No. Group B(21)

Title: STL using Stack

Problem Statement: Implement C++ program using STL to add binary numbers (assume one bitas one number); use STL stack.

Prerequisites: Object Oriented Programming

Objectives: To learn the concept of stack in STL.Theory:

STL

The Standard Library is a fundamental part of the C++ Standard. It provides C++programmers with

a comprehensive set of efficiently implemented tools and facilities that can be used for mosttypes of

applications. The C++ STL (Standard Template Library) is a powerful set of C++ templateclasses to

provides general-purpose templatized classes and functions that implement many popularand

commonly used algorithms and data structures like vectors, lists, queues, and stacks. At thecore of

the C++ Standard Template Library are following three well-structured components

Component Description

Containers Containers are used to manage collections of objects of a

certain kind. There are several different types of containers

like deque, list, vector, map etc.

Algorithms Algorithms act on containers. They provide the means by

which you will perform initialization, sorting, searching, and

transforming of the contents of containers.

Iterators Iterators are used to step through the elements of collections of

Page 74: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

objects. These collections may be containers or subsets of

containers.

Container:

A container is a holder object that stores a collection of other object (its elements).They are

implemented as class templates, which allows a great flexibility in the types supported as

elements.

The container manages the storage space for its elements and provides member functions to

access them, either directly or through iterators (reference objects with similar properties to

pointers).

Many containers have several member functions in common, and share functionalities. The

decision of which type of container to use for a specific need does not generally depend only on

the functionality offered by the container, but also on the efficiency of some of its members

(complexity). This is especially true for sequence containers, which offer different trade-offs in

complexity between inserting/removing elements and accessing them.

Stack, queue and priority_queue are implemented as container adaptors. Container adaptors are

not full container classes, but classes that provide a specific interface relying on an object of one

of the container classes (such as deque or list) to handle the elements. The underlying container is

encapsulated in such a way that its elements are accessed by the members of the container adaptor

independently of the underlying container class used.

Algorithms

Algorithms are independent template functions. They are not members or friend functions. Theyenable the programmer to manipulate the data stored in various containers.

Algorithms carry out operations on containers by dereferencing iterators. Each container has its

functions for performing common operations. An algorithm is nothing but a function template

with arguments of iterator type. Algorithms receive iterators as arguments. The iterator informs

the algorithm regarding the object of the container on which the operation is to be carried out.

In addition, the STL contains approximately 60 standard algorithms. These functions enable quick

operations in complicated and large operations. Including the <algorithm> header file, we can usethese functions. The programmer reuses all these container classes.

Operators Use

Search_n( ) Searches a sequence of a given number of same elements.

Page 75: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

find_if( ) Searches first equivalent of a predicate in a sequence.

Search( ) Searches sub-sequence in other sequence.

find_first_of( ) Searches a value from one sequence in another.

find( ) Searches first presence of a value in a sequence.

find_end( ) Searches last occurrence of a value in a sequence.

adjacent_find( ) Searches contiguous pair of objects that are identical.

mismatch( ) Searches element for which two sequences vary.

count ( ) Calculate presence of a value in a sequence.

count_if( ) Calculate elements that similar a predicate

equal( ) True if two series’ are the identical.

for_each( ) Performs a operation with each elements.

Iterators

Iterators acts as pointers. They are used for accessing contents of container classes. They allowmovement from one element to another element, and this is known as iterating. Each container

type supports one kind of iterator according to the container's necessity. The types are input,

output, forward, bi-directional, and random access.

Iterator Access Way of Action I/O Ability Comments

Mode

Forward Linear Can move forward only Can write and read Storable

Bi-directional Linear Can move Front and back Can write and read Storable

Random Random Can move Front and back Can write and read Storable

Input Linear Can move forward only Can Read only Non-storable

Output Linear Can move forward only Can Write only Non-storable

Page 76: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Container Adapter

In addition to the fundamental container classes, the C++ standard library provides specialpredefined container adapters that meet special needs. These are implemented by using thefundamental containers classes. The predefined container adapters are as followsStack

Is a container that manages its elements by the LIFO (Last-In-Last-Out) policy.

Member Functions

Member DescriptionFunction

empty ( ) Tests if the stack is empty.

pop ( ) Removes the element from the top of the stack.

push ( ) Adds an element to the top of the stack.

size ( ) Returns the number of elements in the stack.

stack ( ) Constructs a stack that is empty or that is a copy of a base container

object.

top ( ) Returns a reference to an element at the top of the stack.

The stack must be nonempty to apply the member function. The top of the stack is the position

occupied by the most recently added element and is the last element at the end of the container.

The top of the stack is the position occupied by the most recently added element and is the lastelement at the end of the container.

//stack, pop(), push()

Conclusion:

Hence, we have studied concept of Stack in STL

Questions:

1. What is STL?

2.What is Container?

3.What is Algorithm?

4.What is Iterator?

Page 77: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Assignment No. Group B(22)

TitleSTL using Stack andQueue

Subject Object Oriented Programming

Class S.E. (C.E.)

Roll No.

Date

Signature

Page 78: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Assignment No. Group B(22)Title: STL using Stack and Queue

Proble Statement:

Objectives:

Theory:

Implement C++ program using STL for implementation of stack & queue.

To learn the concept of stack and queue using STL

STL

The Standard Library is a fundamental part of the C++ Standard. It provides C++ programmers

with a comprehensive set of efficiently implemented tools and facilities that can be used for most

types of applications.

The C++ STL (Standard Template Library) is a powerful set of C++ template classes to provides

general-purpose templatized classes and functions that implement many popular and commonly

used algorithms and data structures like vectors, lists, queues, and stacks.

At the core of the C++ Standard Template Library are following three well-structured

components:

Component Description

Containers Containers are used to manage collections of objects of a certain

kind. There are several different types of containers like deque,

list, vector, map etc.

Algorithms Algorithms act on containers. They provide the means by which

you will perform initialization, sorting, searching, and

transforming of the contents of containers.

Iterators Iterators are used to step through the elements of collections of

Container Adapters:

In addition to the fundamental container classes, the C++ standard library provides special

predefined container adapters that meet special needs. These are implemented by using the

fundamental containers classes. The predefined container adapters are as follows

Page 79: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Container Description

Adapter

Stacks Is a container that manages its elements by the LIFO (Last-In-Last-

Out) policy.

Queue Is a container that manages its elements by the FIFO (First-In-First-

Out) policy. That is, it is an ordinary buffer.

Priority Queues Is a container in which the elements may have different priorities.

The priority queue is, in effect, a buffer in which the next element

is always the element that has the highest priority inside the queue.

If more than one element has the highest priority, the order of these

elements is undefined.

Stack:

Stack is an abstract data type with a bounded(predefined) capacity. It is a simple data structure that

allows adding and removing elements in a particular order. Every time an element is added, it goes on the top of

the stack, the only element that can be removed is the element that was at the top of the stack, just like a pile of

objects.

Member Functions

Page 80: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

empty ( ) Tests if the stack is empty.

pop ( ) Removes the element from the top of the stack.

push ( ) Adds an element to the top of the stack.

size ( ) Returns the number of elements in the stack.

stack ( ) Constructs a stack that is empty or that is a copy of a base container

object.

top ( ) Returns a reference to an element at the top of the stack.

Queue:

Queue is also an abstract data type or a linear data structure, in which the first element is inserted

from one end called REAR(also called tail), and the deletion of exisiting element takes place from

the other end called as FRONT(also called head). This makes queue as FIFO data structure, which

means that element inserted first will also be removed first.

Member Functions:

Member Description

Function

Back ( ) Returns a reference to the last and most recently added element

at the back of the queue.

empty ( ) Tests if the queue is empty.

front ( ) Returns a reference to the first element in the front of the

queue.

pop ( ) Removes an element from the front of the queue.

push ( ) Adds an element to the back of the queue.

queue ( ) Constructs a queue that is empty or that is a copy of a base

container object.

size ( ) Returns the number of elements in the queue.

Page 81: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Facilities:

Linux Operating Systems, G++

Algorithm:

Algorithm for Stack:

1.Start

2.Include the header file <stack>

3.In main() create object of class stack.

4.Use different function of stack to perform different operations on stack.

5.Stop

Algorithm for Queue:

1.Start

2.Include the header file <queue>

3.In main() create object of class queue.

4.Use different function of queue to perform different operations on queue.

5.Stop

Conclusion:

Hence, we have studied concept of Stack and Queue using STL

Questions:

1. What is Stack?

2.What is Queue?

3.Explain different functions of Stack?

4.Explain different functions of Queue?

Page 82: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Assignment No. Group B(23)

Title STL using Deque

Subject Object Oriented Programming

Class S.E. (C.E.)

Roll No.

Date

Signature

Page 83: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Assignment No. Group B(23)

Title: STL using Deque

Problem Statement: Write C++ program using STL for Dqueue (Double ended queue)

Prerequisites: Object Oriented Programming

Objectives: To learn the concept of Deque in STL

Theory:

Double-Ended Queue

A double-ended queue is an abstract data type similar to an simple queue, it allows you to insert

and delete from both sides means items can be added or deleted from the front or rear end.

Operations on Deque:

Mainly the following four basic operations are performed on queue:

insetFront(): Adds an item at the front of Deque.

insertLast(): Adds an item at the rear of Deque.

deleteFront(): Deletes an item from front of Deque.

deleteLast(): Deletes an item from rear of Deque.

In addition to above operations, following operations are also

supported getFront(): Gets the front item from queue. getRear(): Gets

the last item from queue. isEmpty(): Checks whether Deque is empty

or not. isFull(): Checks whether Deque is full or not.

Applications of Deque:

Since Deque supports both stack and queue operations, it can be used as both. The Deque data

structure supports clockwise and anticlockwise rotations in O(1) time which can be useful in certain

applications. Also, the problems where elements need to be removed and or added both ends can be

efficiently solved using Deque. For example see Maximum of all subarrays of size k problem.

Page 84: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Facilities:

Linux Operating Systems, G++

Algorithm:

1. Start

2.Include the header file <deque>

3. In main() create the object of deque

4.Use different functions of deque to perform the operations of deque like insertion of element

from front or rear end,display front element, display real element, display all content of deque etc

5.Stop

Input and Output

1.Insert from rear

2.Insert from front

3.Delete from front

4.Delete from rear

5.Size of deque

6.Display

Enter your choice1

Enter the element1

Do you want to continuey

1.Insert from rear

2.Insert from front

3.Delete from front

4.Delete from rear

5.Size of deque

6.Display

Enter your choice1

Enter the element2

Page 85: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Do you want to continuey

1.Insert from rear

2.Insert from front

3.Delete from front

4.Delete from rear

5.Size of deque

6.Display

Enter your choice2

Enter the element3

Do you want to continuey

1.Insert from rear

2.Insert from front

3.Delete from front

4.Delete from rear

5.Size of deque

6.Display

Enter your choice2

Enter the element4

Do you want to continuey

1.Insert from rear

2.Insert from front

3.Delete from front

4.Delete from rear

5.Size of deque

6.Display

Enter your choice6

Page 86: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Elements in Deque are:

4 3 1 2

Do you want to continuey

1.Insert from rear

2.Insert from front

3.Delete from front

4.Delete from rear

5.Size of deque

6.Display

Enter your choice3

The deleted element is4

Do you want to continuey

1.Insert from rear

2.Insert from front

3.Delete from front

4.Delete from rear

5.Size of deque

6.Display

Enter your choice4

The deleted element is2

Do you want to continuey

1.Insert from rear

2.Insert from front

3.Delete from front

4.Delete from rear

5.Size of deque

6.Display

Enter your choice5

Size of Deque2

Do you want to continuey

Page 87: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

1.Insert from rear

2.Insert from front

3.Delete from front

4.Delete from rear

5.Size of deque

6.Display

Enter your choice6

Elements in Deque are:

3 1

Do you want to continuen

Conclusion:

Hence, we have studied concept of Deque in STL

Questions:

1. What is STL?

2.What is Sequential Container?

3.Explain the concept of deque?

4.Explain the different functions of deque?

Page 88: PVG’s College of Engineering Nashik Department of Computer ... · 3 Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program should take two

Mini Project