Answer to Question #235093 in C++ for SOM

Question #235093

Write a program to perform addition of two complex numbers using constructor. Complex numbers are given through user input.


1
Expert's answer
2021-09-09T04:09:51-0400


#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;
}
 

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS