Sunday, 12 March 2023

7. Create a complex number class. The class should have a constructor and methods to add, subtract and multiply two complex numbers and to return the real and imaginary parts.



class Complex
{
    int real,img;
   
    Complex()
    {
        real = img = 0;
    }
   
    Complex(int x)
    {
        real = img = x;
    }
   
    Complex(int x,int y)
    {
        real = x;
        img = y;
    }
   
    Complex add(Complex a, Complex b)
    {
        Complex temp = new Complex();
       
        temp.real = a.real + b.real;
        temp.img = a.img + b.img;
       
        return (temp);
    }
   
    Complex sub(Complex a, Complex b)
    {
        Complex temp = new Complex();
       
        temp.real = a.real - b.real;
        temp.img = a.img - b.img;
       
        return (temp);
    }
   
    Complex mul(Complex a, Complex b)
    {
        Complex temp = new Complex();
       
        temp.real = a.real * b.real;
        temp.img = a.img * b.img;
       
        return (temp);
    }
   
    void display()
    {
        System.out.print("\nreal: " + real + "  imaginary: " + img);
    }
}

class Program7
{
    public static void main(String args[])
    {
        Complex c1 = new Complex(2,3);
        Complex c2 = new Complex(2,5);
        Complex c3 = new Complex();
       
        c3 = c1.add(c1,c2);
        c3.display();
       
        c3 = c1.sub(c1,c2);
        c3.display();
       
        c3 = c1.mul(c1,c2);
        c3.display();
       
    }
}


No comments:

Post a Comment

python programs

1. sum of two number