cplusplus

110
Ashish K Nayyar Institute of Information Technology and Management Affiliated to Guru Gobind Singh Indraprastha University, New Delhi. Prepared by Mr. Ashish Nayyar Programme Director MCA

Transcript of cplusplus

Page 1: cplusplus

Ashish K Nayyar

Institute of Information Technology and ManagementAffiliated to Guru Gobind Singh Indraprastha University, New Delhi.

Prepared by

Mr. Ashish Nayyar

Programme Director MCA

Page 2: cplusplus

Ashish K Nayyar

OTHER MCA Semester-II LABS

Paper ID Paper Code

Paper L T/P Credit

Practical044152 MCA 152 Data and File Structures Lab 0 2 1044154 MCA 154 Object Oriented Programming in C++ Lab 0 4 2044156 MCA 156 Database Management Systems Lab 0 2 1044158 MCA 158 Software Engineering Lab. 0 2 1

Page 3: cplusplus

Ashish K Nayyar

Special Note to Students

Your preparation before each laboratory session is extremely important. At minimum your

preparation should include reading the entire session and its associated experiments. Your

goal should be to identify the purpose of each experiment within the laboratory session before

the actual session begins. A good approach is to read each experiment and then ask yourself

why that particular experiment was included at that specific point in the laboratory session.

You should approach each session in a spirit of experimentation. The laboratory activities are

not designed to tell you every detail about the topics covered. Instead, are designed to

encourage you to experiment and discover. Once you adapt to this mode of learning, you will

find that a computer installation offers an endless opportunity to explore and learn. In most

cases the laboratory activities involve experimenting with short programs. Your instructor

will tell you how to gain access to this software.

Page 4: cplusplus

Ashish K Nayyar

Special Note to Instructors

Each laboratory session contains more experiments than your students may be able to

complete in a two-hour period. This becomes more pronounced as the sessions progress into

experiments that require the development of entire routines. You are encouraged to assign

those experiments that emphasize the topics you wish to cover.

Many of the experiments consist of running an example program and then modifying it. To

avoid the tedium of typing and to allow students more time for experimentation and

reflection, the initial form of these programs can be stored in files and made available to the

students.

I would like to thank Dr. Prerna Mahajan HOD-IT for her comments and suggestions.

Page 5: cplusplus

Ashish K Nayyar

INTRODUCTION OF THE LANGUAGE (Turbo C++ language) MAIN FEATURES

It is a robust language whose rich set of built-in functions and operators can be

used to write any complex program C++ is highly portable. This means that C+

+programs written for one computer can be run on another with little or no

modification.

C++language is well suited for structured programming, thus requiring the user to

think of a problem in terms of function modules or locks.

Programs written in C++ are efficient and fast. This is due to its variety of data

types and powerful operators. It is many times faster than BASIC.

Another important feature of C++ is its ability to extend itself.

A C++ program is basically a collection of functions, which are supported by the

C++ library.

ADVANTAGES

C++ source code can be optimized much more than higher-level languages because

the language set is relatively small and very efficient C++ has which is its application

in Firmware programming (hardware). That is due to its ability to use/work with

assembly and communicate directly with controllers, processors and other devices.

C++ is a building block for many other currently known languages.

C++ is a compiled language versus an interpreted language. Explained simply, this

means that the code is compacted into executable instruction (in the case of windows

anyway) rather than being "translated" on the fly at run time.

LIMITATIONS Weak text processing capabilities –C++'s string library is extremely primitive (it

doesn't even define an actual string type), and text processing is labor-intensive and

error-prone.

Security and safety issues-several library functions (gets() being the most notorious)

provide easy exploits for malware, and anything involving pointers is going to be

unsafe (it's hard to guard against being passed an invalid pointer);

Weak memory management capabilities -Like text processing, managing memory in

C++ is labor intensive and error-prone

Page 6: cplusplus

Ashish K Nayyar

No built-in collections library –C++doesn't provide readymade collections (lists,

queues, stacks, etc.), meaning you have to roll your own.

No built- in support for networking, sound, graphics, etc. – C++ is a product of the

early 1980s and it shows; byte streams are about the highest level of abstraction

you're going to find in the C++ library.

APPLICATIONS C++language is used for creating computer applications and also used a lot in writing

embedded software/firmware for various electronics, industrial and communications

products which use micro-controllers.

It is also used in developing verification software, test code, simulators etc. for

various applications and hardware products.

C++has been used successfully for every type of programming problem imaginable

from operating systems to spreadsheets to expert systems.

C++ was used for system development work, in particular the programs that make-up

the operating system.

C++has been used as a general-purpose language because of its popularity with

programmers

Page 7: cplusplus

Ashish K Nayyar

SYSTEM REQUIREMENTS

HARDWARE REQUIREMENTS

Processors-2.0 GHz or Higher

RAM-256 MB or Higher

Hard Disk-20 GB or Higher

Operating System-Windows 2000/XP/NT

SOFTWAREREQUIREMENTS

TURBO C (Freeware)

.

Page 8: cplusplus

Ashish K Nayyar

Subject Title: Object Oriented Programming in C++ Lab

Subject Code: MCA 154

Lab No

Unit No

Application Area/Functionality/ Concept on which practical is based

Problem Statement No. of SessionsAllott

ed L1 I If-else construct, loops,

Arrays and Pointers

Cin, cout, new and delete operators, Reference variable, class

1. WAP to check whether the number is prime or not.

2. WAP to find the reverse of an inputted number.

3. WAP to find the sum of the digits of a number.

4. WAP to find the factorial of a number.

5. WAP to print Fibonacci series6. WAP for matrix addition,

subtraction and multiplication.

4

L2 I Structures, Strings in c++ 1. W AP to create a structure Student and add functions to read and show details.

2. W AP to find the length of a string.3. W AP to concatenate two strings

using your defined Function.L3 I,II Class, Constructor,

Destructor, Default Parameter, Polymorphism – function overloading

1. W AP to show the working of a class Student add functions to read and show details.

2. W AP to define a class circle and add functions to perform following tasks. Read, display and calculate area.

3. W AP to overloaded function area ( ) for calculating the area of triangle and circle

4. W AP to create Student class and add constructors, other functions and destructor.

5. W AP a program to demonstrate constructor function overloading.

8

L4 II Polymorphism-Operator overloading

1. W AP to create class DISTANCE and overload Binary + operator to add objects. Use member functions.

2. W AP to create class COMPLEX and overload Binary + operator to add objects. Use member functions.

3. W AP to create class COMPLEX and overload Binary + operator to add objects. Use friend functions.

4. WAP to overload binary < operator

Page 9: cplusplus

Ashish K Nayyar

to compare two objects of user defined English Distance Class.

L5 II Polymorphism-Operator overloading

1. WAP to overload binary + operator to concatenate two objects of user defined class String.

2. WAP to overload binary +operator to add two objects of user defined Time class with data members HH MM SS.

3. W AP to show overloading of ++operator.

4. W AP to show overloading of ( )operator.

5. W AP to show overloading of [ ]operator.

L6 II Inheritance 1. W AP to demonstrate the working of virtual function.

2. WAP to demonstrate the concept of Inheritance use person and student class for the same

L7 Exception Handling 1. W AP to implement a class Stack that throws Overflow and Underflow Exceptions.

2. W AP to implement a class Customer that throws Negative Balance Exceptions.

L8 III Template function and classes

1. W AP to implement template function that interchanges two data values.

2. W AP to implement a generic class Stack, add necessary constructors and other functions

L9 IV File Handling and Stream Class Hierarchy

1. W AP that reads a text file. 2. W AP that writes paragraph to a

text file.3. W AP that writes Student records to

a data file.4. WAP that uses file pointer to display

any arbitrary record from an pre existing file.

5. W AP that writes Student records to a data file. Read records based on name entered

L10 IV Friend function and static 1. Friend function as a bridge between two classes rupee and dollar

2. Static data member and member function

Page 10: cplusplus

Ashish K Nayyar

Lab No.1

Concept: Study of If-else construct, loops, Arrays and Pointers cin, cout, new and delete operators, Reference variable, class and objects.

Objective:

Teach the students how to use the arithmetic operations in mathematical expressions, and use it to write and execute a simple program.

Teach the students the arithmetic operation precedence. Learn the student, how to use if/else selection statements, and use it to write and

execute a simple program. To make student Learn, how to use loops, and use it to write and execute a simple

program. Applying the new and delete statements, and use it to write and execute a program. Learn the concept of reference variable. Learn how to create class and add functionality to the same.

Pre Lab(Background):

An if statement can be followed by an optional else statement, which executes when the boolean expression is false.

Syntax:

The syntax of an if...else statement in C programming language is:

if(boolean_expression){ /* statement(s) will execute if the boolean expression is true */}else{ /* statement(s) will execute if the boolean expression is false */}

If the boolean expression evaluates to true, then the if block of code will be executed, otherwise else block of code will be executed.

C programming language assumes any non-zero and non-null values as true, and if it is either zero or null, then it is assumed as false value.

Page 11: cplusplus

Ashish K Nayyar

Flow Diagram:

LOOPS

There may be a situation, when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.

Programming languages provide various control structures that allow for more complicated execution paths.

A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages:

Page 12: cplusplus

Ashish K Nayyar

C programming language provides the following types of loop to handle looping requirements. Click the following links to check their detail.

Loop Type Description

while loopRepeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.

for loop Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable.

do...while loop Like a while statement, except that it tests the condition at the end of the loop body

nested loops You can use one or more loop inside any another while, for or do..while loop.

Loop Control Statements:

Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.

C supports the following control statements. Click the following links to check their detail.

Control Statement Description

break statement Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.

continue statement Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

goto statement Transfers control to the labeled statement. Though it is not advised to use goto statement in your program.

Lab Assignments:

Page 13: cplusplus

Ashish K Nayyar

1. WAP to check whether the number is prime or not.2. WAP to find the reverse of an inputted number.3. WAP to find the sum of the digits of a number.4. WAP to find the factorial of a number.5. WAP to print Fibonacci series6. WAP for matrix addition, subtraction and multiplication.

Page 14: cplusplus

Ashish K Nayyar

Solutions to Lab No1.

Q-1 W AP to check whether the number is prime or not.

#include<conio.h>#include<iostream.h>void main(){int count=0,i,n;clrscr();cout<<"Enter a number: ";cin>>n;for(i=2;i<n;i++){if(n%i==0){count++;}}if(count==0)cout<<"Prime";elsecout<<"Not Prime";getch();}

Page 15: cplusplus

Ashish K Nayyar

Q-2 W AP to find the reverse of an inputted number.

#include<iostream.h>#include<conio.h>void main(){longintnum,r,reverse=0;clrscr();cout<<"Enter a number";cin>>num;

while(num>0) { r=num%10;reverse=reverse*10+r;num=num/10; }

cout<<"Reversed number: "<<reverse;getch(); }

Page 16: cplusplus

Ashish K Nayyar

Q-3 W AP to find the sum of the digits of a number.

#include<iostream.h>#include<conio.h>void main(){longintnum,r,sum=0;clrscr();cout<<"Enter a number";cin>>num;

while(num>0) { r=num%10;num=num/10;sum=sum+r; }

cout<<"Sum of digits of number: "<<sum;getch(); }

Page 17: cplusplus

Ashish K Nayyar

Q-4 W AP to find the factorial of a number.

#include<conio.h>#include<iostream.h>void main(){longinti,num,fact=1;clrscr();cout<<"Enter a number: ";cin>>num;

for(i=num;i>=1;i--){fact=fact*i;}cout<<"Factorial of "<<num<<" is "<<fact;getch();

}

Page 18: cplusplus

Ashish K Nayyar

Q-5 W AP to print the Fibonacci series.

#include<iostream.h>#include<conio.h>void main(){inti,a=-1,b=1,c=0,num;clrscr();cout<<"Enter limit: ";cin>>num;cout<<"\nFibonacci series:\n";for(i=0;i<=num;i++){c=a+b;cout<<" "<<c;a=b;b=c;}getch();}

Page 19: cplusplus

Ashish K Nayyar

Q-6 W AP for matrix addition, subtraction and multiplication.

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

int a[10][10],b[10][10],c[10][10],i,j,m,n,k,p,q;

void main(){intch;

void add();void sub();voidmul();void input();void show();clrscr();input();while(1) {clrscr();

cout<<"****MENU****\n";cout<<"1.Addition\n";cout<<"2.Subtraction\n";cout<<"3.Multiply\n";cout<<"4.Exit";cout<<"\nEnter your Choice: ";cin>>ch;cout<<"\n";switch(ch) {case 1: add();

break;case 2: sub();

break;case 3: mul();

break;case 4: exit(0);default: cout<<"Invaid choice"; }getch(); }}

void show()

Page 20: cplusplus

Ashish K Nayyar

{cout<<"1st Matrix:\n";for(i=0;i<m;i++)

{for(j=0;j<n;j++){cout<<"\t"<<a[i][j];}cout<<"\n";}

cout<<"2nd Matrix:\n";for(i=0;i<p;i++)

{for(j=0;j<q;j++){cout<<"\t"<<b[i][j];}cout<<"\n";}

}

void input(){clrscr();cout<<"Enter size of First matrix";cin>>m>>n;cout<<"Enter size of Second matrix";cin>>p>>q;

cout<<"\nEnter 1st Matrix:";for(i=0;i<m;i++)

{for(j=0;j<n;j++){cin>>a[i][j];}}

cout<<"\nEnter 2nd Matrix:";for(i=0;i<p;i++)

{for(j=0;j<q;j++){cin>>b[i][j];}}

}

Page 21: cplusplus

Ashish K Nayyar

void add()

{show();if(m==p&&n==q){

for(i=0;i<m;i++){for(j=0;j<q;j++){c[i][j]=a[i][j]+b[i][j];}}cout<<"\nAddition of Two Matrix:\n";for(i=0;i<m;i++){for(j=0;j<q;j++){cout<<c[i][j];}cout<<"\n";}}elsecout<<"addition not possible";

}voidmul(){show();if(n==p) {for(i=0;i<m;i++) {

for(j=0;j<q;j++) {c[i][j]=0;for(k=0;k<n;k++) {c[i][j]=c[i][j]+(a[i][k]*b[k][j]); } }

}cout<<"\nMultiplication of Matrix:\n";for(i=0;i<m;i++) {

for(j=0;j<q;j++){cout<<"\t "<<c[i][j];}

Page 22: cplusplus

Ashish K Nayyar

cout<<"\n"; } }elsecout<<"multiplication not possible";

}

void sub(){show();if(m==p&&n==q)

{for(i=0;i<m;i++){

for(j=0;j<q;j++){c[i][j]=a[i][j]-b[i][j];}

}cout<<"\nSubtraction of Matrix are:\n";for(i=0;i<m;i++){

for(j=0;j<q;j++){cout<<"\t"<<c[i][j];}

cout<<"\n";}}elsecout<<" Subtraction not possible";}

Page 23: cplusplus

Ashish K Nayyar

Page 24: cplusplus

Ashish K Nayyar

Page 25: cplusplus

Ashish K Nayyar

Lab No.2

Concept: Structures, Strings in c++

Objectives: To teach the concept of strings and make students learn how to write string functions To learn Structures and write efficient programs.

Pre Lab(Background):

Structures

C arrays allow you to define type of variables that can hold several data items of the same kind but structure is another user defined data type available in C programming, which allows you to combine data items of different kinds.

Structures are used to represent a record, Suppose you want to keep track of your books in a library. You might want to track the following attributes about each book:

Title Author Subject Book ID

Defining a Structure

To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member for your program. The format of the struct statement is this:

struct [structure tag]{ member definition; member definition; ... member definition;} [one or more structure variables];

The structure tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the structure's definition, before the final semicolon, you can specify one or more structure variables but it is optional. Here is the way you would declare the Book structure:

struct Books{ char title[50]; char author[50];

Page 26: cplusplus

Ashish K Nayyar

char subject[100]; int book_id;} book;

Accessing Structure Members

To access any member of a structure, we use the member access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that we wish to access. You would use struct keyword to define variables of structure type.

STRINGS

The string in C programming language is actually a one-dimensional array of characters which is terminated by a null character '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null.

The following declaration and initialization create a string consisting of the word "Hello". To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word "Hello."

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

If you follow the rule of array initialization then you can write the above statement as follows:

char greeting[] = "Hello";

Following is the memory presentation of above defined string in C/C++:

Actually, you do not place the null character at the end of a string constant. The C compiler automatically places the '\0' at the end of the string when it initializes the array. Let us try to print above mentioned string:

#include <stdio.h>

int main ()

Page 27: cplusplus

Ashish K Nayyar

{ char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

printf("Greeting message: %s\n", greeting );

return 0;}

When the above code is compiled and executed, it produces result something as follows:

Greeting message: Hello

C supports a wide range of functions that manipulate null-terminated strings:

S.N. Function & Purpose

1 strcpy(s1, s2);Copies string s2 into string s1.

2 strcat(s1, s2);Concatenates string s2 onto the end of string s1.

3 strlen(s1);Returns the length of string s1.

4 strcmp(s1, s2);Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.

5 strchr(s1, ch);Returns a pointer to the first occurrence of character ch in string s1.

6 strstr(s1, s2);Returns a pointer to the first occurrence of string s2 in string s1.

Lab Assignments:1. W AP to create a structure Student and add functions to read and show details. 2. W AP to find the length of a string.3. W AP to concatenate two strings using your defined Function.

Page 28: cplusplus

Ashish K Nayyar

Solutions to Lab No2.

Q-1 W AP to create a structure Student and add functions to read and show details.

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

struct student{char name[50];int roll;

};typedefstruct student stud;

studentreadval() {student d;cout<<"\nEnter information of student:\n";cout<<"\nEnter name: ";cin>>d.name;cout<<"Enter roll number: ";cin>>d.roll;return d; }

voidshowval(student s) {cout<<"\n\nDisplaying Information\n";cout<<"Name: "<<s.name;cout<<"\nRoll: "<<s.roll; }

void main() {inti,j,num;clrscr();student s[10];cout<<"How many students to be processed <max-10>: ";cin>>num;for(i=0;i<num;i++) {s[i]=readval(); }for(i=0;i<num;i++) {showval(s[i]); }

Page 29: cplusplus

Ashish K Nayyar

getch(); }

Page 30: cplusplus

Ashish K Nayyar

Q-2 W AP to find the length of a string.

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

intstringLength(char str[]);

void main(){charstr[100];int length;clrscr();cout<<"Enter the String : ";gets(str);

length = stringLength(str);

cout<<"Length of the String is : "<<length;getch();}

intstringLength(char str[]){intlen = 0;while(str[len]!='\0')len++;return(len);}

Page 31: cplusplus

Ashish K Nayyar

Q-3 W AP to concatenate two strings using your defined Function.

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

Void stringConcate(char str1[],char str2[]){inti=0,j=0;while(str1[i]!='\0')i++;while(str2[j]!='\0') {str1[i]=str2[j];j++;i++; }str1[i]='\0';cout<<"\nConcatenated String: "<<str1;}

void main(void){char s1[25],s2[25];clrscr();cout<<"\nEnter First String: ";gets(s1);cout<<"\nEnter Second String: ";gets(s2);stringConcate(s1,s2);getch();}

Page 32: cplusplus

Ashish K Nayyar

Lab No.3

Concept: Class, Constructor, Destructor, Default Parameter, Polymorphism – function overloading

Objective:

To teach the students basic OOPS concepts. To make student learn how to implement OOPS features via classes, objects, and

functions. To demonstrate implementation of Polymorphism.

Pre Lab(Background):

Lab Assignments:

1. W AP to show the working of a class Student add functions to read and show details.

2. W AP to define a class circle and add functions to perform following tasks. Read, display and calculate area.

3. W AP to overloaded function area ( ) for calculating the area of triangle and circle

4. W AP to create Student class and add constructors, other functions and destructor.

5. W AP a program to demonstrate constructor function overloading.

Page 33: cplusplus

Ashish K Nayyar

Solutions to Lab No3.

Q-1 W AP to show the working of a class Student add functions to read and show details.

#include<iostream.h>#include<conio.h>#include<string.h>#include<stdio.h>class student{private:int enroll;charsname[20];public:student() {enroll=10;strcpy(sname,"JAMES"); }

voidsetval(int e, char s[20]) {enroll=e;strcpy(sname,s); }

voidreadval() {cout<<"Enter enroll and name"<<endl;cin>>enroll;gets(sname); }

void show() {cout<<"\nEnrollment= "<<enroll<<endl;cout<<"Name= "<<sname<<endl<<endl; }};

void main(){clrscr();student s1;s1.show();s1.setval(10,"SCOTT");s1.show();s1.readval();s1.show();

Page 34: cplusplus

Ashish K Nayyar

getch();}

Page 35: cplusplus

Ashish K Nayyar

Q-2 W AP to define a class circle and add functions to perform following tasks. Read, display and calculate area.

#include<iostream.h>#include<conio.h>class Circle{private:

doubleradius,area;public:

Circle(){radius=0.0;area=0.0;}voidsetRadius(double r) {radius=r;cout<<"Radius: "<<radius<<endl; }voidreadval() {cout<<"Enter radius:";cin>>radius; }voiddisplay_Area() {area=radius*radius*(22.0/7);cout<<"The area of circle: "<<area<<endl; }

};void main(){ Circle c1,c2;clrscr();

c1.setRadius(5);

c1.display_Area();c2.readval();c2.display_Area();

getch();}

Page 36: cplusplus

Ashish K Nayyar

Page 37: cplusplus

Ashish K Nayyar

Q-3 W AP to overloaded function area ( ) for calculating the area of triangle and circle.

#include<iostream.h>#include<conio.h>#define PI 3.1415926536class function{private:

double radius,area1;intbase,height;

public:function(){radius=0.0; area1=0.0;base=0;height=0;}void area(double r) {radius=r; area1=PI*radius*radius;cout<<"The area of circle: "<<area1<<endl; }

void area(intb,int h) {base=b;height=h; area1=float(base*height)/2;cout<<"The area of triangle: "<<area1<<endl; }

};void main(){function f1,f2;clrscr();

f1.area(3.0);f2.area(3,7);

getch();}

Page 38: cplusplus

Ashish K Nayyar

Page 39: cplusplus

Ashish K Nayyar

Q-4 W AP to create Student class and add constructors, other functions and destructor.

#include<iostream.h>#include<conio.h>#include<string.h>#include<stdio.h>class student{private:int enroll;charsname[20];public:student() {enroll=20;strcpy(sname,"JAMES"); }

student(int e, char s[20]) {enroll=e;strcpy(sname,s); }

voidreadval() {cout<<"Enter enroll and name"<<endl;cin>>enroll;gets(sname); }

void show() {cout<<"\nEnrollment= "<<enroll<<endl;cout<<"Name= "<<sname<<endl<<endl; }

~student() {cout<<"destructor called"<<endl; }

};

void main(){clrscr();student s1,s2(21,"SCOTT");s1.show();

Page 40: cplusplus

Ashish K Nayyar

s2.show();s1.readval();s1.show();getch();

}

Page 41: cplusplus

Ashish K Nayyar

Q5 W AP a program to demonstrate constructor function overloading.

#include<iostream.h>#include<conio.h>class item{private:intm,n,o;public:item(){m=n=0;}item(int x){m=n=x;}item(intx,int y){m=x;n=y;}void show();};void item::show(){cout<<"m="<<m<<endl;cout<<"n="<<n<<endl;}void main(){item i1,i2(5),i3(10,20);clrscr();cout<<"value of m and n on calling default constructor"<<endl;i1.show();cout<<"value of m and n on calling one argument constructor"<<endl;i2.show();cout<<"value of m and n oncalling two argument constructor"<<endl;i3.show();getch();

}

Page 42: cplusplus

Ashish K Nayyar

Page 43: cplusplus

Ashish K Nayyar

Lab No.4

Concept: Polymorphism-Operator overloading

Objective:

To explain what is operator overloading and related benefits. To teach practical implementation of the same

Pre Lab(Background):

In C++ the overloading principle applies not only to functions, but to operators too. That is, of operators can be extended to work not just with built-in types but also classes. A programmer can provide his or her own operator to a class by overloading the built-in operator to perform some specific computation when the operator is used on objects of that class.

We need to design a member operator function that takes this general form:ret-type class-name::operator#(arg-list){// operations}

Lab Assignments:

1. W AP to create class DISTANCE and overload Binary + operator to add objects. Use member functions.

2. W AP to create class COMPLEX and overload Binary + operator to add objects. Use member functions.

3. W AP to create class COMPLEX and overload Binary + operator to add objects. Use friend functions.

4. WAP to overload binary < operator to compare two objects of user defined English Distance Class.

Page 44: cplusplus

Ashish K Nayyar

Solutions to Lab No4.

Q-1 W AP to create class DISTANCE and overload Binary + operator to add objects. Use member functions.

#include <iostream.h>#include<conio.h>class Distance {private:int feet;float inches;public:Distance()

{feet=0;inches=0.0;}

Distance(intft, float in){feet=ft;inches=in;}

voidgetdist(){cout<< "\nEnter feet: ";cin>> feet;cout<< "Enter inches: ";cin>> inches;}

voidshowdist() const {cout<< feet << "feet " << inches<<"inches"<<endl; }

Distance operator +(Distance ); };

Distance Distance::operator +(Distance d2) {int f = feet + d2.feet;floati = inches + d2.inches;if(i>= 12.0) {i -= 12.0;f++; }return Distance(f,i);

Page 45: cplusplus

Ashish K Nayyar

}void main() { Distance dist1(5,6.0), dist2(6,7.0), dist3;clrscr(); dist3 = dist1 + dist2;cout<<"dist1 = "; dist1.showdist(); cout<<endl;cout<<"dist2 = "; dist2.showdist(); cout<<endl;cout<<"dist3 = "; dist3.showdist(); cout<<endl;getch(); }

Page 46: cplusplus

Ashish K Nayyar

Q-2 W AP to create class COMPLEX and overload Binary + operator to add objects. Use member functions.

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

class complex{private:floatx,y;public:complex() { x=y=0.0; }complex(float f) { x=y=f; }complex(float f1,float f2) { x=f1; y=f2; }

void show() {cout<<"x="<<x<<endl;cout<<"y="<<y<<endl; }

complex operator +(complex ); };

complex complex::operator +(complex c) {complex t;t.x=x+c.x;t.y=y+c.y;return t; }

void main() { complex c1(4.0,6.0),c2(6.0,7.0),c3,c4(2.0),c5;clrscr(); c3=c1+c2;

Page 47: cplusplus

Ashish K Nayyar

c3.show(); c5=c1+c4;c5.show();getch(); }

Page 48: cplusplus

Ashish K Nayyar

Q-3 W AP to create class COMPLEX and overload Binary + operator to add objects. Use friend functions.

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

class complex{private:floatx,y;public:complex() { x=y=0.0; }complex(float f) { x=y=f; }complex(float f1,float f2) { x=f1; y=f2; }

void show() {cout<<"x="<<x<<endl;cout<<"y="<<y<<endl; }

friend complex operator +(complex & ,complex & ); };

complex operator +(complex &c1,complex &c2) {complex t;t.x=c1.x+c2.x;t.y=c1.y+c2.y;return t; }

void main() { complex c1(4.0,6.0),c2(6.0,7.0),c3,c4(2.0),c5;clrscr(); c3=c1+c2;

Page 49: cplusplus

Ashish K Nayyar

c3.show(); c5=c1+c4;c5.show();getch(); }

Page 50: cplusplus

Ashish K Nayyar

Q-4 WAP to overload binary < operator to compare two objects of user defined English Distance Class.

#include <iostream.h>#include<conio.h>class Distance {private:intfeet,inches;public:Distance()

{feet=0;inches=0;}

Distance(intf,inti){feet=f;inches=i;}

voidgetdist(){cout<< "\nEnter feet: ";cin>> feet;cout<< "Enter inches: ";cin>> inches;}

voidshowdist() const {cout<< feet << "-" << inches <<endl; }

friendint operator <(Distance & ,Distance & ); };

int operator <(Distance &d1,Distance &d2) {int l1,l2; l1=d1.feet*12+d1.inches; l2=d2.feet*12+d2.inches;if(l1<l2)return 1;elsereturn 0; }

Page 51: cplusplus

Ashish K Nayyar

void main() { Distance d1(5,6), d2(6,7);clrscr();

if(d1<d2)cout<<"d2 is larger";elsecout<<"d1 is larger";getch(); }

Page 52: cplusplus

Ashish K Nayyar

Lab No.5

Concept: Polymorphism-Operator overloading

Objective:

To explain what is operator overloading and related benefits. To teach practical implementation of the same

Pre Lab(Background):

Lab Assignments:

1. WAP to overload binary + operator to concatenate two objects of user defined class String.

2. WAP to overload binary +operator to add two objects of user defined Time class with data members HH MM SS.

3. W AP to show overloading of ++operator.4. W AP to show overloading of ( )operator.5. W AP to show overloading of [ ]operator.

Page 53: cplusplus

Ashish K Nayyar

Solutions to Lab No5.

Q-1WAP to overload binary + operator to concatenate two objects of user defined class String.

#include<iostream.h>#include<conio.h>#include<string.h>#include<process.h>#define SZ 80class String {private:charstr[SZ];public:String()

{strcpy(str," ");}

String( char s[] ){strcpy(str,s);}

void display() const {

cout<<str; } String operator +(String ss) {

String temp;if(strlen(str)+strlen(ss.str) < SZ ) {strcpy(temp.str, str);strcat(temp.str, ss.str); }else {cout<< "\nString overflow";exit(1); }

return temp; }};

void main() {

Page 54: cplusplus

Ashish K Nayyar

String s1 = " Hello!!"; String s2 = " How are you?";clrscr(); String s3;cout<<"String1: ";s1.display();cout<<endl;cout<<"String2: ";s2.display();cout<<endl; s3 = s1 + s2;cout<<"String3: ";s3.display();getch(); }

Page 55: cplusplus

Ashish K Nayyar

Q-2 WAP to overload binary +operator to add two objects of user defined Time class with data members HH MM SS.

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

class time{private:inthrs,min,sec;public:

time(){hrs=0;min=0;sec=0;}

time(inth,intm,int s){hrs=h;min=m;sec=s;}

voidgetdata(){cout<<"Enter hrs:";cin>>hrs;cout<<"Enter min:";cin>>min;cout<<"Enter sec:";cin>>sec;

while(sec>=60){sec=sec-60;min++;}

while(min>59){min=min-60;hrs++;}

Page 56: cplusplus

Ashish K Nayyar

}

void display(){cout<<hrs<<":"<<min<<":"<<sec<<endl;}

time operator +(time t1){time t2;t2.sec=sec+t1.sec;t2.min=min+t1.min;t2.hrs=hrs+t1.hrs;

if(t2.sec>=60){t2.sec-=60;t2.min++;}

if(t2.min>=60){t2.min-=60;t2.hrs++;}

return t2;}};

void main(){time time1,time2,time3;clrscr();

cout<<"Time1\n";time1.getdata();

cout<<"\nTime2\n";time2.getdata();

cout<<"\nTime1 is-> ";time1.display();

cout<<"Time2 is-> ";time2.display();

time3=time1+time2;

Page 57: cplusplus

Ashish K Nayyar

cout<<"\nTime3(Time1+Time2) is->\n";time3.display();getch();}

Page 58: cplusplus

Ashish K Nayyar

Q-3W AP to show overloading of ++operator.

#include<iostream.h>#include<conio.h>class Counter {private:unsignedint count;public:Counter()

{count=0;}

unsignedintget_count() {return count; } Counter operator ++ () { ++count; Counter temp;temp.count = count;return temp; } };

void main() { Counter c1, c2;clrscr();cout<< "\nc1=" << c1.get_count();cout<< "\nc2=" << c2.get_count();

c2 = ++c1;cout<< "\nc1=" << c1.get_count();cout<< "\nc2=" << c2.get_count() <<endl;getch(); }

Page 59: cplusplus

Ashish K Nayyar

Q-4W AP to show overloading of ( )operator.

#include<iostream.h>#include<conio.h>classloc{intlongitude,latitude;public:loc(){longitude=latitude=0;}loc(intlg, intlt){longitude = lg;latitude = lt;}void show(){cout<<"Longitude: "<<longitude<<endl;cout<<"Latitude: "<<latitude<<endl;}loc operator+(loc op2);loc operator()(inti, int j);};

locloc::operator()(inti, int j){longitude = i;latitude = j;return *this;}

locloc::operator+(loc op2){loc temp;temp.longitude = op2.longitude + longitude;temp.latitude = op2.latitude + latitude;return temp;}

int main(){loc ob1(10,20), ob2(1,1);clrscr();ob1.show();ob1(7,8);

Page 60: cplusplus

Ashish K Nayyar

ob1.show();ob1 = ob2+ob1(10,10);ob1.show();return 0;}

Page 61: cplusplus

Ashish K Nayyar

Q-5W AP to show overloading of [ ]operator.

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

classatype{private:int a[3];

public:atype(inti, int j, int k){a[0] = i;a[1] = j;a[2] = k;}int&operator[](inti){return a[i]; }};

void main(){atypeob(1, 2, 3);clrscr();cout<<"ob[1]: "<<ob[1]<<endl;ob[1] = 25;cout<<"ob[1]: "<<ob[1];getch();}

Page 62: cplusplus

Ashish K Nayyar

Lab No.6

Concept: Inheritance

Objective:

To teach the students the benefits of inheritance. To explain the use of public, private and protected specifier. To explain the concept of overriding and virtual functions. To explain the concept of abstract class and its applications.

Pre Lab(Background):

Inheritance is one of the cornerstones of OOP because it allows the creation of hierarchical classifications. Using inheritance, you can create a general class that defines traits common to a set of related items. This class may then be inherited by other, more specific classes, each adding only those things that are unique to the inheriting class. In keeping with standard C++ terminology, a class that is inherited is referred to as a base class. The class that does the inheriting is called the derived class. Further, a derived class can be used as a base class for another derived class. In this way, multiple inheritance is achieved.When a class inherits another, the members of the base class become members of thederived class. Class inheritance uses this general form:class derived-class-name : access base-class-name {// body of class};The access status of the base-class members inside the derived class is determined by access. The base-class access specifier must be either public, private, or protected. If no access specifier is present, the access specifier is private by default if the derived class is a class. If the derived class is a struct, then public is the default in the absence of an explicit access specifier. Let's examine the ramifications of using public or private access.Lab Assignments:

1. W AP to demonstrate the working of virtual function. 2. WAP to demonstrate the concept of Inheritance use person and student class for

the same

Page 63: cplusplus

Ashish K Nayyar

Solutions to Lab No6.

Q-1 Program that demonstrate the working of virtual function

#include<iostream.h>#include<conio.h>class base{public:virtual void func(){cout<<"This is base func()\n";}};class derived1:public base{public:voidfunc(){cout<<"This is derived1's func()\n";}};void main(){clrscr();base b,*bp;derived1 d1;bp=&b;bp->func();bp=&d1;bp->func();

1. getch();}

Page 64: cplusplus

Ashish K Nayyar

Q-2 WAP to demonstrate the concept of Inheritance use person and student class for the same

Page 65: cplusplus

Ashish K Nayyar

Lab No.7

Concept: Exception Handling

Objective:

To make student understand the real purpose of exception handling. To teach students to apply exception handling mechanism in coding.

Pre Lab(Background):

C++ exception handling is built upon three keywords: try, catch, and throw. In the most general terms, program statements that you want to monitor for exceptions are contained in a try block. If an exception (i.e., an error) occurs within the try block, it is thrown (using throw). The exception is caught, using catch, and processed. The following discussion elaborates upon this general description. Code that you want to monitor for exceptions must have been executed from within a try block. (Functions called from within a try block may also throw an exception.) Exceptions that can be thrown by the monitored code are caught by a catch statement, which immediately follows the try statement in which the exception was thrown. The general form of try and catch are shown here.try {// try block}catch (type1 arg) {// catch block}catch (type2 arg) {// catch block}catch (type3 arg) {// catch block}...catch (typeN arg) {// catch block}The try can be as short as a few statements within one function or as all encompassing as enclosing the main( ) function code within a try block (which effectively causes the entire program to be monitored).Lab Assignments:

1. W AP to implement a class Stack that throws Overflow and Underflow Exceptions.

2. W AP to implement a class Customer that throws Negative Balance Exceptions.

Page 66: cplusplus

Ashish K Nayyar

Solutions to Lab No7.

Q-1 W AP to implement a class Stack that throws Overflow and Underflow Exceptions.

#include<iostream.h>#include<conio.h>#include<except.h>class overflow{};class underflow{};class stack{private:int a[5], top;public:stack() {top=-1; }void push(inti) {

if(top==4){throw overflow();}else{a[++top]=i;}}void pop(){

if(top==-1){

throw underflow();}

else{

cout<<a[top--]; }

}};

void main(){

stack s;try

{s.push(3);s.push(4);s.push(5);

Page 67: cplusplus

Ashish K Nayyar

s.push(6);s.push(7);

s.pop();s.pop();s.pop();s.pop();s.pop();}

catch(overflow of){

cout<<"overflow stack"; }

catch(underflow uf) {cout<<"underflow stack";

}getch(); }

Q-2 W AP to implement a class Customer that throws Negative Balance Exceptions.

Page 68: cplusplus

Ashish K Nayyar

Lab No.8

Concept: Template function and classes

Objective:

To teach the students the implementation of Generic functions and classes and their by reducing the code size.

Pre Lab(Background):

Generic Function

A generic function defines a general set of operations that will be applied to various types of data. The type of data that the function will operate upon is passed to it as a parameter. Through a generic function, a single general procedure can be applied to a wide range of data. As you probably know, many algorithms are logically the same no matter what type of data is being operated upon. For example, the Quicksort sorting algorithm is the same whether it is applied to an array of integers or an array of floats. It is just that the type of the data being sorted is different. By creating a generic function, you can define the nature of the algorithm, independent of any data. Once you have done this, the compiler will automatically generate the correct code for the type of data that is actuallyused when you execute the function. In essence, when you create a generic function you are creating a function that can automatically overload itself. A generic function is created using the keyword template. The normal meaning of the word "template" accurately reflects its use in C++. It is used to create a template (or framework) that describes what a function will do, leaving it to the compiler to fill in the details as needed. The general form of a template function definition is shown here:template <class Ttype> ret-type func-name(parameter list){// body of function}Here, Ttype is a placeholder name for a data type used by the function. This name may be used within the function definition. However, it is only a placeholder that the compiler will automatically replace with an actual data type when it creates a specific version of the function. Although the use of the keyword class to specify a generic type in a template declaration is traditional, you may also use the keyword typename.Lab Assignments:

1. W AP to implement template function that interchanges two data values.2. W AP to implement a generic class Stack, add necessary constructors and other

functions

Page 69: cplusplus

Ashish K Nayyar

Solutions to Lab No8.

Q-1 Program that implements template function that interchange two data values.

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

template<class T1,class T2>void swap(T1 &a,T2 &b){T1 temp;temp=a;a=b;b=temp;cout<<"\nInside template function\n";}

void swap(int&a,int&b){int temp;temp=a;a=b;b=temp;cout<<"\nInside overloaded swap\n";}

void main(){inti=10,j=20;char x='a',y='b';clrscr();cout<<"original x,y: "<<x<<" "<<y<<endl;cout<<"original i,j: "<<i<<" "<<j<<endl;swap(i,j);cout<<"swapped i,j: "<<i<<" "<<j<<endl;swap(x,y);cout<<"swapped x,y: "<<x<<" "<<y<<endl;getch();

}

Page 70: cplusplus

Ashish K Nayyar

Page 71: cplusplus

Ashish K Nayyar

Q-2 W AP to implement a generic class Stack, add necessary constructors and other functions.

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

class overflow{ };class underflow{ };

template<class T> class stack{

private:

int top;T s[3];

public:stack(){

top=-1;}void push(T );T pop();

};

template<class T> void stack<T> :: push(T item){

if(top==2)throw overflow();

else{

top++;s[top]=item;cout<<"\n Item "<<item<<" is pushed";

}}

template<class T> T stack<T> :: pop(){

T item;if(top==-1)

throw underflow();else{

item=s[top];top--;

Page 72: cplusplus

Ashish K Nayyar

return item;}

}

void main(){

stack<int>s1;intnum;charch;float f;clrscr();try{

s1.push(20);s1.push(50);s1.push(70);s1.push(30);

f=s1.pop();cout<<"\nvalue is popped :"<<f;num=s1.pop();cout<<"\n value is popped :"<<num;ch=s1.pop();cout<<"\n value is popped :"<<ch;ch=s1.pop();

}catch(overflow o){

cout<<"\n\n Overflow stack";}catch(underflow u){

cout<<"\n\n Underflow stack";}getch();

}

Page 73: cplusplus

Ashish K Nayyar

Lab No.9

Concept: File Handling and Stream Class Hierarchy

Objective:

To teach students various classes and function involved in file read and write operations.

To make students design real life software.

Pre Lab(Background):

To perform file I/O, you must include the header <fstream> in your program. Itdefines several classes, including ifstream, ofstream, and fstream. These classes arederived from istream, ostream, and iostream, respectively. Remember, istream,ostream, and iostream are derived from ios, so ifstream, ofstream, and fstream alsohave access to all operations defined by ios (discussed in the preceding chapter).Another class used by the file system is filebuf, which provides low-level facilities tomanage a file stream. Usually, you don't use filebuf directly, but it is part of the otherfile classes

.

Lab Assignments:

1. W AP that reads a text file. 2. W AP that writes paragraph to a text file.3. W AP that writes Student records to a data file.

Page 74: cplusplus

Ashish K Nayyar

4. WAP that uses file pointer to display any arbitrary record from an pre existing file.

5. W AP that writes Student records to a data file. Read records based on name entered

Page 75: cplusplus

Ashish K Nayyar

Solutions to Lab No9.

Q-1 W AP that reads a text file.

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

int main(){ifstream fin;clrscr();

fin.open("out.txt");charch;

while(!fin.eof()) {fin.get(ch);cout<<ch; }

fin.close();getch();return 0;}

Page 76: cplusplus

Ashish K Nayyar

Q-2 W AP that writes paragraph to a text file.

#include<fstream.h>#include<conio.h>void main(){ofstreamfout;

clrscr();fout.open("out.txt");

charstr[300]="C++ provides the following classes to perform output and input of characters to/from files:\nofstream: Stream class to write on files\nifstream: Stream class to read from files\nfstream: Stream class to both read and write from/to files.\n ";

fout<<str;

cout<<"File written successfully!!";

fout.close();

getch(); }

Page 77: cplusplus

Ashish K Nayyar

Q-3 W AP that writes Student records to a data file.

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

class stud{

private:intrno;char *name;

public:stud(){

rno=0;strcpy(name,"NO_name");

}stud(intr,char *n){

rno=r;strcpy(name,n);

}

void show();void read();

};

void stud::show(){cout<<"Roll no: "<<rno<<endl;cout<<"Name: "<<name<<endl;}

void stud::read(){

cout<<"\nEnter the roll no :";cin>>rno;cout<<"\nEnter the name :";gets(name);

}

void main()

Page 78: cplusplus

Ashish K Nayyar

{stud s[3];inti;clrscr();fstreamfp;fp.open("student.dat",ios::binary|ios::out);cout<<"Enter the details of students to be written onto the data file student.dat:";for(i=0;i<=2;i++){s[i].read();fp.write((char*)&s[i],sizeof(stud));}fp.close();fp.open("student.dat",ios::binary|ios::in);cout<<"\nRecords stored in student.dat :\n";for(i=0;i<=2;i++){fp.read((char*)&s[i],sizeof(stud));s[i].show();}fp.close();getch();}

Q-4 WAP that uses file pointer to display any arbitrary record from an pre existing file.

Page 79: cplusplus

Ashish K Nayyar

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

class stud{

private:intrno;char *name;float per;

public:stud(){

rno=0;strcpy(name,"NO_name");per=0.0;

}stud(intr,char *n,floatpr){

rno=r;strcpy(name,n);per=pr;

}

void show();void read();voidcmpname(char *);

};

void stud::show(){cout<<"Roll no: "<<rno<<endl;cout<<"Name: "<<name<<endl;cout<<"Percentage: "<<per<<endl;}

void stud::read(){

cout<<"\nEnter the roll no :";cin>>rno;cout<<"Enter the name :";gets(name);cout<<"Enter percentage:";cin>>per;

Page 80: cplusplus

Ashish K Nayyar

}

void main(){stud s[3],p;intnor,pos,i,n;clrscr();fstreamfp;fp.open("student.dat",ios::binary|ios::out);cout<<"Enter the details of students to be written onto the data file student.dat:";for(i=0;i<=2;i++){s[i].read();fp.write((char*)&s[i],sizeof(stud));}fp.close();fp.open("student.dat",ios::binary|ios::in);fp.seekg(0,ios::end);pos=fp.tellg();nor=pos/sizeof(stud);cout<<"\nNO OF RECORDS IN THE FILE student.dat: "<<nor<<endl<<endl;cout<<"Enter record no: ";cin>>n;pos=(n-1)*sizeof(stud);fp.seekg(pos,ios::beg);fp.read((char*)&p,sizeof(stud));p.show();fp.close();getch();}

Page 81: cplusplus

Ashish K Nayyar

Page 82: cplusplus

Ashish K Nayyar

Q-5 W AP that writes Student records to a data file. Read records based on name entered.

#include<iostream.h>#include<fstream.h>#include<conio.h>#include<string.h>#include<stdio.h>class stud{

private:intrno;char *name;

public:stud(){

rno=0;strcpy(name,"NO_name");

}

stud(intr,char *n){

rno=r;strcpy(name,n);

}

void show();void read();voidcmpname(char *);

};

void stud::show(){cout<<rno;cout<<name;}

void stud::read(){

cout<<"\nEnter roll no :";cin>>rno;cout<<"\nEnter the name :";gets(name);

}

Page 83: cplusplus

Ashish K Nayyar

void stud::cmpname(char *nm){

if(strcmp(nm,name)==0){

cout<<rno;cout<<"\t"<<name<<endl;

}}

void main(){inti;char *name=" ";stud s[3];clrscr();

fstreamfp;fp.open("student.dat",ios::binary|ios::out);

for(i=0;i<=2;i++){s[i].read();fp.write((char*)&s[i],sizeof(stud));}

for(i=0;i<=2;i++){fp.read((char*)&s[i],sizeof(stud));}cout<<"\nEnter name to be search :\n";gets(name);

cout<<"Rollno\tName "<<endl;for(i=0;i<=2;i++){s[i].cmpname(name);}

fp.close();getch();}

Page 84: cplusplus

Ashish K Nayyar

Page 85: cplusplus

Ashish K Nayyar

Lab No.10

Concept: Friend function and static

Objective:

Pre Lab (Background):

To teach students the application of friend and static keywords

Lab Assignments:

1. Friend function as a bridge between two classes rupee and dollar2. Static data member and member function

Page 86: cplusplus

Ashish K Nayyar

Solutions to Lab No10.

Q-1 Friend function as a bridge between two classes rupee and dollar

#include<iostream.h>#include<conio.h>class dollar;class rupee{private:int r;public:rupee(){r=0;}rupee(inti){r=i;}voidsetrs(inti){cout<<"RUPEES : Rs"<<i<<endl;r=i;}voiddisplayrs(){cout<<"RUPEES : Rs"<<r<<endl;}

friend void convertdtr(rupee &r,dollar&d);friend void convertrtd(dollar &d,rupee&r);

};

class dollar{private:int d;public:dollar(){d=0;}dollar(inti){d=i;}voidsetdl(inti){cout<<"DOLLAR : $"<<i<<endl;d=i;}voiddisplaydl(){cout<<"DOLLAR : $"<<d<<endl;}

friend void convertdtr(rupee &r,dollar&d);friend void convertrtd(dollar &d,rupee&r);};

Page 87: cplusplus

Ashish K Nayyar

voidconvertdtr(rupee &rs,dollar&dl){rs.r=dl.d*55;}voidconvertrtd(dollar &ds,rupee&rs){ds.d=rs.r/55.0;}void main(){rupee r1;dollar d1;clrscr();cout<<"CONVERTING RUPEES TO DOLLAR"<<endl;r1.setrs(110);convertrtd(d1,r1);d1.displaydl();cout<<"CONVERTING DOLLAR TO RUPEES"<<endl;d1.setdl(5);convertdtr(r1,d1);r1.displayrs();getch();}

Page 88: cplusplus

Ashish K Nayyar

Q-2 Static data member and member function

#include<stdio.h>#include<conio.h>#include<iostream.h>classstdata{private:inti;staticint j;public:stdata() {i=0; j=0; }void set(inta,int b) {i=a; j=b; }static void show(stdata&m) {cout<<"i= "<<m.i<<endl;cout<<"static j="<<j<<endl; } };intstdata::j;void main(){stdata s1,s2;clrscr();cout<<"initialising class data member using object s1"<<endl;s1.set(10,20);cout<<"passing object s1 as parameter to static void show()"<<endl;s1.show(s1);cout<<"initialising class data member using object s1"<<endl;s1.set(30,60);cout<<"passing object s1 as parameter to static void show()"<<endl;s1.show(s1);cout<<"passing object s2 as parameter to static void show()"<<endl;s1.show(s2);getch();}

Page 89: cplusplus

Ashish K Nayyar