Skip to main content

How To Think Like a Computer Scientist C++ Edition The Pretext Interactive Version

Section 14.6 A function on Complex numbers

A natural operation we might want to perform on complex numbers is addition. If the numbers are in Cartesian coordinates, addition is easy: you just add the real parts together and the imaginary parts together. If the numbers are in polar coordinates, it is easiest to convert them to Cartesian coordinates and then add them.
Again, it is easy to deal with these cases if we use the accessor functions:
Complex add (Complex& a, Complex& b)
{
  double real = a.getReal() + b.getReal();
  double imag = a.getImag() + b.getImag();
  Complex sum (real, imag);
  return sum;
}
Notice that the arguments to add are not const because they might be modified when we invoke the accessors. To invoke this function, we would pass both operands as arguments:
Complex c1 (2.0, 3.0);
Complex c2 (3.0, 4.0);

Complex sum = add (c1, c2);
sum.printCartesian();
The output of this program is
5 + 7i

Checkpoint 14.6.1.

This active code uses the add function for Complex objects. As an exercise, write the subtract function for Complex objects in the commented area of the active code. If you get stuck, you can reveal the hint below for help. Once you are finished, feel free to modify the code and experiment around!
Hint. subtract

Activity 14.6.1.

Let’s write the code for the subtract function, which should return the difference of two Complex objects.

Checkpoint 14.6.2.

What is the correct output of the code below?
int main() {
  Complex c1 (2.5, 1.3);
  Complex c2 (3.9, 4.4);
  Complex c3 (9.5, 7.6);
  Complex sum = add (c1, c2);
  Complex diff = subtract(c3, sum);
  diff.printCartesian();
}
  • 3.1i + 1.9i
  • Incorrect! Try using the active code above.
  • 1.9i + 3.1
  • Incorrect! Try using the active code above.
  • 3.0 + 1.9i
  • Incorrect! Try using the active code above.
  • 3.1 + 1.9i
  • Correct!
You have attempted 1 of 4 activities on this page.