You are here

C++ program to add two complex numbers

C++ program to add two complex numbers.

C++ programming code

  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. class complex
  6. {
  7.    public :
  8.       int real, img;
  9. };
  10.  
  11. int main()
  12. {
  13.    complex a, b, c;
  14.  
  15.    cout << "Enter a and b where a + ib is the first complex number.";
  16.    cout << "\na = ";
  17.    cin >> a.real;
  18.    cout << "b = ";
  19.    cin >> a.img;
  20.    cout << "Enter c and d where c + id is the second complex number.";
  21.    cout << "\nc = ";
  22.    cin >> b.real;
  23.    cout << "d = ";
  24.    cin >> b.img;
  25.    
  26.    c.real = a.real + b.real;
  27.    c.img = a.img + b.img;
  28.  
  29.    if (c.img >= 0)
  30.       cout << "Sum of two complex numbers = " << c.real << " + " << c.img << "i";
  31.    else
  32.       cout << "Sum of two complex numbers = " << c.real << " " << c.img << "i";
  33.  
  34.    return 0;
  35. }