Java Program to Add Two Complex Numbers

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. Add the real parts (5 + 11), and then add the imaginary parts of the two complex numbers (10 + 9).

Program to Add Two Complex Numbers

In this Java example, we created a constructor to initialize the complex numbers. Next, create an instance of that class with default values to add those two Complex Numbers.

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;
	}
}
Java Program to Add two Complex Numbers Example

In the above program, we defined a constructor to initialize the real and imaginary values.

acn(double r, double i) {

The sum() function accepts two complex numbers as parameters. First, it adds the real parts of the two numbers. Next, it adds the imaginary parts of the two complex numbers.  

public static acn sum(acn cn1, acn cn2) {

Within the main() function, we can call sum() by passing the user-entered complex numbers and print the result.

Also visit