You are on page 1of 2

Design a class for Complex numbers in Java.

In addition to methods for basic operations on complex numbers, provide a method to return the number of active objects created. AIM: To write a java program to implement basic operations on complex numbers and to display the number of active objects created. ALGORITHM: STEP 1: Create a class named Complex and declare necessary variables. STEP 2: Create a constructor containing a static integer variable count, and declare it as count++ to determine the number of active objects created. STEP 3: Include functions to perform complex number addition and declare it as public static Complex add(Complex c1, Complex c2). STEP 4: Include functions to perform complex number subtraction and declare it as public static Complex subtract(Complex c1, Complex c2). STEP 5: Create needed objects for the class Complex in main class STEP 6: Initialize the parameterized constructor Complex(double rr, double ii) using the input complex numbers. STEP 7: Perform the operations addition and subtraction for the given input numbers STEP 8: Display the result PROGRAM: import java.util.*; import java.io.*; class Complex { private double r; private double i; static double a1; static double b1; static int count=0; Complex(double rr, double ii) { r = rr; i = ii; count++; } Complex() { count++; } public static Complex add(Complex c1, Complex c2) { a1=c1.r+c2.r; b1=c1.i+c2.i; if(b1<0) System.out.println(a1+""+b1+"i"); else System.out.println(a1+"+"+b1+"i"); return null;

} public static Complex subtract(Complex c1, Complex c2) { a1=c1.r-c2.r; b1=c1.i-c2.i; if(b1<0) System.out.println(a1+""+b1+"i"); else System.out.println(a1+"+"+b1+"i"); return null; } public void show() { System.out.println(r+"+"+i+"i"); } public static void main(String[] args) { Complex c = new Complex(10, 12); Complex d = new Complex(4, 18); Complex e = new Complex(); System.out.println("Number of Objects created :"+count); System.out.print("First number:"); c.show(); System.out.print("Second number:"); d.show(); System.out.print("Sum:"); e = add(c,d); System.out.print("Difference:"); e =subtract(c,d); } }

You might also like