**(Complex Numbers) Create a class called Complex for performing arithmetic with complex numbers. Complex numbers have the form
realPart + imaginaryPart * i
where i is
Write a program to test your class. Use floating-point variables to represent the private data of the class. Provide a constructor that enables an object of this class to be initialized when it’s declared. Provide a no-argument constructor with default values in case no initializers are provided. Provide public methods that perform the following operations:
a) Add two Complex numbers: The real parts are added together and the imaginary parts are added together.
b) Subtract two Complex numbers: The real part of the right operand is subtracted from the real part of the left operand, and the imaginary part of the right operand is subtracted from the imaginary part of the left operand.
c) Print Complex numbers in the form (realPart, imageinaryPart).
**

*
Advertisements
*

**Solution**

`public class no13`

{

private double real;

private double imaginary;

```
``` // Initialize both parts to 0

public no13()

{

this( 0.0, 0.0 );

} // end Complex no-argument constructor

public no13( double r, double i )

{

real = r;

imaginary = i;

} // end Complex two-argument constructor

// Add two Complex numbers

public no13 add( no13 right )

{

return new no13( real + right.real,

imaginary + right.imaginary );

} // end method add

// Subtract two Complex numbers

public no13 subtract( no13 right )

{

return new no13( real - right.real,

imaginary - right.imaginary );

} // end method subtract

// Return String representation of a Complex number

public String toString()

{

return String.format( "(%.1f, %.1f)", real, imaginary );

} // end method toComplexString;

} // end class Complex

class ComplexTest

{

public static void main( String args[] )

{

// initialize two numbers

no13 a = new no13( 9.5, 7.7 );

no13 b = new no13( 1.2, 3.1 );

System.out.printf( "a = %s\n", a.toString() );

System.out.printf( "b = %s\n", b.toString() );

System.out.printf( "a + b = %s\n", a.add( b ).toString() );

System.out.printf( "a - b = %s\n", a.subtract( b ).toString() );

} // end main

} // end class ComplexTest

solved by : arifur rahman