# Exam2Lab: Simple Complex Numbers¶

We are going to implement a class that manages a form of `complex numbers`

.
These numbers are made up of two numerical parts, called real and
imaginary.

Traditionally, they are written like this: 1.0 + 2.0i

Objects constructed from this class can be combined to form new objects using simple math operations. Yikes, I hear you say, we do not know how to set up methods that let us create new math operations. Well, this is pretty easy. Here is the skeleton of the class you need to get started which includes the method needed to do addition. The operator + method is how we overload the plus symbol so it knows how to add two complex data items.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | ```
#ifndef COMPLEX_H
#define COMPLEX_H
#include <iostream>
using namespace std;
class Complex {
public:
double r;
double i;
Complex(double, double);
Complex(double);
Complex();
Complex operator +(const Complex & rhs);
friend ostream & operator<< (ostream & out, const Complex);
};
#endif
``` |

The implementation for this skeleton is here:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | ```
#include "Complex.h"
#include <iostream>
using namespace std;
Complex::Complex(double _r, double _i) {
this->r = _r;
this->i = _i;
}
Complex::Complex(double _r) {
this->r = _r;
this->i = 0.0;
}
Complex::Complex() {
this->r = 0.0;
this->i = 0.0;
}
Complex Complex::operator + (const Complex & rhs) {
Complex temp;
temp.r = this->r + rhs.r;
temp.i = this->i + rhs.i;
return temp;
}
ostream & operator << (ostream & out, const Complex rhs) {
return out << rhs.r << "+" << rhs.i << "i";
}
``` |

Note

The friend operator << function is special,, and we will talk about it in class. It lets is print out our complex nembers using the normal cout methods.

And here is a simple test program that runs this code:

1 2 3 4 5 6 7 8 9 10 11 | ```
#include <iostream>
#include "Complex.h"
int main(int argc, char *argv[]) {
std::cout << "Complex Testing" << std::endl;
Complex a(2,2);
Complex b(4,4);
Complex c = a + b;
std::cout << c << std::endl;
}
``` |

## Your job¶

Here is what we need to do for this lab part:

First, make sure the given code works! Set this project up in your Homework repository on GitHub, and commit it before you go any further!

Once that is working, extend this class so it supports the following math operations:

```
add: (a+b*i) + (c+d*i) = (a+c) + (b+d)*i
sub: (a+b*i) - (c+d*i) = (a-c) + (b-d)*i
mul: (a+b*i)*(c+d*i) = a*c + a*d*i + b*c*i + b*d*i*i = (a*c-b*d) + (a*d+b*c)*i
mul: B * (a+b*i) = (a*B + b*B*i)
div: (a+b*i)/(c+d*i) = (a*c + b*d)/(c*c + d*d) + (b*c-a*d)/(c*c+d*d)*i
div: (a+b*i)/B = (a/B + b/B*i)
```

Note

In the above formulas, `B`

is a simple number, not a complex one.

You should follow the notation shown in the example for addition in the given code. This will not be too bad if you add things slowly, and test things as you go.