C++ program to add two complex numbers using classIn this article, we will write a program to add two complex numbers (a1 + ib1) and (a2 + ib2) using class. For example 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 Class constructionAt 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: ConstructorsTwo 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 AlgorithmFor 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. C++ code Output 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. |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India