Google News
logo
C++ Program to Add Complex Numbers by Passing Structure to a Function
In the following example of C++ program to add complex numbers by passing structure to a function :
Program :
#include <iostream>
using namespace std;

struct complex {
   double real;
   double imag;
};

complex add(complex num1, complex num2);

int main() {
   complex num1, num2, sum;
   cout << "Enter the real and imaginary parts of the first complex number: ";
   cin >> num1.real >> num1.imag;
   cout << "Enter the real and imaginary parts of the second complex number: ";
   cin >> num2.real >> num2.imag;
   sum = add(num1, num2);
   cout << "Sum = " << sum.real << " + " << sum.imag << "i" << endl;
   return 0;
}

complex add(complex num1, complex num2) {
   complex temp;
   temp.real = num1.real + num2.real;
   temp.imag = num1.imag + num2.imag;
   return temp;
}
Output :
Enter the real and imaginary parts of the first complex number: 2.6 7.1
Enter the real and imaginary parts of the second complex number: -3.4 2.9
Sum = -0.8 + 10i
* In this program, we define a structure complex with two members real and imag representing the real and imaginary parts of a complex number.

* We declare three variables num1, num2, and sum of type complex. We use cin to input the real and imaginary parts of the two complex numbers.

* We then call the function add() by passing the two complex numbers as arguments. The function returns a complex number which is stored in the variable sum.

* Finally, we display the sum of the complex numbers using cout.