Java program to add two complex numbers by passing class to a function
Here's an example Java program that demonstrates how to add two complex numbers by passing a class to a function:
class Complex { double real; double imag; public Complex(double real, double imag) { this.real = real; this.imag = imag; } public Complex add(Complex other) { return new Complex(this.real + other.real, this.imag + other.imag); } } public class ComplexAdditionExample { public static void main(String[] args) { Complex num1 = new Complex(2.3, 4.5); Complex num2 = new Complex(3.4, 5.0); Complex sum = addComplexNumbers(num1, num2); System.out.println("Sum = " + sum.real + " + " + sum.imag + "i"); } public static Complex addComplexNumbers(Complex num1, Complex num2) { return num1.add(num2); } }Source:www.theitroad.com
In this example, we have a Complex
class that represents a complex number. The class has two double fields, real
and imag
, which represent the real and imaginary parts of the complex number.
The Complex
class also has a add()
method that takes another Complex
object as an argument and returns a new Complex
object that represents the sum of the two complex numbers.
In the main()
method, we create two Complex
objects (num1
and num2
) and pass them to the addComplexNumbers()
function. The addComplexNumbers()
function calls the add()
method on the num1
object, passing in the num2
object as an argument. The function then returns the result of the add()
method, which is the sum of the two complex numbers.
Finally, we print the real and imaginary parts of the sum to the console.