C++ Program To Add Two Complex Numbers
Last Updated :
23 Jun, 2023
Given two complex numbers of the form and the task is to add these two complex numbers.
a1 + ib1 and a2 + ib2
Here the values of real and imaginary numbers are passed while calling the parameterized constructor and, with the help of a default(empty) constructor, the function addComp is called to get the addition of complex numbers.
Examples:
Input: a1 = 4, b1 = 8
a2 = 5, b2 = 7
Output: Sum = 9 + i15
Explanation: (4 + i8) + (5 + i7)
= (4 + 5) + i(8 + 7)
= 9 + i15
Below is the C++ program to add two complex numbers:
C++
#include<bits/stdc++.h>
using namespace std;
class Complex
{
public : int real, imaginary;
Complex( int tempReal = 0,
int tempImaginary = 0)
{
real = tempReal;
imaginary = tempImaginary;
}
Complex addComp(Complex C1, Complex C2)
{
Complex temp;
temp.real = C1.real + C2.real;
temp.imaginary = (C1.imaginary + C2.imaginary);
return temp;
}
};
int main()
{
Complex C1(3, 2);
cout << "Complex number 1 : " <<
C1.real << " + i" <<
C1.imaginary << endl;
Complex C2(9, 5);
cout << "Complex number 2 : " <<
C2.real << " + i" <<
C2.imaginary << endl;
Complex C3;
C3 = C3.addComp(C1, C2);
cout << "Sum of complex number : " <<
C3.real << " + i" <<
C3.imaginary;
}
|
Output
Complex number 1 : 3 + i2
Complex number 2 : 9 + i5
Sum of complex number : 12 + i7
Explanation of the above method
- A class Complex is created for complex numbers with two data members real and imaginary, a parameterized constructor, and a function to add complex numbers.
- Parameterized constructor is used to initialize the data members real and imaginary.
- A function addComp() with Class return type is created to add two complex numbers.
The complexity of the above method
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...