OOPS Manual

You might also like

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

LAB MANUAL

Object Oriented Programming

Dr. Akhilesh Das Gupta Institute of Technology & Management,


FC-26, Panduk Shila Marg, Zero Pusta Rd, Shastri Park, Shahdara, New Delhi-110053

(Affiliated to Guru Gobind Singh Indraprastha University, New Delhi)

INDEX OF THE CONTENTS

1
Vision of the Institute ..................................................................................................................... 3
Mission of the Institute ................................................................................................................... 3
Vision of the Department: .............................................................................................................. 4
Mission of the Department: ............................................................................................................ 4
1. Introduction to Object Oriented Programming ........................................................................... 5
Objective ............................................................................................................................... 6
Course outcomes ................................................................................................................... 6
2. LIST OF EXPERIMENTS ......................................................................................................... 7
(as per GGSIPU Syllabus) .............................................................................................................. 7
3. LIST OF EXPERIMENTS ......................................................................................................... 8
(Beyond Curricula) ......................................................................................................................... 8
4. How to Compile & Run a C++ Program .................................................................................... 9
5. FORMAT OF THE LAB RECORD TO BE PREPARED BY THE STUDENTS .................. 10
6. Experiments according to the Lab Syllabus ........................................................................... 11
7. Experiment No 1 ..................................................................................................................... 12
8. Experiment No 2 ..................................................................................................................... 15
9. Experiment No.3 ..................................................................................................................... 17
10. Experiment No.4 ..................................................................................................................... 20
11. Experiment No. 5 .................................................................................................................... 23
12. Experiment No. 6 .................................................................................................................... 32
13. Experiment No. 7 .................................................................................................................... 34
14. Experiment No. 8 .................................................................................................................... 36
15. Experiment No. 9 .................................................................................................................... 38
16. Experiment No. 10 .................................................................................................................. 40
17. Experiment No. 11 .................................................................................................................. 43
18. Experiment No. 12 .................................................................................................................. 45
19. Experiment No. 13 .................................................................................................................. 47
20. Experiment No. 14 .................................................................................................................. 49
21. Experiment No. 15 .................................................................................................................. 51
22. Experiment No. 16 .................................................................................................................. 54
23. Experiment No. 17 .................................................................................................................. 55
24. Experiment No. 18 .................................................................................................................. 59

2
Dr. Akhilesh Das Gupta Institute of Technology & Management

Vision of the Institute


To produce globally competent and socially responsible technocrats and entrepreneurs
who can develop innovative solutions to meet the challenges of 21st century.

Mission of the Institute

1. To produce value-based education through multi-grade teaching methodologies and


modern education facilities.
2. To sustain an active partnership program with industry and other academic institutes
with an aim to promote knowledge and resource sharing.
3. To conduct value-added training programme to enhance employability.
4. To provide conductive environment for development of ethical and socially
responsible technocrats, manager and entrepreneurs.

3
Vision of the Department:

“To emerge as a center of excellence by providing technologically competent


environment in Information Technology.”

Mission of the Department:

 To provide managerial and professional skills among the students through value-
added programs.

 To provide an atmosphere where faculty and students can be engaged in


continuous learning and contribute in the overall growth of the society.

 To provide industry oriented technical environment to help students excel in


diversified fields.

Program Educational Objective:

 PEO1 To produce graduates having strong practical and theoretical knowledge of


computer hardware and software.

 PEO2To produce graduates having strong knowledge of basics of programming


and database management system.

 PEO3To produce graduates who are proficient in coding and problem-solving


skills.

 PEO4To produce graduates having technical as well as non-technical skills like


social behavior,logical reasoning,team management, communication skills.

 PEO5To produce graduates having willingness to learn new things and work as a
part of team for the attainment of individual and organizations

4
1. INTRODUCTION TO OBJECT ORIENTED
PROGRAMMING

Introduction
C++ is a general-purpose programming language that was developed as an enhancement of the
C language to include object-oriented paradigm. It is an imperative and a compiled language.

C++ is a middle-level language rendering it the advantage of programming low-level (drivers,


kernels) and even higher-level applications (games, GUI, desktop apps etc.). The basic syntax
and code structure of both C and C++ are the same.
Some of the features & key-points to note about the programming language are as follows:
 Simple: It is a simple language in the sense that programs can be broken down into logical
units and parts, has a rich library support and a variety of data-types.
 Machine Independent but Platform Dependent: A C++ executable is not platform-
independent (compiled programs on Linux won’t run on Windows), however they are
machine independent.
 Mid-level language: It is a mid-level language as we can do both systems-programming
(drivers, kernels, networking etc.) and build large-scale user applications (Media Players,
Photoshop, Game Engines etc.)
 Rich library support: Has a rich library support (Both standard ~ built-in data structures,
algorithms etc.) as well 3rd party libraries (e.g. Boost libraries) for fast and rapid
development.
 Speed of execution: C++ programs excel in execution speed. Since, it is a compiled
language, and also hugely procedural. Newer languages have extra in-built default features
such as garbage-collection, dynamic typing etc. which slow the execution of the program
overall. Since there is no additional processing overhead like this in C++, it is blazing fast.
 Pointer and direct Memory-Access: C++ provides pointer support which aids users to
directly manipulate storage address. This helps in doing low-level programming (where
one might need to have explicit control on the storage of variables).
 Object-Oriented: One of the strongest points of the language which sets it apart from C.
Object-Oriented support helps C++ to make maintainable and extensible programs. i.e.

5
Large-scale applications can be built. Procedural code becomes difficult to maintain as
code-size grows.
 Compiled Language: C++ is a compiled language, contributing to its speed.

Objective :
The prime purpose of C++ programming was to add object orientation to the C programming
language, which is in itself one of the most powerful programming languages.
The core of the pure object-oriented programming is to create an object, in code, that has certain
properties and methods.

Course Outcomes :
1. Recall all the data types and header files in C++.
2. Illustrate Function overloading, Inline function with Default argument.
3. Apply the Object Oriented Paradigm into the C++ Programming Language.
4. Test C++ codes, into various Programs.
5. Explain Class & Function for generic data.
6. Create programs using File handling.

6
2. LIST OF EXPERIMENTS
(As prescribed by G.G.S.I.P.U)

OBJECT ORIENTED PROGRAMMING LAB

Paper Code: ETCS-258

Paper: Object Oriented Programming

List of Experiments:

1. Write a program for multiplication of two matrices using OOP.


2. Write a program to perform addition of two complex numbers using constructor
overloading. The first constructor which takes no argument is used to create objects which
are not initialized, second which takes one argument is used to initialize real and imag
parts to equal values and third which takes two argument is used to initialized real and
imag to two different values.
3. Write a program to find the greatest of two given numbers in two different classes using
friend function.
4. Implement a class string containing the following functions:
- Overload + operator to carry out the concatenation of strings.
- Overload = operator to carry out string copy.
- Overload <= operator to carry out the comparison of strings.
- Function to display the length of a string.
- Function tolower( ) to convert upper case letters to lower case.
- Function toupper( ) to convert lower case letters to upper case.
5. Create a class called LIST with two pure virtual function store() and retrieve().To store a
value call store and to retrieve call retrieve function. Derive two classes stack and queue
from it and override store and retrieve.
6. Write a program to define the function template for calculating the square of given
numbers with different data types.
7. Write a program to demonstrate the use of special functions, constructor and destructor in
the class template. The program is used to find the bigger of two entered numbers.
8. Write a program to perform the deletion of white spaces such as horizontal tab, vertical
tab, space ,line feed ,new line and carriage return from a text file and store the contents of
the file without the white spaces on another file.
9. Write a program to read the class object of student info such as name , age ,sex ,height
and weight from the keyboard and to store them on a specified file using read() and
write() functions. Again the same file is opened for reading and displaying the contents of
the file on the screen.

NOTE: - At least 8 Experiments out of the list must be done in the semester.

7
3. LIST OF EXPERIMENTS
(Beyond the syllabus prescribed by G.G.S.I.P.U)

OBJECT ORIENTED PROGRAMMING LAB

Paper Code: ETCS-258

Paper: Object Oriented Programming

List of Experiments:

1. Write a program to calculate the area of circle, rectangle, triangle & square using the
function overloading.
2. Write a program to implement the new & delete operators.
3. Write a program to implement the static data member & static member function.
4. Write a program to compute the time using passing the object as argument.
5. Write a program to sum of two complex numbers using a returning object by friend
function.

6. Write a program to represent a Bank Account :


Data Members:
Name of depositer
Account number
Account type
Balance amount
Member functions:
Initialize the data members
Deposite the amount
Widthrawl the amount (If the balance sufficient)
Display the data members
Write a main program to handle the 10 customers.
7. Write a program to implement the Destructor.
8. Write a program to implement the following Inheritance :

9. Write a program to implement the use of constructors in derived class.

8
4. How to Compile and Run a Program on Turbo C++

 There are 2 ways to compile and run the C++ program, by menu and by shortcut.
 By menu
 Now click on the compile menu then compile sub menu to compile the C++ program.
 Then click on the run menu then run sub menu to run the C++ program.
 By shortcut
 Or, press ctrl+f9 keys compile and run the program directly.
 You will see the following output on user screen.

 You can view the user screen any time by pressing the alt+f5 keys.
 Now press Esc to return to the turbo C++ console.

9
5. FORMAT OF THE LAB RECORD TO BE PREPARED BY THE STUDENTS

The front page of the lab record prepared by the students should have a cover page as displayed
below.

Dr. Akhilesh Das Gupta Institute of Technology & Management


(FC-26, Panduk Shila Marg, Zero Pusta Rd, Shastri Park, Shahdara,
New Delhi, Delhi 110053)

DEPARTMENT OF INFORMATION TECHNOLOGY

OBJECT ORIENTED PROGRAMMING

Font should be (Size 20”, italics bold, Times New Roman)

Faculty Name Student Name

Roll No.

Sem.

Font should be (12”, Times Roman)

(Affiliated to Guru Gobind Singh Indraprastha University, Dwarka, New Delhi)

10
6. Experiments according to the lab syllabus

Exp. Experiment Name Date of Date of Marks Signature


No performance checking

11
EXPERIMENT: 1
AIM: Write a program for multiplication of two matrices using OOP.

Tool Required : Turbo C++

Program:

#include <iostream.h>
intmain()
{
inta[10][10], b[10][10], mult[10][10], r1, c1, r2, c2, i, j, k;

cout<<"Enter rows and columns for first matrix: ";


cin>> r1 >>c1;
cout<<"Enter rows and columns for second matrix: ";
cin>> r2 >>c2;

while (c1 != r2)


{
cout<<"Error! column of first matrix not equal to row of second.\n";

cout<<"Enter rows and columns for first matrix: ";


cin>> r1 >>c1;

cout<<"Enter rows and columns for second matrix: ";


cin>> r2 >>c2;
}

cout<<endl
<<"Enter elements of matrix 1:"<<endl;
for (i = 0; i< r1; ++i)
for (j = 0; j < c1; ++j)
{
cout<<"Enter element a"<<i + 1<< j + 1<<" : ";
cin>> a[i][j];
}

cout<<endl
<<"Enter elements of matrix 2:"<<endl;
for (i = 0; i< r2; ++i)

12
for (j = 0; j < c2; ++j)
{
cout<<"Enter element b"<<i + 1<< j + 1<<" : ";
cin>> b[i][j];
}

for (i = 0; i< r1; ++i)


for (j = 0; j < c2; ++j)
{
mult[i][j] = 0;
}

for (i = 0; i< r1; ++i)


for (j = 0; j < c2; ++j)
for (k = 0; k < c1; ++k)
{
mult[i][j] += a[i][k] * b[k][j];
}

cout<<endl
<<"Output Matrix: "<<endl;
for (i= 0; i< r1; ++i)
for (j = 0; j < c2; ++j)
{
cout<<" "<<mult[i][j];
if (j == c2 - 1)
cout<<endl;
}

return0;
}

13
Output:

14
EXPERIMENT: 2

AIM: Write a program to perform addition of two complex numbers using constructor overloading. The
first constructor which takes no argument is used to create objects which are not initialized, second which
takes one argument is used to initialize real and imag parts to equal values and third which takes two
argument is used to initialized real and imag to two different values.

Tool Required : Turbo C++

Program:

#include<iostream.h>
class Complex {

public:
int real, imaginary;

Complex()
{
}
Complex(inttempReal, inttempImaginary)
{
real = tempReal;
imaginary = tempImaginary;
}
Complex addComp(Complex C1, Complex C2)
{

Complex temp;

temp.real = C1.real + C2.real;

temp.imaginary = C1.imaginary + C2.imaginary;

returntemp;
}
};

intmain()
{

Complex C1(3, 2);

15
cout<<"Complex number 1 : "<< C1.real
<<" + i"<< C1.imaginary<<endl;

Complex C2(9, 5);

cout<<"Complex number 2 : "<< C2.real


<<" + i"<< C2.imaginary<<endl;

Complex C3;
C3 = C3.addComp(C1, C2);
cout<<"Sum of complex number : "
<< C3.real<<" + i"
<< C3.imaginary;
}

Output:

16
EXPERIMENT: 3

AIM: Write a program to find the greatest of two given numbers in two different classes using friend
function.

Tool Required : Turbo C++

Program:
#include <iostream.h>

class second;

class first

intx;

public:
voidgetx()

cout<<"\nEnter the value of x:";

cin>>x;
}

friendvoidmax(first, second);
};

class second

inty;

public:
voidgety()

17
cout<<"\nEnter the value of y:";

cin>>y;
}

friendvoidmax(first, second);
};

voidmax(first a, second b)

if (a.x>b.y)

cout<<"\nGreater value is:"<<a.x;


}

else

cout<<"\nGreater value is:"<<b.y;


}
}

intmain()

first a;

second b;

a.getx();

b.gety();

max(a, b);

18
}

Output:

19
EXPERIMENT: 4

AIM: Implement a class string containing the following functions:


- Overload + operator to carry out the concatenation of strings.
- Overload = operator to carry out string copy.
- Overload <= operator to carry out the comparison of strings.
- Function to display the length of a string.
- Function tolower( ) to convert upper case letters to lower case.
- Function toupper( ) to convert lower case letters to upper case.

Tool Required : Turbo C++

Program:

#include <iostream.h>
#include <string.h>
class strings
{
public:
string s;
strings()
{
}
strings(string v)
{
s = v;
}
strings operator+(strings s1)
{
strings m;
m.s = s + s1.s;
returnm;
}
strings operator=(strings s1)
{
strings o;
s = s1.s;
returno;
}
string operator<=(strings s1)
{
if (s.length() > s1.s.length())
{

20
return s + ">" + s1.s;
}
if (s.length() < s1.s.length())
{
return s + "<" + s1.s;
}
else
{
return s + "=" + s1.s;
}
}
intlen()
{
returns.length();
}
chartolower(char c)
{
return c + 32;
}
chartoupper(char c)
{
return c - 32;
}
};

intmain()
{
strings s("Iron"), g("Man"), n;
cout<<"Concatenated string: "<< (s + g).s<<endl;
n = s;
cout<<"Copied string: "<<n.s<<endl;
cout<<"Comparison strings: "<< (s <= g) <<endl;
cout<<"Length of string \""<<n.s<<"\": "<<n.len() <<endl;
cout<<"Uppercase to lowercase: "<<s.tolower('I') <<endl;
cout<<"Lowercase to uppercase: "<<s.toupper('m') <<endl
<<endl;
return0;
}

21
Output:

22
EXPERIMENT: 5

AIM: Create a class called LIST with two pure virtual function store() and retrieve().To store a value call
store and to retrieve call retrieve function. Derive two classes stack and queue from it and override store
and retrieve.

Tool Required : Turbo C++

Program:

#include<iostream.h>
#include<stdlib.h>
#include<conio.h>
using namespace std;

struct node
{
int data;
node *next;
};

node *head=NULL,*tail=NULL;

class List
{
public:
void view()
{
node *n = head;
if(head==NULL)
{
cout<<"\n No elements found...";
}
else
{
cout<<" ";
while(n!=NULL)
{
if(n->next==NULL)
{
cout<<n->data;
}
else
{
cout<<n->data<<"->";
}
n = n->next;
}
}
}
virtual void store(int n)=0;
virtual int retrive()=0;
};

23
class Stack :public List
{
public:
void store(int n)
{
node *n1 = new node();
n1->data = n;
n1->next=NULL;
if((head==NULL)&&(tail==NULL))
{
head = n1;
tail = n1;
}
else
{
tail->next = n1;
tail = n1;
}
}
int retrive()
{
if((tail==NULL)&&(head==NULL))
{
return -1;
}
else
{
int n = tail->data;
node *n1 = head;
while((n1->next!=tail)&&(head!=tail))
{
n1 = n1->next;
}
n1->next = NULL;
free(tail);
if(head!=tail)
{
tail = n1;
}
else
{
tail=NULL;
head=NULL;
}
return n;
}
}
};

class Queue:public List


{
public:
void store(int n)
{

24
node *n1 = new node();
n1->data = n;
n1->next=NULL;
if((head==NULL)&&(tail==NULL))
{
head = n1;
tail = n1;
}
else
{
tail->next = n1;
tail = n1;
}
}
int retrive()
{
if((tail==NULL)&&(head==NULL))
{
return -1;
}
else
{
int n = head->data;
if(head==tail)
{
head = tail = NULL;
}
else
{
head = head->next;
}
return n;
}
}
};

int main()
{
Stack s1;
int ch;
while(1)
{
system("cls");
cout<<"\n\n Program to implement stack and queue using pure virtual functions
store and retrieve";
cout<<"\n ^^^^^^^ ^^ ^^^^^^^^^ ^^^^^ ^^^ ^^^^^ ^^^^^ ^^^^ ^^^^^^^ ^^^^^^^^^ ^^
^^^ ^^^ ^^^^^^^^";
cout<<"\n\n Menu";
cout<<"\n ^^^^";
cout<<"\n\n 1. Stack";
cout<<"\n 2. Queue";
cout<<"\n 3. Exit";
cout<<"\n\n Enter your choice - ";
cin>>ch;
if(ch==1)

25
{
Stack s1;
int ch1;
while(1)
{
system("cls");
cout<<"\n\n Stack Menu";
cout<<"\n ^^^^^ ^^^^";
cout<<"\n 1. Push Element";
cout<<"\n 2. Pop Element";
cout<<"\n 3. View Stack";
cout<<"\n 4. Exit";
cout<<"\n\n Enter your choice - ";
cin>>ch1;
if(ch1==1)
{
int element;
cout<<"\n Enter the element you want to push - ";
cin>>element;
s1.store(element);
cout<<"\n Element Pushed";
}
else if(ch1==2)
{
int element=0;
element = s1.retrive();
if(element==-1)
{
cout<<"\n Stack is Empty";
}
else
{
cout<<"\n Element Popped = "<<element;
}
}
else if(ch1==3)
{
cout<<"\n Elements in stack from bottom to top:- ";
s1.view();
}
else if(ch1==4)
{
break;
}
else
{
cout<<"\n\n Wrong choice";
}
getch();
}
}
else if(ch==2)
{
Queue q1;
int ch1;

26
while(1)
{
system("cls");
cout<<"\n\n Queue Menu";
cout<<"\n ^^^^^ ^^^^";
cout<<"\n 1. Push Element";
cout<<"\n 2. Pop Element";
cout<<"\n 3. View Queue";
cout<<"\n 4. Exit";
cout<<"\n\n Enter your choice - ";
cin>>ch1;
if(ch1==1)
{
int element;
cout<<"\n Enter the element you want to push - ";
cin>>element;
q1.store(element);
cout<<"\n Element Pushed";
}
else if(ch1==2)
{
int element=0;
element = q1.retrive();
if(element==-1)
{
cout<<"\n Queue is Empty";
}
else
{
cout<<"\n Element Popped = "<<element;
}
}
else if(ch1==3)
{
cout<<"\n Elements in queue from front to rear:- ";
q1.view();
}
else if(ch1==4)
{
break;
}
else
{
cout<<"\n\n Wrong choice";
}
getch();
}
}
else if(ch==3)
{
exit(0);
}
else
{
cout<<"\n\n Wrong Choice";

27
}
getch();
}
return 0;
}

Output:
Program to implement stack and queue using pure virtual functions store
and retrieve
^^^^^^^ ^^ ^^^^^^^^^ ^^^^^ ^^^ ^^^^^ ^^^^^ ^^^^ ^^^^^^^ ^^^^^^^^^ ^^^^^
^^^ ^^^^^^^^

Menu
^^^^

1. Stack
2. Queue
3. Exit

Enter your choice - 1

Stack Menu
^^^^^ ^^^^
1. Push Element
2. Pop Element
3. View Stack
4. Exit

Enter your choice - 1

Enter the element you want to push - 1

Element Pushed

Stack Menu
^^^^^ ^^^^
1. Push Element
2. Pop Element
3. View Stack
4. Exit

Enter your choice - 1

Enter the element you want to push - 2

Element Pushed

Stack Menu
^^^^^ ^^^^
1. Push Element
2. Pop Element
3. View Stack
4. Exit

Enter your choice - 1

28
Enter the element you want to push - 3

Element Pushed

Stack Menu
^^^^^ ^^^^
1. Push Element
2. Pop Element
3. View Stack
4. Exit

Enter your choice - 3

Elements in stack from bottom to top:- 1->2->3

Stack Menu
^^^^^ ^^^^
1. Push Element
2. Pop Element
3. View Stack
4. Exit

Enter your choice - 4

Program to implement stack and queue using pure virtual functions store
and retrieve
^^^^^^^ ^^ ^^^^^^^^^ ^^^^^ ^^^ ^^^^^ ^^^^^ ^^^^ ^^^^^^^ ^^^^^^^^^ ^^^^^
^^^ ^^^^^^^^

Menu
^^^^

1. Stack
2. Queue
3. Exit

Enter your choice - 2

Queue Menu
^^^^^ ^^^^
1. Push Element
2. Pop Element
3. View Queue
4. Exit

Enter your choice - 3

Elements in queue from front to rear:- 1->2->3

Queue Menu
^^^^^ ^^^^
1. Push Element
2. Pop Element
3. View Queue

29
4. Exit

Enter your choice - 2

Element Popped = 1

Queue Menu
^^^^^ ^^^^
1. Push Element
2. Pop Element
3. View Queue
4. Exit

Enter your choice - 3

Elements in queue from front to rear:- 2->3

Queue Menu
^^^^^ ^^^^
1. Push Element
2. Pop Element
3. View Queue
4. Exit

Enter your choice - 4

Program to implement stack and queue using pure virtual functions store
and retrieve
^^^^^^^ ^^ ^^^^^^^^^ ^^^^^ ^^^ ^^^^^ ^^^^^ ^^^^ ^^^^^^^ ^^^^^^^^^ ^^^^^
^^^ ^^^^^^^^

Menu
^^^^

1. Stack
2. Queue
3. Exit

Enter your choice - 1

Stack Menu
^^^^^ ^^^^
1. Push Element
2. Pop Element
3. View Stack
4. Exit

Enter your choice - 3

Elements in stack from bottom to top:- 2->3

Stack Menu
^^^^^ ^^^^
1. Push Element
2. Pop Element

30
3. View Stack
4. Exit

Enter your choice - 2

Element Popped = 3

Stack Menu
^^^^^ ^^^^
1. Push Element
2. Pop Element
3. View Stack
4. Exit

Enter your choice - 3

Elements in stack from bottom to top:- 2

31
EXPERIMENT: 6

AIM: Write a program to define the function template for calculating the square of given numbers with
different data types.
Tool Required : Turbo C++

Program:

#include <iostream.h>
template<class T>
inline T square(T x)
{
T result;
result = x * x;
returnresult;
};

intmain()
{
inti, ii;
float x, xx;
double y, yy;

i = 2;
x = 2.2;
y = 2.2;

ii = square<int>(i);
cout<<i<<": "<< ii <<endl;

xx = square<float>(x);
cout<< x <<": "<< xx <<endl;

yy = square<double>(y);
cout<< y <<": "<<yy<<endl;

yy = square(y);
cout<< y <<": "<<yy<<endl;
return0;
}

32
Output:

33
EXPERIMENT: 7

AIM: Write a program to demonstrate the use of special functions, constructor and destructor in the class
template. The program is used to find the bigger of two entered numbers.

Tool Required : Turbo C++

Program:

#include <iostream.h>
template<class T>
inline T square(T x)
{
T result;
result = x * x;
returnresult;
};

intmain()
{
inti, ii;
float x, xx;
double y, yy;

i = 2;
x = 2.2;
y = 2.2;

ii = square<int>(i);
cout<<i<<": "<< ii <<endl;

xx = square<float>(x);
cout<< x <<": "<< xx <<endl;

yy = square<double>(y);
cout<< y <<": "<<yy<<endl;

yy = square(y);
cout<< y <<": "<<yy<<endl;
return0;
}

34
Output:

35
EXPERIMENT: 8

AIM: Write a program to perform the deletion of white spaces such as horizontal tab, vertical tab, space
,line feed ,new line and carriage return from a text file and store the contents of the file without the white
spaces on another file.

Tool Required : Turbo C++

Program:

#include<iostream.h>
#include<fstream.h>
#include<conio.h>

void main()
{
clrscr();
fstream file1;
fstream file2;
char ch;
file1.open("data1.txt",ios::out);
do
{
cin.get(ch);
file1.put(ch);
}while(ch!=EOF);
file1.close();
cout<<"\nData written successfully...\n";
file1.open("data1.txt",ios::in);
file2.open("data2.txt",ios::out);
while(!file1.eof())
{
file1.get(ch);
if(ch!=' ')
file2.put(ch);
}
file1.close();
file2.close();
file2.open("data2.txt",ios::in);
while(!file2.eof())
{
file2.get(ch);
cout<<ch;
}
file2.close();
getch();
}

36
Output:

37
EXPERIMENT: 9

AIM: Write a program to read the class object of student info such as name , age ,sex ,height and weight
from the keyboard and to store them on a specified file using read() and write() functions. Again the same
file is opened for reading and displaying the contents of the file on the screen.

Tool Required : Turbo C++

Program:
#include<iostream.h>
#include<fstream.h>
#include<conio.h>
class student
{
private:
char name[30];
int age;
char sex[10];
float height;
float weight;
public:
void getData(void)
{ cout<<"Enter name:";
cin>>name;
cout<<"Enter age:";
cin>>age;
cout<<"Enter Sex (Male/Female):";
cin>>sex;
cout<<"Enter Height in cm.:";
cin>>height;
cout<<"Enter weight in Kg.:";
cin>>weight;
}

void showData(void)
{
cout<<"Name:"<<name<<endl;
cout<<"Age:"<<age<<endl;
cout<<"Sex:"<<sex<<endl;
cout<<"Height:"<<height<<endl;
cout<<"Weight:"<<weight<<endl;
}
};

void main()
{
clrscr();
student s;
ofstream file;
file.open("Data.txt",ios::out);
s.getData();
file.write((char*)&s,sizeof(s));
file.close();
cout<<"\nFile saved and closed succesfully."<<endl;

38
ifstream file1;
file1.open("Data.txt",ios::in);
file1.read((char*)&s,sizeof(s));
s.showData();
file1.close();
getch();
}

Output:

39
EXPERIMENT: 10

AIM: Write a program to calculate the area of circle, rectangle, triangle & square using the function
overloading.

Tool Required : Turbo C++

Program:

#include<iostream.h>
#include<math.h>
#include<conio.h>

doubleconst pi=3.141592;

floatarea(float a)
{
return a*a;
}

floatarea(float l, float b)
{
return l*b;
}

floatarea(float a, float b, float c)


{
floatar,s;
s=(a+b+c)/2;
ar=sqrt(s*(s-a)*(s-b)*(s-c));
returnar;
}

floatarea(double pi, float r)


{
return pi*r*r;
}

intmain()
{
intop;
floatar, a,b,c;

40
cout<<"AREA CALCULATOR\n";
cout<<"1. SQUARE \t2. RECTANGLE \t3. TRIANGLE \t4. CIRCLE \n0. EXIT \n";
do
{
cout<<"\nMENU OPTION: ";
cin>>op;
switch(op)
{
case1: cout<<"Enter Side: ";
cin>>a;
ar=area(a);
break;
case2: cout<<"Enter Length & Breadth: ";
cin>>a>>b;
ar=area(a,b);
break;
case3: cout<<"Enter 3 sides: ";
cin>>a>>b>>c;
ar=area(a,b,c);
break;
case4: cout<<"Enter radius: ";
cin>>a;
ar=area(pi,a);
break;
case0: break;
default: cout<<"Invalid Entry. Try Again\n";
}
if((op>0)&&(op<5))
{ cout<<"Area : "<<ar<<endl;
getch();
}
}while(op>0);
return0;
}

41
Output:

42
EXPERIMENT: 11

AIM: Write a program to implement the new & delete operators.

Tool Required : Turbo C++

Program:
#include <iostream.h>
#include <string.h>

int main()
{
int *ptr = NULL;
ptr = newint();
int *var = newint(12);

if(!ptr)
{
cout<<"bad memory allocation"<<endl;
}
else
{
cout<<"memory allocated successfully"<<endl;
*ptr = 10;
cout<<"*ptr = "<<*ptr<<endl;
cout<<"*var = "<<*var<<endl;
}

double *myarray = NULL;


myarray = newdouble[10];
if(!myarray)
{cout<<"memory not allocated"<<endl;}
else
{
for(inti=0;i<10;i++)
myarray[i] = i+1;
cout<<"myarrayvalues : ";
for(inti=0;i<10;i++)
cout<<myarray[i]<<"\t";
}
deleteptr;

43
deletevar;
delete[]myarray;

return0;

Output:

44
EXPERIMENT: 12

AIM: Write a program to implement the static data member & static member function.

Tool Required : Turbo C++

Program:

#include <iostream.h>
#include <string.h>

usingnamespacestd;
class Student
{
private:
introllNo;
charname[10];
intmarks;

public:
staticintobjectCount;
Student()
{
objectCount++;
}

voidgetdata()
{
cout<<"Enter roll number: "<<endl;
cin>>rollNo;
cout<<"Enter name: "<<endl;
cin>>name;
cout<<"Enter marks: "<<endl;
cin>>marks;
}

voidputdata()
{
cout<<"Roll Number = "<<rollNo<<endl;
cout<<"Name = "<< name <<endl;
cout<<"Marks = "<< marks <<endl;

45
cout<<endl;
}
};
intStudent::objectCount = 0;
int main(void)
{
Student s1;
s1.getdata();
s1.putdata();
Student s2;

s2.getdata();
s2.putdata();
Student s3;

s3.getdata();
s3.putdata();
cout<<"Total objects created = "<<Student::objectCount<<endl;
return0;
}

Output:

46
EXPERIMENT: 13

AIM: Write a program to compute the time using passing the object as argument.

Tool Required : Turbo C++

Program:

#include<iostream.h>
#include<conio.h>
class time
{
int hour,min;
public:
void get()
{
cout<<"Enter Hour & Minute :\n";
cin>>hour>>min;
}
void put()
{
cout<<hour<<"Hour and "<<min<<" Minute\n";
}
void sum(time t1, time t2)
{
time t3;
min=t1.min+t2.min;
hour=min/60;
min=min%60;
hour=hour+t1.hour+t2.hour;
}
};
void main()
{
time s1,s2,s3;
clrscr();
s1.get();
s2.get();

47
s3.sum(s1,s2);
s1.put();
s2.put();
s3.put();
getch();
}

Output:

48
EXPERIMENT: 14

AIM: Write a program to sum of two complex numbers using a returning object by friend function.

Tool Required : Turbo C++

Program:

#include <iostream.h>

class complex

int real, imag;

public:
voidset()

{
cout<<"Enter real and imagpart : ";

cin>> real >>imag;


}

friend complex sum(complex, complex);

voiddisplay();
};

voidcomplex::display()

cout<<"The sum of complex numis : "<< real <<" + "<<imag<<"i";


}

complex sum(complex a, complex b)

49
complex t;

t.real = a.real + b.real;

t.imag = a.imag + b.imag;

returnt;
}

intmain()

complex a, b, c;

a.set();

b.set();

c = sum(a, b);

c.display();

return (0);
}

Output:

50
EXPERIMENT: 15

AIM: Write a program to represent a Bank Account :


Data Members:
Name of depositer
Account number
Account type
Balance amount
Member functions:
Initialize the data members
Deposite the amount
Widthrawl the amount (If the balance sufficient)
Display the data members

Write a main program to handle the 10 customers.

Tool Required : Turbo C++

Program:
#include <iostream.h>
#include <stdio.h>
#include <string.h>

usingnamespacestd;

class bank
{
intacno;
charnm[100], acctype[100];
floatbal;

public:
bank(intacc_no, char*name, char*acc_type, float balance)
{
acno = acc_no;
strcpy(nm, name);
strcpy(acctype, acc_type);
bal = balance;
}
voiddeposit();
voidwithdraw();
voiddisplay();

51
};
voidbank::deposit()
{
intdamt1;
cout<<"\n Enter Deposit Amount = ";
cin>>damt1;
bal += damt1;
}
voidbank::withdraw()
{
intwamt1;
cout<<"\n Enter Withdraw Amount = ";
cin>>wamt1;
if (wamt1 >bal)
cout<<"\n Cannot Withdraw Amount";
bal -= wamt1;
}
voidbank::display()
{
cout<<"\n ----------------------";
cout<<"\n AccoutNo. : "<<acno;
cout<<"\n Name : "<< nm;
cout<<"\n Account Type : "<<acctype;
cout<<"\n Balance : "<<bal;
}
intmain()
{
intacc_no;
charname[100], acc_type[100];
floatbalance;
cout<<"\n Enter Details: \n";
cout<<"-----------------------";
cout<<"\n Accout No. ";
cin>>acc_no;
cout<<"\n Name : ";
cin>>name;
cout<<"\n Account Type : ";
cin>>acc_type;
cout<<"\n Balance : ";
cin>>balance;

52
bank b1(acc_no, name, acc_type, balance);
b1.deposit();
b1.withdraw();
b1.display();
return0;
}

Output:

53
EXPERIMENT: 16

AIM: Write a program to implement the Destructor.

Tool Required : Turbo C++

Program:

#include <iostream.h>

class BaseClass
{
public:
BaseClass()
{
cout<<"Constructor of the BaseClass : Object Created"<<endl;
}
~BaseClass()
{
cout<<"Destructor of the BaseClass : Object Destroyed"<<endl;
}
};

intmain()
{
BaseClassdes;
return0;
}

Output:

54
EXPERIMENT: 17

AIM: Write a program to implement the following Inheritance :

Tool Required : Turbo C++

Program:
#include <iostream.h>
#include <process.h>

class person
{
protected:
charname[20];
intcode;

public:
voidgetcode()
{
cout<<"\n Enter the code ";
cin>>code;
}
voidgetname()
{
cout<<"\n Enter the name ";
cin>>name;
}
};
classaccount :virtualpublic person
{
protected:
intpay;

55
public:
voidgetpay()
{
cout<<"\n Enter the payment ";
cin>>pay;
}
};
classadmin :virtualpublic person
{
protected:
intexp;

public:
voidgetexp()
{
cout<<"\n Enter the experiance";
cin>>exp;
}
};
classmaster :public account, public admin
{
public:
voidgetdata()
{
getcode();
getname();
getpay();
getexp();
}
voidupdate()
{
intc;
cout<<"\n You want 2 update\n1.code\n2.name\n3.payment\n4.experiance";
cout<<"\nEnterur choice ";
cin>>c;
switch (c)
{
case1:
getcode();
break;

56
case2:
getname();
break;
case3:
getpay();
break;
case4:
getexp();
break;
default:
cout<<"\n Invalid choice";
}
}
voidputdata()
{
cout<<"\nDetails";
cout<<"\n Code "<< code <<"\n Name "<<name;
cout<<"\n Payment "<< pay <<"\n Experiance "<<exp;
cout<<"\nPress any key 2 continue ";
}
};
intmain()
{
intch;
master m;
while (1)
{
cout<<"\nMENU\n1.Create\n2.Update\n3.Display\n4.Exit";
cout<<"\nEnterur choice ";
cin>>ch;
switch (ch)
{
case1:
m.getdata();
break;
case2:
m.update();
break;
case3:
m.putdata();
break;

57
case4:
exit(0);
default:
cout<<"\n Invalid choice";
}
}
}

Output:

58
EXPERIMENT: 18

AIM: Write a program to implement the use of constructors in derived class.

Tool Required : Turbo C++

Program:

#include <iostream.h>
class Base
{
private:
intm_id;

public:
Base(int id = 0)
: m_id{id}
{
}

intgetId() const { returnm_id; }


};

classDerived :public Base


{
private:
doublem_cost;

public:
Derived(double cost = 0.0, int id = 0)
: Base{id},
m_cost{cost}
{
}

doublegetCost() const { returnm_cost; }


};

intmain()
{
Derived derived{1.3, 5};

59
std::cout<<"Id: "<<derived.getId() <<'\n';
std::cout<<"Cost: "<<derived.getCost() <<'\n';

return0;
}

Output:

60

You might also like