C++ Program to Add Complex Numbers by Passing Structure to a Function

This program takes two complex numbers as structures and adds them with the use of functions.

To understand this example, you should have the knowledge of following C++ programming topics:


Example: Source Code to Add Two Complex Numbers

// Complex numbers are entered by the user

#include <iostream>
using namespace std;

typedef struct complex
{
    float real;
    float imag;
} complexNumber;

complexNumber addComplexNumbers(complex, complex);

int main()
{
    complexNumber n1, n2, temporaryNumber;
    char signOfImag;

    cout << "For 1st complex number," << endl;
    cout << "Enter real and imaginary parts respectively:" << endl;
    cin >> n1.real >> n1.imag;

    cout << endl << "For 2nd complex number," << endl;
    cout << "Enter real and imaginary parts respectively:" << endl;
    cin >> n2.real >> n2.imag;

    signOfImag = (temporaryNumber.imag > 0) ? '+' : '-';
    temporaryNumber.imag = (temporaryNumber.imag > 0) ? temporaryNumber.imag : -temporaryNumber.imag; 

    temporaryNumber = addComplexNumbers(n1, n2);    
    cout << "Sum = "  << temporaryNumber.real << temporaryNumber.imag << "i";
    return 0;
}

complexNumber addComplexNumbers(complex n1,complex n2)
{
      complex temp;
      temp.real = n1.real+n2.real;
      temp.imag = n1.imag+n2.imag;
      return(temp);
}

Output

Enter real and imaginary parts respectively:
3.4
5.5

For 2nd complex number,
Enter real and imaginary parts respectively:
-4.5
-9.5
Sum = -1.1-4i

In the problem, two complex numbers entered by the user is stored in structures n1 and n2.

These two structures are passed to addComplexNumbers() function which calculates the sum and returns the result to the main() function.

Finally, the sum is displayed from the main() function.