C++ program to add two complex numbers using class
In this article, we will write a program to add two complex numbers (a1 + ib1) and (a2 + ib2) using class.
Input: 4 + i5 and 8 + i9
Here a1= 4 and a2 = 8. On adding a1 and a2, we get (8 + 4) = 12
Further, b1 = 5 and b2 = 9. On adding b1 and b2, we get (5 + 9) = 14
Output: 9 + i14
Input: 2 + i7 and 10 + i6
Here a1= 2 and a2 = 10. On adding a1 and a2, we get (2 + 10) = 12
Further, b1 = 7 and b2 =6. On adding b1 and b2, we get (7 + 6) = 13
Output: 12 + i13
At first, we will create a class for complex numbers. The observation shows that there is a real number(a1) and an imaginary number(b1) in a complex number.
We need two data members to represent the complex numbers.
Below is the class structure:
Two constructors will be made to initialize the data members of the class Complex.
We need a non - parameterized constructor to initialize the default values of the data members to zero.
Below is the structure of non-parameterized constructor
We need a non-parameterized constructor to initialize the data members to the value passed by the main function.
Below is the structure of parameterized constructor
For adding two complex numbers, we will make two objects of the Complex class and initialize them with the values. After that, we will make a third object that will store the result.
Complex number 1 : 4 + i5 Complex number 2 : 8 + i9 Sum of complex number : 12 + i14 Complex number 1 : 2 + i7 Complex number 2 : 10 + i6 Sum of complex number : 12 + i13 Time complexity The time complexity is O(1) as we have to call the function addComplexNumber() to add the two complex numbers.