OneCompiler

Performing arithmetic operations on complex numbers

29

import java.util.*;
class complex
{
int real;
int imag;
public complex()
{
this.real=0;
this.imag=0;
}
public complex(int real,int imag)
{
this.real=real;
this.imag=imag;
}
public void display()
{
System.out.println("(" + real + ")" + "+" + "(" + imag + "i" + ")");
}

public void add(complex c1,complex c2)
{
 complex c3 = new complex();
 c3.real = (c1.real + c2.real);
 c3.imag = (c1.imag + c2.imag);
 System.out.println("Addition :");
 c3.display();
 }
 public void sub(complex c1,complex c2)
{
 complex c4 = new complex();
 c4.real = (c1.real - c2.real);
 c4.imag = (c1.imag - c2.imag);
 System.out.println("Subraction :");
 c4.display();
 }
 public void mul(complex c1,complex c2)
{
 complex c5 = new complex();
 c5.real = ((c1.real * c2.real) - (c1.imag * c2.imag));
 c5.imag = ((c1.real * c2.imag) + (c1.imag * c2.real));
 System.out.println("Multiplication:");
 c5.display();
 }
 public void div(complex c1,complex c2)
{
 complex c6 = new complex();
 c6.real = (((c1.real * c2.real) + (c1.imag * c2.imag))/ ((c2.real*c2.real)+(c2.imag*c2.imag))); 
 c6.imag = (((c1.imag * c2.real) - (c1.real * c2.imag))/((c2.real*c2.real)+(c2.imag*c2.imag)));  ;
 System.out.println("Division :");
 c6.display();
 }

}
public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in );
System.out.println("Enter complex 1:");
int a = sc.nextInt();
int b = sc.nextInt();
complex c1 = new complex(a,b);
c1.display();
System.out.println("Enter complex 2 :");
a = sc.nextInt();
b = sc.nextInt();
complex c2 = new complex(a,b);
c2.display();

  c1.add(c1,c2);
  c1.sub(c1,c2);
  c1.mul(c1,c2);
  c1.div(c1,c2);
}

}