Friday, 15 November 2013

C++ program to create a class called COMPLEX and implement the following overloading functions ADD that return a complex number: (i) ADD(a, s2) – where ‘a’ is an integer (real part) and s2 is a complex number (ii) ADD(s1, s2) – where s1 and s2 are complex numbers


#include <iostream.h>
#include <conio.h>
#include <math.h>
class COMPLEX
{
Private: int a, imaginary; 

Public:   void getdata();
               void Add(COMPLEX s1, COMPLEX s2);
               void Add(int r, COMPLEX s2);
               friend ostream& operator << (ostream& out, COMPLEX t);
};

void COMPLEX::getdata()
{
cout << "Enter the real part and imaginary part: ";cin >> a >> imaginary;
}

void COMPLEX::Add(COMPLEX s1,COMPLEX s2)
{
a = s1.a + s2.a;
imaginary = s1.imaginary + s2.imaginary;
}

void COMPLEX::Add(int r, COMPLEX s2)
{
a = r + s2.a;
imaginary =s 2.imaginary;
}

ostream& operator<<(ostream& out, COMPLEX t)
{
out << t.a;
if(t.imaginary < 0)
{
cout << "-i";
}
else
cout << "+i";
cout << abs(t.imaginary);
return cout;
}

void main()
{
COMPLEX s1, s2, s3, s4;
clrscr();
cout << "Addition of two complex numbers -" << endl;
s1.getdata();
s2.getdata();
s3.Add(s1,s2);
cout << "The resultant complex number is: ";
cout << s3 << endl;
cout << "Addition of a real number only-" << endl;
cout << "Enter the real part: ";
int r;
cin >> r;
s4.Add(r, s2);
cout << "The resultant complex number: ";
cout << s4;
}




No comments:

Post a Comment