OOPc using C++

With this blog I want to share my knowledge of OOPs and C++. I Hope this can quench your thirst for learning.Any suggestions and comments are welcome.

Monday, August 23, 2010

Program 12 - C++ program to perform arithmetic operations on complex numbers using operator overloading

/*C++ program to perform arithmetic operations on complex numbers using operator overloading*/
#include<iostream.h>
#include<conio.h>
class complex
{
          float x,y;
          public:
              complex() {}
              complex(float real,float img)
               {
                       x=real; y=img;
                }
complex operator+(complex);
complex operator-(complex);
complex operator*(complex);
void operator/(complex);
void display()
{
        cout<<x<<" + "<<y<<"i"<<endl;
}
};
complex complex::operator+(complex c)
{
         complex temp;
         temp.x=x+c.x;
         temp.y=y+c.y;
         return(temp);
}
complex complex::operator-(complex d)
{
         complex temp;
         temp.x=x-d.x;
         temp.y=y-d.y;
         return(temp);
}
complex complex::operator*(complex e)
{
        complex temp;
        temp.x=x*e.x+y*e.y*(-1);
        temp.y=x*e.y+y*e.x;
        return(temp);
}
void complex::operator/(complex f)
{
       complex temp;                               //Numerator
       temp.x=x*f.x+y*(-f.y)*(-1);        //Real number of the numerator
       temp.y=x*(-f.y)+y*f.x;               //Imaginery number of the numerator
       float deno;                                  //Denominator
       deno=f.x*f.x-f.y*f.y*(-1);        //Similar to (a+b)(a-b)=a2-b2
       cout<<temp.x<<" + "<<temp.y<<"i / "<<deno;
}

void main()
{
      clrscr();
      complex c1(5,3),c2(3,2),c3=c1+c2,c4=c1-c2,c5=c1*c2;
      c1.display();
      c2.display();
      cout<<"Addition"<<endl;
      c3.display();
      cout<<"Subtraction"<<endl;
      c4.display();
      cout<<"Multiplication"<<endl;
      c5.display();
      cout<<"Division"<<endl;
      c1/c2;
     getch();
}

OUTPUT:
5 + 3i
3 + 2i
Addition
8 + 5i
Subtraction
2 + 1i
Multiplication
9 + 19i
Division
21 + -1i / 13

No comments:

Post a Comment