Using Functions to Add Complex Numbers in C++

Exercise:

Write a C++ program that can take complex numbers and store them as structures and then add them with the help of functions.

Click Here to View the Solution:
#include <iostream>
using namespace std;
typedef struct Complex
{
    float R, imag;
} 
CplxNum;
CplxNum SumCplxNum(Complex, Complex);
int main()
{
    CplxNum num1, num2, ComplexSum;
    char sgnI;
    cout << "Complex # 1 Insert Real and imaginary parts:\n";
    cin >> num1.R >> num1.imag;
    cout << endl;
    cout << "Complex # 2 Insert Real and imaginary parts:\n";
    cin >> num2.R >> num2.imag;
    ComplexSum = SumCplxNum(num1, num2);          // Call function and store result in ComplexSum
    sgnI = (ComplexSum.imag > 0) ? '+' : '-';         // Ternary Operator to check and adjust the sign of imag
    ComplexSum.imag = (ComplexSum.imag > 0) ? ComplexSum.imag :  ComplexSum.imag;      
    cout << "\nSum = " << ComplexSum.R << sgnI << ComplexSum.imag << "i";
    return 0;
}
CplxNum SumCplxNum(Complex num1, Complex num2)
{
    Complex temp;
    temp.R = num1.R + num2.R;
    temp.imag = num1.imag + num2.imag;
    return (temp);
}
Click Here to View the Output:
Complex # 1 Insert Real and imaginary parts:
 12
 23

 Complex # 2 Insert Real and imaginary parts:
 41
 19

 Sum = 53+42i
Click Here to View the Explanation:
  • A structure is created and two float type variables are initialized in it R and imag. A char type variable sgn1 is also declared.
  • The user enters the first number and it is saved in the structure variable num1. The real and imaginary parts of the complex number are entered by the user.
  • To add two complex numbers, a function is created SumCplxNum ()
  • The function is called in the main () function and the result is stored in ComplexSum variable.
  • The sign of imaginary part imag is checked adjusted by a ternary operator. The operator is saved in a char type variable sgn1.
  • It is assigned a + if it is positive and - if it is negative.
  • After sgn1 is assigned an operator, ComplexSum.imag is assigned a sign. If ComplexSum is positive, it is considered negative. Otherwise, two signs would be assigned to ComplexSum
  • Sign repetition is avoided by changing the value to a positive. The sum of the complex numbers is displayed on the screen.

%d bloggers like this: