You are on page 1of 4

// IMPLEMENTATION OF ARITHMETIC OPERATIONS ON COMPLEX

NUMBERS USING CONSTRUCTOR OVERLOADING.

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

class complex
{
int re;
float im;
public:
complex()
{
re = 0;
im = 0.0;
}
complex(int x)
{
re = x;
im = 0.0;
}
complex(int x, float y)
{
re = x;
im = y;
}
void display(void);
complex operator+(complex);
complex operator-(complex);
complex operator*(complex);
complex operator/(complex);
};

void complex::display(void)
{
if(im>=0)
cout<<"\t"<<re<<"+i("<<im<<")\n";
else
cout<<"\t"<<re<<"-i("<<im<<")\n";
}

complex complex::operator+(complex c2)


{
complex sum;
sum.re=re+c2.re;
sum.im=im+c2.im;
return(sum);
}

complex complex::operator-(complex c2)


{
complex sub;
sub.re=re-c2.re;
sub.im=im-c2.im;
return(sub);
}

complex complex::operator*(complex c2)


{
complex pro;
pro.re=((re*c2.re)-(im*c2.im));
pro.im=((re*c2.im)+(im*c2.re));
return(pro);
}

complex complex::operator/(complex c2)


{
complex div;
float d;
d=((c2.re*c2.re)+(c2.im*c2.im));
div.re=((re*c2.re)+(im*c2.im))/d;
div.im=((re*c2.re)-(im*c2.re))/d;
return(div);
}

void main()
{
clrscr();
complex c1, c;
complex c2(10);
complex c3(15, 10.5);
complex c4(5, 5);
cout<<"\nc1";c1.display();
cout<<"\nc2";c2.display();
cout<<"\nc3";c3.display();
cout<<"\nc4";c4.display();
cout<<"\nresult";c.display();
c=c1+c2;
cout<<"\nresult of addition is \n";
cout<<"result";c.display();
c= c3-c2;
cout<<"\nresult of subtraction is \n";
cout<<"result";c.display();
c=c3*c2;
cout<<"\nresult of product is \n";
cout<<"result";c.display();
c=c3/c4;
cout<<"\nresult of division is \n";
cout<<"result";c.display();
getch();
}
SAMPLE INPUT AND OUTPUT:

c1 0+i(0)

c2 10+i(0)

c3 15+i(10.5)

c4 5+i(5)

result 0+i(0)

result of addition is
result 10+i(0)

result of subtraction is
result 5+i(10.5)

result of product is
result 150+i(105)

result of division is
result 2+i(0.45)

RESULT:

Thus the C++ program for using operator overloading-binary operator has been
executed successfully and output verified.