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



Complex numbers are numbers that are expressed as a+bi, where i is an imaginary number and a and b, are real numbers. Some of the example of complex numbers are 2 + 5i, 3 - 9i, 8 + 2i, etc.

How to add complex number?

Here, we will explain how to add two complex numbers. Let us assume we have two complex numbers, Z1 and Z2.

// a and b are the real and imaginary parts of Z1
Z1 = a + bi

// c and d are the real and imaginary parts of Z2
Z2 = c + di

Next, we demonstrate the formula for adding two complex numbers as follows:

Sum of Z1 and Z2 = (a + c) + (b + d)i

Now, proceed with the example to learn the addition of complex numbers.

If, 
Z1 = 3 + 2i and Z2 = 1 + 7i,

Then, 
sum(Z1 and Z2) = (3 + 1) + (2 + 7)i = 4 + 9i

Addition of Complex Number Using Structure

To add complex numbers using a structure, we first define a structure to represent a complex number with real and imaginary parts. Secondly, we create a custom function addComplex() for the sum of two complex numbers. Finally, we use the displayComplex() function to display the value of real and imaginary parts.

Syntax

The following is the basic syntax of struture in C++:

struct Complex {
   float real;
   float imag;
};

Here,

  • struct Complex: This is the name of the structure.
  • real: It holds the values of the real part of a complex number.
  • imag: It holds the values of imaginary value.

Example

In this example, we shows the addition of complex number using structure.

#include <iostream>
using namespace std;

// Define a structure for complex numbers
struct Complex {
   float real;
   float imag;
};

// Function to add two complex numbers
Complex addComplex(Complex a, Complex b) {
   Complex result;
   result.real = a.real + b.real;
   result.imag = a.imag + b.imag;
   return result;
}

// Function to display a complex number
void displayComplex(Complex c) {
   cout << c.real << " + " << c.imag << "i" << endl;
}

int main() {
   // Define and initialize two complex numbers
   Complex num1 = {3.5, 2.5};
   Complex num2 = {1.5, 4.5};

   // Add the complex numbers
   Complex sum = addComplex(num1, num2);

   // Display the result
   cout << "First Complex Number: ";
   displayComplex(num1);

   cout << "Second Complex Number: ";
   displayComplex(num2);

   cout << "Sum of Complex Numbers: ";
   displayComplex(sum);

   return 0;
}

The above program produces the following result:

First Complex Number: 3.5 + 2.5i
Second Complex Number: 1.5 + 4.5i
Sum of Complex Numbers: 5 + 7i
Updated on: 2025-05-02T15:25:14+05:30

766 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements