Answer to Question #297392 in C++ for Sonu

Question #297392

Develop c++ program with a class complex containing data members real and imaginary .Overload'+' operator and '-: operator to perform complex number addition and subtraction

1
Expert's answer
2022-02-13T13:00:29-0500




#include <iostream>
using namespace std;


class Complex
{
private:
	float real;
	float imaginary;
public:
	Complex(): real(0), imaginary(0){ }
	void input(){
		cout << "Enter real part: ";
		cin >> real;
		cout << "Enter imaginary part: ";
		cin >> imaginary;
	}


	Complex operator + (Complex c2)
	{
		Complex result;
		result.real = real + c2.real;
		result.imaginary = imaginary + c2.imaginary;
		return result;
	}
	Complex operator - (Complex c2)
	{
		Complex result;
		result.real = real - c2.real;
		result.imaginary = imaginary - c2.imaginary;
		return result;
	}




	void dipslay()
	{
		if(imaginary < 0)
			cout << real << imaginary << "i";
		else
			cout << real << "+" << imaginary << "i";
	}
};


int main()
{
	Complex Complex1, Complex2, result;
	cout<<"Enter first complex number:\n";
	Complex1.input();
	cout<<"Enter second complex number:\n";
	Complex2.input();
	result = Complex1 + Complex2;
	cout<<"\nSum: ";
	result.dipslay();
	result = Complex1 - Complex2;
	cout<<"\nDifference: ";
	result.dipslay();
	cout<<"\n\n";
	system("pause");
	return 0;
}

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
New on Blog