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

Add Complex Numbers by Passing Structure to a Function

This program takes two complex numbers as structures and adds them with the use of functions.

Example: Source Code to Add Two Complex Numbers


  1. // Complex numbers are entered by the user
  2. #include <iostream>
  3. using namespace std;
  4. typedef struct complex
  5. {
  6. float real;
  7. float imag;
  8. } complexNumber;
  9. complexNumber addComplexNumbers(complex, complex);
  10. int main()
  11. {
  12. complexNumber n1, n2, temporaryNumber;
  13. char signOfImag;
  14. cout << "For 1st complex number," << endl;
  15. cout << "Enter real and imaginary parts respectively:" << endl;
  16. cin >> n1.real >> n1.imag;
  17. cout << endl << "For 2nd complex number," << endl;
  18. cout << "Enter real and imaginary parts respectively:" << endl;
  19. cin >> n2.real >> n2.imag;
  20. signOfImag = (temporaryNumber.imag > 0) ? '+' : '-';
  21. temporaryNumber.imag = (temporaryNumber.imag > 0) ? temporaryNumber.imag : -temporaryNumber.imag;
  22. temporaryNumber = addComplexNumbers(n1, n2);
  23. cout << "Sum = " << temporaryNumber.real << temporaryNumber.imag << "i";
  24. return 0;
  25. }
  26. complexNumber addComplexNumbers(complex n1,complex n2)
  27. {
  28. complex temp;
  29. temp.real = n1.real+n2.real;
  30. temp.imag = n1.imag+n2.imag;
  31. return(temp);
  32. }
Output
Enter real and imaginary parts respectively:
3.4
5.5

For 2nd complex number,
Enter real and imaginary parts respectively:
-4.5
-9.5
Sum = -1.1-4i




Comments

Popular posts from this blog

C++ Program to Store and Display Information Using Structure