Slip24
Q.1) Create a
C++ class Sumdata to perform following functions:
int sum( int, int) – returns the
addition of two integer arguments.
float sum(flaot, float, float) –
returns the addition of three float arguments.
int sum( int [ ] ,int) – returns the
sum of all elements in an array of size ‘n’.
#include<stdio.h>
#include<conio.h>
#include<iostream.h>
class sumdata
{
public:
void sum(int a,int b)
{
int c;
c=a+b;
cout<<"\n Addition = "<<c;
}
void sum(float a,float b,float c)
{
float d;
d=a+b+c;
cout<<"\n Addition = "<<d;
}
void sum(int a[],int n)
{
int sum=0;
for(int i=0;i<n;i++)
{
sum=sum+a[i];
}
cout<<"sum="<<sum;
}
void accept(int a[],int n)
{
int sum=0;
cout<<"enter elements";
for(int i=0;i<n;i++)
{
cin>>a[i];
}
}
};
void main()
{
int a,b,j,k[19];
sumdata ob;
float x,y,z;
clrscr();
cout<<"\n Enter 2 numbers";
cin>>a;
cin>>b;
ob.sum(a,b);
cout<<"\n How many numbers you want to enter";
cin>>j;
ob.accept(k,j);
ob.sum(k,j);
cout<<"\n Enter 3 float values";
cin>>x;
cin>>y;
cin>>z;
ob.sum(x,y,z);
getch();
}
Q.2) Write a C++ program to create two
classes Class1 and Class2. Each class contains one float data member. Write following functions:
- To accept float numbers
- To display float numbers in right justified format with precision of two digits
- To Exchange the private values of both these classes by using Friend function.
#include<iostream.h>
#include<conio.h>
class
class2;
class
class1
{
float
value1;
public:
void
indata(float a) {value1=a;}
void
display(void) {cout<<value1<<"\n";}
friend
void exchange(class1 &,class2 &);
};
class
class2
{
float
value2;
public:
void
indata(float b) {value2=b;}
void
display(void) {cout<<value2<<"\n";}
friend
void exchange(class1 &,class2 &);
};
void
exchange(class1 &x,class2 &y)
{
int
temp;
temp=x.value1;
x.value1=y.value2;
y.value2=temp;
}
int
main()
{
clrscr();
class1
C1;
class2
C2;
C1.indata(6.7847);
C2.indata(12.4514);
cout<<"\nValues
Before Exchange.\n";
cout.precision(2);
cout.setf(ios::right,ios::adjustfield);
C1.display();
C2.display();
exchange(C1,C2);
cout<<"\nValues
After Exchange.\n";
C1.display();
C2.display();
getch();
return
0;
}
Another way
#include<iostream.h>
#include<conio.h>
class class2;
class class1
{
float val1;
public:
void get(float a)
{
cout.precision(2);
val1=a;
}
void display(void)
{
cout.width(20);
cout<<val1<<"\n";
cout.setf(ios::right, ios::adjustfield);
}
friend void exchange(class1 &, class2 &);
};
class class2
{
float val2;
public:
void get(float a)
{
cout.precision(2);
val2=a;
}
void display(void)
{
cout.width(20);
cout<<val2<<"\n";
cout.setf(ios::right, ios::adjustfield);
}
friend void exchange(class1 &, class2 &);
};
void exchange(class1 & x, class2 & y)
{
float temp=x.val1;
x.val1=y.val2;
y.val2=temp;
}
void main()
{
class1 c1;
class2 c2;
clrscr();
c1.get(14.444);
c2.get(27.777);
cout<<"Values before exchange\n";
c1.display();
c2.display();
exchange(c1,c2);
cout<<"Values after exchange\n";
c1.display();
c2.display();
getch();
}