Ex No.2a PROGRAM USING OPERATOR OVERLOADING
7-8-10
AIM:
To write a c++ program to perform arithmetic operations like addition, subraction, multiplication and division of two complex no.s using operator overloading,
ALGORTHIM:
Step 1:Start the program.
Step 2:In order to perform the basic arithmetic operation like addition, subraction, multiplication and division of two complex no.s using operator overloading function.
Step 3:Call the operator overloading function '+','-','*','/' operators to perform addition,subraction,multiplication and division of two complex no.s and display the results respectively.
Step 4:Stop the program.
PROGRAM:
#include<iostream.h>
#include<conio.h>
class complex
{
float x;float y;
public:
complex(){}
complex(float real,float imag)
{x=real;y=imag}
complex operator+(complex c);
complex operator-(complex c);
complex operator*(complex c2);
complex operator/(complex c2);
void display(void);
};
void complex::display(void)
{
cout<<x<<"+j"<<y;
};
complex complex::operator+(complex c)
{
complex temp;
temp.x=x+c.x;
temp.y=y+c.y;
return temp;
}
complex complex::operator-(complex c)
{
complex temp;
temp.x=x-c.x;
temp.y=y-c.y;
return temp;
}
complex complex::operator*(complex c2)
{
complex temp;
temp.x=x*2.x-y*c2.y;
temp.y=x*2.y+y*c2.x;
return temp;
}
complex complex::operator/(complex c2)
{
complex temp;
float d;
d=c2.x*c2.x+c2.y*c2.y;
temp.x=(x*c2.y+y*c2.y)/d;
temp.y=(y*c2.x-x*c2.y)/d;
return temp;
}
int main()
{
complex c1,c2,c3;
c1=complex(3.1,5.1);
c2=complex(6.2,7.1);
clrscr();
cout<<"c1:";c1.display();
cout<<"c2:";c2.display();
c3=c1+c2;cout<<"\n sum:"c3.display();
c3=c1-c2;cout<<"\n difference:";c3.display();
c3=c1*c2;cout<<"\n product:";c3.display();
c3=c1/c2;cout<<"\n division:";c3.display();
getch();
return 0;
}
RESULT:Thus a c++ program for performing arithmetic operation of two complex no. using operator overloading is executed and verified successfully.