//Program : Part B-4
//Using operator overloading concepts do the following
//a)To add two complex numbers
//b)To subtract complex numbers
//c)To compare two complex numbers.
//(Hint : To add (+),to subtract (-),to compare only (==) must be overloaded and //compare the real with real and imaginary with an imaginary part).
//Name : LDK E-NOTES Reg.No. : **********
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
#include<stdlib.h>
class complex
{
int real,imag;
public:
void accept();
void display();
complex operator+(complex b);
complex operator-(complex b);
complex operator==(complex b);
};
void complex::accept()
{
cout<<"Enter the real part : ";
cin>>real;
cout<<"Enter the imaginary part : ";
cin>>imag;
}
void complex::display()
{
cout<<real<<"+"<<imag<<"i"<<endl;
}
complex complex::operator+(complex b)
{
complex c;
c.real=real+b.real;
c.imag=imag+b.imag;
return c;
}
complex complex::operator-(complex b)
{
complex c;
c.real=real-b.real;
c.imag=imag-b.imag;
return c;
}
complex complex::operator==(complex b)
{
complex c;
if((real==b.real)&&(imag==b.imag))
cout<<"Complex number is equal"<<endl;
else
cout<<"Comlpex number is not equal"<<endl;
return c;
}
void main()
{
complex c1,c2,c3;
clrscr();
cout<<"Enter the first complex number"<<endl;
c1.accept();
cout<<"Enter the second complex number"<<endl;
c2.accept();
cout<<"First complex number = ";
c1.display();
cout<<"Second complex number = ";
c2.display();
while(1)
{
cout<<"1.Addition"<<endl;
cout<<"2.Subtraction"<<endl;
cout<<"3.Compare"<<endl;
cout<<"4.Exit"<<endl;
int ch;
cout<<"Enter your choice [1/2/3/4] : ";
cin>>ch;
switch(ch)
{
case 1 : c3=c1+c2;
cout<<"Complex number after addition : ";
c3.display();
break;
case 2 : c3=c1-c2;
cout<<"Complex nunmber after subtraction : ";
c3.display();
break;
case 3 : c1==c2;
break;
case 4 : exit(0);
break;
default : cout<<"Invalid choice...";
}
getch();
}
}
Output :
Enter the first complex number
Enter the real part : 6
Enter the imaginary part : 4
Enter the second complex number
Enter the real part : 4
Enter the imaginary part : 2
First complex number = 6+4i
Second complex number = 4+2i
1.Addition
2.Subtraction
3.Compare
4.Exit
Enter your choice [1/2/3/4] : 1
Complex number after addition : 10+6i
1.Addition
2.Subtraction
3.Compare
4.Exit
Enter your choice [1/2/3/4] : 2
Complex nunmber after subtraction : 2+2i
1.Addition
2.Subtraction
3.Compare
4.Exit
Enter your choice [1/2/3/4] : 3
Comlpex number is not equal
Saturday, 7 March 2015
C++ LAB Part-B 4
Labels:
CPP LAB
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment