OOP/CPP Complex class to add and subtract complex numbers

/* 3. Create a class called COMPLEX
that has two private data called real and imaginary.
Include member function input() to input
real & imaginary values, show() to display complex numbers.
Write a program to add and subtract two complex numbers.*/
#include <iostream>
using namespace std;
class complex // x+iy form
{float x; //real part
float y; //imaginary part
void input (float real, float imag)
{x= real; y = imag;}
friend complex sum(complex, complex);
void subtract(complex, complex);
void show();
complex sum(complex c1, complex c2)
{complex c3; //objects c3 is created
c3.x = c1.x + c2.x;
c3.y = c1.y + c2.y;
return(c3); //returns object c3
void complex::subtract(complex c1, complex c2)
{x = c1.x – c2.x;
y = c1.y – c2.y;
void complex :: show()
cout << x << “+j”<< y << endl;

int main()
complex A,B,C,D;
A.input(3.1, 5.65);
B.input(2.75, 1.2);

C = sum(A, B);
D.subtract(A,B); //C = A + B
cout << “A = “; A.show();
cout << “B = “; B.show();
cout << “C = “; C.show();
cout << “D = “; D.show();


Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>