Question
Create a class called Complex for performing arithmetic with complex numbers. Use the given testing program to test your class. Complex numbers have the form
Create a class called Complex for performing arithmetic with complex numbers. Use the given testing program to test your class. Complex numbers have the form realPart + imaginaryPart * i where i is (- 1)^(). Use integers to represent the realPart and imaginaryPart components as the private members of the class. Provide a constructor function that enables an object of this class initialized when it is declared. The constructor should contain default values in case no initial values provided. Provide public member functions for each of the following:
a) Addition of two Complex numbers: The real parts added together and the imaginary parts added together. b) Subtraction of 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) Printing Complex numbers in the form (a, b) where a is the real part and b is the imaginary part.
The testing program is given as follows:
public static void main(String[]args) {
Complex c1= new Complex(3, -5);
Complex c2= new Complex(8, 7);
Complex sum = new Complex();
sum.add(c1, c2);
Complex diff = new Complex();
diff.subtract(c1, c2);
System.out.println("The sum is "); Complex.printResult(sum);
System.out.println("The difference is "); Complex.printResult(diff);
}
///// Code
public class Complex { private int real; private int imaginary; Complex(){ // TODO initialize real and imaginary with a value (e.g., 0) } Complex(int x, int y){ // TODO initialize real and imaginary with the inputs x and y respectively } public Complex add (Complex x, Complex y) { // TODO add two complex numbers x and y return this; } public Complex subtract (Complex x, Complex y) { // TODO subtract the complex number y from the complex number x return this; } public void display () { // Display the real and imaginary parts of the given complex number. System.out.println("("+real+","+imaginary+")"); } public static void main(String[] args) { // TODO // Here is an example of a test program Complex num1=new Complex(5, 8); Complex num2=new Complex(2, -9); System.out.println("The two numbers:"); num1.display(); num2.display(); Complex num3=new Complex(); Complex num4=new Complex(); System.out.println("The sum:"); num3.add(num1, num2); num3.display(); System.out.println("The difference:"); num4.subtract(num1, num2); num4.display(); } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started