Monday, January 20, 2014

C++ Program for Adding Two Complex Numbers Using Operator Overloading

with 0 Comment
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class complex
{
float x,y;
public:
complex()
{
x=0.0;
y=0;
}
complex(float real,float img)
{
x=real;
y=img;
}
friend complex operator+(complex,complex);
friend void display(complex);
};

complex operator+(complex c1,complex c2)
{
complex temp;
temp.x=c1.x+c2.x;
temp.y=c1.y+c2.y;
return temp;
}

void display(complex c)
{
cout<<c.x<<"+i"<<setprecision(2)<<c.y;
}

void main()
{
float a,b,c,d,e;
complex A,B,C;
clrscr();
cout<<"\n\t\t OPERATOR OVERLOADING USING FRIEND FUNCTION";
cout<<"\n\t\t *********************************";
cout<<"\n Enter the First Real and img values:";
cin>>a>>b;
cout<<"\n Enter the Second Real and img values:";
cin>>c>>d;
A=complex(a,b);
B=complex(c,d);
C=operator+(A,B);
cout<<"\n Result";
cout<<"\n -----";
cout<<"\n A:";
display(A);
cout<<"\n B:";
display(B);
cout<<"\n C:";
display(C);
getch();
}

-------------
OUTPUT:
-------------
Operator Overloading Using Friend Function
------------------------------------------------------
Enter the First Real and img Values:
2.4
5.1
Enter the Second Real and img Values:
4.8
6.2

Result:
--------
A:2.4+i5.1
B:4.8+i6.2
C:7.2+i11.3

0 comments:

Post a Comment

Powered by Blogger.

Blog Archive