Write a program to perform addition of two complex numbers using constructor. Complex numbers are given through user input.
#include<iostream>
using namespace std;
class Complex {
public:
int realPart, imaginaryPart;
Complex(int real = 0, int imag = 0)
{
realPart = real;
imaginaryPart = imag;
}
Complex addComplexNumbers(Complex Comp1, Complex Comp2)
{
Complex comp;
comp.realPart = Comp1.realPart + Comp2.realPart;
comp.imaginaryPart = Comp1.imaginaryPart + Comp2.imaginaryPart;
return comp;
}
};
// Testing code
int main()
{
int real1, imag1;
cout<<"Enter the first complex number:\n";
cout<<"Real Part\n";
cin>>real1;
cout<<"Imaginary Part\n";
cin>>imag1;
Complex Comp1(real1, imag1);
cout<<"Complex number 1 : "<< Comp1.realPart
<< " + i"<< Comp1.imaginaryPart<<endl;
int real2, imag2;
cout<<"Enter the second complex number:\n";
cout<<"Real Part\n";
cin>>real2;
cout<<"Imaginary Part\n";
cin>>imag2;
Complex Comp2(real2, imag2);
cout<<"Complex number 2 : "<< Comp2.realPart
<< " + i"<< Comp2.imaginaryPart<<endl;
Complex Comp3;
Comp3 = Comp3.addComplexNumbers(Comp1, Comp2);
cout<<"\n\nSum of complex numbers is : "
<< Comp3.realPart << " + i"
<< Comp3.imaginaryPart;
}
Comments
Leave a comment