|
| 1 | +--- |
| 2 | +title: Java Program to Add Two Complex Numbers |
| 3 | +shortTitle: Add Two Complex Numbers |
| 4 | +description: In this tutorial, we will write a Java program to add two complex numbers. |
| 5 | +--- |
| 6 | + |
| 7 | +Complex numbers have two parts – real part and imaginary part. When adding complex numbers we add real parts together and imaginary parts together as shown in the following diagram. |
| 8 | + |
| 9 | + |
| 10 | +## Adding two complex numbers in Java |
| 11 | + |
| 12 | +n this program we have a class `ComplexNumber`. In this class we have two instance variables `real` and `img` to hold the real and imaginary parts of complex numbers. |
| 13 | + |
| 14 | +We have declared a method sum() to [add the two numbers](./add-two-integers) by adding their real and imaginary parts together. |
| 15 | + |
| 16 | +The constructor of this class is used for initializing the complex numbers. For e.g. when we create an instance of this class like this `ComplexNumber temp = new ComplexNumber(0, 0);`, it actually creates a complex number `0 + 0i`. |
| 17 | + |
| 18 | +### Code: |
| 19 | + |
| 20 | +```java |
| 21 | +public class ComplexNumber{ |
| 22 | + //for real and imaginary parts of complex numbers |
| 23 | + double real, img; |
| 24 | + |
| 25 | + //constructor to initialize the complex number |
| 26 | + ComplexNumber(double r, double i){ |
| 27 | + this.real = r; |
| 28 | + this.img = i; |
| 29 | + } |
| 30 | + |
| 31 | + public static ComplexNumber sum(ComplexNumber c1, ComplexNumber c2) |
| 32 | + { |
| 33 | + //creating a temporary complex number to hold the sum of two numbers |
| 34 | + ComplexNumber temp = new ComplexNumber(0, 0); |
| 35 | + |
| 36 | + temp.real = c1.real + c2.real; |
| 37 | + temp.img = c1.img + c2.img; |
| 38 | + |
| 39 | + //returning the output complex number |
| 40 | + return temp; |
| 41 | + } |
| 42 | + public static void main(String args[]) { |
| 43 | + ComplexNumber c1 = new ComplexNumber(5.5, 4); |
| 44 | + ComplexNumber c2 = new ComplexNumber(1.2, 3.5); |
| 45 | + ComplexNumber temp = sum(c1, c2); |
| 46 | + System.out.printf("Sum is: "+ temp.real+" + "+ temp.img +"i"); |
| 47 | + } |
| 48 | +} |
| 49 | +``` |
| 50 | +### Output: |
| 51 | + |
| 52 | +```text |
| 53 | +Sum is: 6.7 + 7.5i |
| 54 | +``` |
0 commit comments