A complex number is a number that consists of a real part and an imaginary part, and is written in the form a + bi, where a is the real part and b is the imaginary part. To add two complex numbers, simply add their real parts together and their imaginary parts together.
- The real and imaginary parts are added separately.
- A class can be used to represent and manipulate complex numbers in Java.
Illustration:
Input: z₁ = 4 + 5i, z₂ = 10 + 5i
Output: 14 + 10iInput: z₁ = 3 + 2i, z₂ = 6 + 7i
Output: 9 + 9i
Formula to Add Two Complex Numbers
If we have two complex numbers:
- z₁ = a + bi
- z₂ = c + di
Then their addition is calculated as:
z₁ + z₂ = (a + c) + (b + d)i
Adding Two Complex Numbers
The addition of two complex numbers is done by adding the real parts and imaginary parts separately:
Example: Add Two Complex Numbers
class ComplexNumber {
int real, imaginary;
// Constructor
ComplexNumber(int real, int imaginary) {
this.real = real;
this.imaginary = imaginary;
}
// Method to add two complex numbers
ComplexNumber add(ComplexNumber other) {
return new ComplexNumber(
this.real + other.real,
this.imaginary + other.imaginary
);
}
// Method to display the complex number
void display() {
System.out.println(real + " + " + imaginary + "i");
}
public static void main(String[] args) {
ComplexNumber c1 = new ComplexNumber(4, 5);
ComplexNumber c2 = new ComplexNumber(10, 5);
System.out.print("First Complex Number: ");
c1.display();
System.out.print("Second Complex Number: ");
c2.display();
ComplexNumber result = c1.add(c2);
System.out.print("Sum: ");
result.display();
}
}
Output
First Complex Number: 4 + 5i Second Complex Number: 10 + 5i Sum: 14 + 10i
Explanation: In this example, two complex numbers (4 + 5i and 10 + 5i) are created using the ComplexNumber class. The add() method adds their real parts and imaginary parts separately, creates a new complex number with the sum, and the display() method prints the result.