Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

ComplexNum

/* C++ program to find sum, subtraction, multiplication, divison


magnitude, conjugate of complex numbers with Operator overloading
*/

#include <iostream>
#include<cmath>
using namespace std;

class Complex {
private:
double real;
double imag;

public:
// Constructor to initialize real and imag to 0
Complex() : real(0), imag(0) {}

void input() {
cout << "Enter real and imaginary parts respectively: "<<endl;
cin >> real;
cin >> imag;
}

// Overload the + operator


Complex operator + (const Complex& obj) {
Complex temp;
temp.real = real + obj.real;
temp.imag = imag + obj.imag;
return temp;
}
Complex operator - (const Complex& obj){
Complex temp;
temp.real=real-obj.real;
temp.imag=imag-obj.imag;
return temp;
}
// friend function for multiplication
friend Complex operator * ( Complex z1, Complex z2 );

Page 1/4
ComplexNum

//Friend function for division

friend Complex operator / (Complex z1, Complex z2);

// Conjugate of Complex Number


void Conjugate1(Complex z1){
real=z1.real;
imag= -1 * z1.imag;

}
void Conjugate2(Complex z2){
real=z2.real;
imag= -1 * z2.imag;

// Function to find absolute value of complex numbers

void FindModulus(){

cout<<sqrt(real*real+imag*imag);

// Function to display complex numbers;


void output() {
if (imag < 0)
cout <<real << imag << "i";
else if(imag==0){
cout<<real;
}

else

cout << real << "+" << imag << "i";


}

Page 2/4
ComplexNum

};

// Multiplication of Complex numbers


Complex operator * (Complex z1,Complex z2){
Complex temp;

temp.real=z1.real*z2.real -z1.imag*z2.imag;
temp.imag=z1.real*z2.imag + z1.imag* z2.real;
return temp;
}

// Division
Complex operator / (Complex z1,Complex z2){
Complex temp;
temp.real = ((z1.real * z2.real) + (z1.imag * z2.imag)) /
(z2.real * z2.real + z2.imag * z2.imag);
temp.imag = ((z1.imag * z2.real) - (z1.real * z2.imag)) /
(z2.real * z2.real + z2.imag * z2.imag);

return temp;
}

int main() {
Complex z1, z2, result;

cout << "Enter first complex number:\n";


z1.input();

cout <<"Enter second complex number:\n";


z2.input();

cout<<"Sum of Complex numbers is: ";

result = z1 + z2;
result.output();
cout<<endl;

//Subtraction

Page 3/4
ComplexNum

cout<<"\nSubtraction of Complec Numbers is : ";


result=z1 - z2;
result.output();
cout<<endl;

cout<<"\nMultiplication of Complex numbers: ";


result=z1 * z2;
result.output();
cout<<endl;
//Display division
cout<<"\nDivision of complex number: ";
result = z1/z2;
result.output();

cout<<endl;

cout<<"\nModulus of Complex numbers : "<<endl;


z1.FindModulus();
cout<<endl;
z2.FindModulus();
cout<<endl;
//Conjugate of complext nimbers

cout<<"\nComplex conjugate is: "<<endl;


result.Conjugate1(z1);
result.output();

cout<<endl;

result.Conjugate2(z2);
result.output();

return 0;
}

Page 4/4

You might also like