Write a Java program to add two complex numbers with an example. Unfortunately, complex Numbers have a real part and an imaginary part, and it is tricky to perform addition on two of them.
For example, 5 + 10i means 5 is a real part, and 10 is an imaginary part. And adding another one 11 + 9i has to give 16 + 19i.
Java Program to Add two Complex Numbers
In this example, we created a constructor to initialize the complex numbers. Next, create an instance of that class with default values.
package SimpleNumberPrograms; public class acn { double real, imaginary; acn(double r, double i) { this.real = r; this.imaginary = i; } public static void main(String args[]){ acn cn1 = new acn(10.7, 22.5); acn cn2 = new acn(28.2, 68); acn addition = sum(cn1, cn2); System.out.printf("\nComplex Numbers Sum = " + addition.real + " + " + addition.imaginary + "i "); } public static acn sum(acn cn1, acn cn2) { acn addition = new acn(0, 0); addition.real = cn1.real + cn2.real; addition.imaginary = cn1.imaginary + cn2.imaginary; return addition; } }
