Write a Complex class with following operations:
parameterized constructor
addition, subtraction, multiplication of 2 complex numbers
conjugate of complex number.
Source code :
#include <iostream>
using namespace std;
class complex{
private:
int real,imaginary;
public:
complex(){
real=1,imaginary=1;
}
complex(int a, int b){
real=a;
imaginary=b;
}
complex add(complex &co){
complex c;
c.real=real+co.real;
c.imaginary=imaginary+co.imaginary;
return c;
}
complex sub(complex &co){
complex c;
c.real=real-co.real;
c.imaginary=imaginary-co.imaginary;
return c;
}
complex mul(complex &co){
complex c;
c.real=(real*co.real)-(imaginary*co.imaginary);
c.imaginary=real*co.imaginary+co.real*imaginary;
return c;
}
void conjugate(complex &co){
co.imaginary=-co.imaginary;
}
void show(){
if(imaginary>=0){
cout<<real<<'+'<<imaginary<<'i'<<endl;
}
else if(imaginary<0){
cout<<real<<imaginary<<'i'<<endl;
}
}
};
int main(){
complex c1(5,1),c2(2,-4);
cout<<"The first complex number is: ";
c1.show();
cout<<"The second complex number is: ";
c2.show();
cout<<"The sum of the two complex numbers is: ";
complex c;
c=c1.add(c2);
c.show();
cout<<"The difference between the two complex numbers is: ";
c=c1.sub(c2);
c.show();
cout<<"The product of the two complex numbers is: ";
c=c1.mul(c2);
c.show();
cout<<"The conjugate of the first complex number is: ";
c.conjugate(c1);
c1.show();
cout<<"The conjugate of the second complex number is: ";
c.conjugate(c2);
c2.show();
return 0;
}
0 Comments
Post a Comment