payoffer

PayOffers.in

Tuesday, March 25, 2014

Program for performing arithmetic operations of two complex numbers using operator overloading in C++

Description :Operator Overloading : It is a specific case of polymorphism where different operators have different implementations depending on their arguments.

Code :
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
class complex
{
float real,img;
public:
complex()
{
real=0;
img=0;
}
complex(float a,float b)
{
real=a;
img=b;
}

void get()
{
cout<<”\n\nEnter the real part of number: “;
cin>>real;
cout<<”\n\nEnter the imaginary part of number: “;
cin>>img;
}
void print()
{
cout<<”(“<<real<<”)”<<” + “<<”(“<<img<<”i”<<”)”;
}
complex operator+(complex c1)
{
complex temp;
temp.real=real+c1.real;
temp.img=img+c1.img;
return temp;
}
complex operator-(complex c1)
{
complex temp;
temp.real=real-c1.real;
temp.img=img-c1.img;
return temp;
}
complex operator*(complex c1)
{
complex temp;
temp.real=(real*c1.real)-(img*c1.img);
temp.img=(img*c1.real)+(real*c1.img);
return temp;
}
complex operator/(complex c1)
{
complex temp,c2;
c2.img=-c1.img;
float x;
temp.real=(real*c1.real)-(img*(c2.img));
temp.img=(real*c1.real)+(real*(c2.img));
x=(c1.real)*(c1.real)+(c1.img)*(c1.img);
temp.real=temp.real/x;
temp.img=temp.img/x;
return temp;
}
};
void main()
{
complex c1,c2,c3;
int choice;
char ans;
clrscr();
do
{
cout<<”\n\n MENU: “;
cout<<”\n\n\t1.Addition\n\n\t2.Subtraction\n\n\t3.Multiplication\n\n\t4.Division”;
cout<<”\n\nEnter your choice: “;
cin>>choice;
switch(choice)
{
case 1:
c1.get();
c2.get();
c3=c1+c2;
cout<<”\n\nAddition is: “;
c3.print();
break;
case 2:
c1.get();
c2.get();
c3=c1-c2;
cout<<”\n\nSubtraction is: “;
c3.print();
break;
case 3:
c1.get();
c2.get();
c3=c1*c2;
cout<<”\n\nMultiplication is: “;
c3.print();
break;
case 4:
c1.get();
c2.get();
c3=c1/c2;
cout<<”\n\nDivision is: “;
c3.print();
break;
}
cout<<”\n\nDo you want to continue?(y/n): “;
fflush(stdin);
cin>>ans;
}while(ans==’y’ || ans==’Y');
getch();
}

No comments:

Post a Comment