Open In App

C++ Program To Add Two Complex Numbers

Last Updated : 23 Jun, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two complex numbers of the form and the task is to add these two complex numbers.

a1 + ib 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++
// C++ Program to Add 
// Two Complex Numbers

// Importing all libraries
#include<bits/stdc++.h>
using namespace std;
 
// User Defined Complex class
class Complex 
{ 
    // Declaring variables
    public: int real, imaginary;
 
    // Constructor to accept
    // real and imaginary part
    Complex(int tempReal = 0, 
            int tempImaginary = 0)
    {
        real = tempReal;
        imaginary = tempImaginary;
    }
 
    // Defining addComp() method
    // for adding two complex number
    Complex addComp(Complex C1, Complex C2)
    {
        // Creating temporary variable
        Complex temp;
 
        // Adding real part of 
        // complex numbers
        temp.real = C1.real + C2.real;
 
        // Adding Imaginary part of 
        // complex numbers
        temp.imaginary = (C1.imaginary + C2.imaginary);
 
        // Returning the sum
        return temp;
    }
};
 
// Driver code
int main()
{
    // First Complex number
    Complex C1(3, 2);

    // printing first complex number
    cout << "Complex number 1 : " << 
             C1.real << " + i" << 
             C1.imaginary << endl;

    // Second Complex number
    Complex C2(9, 5);

    // Printing second complex number
    cout << "Complex number 2 : " << 
             C2.real << " + i" << 
             C2.imaginary << endl;

    // For Storing the sum
    Complex C3;

    // Calling addComp() method
    C3 = C3.addComp(C1, C2);

    // Printing the sum
    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

  1.  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.
  2.  Parameterized constructor is used to initialize the data members real and imaginary.
  3.  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)


Next Article
Practice Tags :

Similar Reads