C++ program to perform arithmatic operations on complex numbers

, by Prashant Gunjal

Design a Class ‘Complex ‘ with data members for real and imaginary part. Provide default and parametrized constructors.Write a program to perform arithmetic operations of two complex numbers using operator overloading (using either member functions or friend functions).


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

class comp
{
private:
int r,i;
public:
comp()
{
r=i=0;
}
void create();
void display();
comp operator+(comp c2);
comp operator-(comp c2);
comp operator*(comp c2);
};
void comp::create()
{
cout<<"\nEnter real part=>";
cin>>r;
cout<<"\nEnter imaginary part=> ";
cin>>i;
}
void comp::display()
{
cout<<"\n\tno =>"<<r<<"+"<<i<<"i";
}
comp comp::operator+(comp c2)
{
comp c3;
c3.r=r+c2.r;
c3.i=i+c2.i;
return c3;
}
comp comp::operator*(comp c2)
{
comp c3;
c3.r=r*c2.r;
c3.i=i*c2.i;
return c3;
}
comp comp::operator-(comp c2)
{
comp c3;
c3.r=r-c2.r;
c3.i=i-c2.i;
return c3;
}

void main()
{
clrscr();
comp c1,c2,add,sub,mul;
cout<<"\nEnter no1=>";
c1.create();
cout<<"\nEnter no2=>";
c2.create();
cout<<"\nYour c1";
c1.display();
cout<<"\nYour c2";
c2.display();
add=c1+c2;
cout<<"\nAddition";
add.display();
sub=c1-c2;
cout<<"\nSubtraction";
sub.display();
mul=c1*c2;
cout<<"\nMultiplication";
mul.display();
getch();
}

OUTPUT :

Enter no1=>
Enter real part=>12

Enter imaginary part=> 13

Enter no2=>
Enter real part=>14

Enter imaginary part=> 15

Your c1
        no =>12+13i
Your c2
        no =>14+15i
Addition
        no =>26+28i
Subtraction
        no =>-2+-2i
Multiplication
        no =>168+195i

0 comments: