Google News
logo
C++ Program to Add Complex Numbers
In the following example of C++ program takes two complex numbers (entered by user) as input and displays the sum of them.
Program :
#include <iostream> 

using namespace std;

class complex_number
{
   public :
      int real, imag;
};

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

   //getting the value of first complex number from user
   cout << "Enter real and imaginary parts of first complex number:"<<endl; 
   cin >> num1.real >> num1.imag;

   //getting the value of second complex number from user
   cout << "Enter real and imaginary parts of second complex number:"<<endl; 
   cin >> num2.real >> num2.imag;

   //addition of real and imaginary parts of complex numbers entered by user
   sum.real = num1.real + num2.real;
   sum.imag = num1.imag + num2.imag;

   //displaying the sum of complex numbers
   if ( sum.imag >= 0 )
      cout << "Sum of two complex numbers = " << sum.real << " + " << sum.imag << "i";
   else
      cout << "Sum of two complex numbers = " << sum.real << " - " << sum.imag << "i";

   return 0;
}
Output :
Enter real and imaginary parts of first complex number:
5 9
Enter real and imaginary parts of second complex number:
3 7
Sum of two complex numbers = 8 + 16i