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

C++ProgrammingServer Side Programming

Complex numbers are numbers that are expressed as a+bi where i is an imaginary number and a and b are real numbers. Some examples on complex numbers are −

2+5i
3-9i
8+2i

A program to add complex numbers by passing structure to a function is given as follows −

Example

 Live Demo

#include <iostream>

using namespace std;
typedef struct complexNumber {
   float real;
   float imag;
};
complexNumber addCN(complexNumber num1,complexNumber num2) {
   complexNumber temp;
   temp.real = num1.real + num2.real;
   temp.imag = num1.imag + num2.imag;
   return(temp);
}
int main() {
   complexNumber num1, num2, sum;
   cout << "Enter real part of Complex Number 1: " << endl;

   cin >> num1.real;
   cout << "Enter imaginary part of Complex Number 1: " << endl;

   cin >> num1.imag;
   cout << "Enter real part of Complex Number 2: " << endl;

   cin >> num2.real;
   cout << "Enter imaginary part of Complex Number 2: " << endl;

   cin >> num2.imag;
   sum = addCN(num1, num2);

   if(sum.imag >= 0)
   cout << "Sum of the two complex numbers is "<< sum.real <<" + "<< sum.imag <<"i";
   else
   cout << "Sum of the two complex numbers is "<< sum.real <<" + ("<< sum.imag <<")i";
   return 0;
}

Output

The output of the above program is as follows −

Enter real part of Complex Number 1: 5
Enter imaginary part of Complex Number 1: -9
Enter real part of Complex Number 2: 3
Enter imaginary part of Complex Number 2: 6
Sum of the two complex numbers is 8 + (-3)i

In the above program, the structure complexNumber contains the real and imaginary parts of the complex number. This is given below −

struct complexNumber {
   float real;
   float imag;
};

The function addCN() takes two arguments of type complexNumber type and adds the real and imaginary parts of the two numbers. Then the added value is returned to the main() function. This is given below −

complexNumber addCN(complexNumber num1,complexNumber num2) {
   complexNumber temp;
   temp.real = num1.real + num2.real;
   temp.imag = num1.imag + num2.imag;
   return(temp);
}

In the main() function, the values of the numbers are obtained from the user. This is given below −

cout << "Enter real part of Complex Number 1: " << endl;
cin >> num1.real;
cout << "Enter imaginary part of Complex Number 1: " << endl;
cin >> num1.imag;

cout << "Enter real part of Complex Number 2: " << endl;
cin >> num2.real;
cout << "Enter imaginary part of Complex Number 2: " << endl;
cin >> num2.imag;

The sum of the two numbers is obtained by the calling the addCN() function. Then the sum is printed. This is given below −

sum = addCN(num1, num2);
if(sum.imag >= 0)
cout << "Sum of the two complex numbers is "<< sum.real <<" + "<< sum.imag <<"i";

else
cout << "Sum of the two complex numbers is "<< sum.real <<" + ("<< sum.imag <<")i";
raja
Published on 22-Oct-2018 18:01:34
Advertisements