Adding complex numbers can be accomplished in C++ by creating a structure to hold the real and imaginary components of the numbers, and passing this structure to a function that will perform the addition.
In this tutorial, we will see how to implement this functionality.
First, we define a structure to hold the real and imaginary parts of a complex number:
struct Complex {
double real;
double imaginary;
};
Next, we define a function that takes two complex numbers as arguments, adds them, and returns the result as a complex number:
Complex addComplex(Complex num1, Complex num2) {
Complex result;
result.real = num1.real + num2.real;
result.imaginary = num1.imaginary + num2.imaginary;
return result;
}
In this function, we create a new complex number called result, and set its real and imaginary components to the sum of the corresponding components of the two input complex numbers.
To use this function, we create two complex numbers, and call the addComplex function with these numbers as arguments.
The resulting complex number can be stored in a third complex number.
int main() {
Complex num1 = {1.0, 2.0};
Complex num2 = {3.0, 4.0};
Complex sum = addComplex(num1, num2);
std::cout << "Sum = " << sum.real << " + " << sum.imaginary << "i" << std::endl;
return 0;
}
In this example, we create two complex numbers num1 and num2, and set their real and imaginary components to 1.0, 2.0 and 3.0, 4.0, respectively.
We then call the addComplex function with these two numbers, and store the result in the sum variable. Finally, we print the result using std::cout.
This program will output: Sum = 4 + 6i
In conclusion, we have seen how to add complex numbers using a structure and a function in C++.
By encapsulating the real and imaginary components of the numbers in a structure, we can easily pass them to a function for manipulation.




