Addition of Complex numbers using Operator Overloading cpp
In this program, we are going see how to perform and display Addition of Complex numbers using Function Overloading  in C++ Programming Language.
 


The Code given below can be used in TURBO C++ Compilers: -

#include <iostream.h>
#include <conio.h>

class Complex
{
    int real, imag;

    public:
    Complex(int r = 0, int i = 0)
    {
        real = r;
        imag = i;
    }
    Complex operator+(Complex obj)
    {
        Complex tobj;
        tobj.real = real + obj.real;
        tobj.imag = imag + obj.imag;
        return tobj;
    }
    void display()
    {
        cout << "\n\nThe result after addition: " << real << " + " << imag << "i" << endl;
    }
};

void main()
{
    clrscr();
    int r1, r2, i1, i2;
    cout << "Enter the real part of equation 1: ";
    cin >> r1;
    cout << "Enter the integer of imaginary part of equation 1: ";
    cin >> i1;
    cout << "\nFirst Equation is: " << r1 << " + " << i1 << "i";
    cout << "\n\nEnter the real part of equation 2: ";
    cin >> r2;
    cout << "Enter the integer of imaginary part of equation 2: ";
    cin >> i2;
    cout << "\nSecond Equation is: " << r2 << " + " << i2 << "i";
    Complex c1(r1, i1);
    Complex c2(r2, i2);
    Complex c3;
    c3 = c1 + c2;
    c3.display();
    getch();
}

//.......Coded by SAHIL SHAIKH


The Code given below can be used in gcc/g++ Compilers: -

#include <iostream>
using namespace std;

class Complex
{
    int real, imag;

    public:
    Complex(int r = 0, int i = 0)
    {
        real = r;
        imag = i;
    }
    Complex operator+(Complex obj)
    {
        Complex tobj;
        tobj.real = real + obj.real;
        tobj.imag = imag + obj.imag;
        return tobj;
    }
    void display()
    {
        cout << "\n\nThe result after addition: " << real << " + " << imag << "i" << endl;
    }
};

int main()
{
    int r1, r2, i1, i2;
    cout << "Enter the real part of equation 1: ";
    cin >> r1;
    cout << "Enter the integer of imaginary part of equation 1: ";
    cin >> i1;
    cout << "\nFirst Equation is: " << r1 << " + " << i1 << "i";
    cout << "\n\nEnter the real part of equation 2: ";
    cin >> r2;
    cout << "Enter the integer of imaginary part of equation 2: ";
    cin >> i2;
    cout << "\nSecond Equation is: " << r2 << " + " << i2 << "i";
    Complex c1(r1, i1);
    Complex c2(r2, i2);
    Complex c3;
    c3 = c1 + c2;
    c3.display();
    return 0;
}

//.......Coded by SAHIL SHAIKH

#ENJOY CODING

Post a Comment

FOR ANY DOUBTS AND ERRORS FEEL FREE TO ASK. YOUR DOUBTS WILL BE ADDRESSED ASAP

Previous Post Next Post