JAVA-Arithmetic operation on Complex Numbers

Q. Create a class called Complex for performing arithmetic operation with complex numbers with the following criteria: 
a. A two-argument constructor 
b. Methods for add, subtract, multiply and divide two complex numbers 
c. A method to display the complex number in the form A+iB 
Write a JAVA program to implement all the arithmetic operations and display the result for Complex class.



import java.util.Scanner;
class complex
{
private double real,img;
complex(double r,double i)
{
real=r;
img=i;
}
void add(complex c1,complex c2)
{
real=c1.real+c2.real;
img=c1.img+c2.img;
}
void sub(complex c1,complex c2)
{
real=c1.real-c2.real;
img=c1.img-c2.img;
}
void mul(complex c1,complex c2)
{
real=(c1.real*c2.real-c1.img*c2.img);
img=(c1.real*c2.img+c1.img*c2.real);
}
void div(complex c1,complex c2)
{
real=(c1.real*c2.real+c1.img*c2.img)/(c2.real*c2.real-c2.img*c2.img);
img=(c1.img*c2.real-c1.real*c2.img)/(c2.real*c2.real-c2.img*c2.img);
}
void disp()
{
System.out.println(real+"+i"+img);
}
}
class prog4
{
public static void main(String args[])
{
complex c1=new complex(8,9);
complex c2=new complex(2,3);
complex c3=new complex(0,0);
complex c4=new complex(0,0);
complex c5=new complex(0,0);
complex c6=new complex(0,0);
System.out.println("1st complex number: ");
c1.disp();
System.out.println("2nd complex number: ");
c2.disp();
System.out.println("addition of complex number: ");
c3.add(c1,c2);
System.out.println("subtraction of complex number: ");
c4.sub(c1,c2);
System.out.println("multiplication of complex number: ");
c5.mul(c1,c2);
System.out.println("division of complex number: ");
c6.div(c1,c2);
c3.disp();
c4.disp();
c5.disp();
c6.disp();
}
}

Output:
1st complex number: 8.0+i 9.0
2nd complex number: 2.0+i 3.0
addition of complex number: 10.0+i 12.0
subtraction of complex number: 6.0+i 6.0
multiplication of complex number: -11.0+i 42.0
division of complex number: -8.6+i 1.2

//if you have any problem, comment below

Comments

Post a Comment