Javatpoint Logo
Javatpoint Logo

Java Program to Add two Complex Numbers

Complex numbers consist of two components - a real number and an imaginary number, which are distinct from each other. These numbers are widely used in mathematics, particularly in algebra. The standard format for a complex number is a + bi, where "a" represents the real number component and "b" represents the imaginary number component.

The general representation of a complex number follows a specific format, which includes both a real part and an imaginary part.

Example

Algorithm:

  1. Define a class named "ComplexNumber" with variables "real" and "imag" to hold the real and imaginary parts of the complex number.
  2. To initialise the real and imaginary components of the complex number, create a constructor for the class.
  3. Define a method named "showC" to print the complex number as (a + bi).
  4. Define a static method named "add" to add two complex numbers. The method takes two ComplexNumber objects as parameters and returns a ComplexNumber object.
  5. Create a new ComplexNumber object to store the addition result in the add method.
  6. Add the real parts of the two complex numbers and assign the result to the real part of the new ComplexNumber object. Similarly, add the imaginary parts of the two complex numbers and assign the result to the imaginary part of the new ComplexNumber object.

Implementation:

Filename: ComplexNumber.java

Output:

First Complex number: (4 + 5i)
Second Complex number: (10 + 5i)
Addition is :
(14 + 10i)

Complexity Analysis:

The time complexity of the add method in the ComplexNumber class is O(1), as it performs a constant number of operations (adding the real and imaginary parts of the complex numbers). The time complexity of the showC method is also O(1), as it performs a constant number of operations (printing the real and imaginary parts in a specific format). The time complexity of the main method is also O(1), as it creates two complex numbers, calls the add method to perform the addition, and then calls the showC method to display the result.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA