IMPLEMENTATION OF COMPLEX NUMBER OPERATIONS USING OPERATOR OVERLOADING
AIM :
To write a C++ program to implement the complex number operations using operator overloading.
ALGORITHM:
Step 1: Start the process
Step 2: Create a class complex with real and imaginary data members.
Step 3: A parameterized constructor is used here for initializing real and
imaginary data members during object creation.
Step 4: The operators such as +, -,* and / are overloaded.
Step 5: In the main function the complex number operations are done with the
help of overloaded operators.
Step 6: The result is displayed.
Step 7: Stop the process.
PROGRAM:
#include <math.h>
#include <iostream.h>
#include <iomanip.h>
#include<conio.h>
class complex
{
private:
float real; // Real Part
float imag; // Imaginary Part
public:
complex(float,float);
complex operator +(complex);
complex operator -(complex);
complex operator *(complex);
complex operator /(complex);
void printdata();
};
// CONSTRUCTOR
complex::complex(float r=0.0f,float im=0.0f)
{
real=r;
imag=im;
}
complex complex::operator +(complex c)
{
complex tmp=c;
tmp.real=this->real+tmp.real;
tmp.imag=this->imag+tmp.imag;
return tmp;
}
complex complex::operator -(complex c)
{
complex tmp=c;
tmp.real=this->real - tmp.real;
tmp.imag=this->imag - tmp.imag;
return tmp;
}
complex complex::operator *(complex c)
{
complex tmp=c;
tmp.real=(real*tmp.real)-(imag*tmp.imag);
tmp.imag=(real*tmp.imag)+(imag*tmp.real);
return tmp;
}
complex complex::operator /(complex c)
{
complex tmp=c;
float res= (imag*tmp.real)-(real*tmp.imag);
float div=(tmp.real*tmp.real)+(tmp.imag*tmp.imag);
tmp.real=(real*tmp.real)+(imag*tmp.imag);
tmp.real/=div;
tmp.imag= res;
tmp.imag/=div;
return tmp;
}
void complex::printdata()
{
cout<<real<<" + ("<<imag<<")j\n";
}
void main()
{
complex c1(5,3),c2(3,2),c3; // Calls Constructor
clrscr();
c3=c1+c2; // Calls overloaded +
cout<<"\nComplex addition:\n";
c1.printdata();
c2.printdata();
c3.printdata();
cout<<"\nComplex subtraction:\n";
c3=c1-c2; // Calls overloaded -
c1.printdata();
c2.printdata();
c3.printdata();
cout<<"\nComplex multiplication:\n";
c3=c1*c2; // Calls overloaded *
c1.printdata();
c2.printdata();
c3.printdata();
cout<<"\nComplex division:\n";
c3=c1/c2; // Calls overloaded /
c1.printdata();
c2.printdata();
c3.printdata();
getch();
}
OUTPUT:
Complex addition:
5 + (3)j
3 + (2)j
8 + (5)j
Complex subtraction:
5 + (3)j
3 + (2)j
2 + (1)j
Complex multiplication:
5 + (3)j
3 + (2)j
9 + (37)j
Complex division:
5 + (3)j
3 + (2)j
1.615385 + (-0.076923)j
RESULT:
Thus the program to implement the complex number operations using operator overloading.
0 comments:
Post a Comment