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

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

Complex numbers in mathematics consist of a real part and an imaginary part. Adding complex numbers follows the same rules as adding real numbers, with the imaginary parts being added separately. In this article, we will explore how to add complex numbers in C++ by passing a structure to a function.

Here is the C++ program:

``````#include <iostream>
using namespace std;

// Structure to represent a complex number
struct Complex {
float real;
float imag;
};

// Function to add two complex numbers
Complex addComplex(Complex num1, Complex num2) {
Complex sum;
sum.real = num1.real + num2.real;
sum.imag = num1.imag + num2.imag;
return sum;
}

int main() {
Complex num1, num2, sum;

// Get real and imaginary parts for first complex number
cout << "Enter real and imaginary parts for the first complex number: ";
cin >> num1.real >> num1.imag;

// Get real and imaginary parts for second complex number
cout << "Enter real and imaginary parts for the second complex number: ";
cin >> num2.real >> num2.imag;

// Add the two complex numbers

// Display the result
cout << "Sum = " << sum.real << " + " << sum.imag << "i";

return 0;
}
``````

## Output:

``````Enter real and imaginary parts for the first complex number: 3 4
Enter real and imaginary parts for the second complex number: 2 6
Sum = 5 + 10i
``````

In the above program, we define a structure `Complex` to represent a complex number. It has two float members: `real` for the real part and `imag` for the imaginary part.

The `addComplex` function takes two complex numbers as parameters and returns their sum. Inside the function, we simply add the corresponding real and imaginary parts of the numbers and store the result in a new complex number.

You Might Be Interested In

In the `main` function, we create two complex number variables `num1` and `num2`. We then prompt the user to enter the real and imaginary parts for each number. After that, we call the `addComplex` function, passing `num1` and `num2` as arguments, and store the result in the `sum` variable.

Finally, we display the sum by accessing the `real` and `imag` members of the `sum` complex number.

This program demonstrates how to add complex numbers using a structure in C++. Feel free to modify and experiment with the code to explore more complex number operations.