# Add Complex Numbers in C++

Add complex numbers in c++. This page provides a c++ program to add complex numbers.

## Add complex numbers in c++

Lets first understand how the program works. If you don't want this explanation the source code is right below.

A complex number is a type of number that contains real and imaginary numbers.

Every complex number can be represented in the form **a + bi**, where **a** and **b** are real numbers and **i** is imaginary number.

To write a c++ program to add two complex numbers we first need to find a way represent complex number in c++.

We create a class named complex with two float variable a and b to represent the real part of complex number.

Then default and parameterized constructors are written to set or accept values for those two variables.

This complex class only represents one complex number.

Then we use operator overloading for addition (+) operator.

Operator overloading is simply defining a different meaning than usual for an operator.

Then in main function we create three complex variables.

Third variable is used to store the addition of first two variables.

Finally addition is displayed.

Here is the source code of c++ program to add two complex numbers.

/* Aim: Write a C++ program to add two complex numbers. */ #include<iostream> using namespace std; class complex { float a,b; public: complex() { a=b=1; } complex(float x, float y) { a=x;b=y; } complex operator + (complex c2) { complex tmp; tmp.a=a+c2.a; tmp.b=b+c2.b; return tmp; } void display() { if(b>=0) cout<<" Complex number : "<<a<<"+"<<b<<"i"<<endl; else cout<<" Complex number : "<<a<<b<<"i"<<endl; } void display(char op) { cout<<a<<"i"<<"/"<<b<<endl; } }; int main() { complex c1(7,-3),c2,c3; add-complex- c1.display(); c2.display(); cout<<" Addition is "; c3=c1+c2; c3.display(); return 0; } /* Output of above code:- Complex number : 7-3i Complex number : 1+1i Addition is Complex number : 8-2i */

### Related articles to addition of complex numbers in c++

You might want to check same program with multiplication operator, Division of complex numbers in c++.

Another one with multiplication operator, multiplication of complex numbers in c++.

## Comments

## Post a Comment