C++ Programming
Slip2
Q.1) Write a C++ program using class which contains two data members of type integer.
Create and initialize the object using default constructor, parameterized constructor and
parameterized constructor with default value. Write a member function to display
maximum from given two numbers for all objects. [Marks 15]
Solution
#include<iostream.h>
#include<conio.h>
class max
{
private:
int x,y;
public:
max()
{
x=0;
y=0;
}
void display()
{ if(x>y)
cout<<"\nX greater. nunber is "<<x;
else
cout<<"\nY greater. number is "<<y;
}
max(int a,int b)
{
x=a;
y=b;
}
max(int q,int p=5)
{
x=q;
y=p;
}
};
int main()
{
max m;
m.display();
max m1(2,10);
m1.display();
max m2(8);
m2.display();
getch();
return 0;
}
Output
Y greater. number is 0
Y greater. number is 10
X greater. nunber is 8
Q.2) Create a class ComplexNumber containing members as:
- real
- imaginary
Write a C++ program to calculate and display the sum of two complex numbers. (Use
friend function and return by object) [Marks 25]
Solution
#include<iostream.h>
#include<conio.h>
class Complex
{
float real;
float imaginary;
public:
Complex(){};
Complex(float x,float y)
{
real=x;
imaginary=y;
}
void disp()
{
cout<<real<<"+i"<<imaginary<<"\n";
}
Complex operator +(Complex );
};
Complex Complex:: operator +(Complex c1)
{
Complex tmp;
tmp.real=real+c1.real;
tmp.imaginary=imaginary+c1.imaginary;
return tmp;
}
int main()
{
clrscr();
Complex c1,c2,c3;
c1=Complex(2.5,3.5);
c2=Complex(1.5,4.5);
c3=c1+c2;
cout<<"\nFirst complex number:"<<"\n";
c1.disp();
cout<<"\n Second complex number:"<<"\n";
c2.disp();
cout<<"\nAddition of two complex numbers:"<<"\n";
c3.disp();
getch();
return(0);
}
Output
First complex number:
2.5+i3.5
Second complex number:
1.5+i4.5
Addition of two complex numbers:
4+i8
Tags:
c++