In the previous article, we have discussed C++ Program to Calculate Difference Between Two Time Periods Using Structure. In this article, we will see C++ Program to Add Two Complex Numbers Using Structure.

## C++ Program to Add Two Complex Numbers Using Structure

- Write a C++ program to find sum of two complex numbers using structure.

In this C++ program, we will add two complex numbers using a user defined structure. A complex number is a number that can be expressed in the form a + bi, where a and b are real numbers and i is the imaginary unit, which satisfies the equation i2 = -1.

In complex number a + bi, a is the real part and b is the imaginary part.

For Example :

5 + 7i, -3 -2i, 2 - 6i

### How to Add Two Complex Numbers.

Let Sum(x + iy) is the sum of C1 and C2

Sum = C1 + C2

(x + iy) = (a + ib) + (c + id)

(x + iy) = (a + c) + i(b + d)

x = (a + c) and,

y = (b + d)

We will create a custom structure name “complex” which contains two member variables realPart and imaginaryPart.

struct Complex { int realPart; int imaginaryPart; };

We will use variables of structure Complex, to store complex numbers.

### C++ Program to Find Sum of Two Complex Numbers Using Structure

// C++ program to add two complex numbers using structure and function #include <iostream> using namespace std; /* Structure to store complex number in the form of x + yi, * realPart = x and imaginaryPart = y; */ struct Complex { int realPart; int imaginaryPart; }; int main() { Complex c1, c2, sum; cout << "Enter value of A and B where A + iB is first complex number\n"; cin >> c1.realPart >> c1.imaginaryPart; cout << "Enter value of A and B where A + iB is second complex number\n"; cin >> c2.realPart >> c2.imaginaryPart; /* (A + Bi) + (C + Di) = (A+C) + (B+D)i */ sum.realPart = c1.realPart + c2.realPart; sum.imaginaryPart = c1.imaginaryPart + c2.imaginaryPart; if(sum.imaginaryPart >= 0 ) cout << sum.realPart << " + " << sum.imaginaryPart<<"i"; else cout << sum.realPart << " - " << sum.imaginaryPart<<"i"; return 0; }

Output

Enter value of A and B where A + iB is first complex number 2 5 Enter value of A and B where A + iB is second complex number 7 4 9 + 9i

In this program, we take two complex numbers as input from user in the form of A + iB and store in structure variable c1 and c2. We will add real parts of input complex numbers to get the real part of sum complex and add imaginary part of input complex numbers to get imaginary part of sum complex number.

Explore various CPP Codes lists that are used in C++ programming to write a sample program. These codes play an important role while learning the programs.