Create a class called Complex for performing arithmetic with complex numbers. Wr
ID: 3541634 • Letter: C
Question
Create a class called Complex for performing arithmetic with complex numbers. Write a driver program to test your class.
Complex numbers have the form
realPart + imaginaryPart * i
where i is (-1)^(1/2)
Use integer (or floating-point) to represent the private data of the class. Provide a constructor function that enables an object of this class to be initialized when it is declared. The constructor should contain default values in case no initial values are provided. Provide public member functions for each of the following:
a) Addition of two Complex numbers: The real parts are added together and the imaginary parts are added together.
b) Subtraction of two Complex numbers: The real part of the right operand is subtracted from the real part of the left operand and the imaginary part of the right operand is subtracted from the imaginary part of the left operand.
c) Printing Complex numbers in the form (a, b) where a is the real part and b is the imaginary part
Explanation / Answer
#include<iostream>
using namespace std;
class Complex
{
private:
int real;
int img;
public:
Complex(int real=0,int img=0)
{
this->real = real;
this->img = img;
}
Complex add(Complex other)
{
return Complex(real+other.real,img+other.img);
}
Complex subtract(Complex other)
{
return Complex(real-other.real,img-other.img);
}
void print()
{
cout << "(" << real << " , " << img << ") " << endl;
}
};
int main()
{
Complex C1(4,5);
Complex C2(2,3);
C1.print();
C2.print();
cout << "Addition of C1 and C2 given by " << endl;
Complex C3 = C1.add(C2);
C3.print();
cout << "subtraction of C2 and C1 given by " << endl;
Complex C4 = C1.subtract(C2);
C4.print();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.