Open In App

Java Program to Add two Complex Numbers

Last Updated : 13 Jul, 2022
Comments
Improve
Suggest changes
33 Likes
Like
Report

Complex numbers are numbers that consist of two parts — a real number and an imaginary number. Complex numbers are the building blocks of more intricate math, such as algebra. The standard format for complex numbers is a + bi, with the real number first and the imaginary number last.

General form for any complex number is:

a+ib

Where "a" is real number and "b" is Imaginary number.

Construction of Complex number

For creating a complex numbers, we will pass imaginary numbers and real numbers as parameters for constructors.

Time Complexity: O(1)

Auxiliary Space: O(1)

 
Add function

  • Basically, addition of two complex numbers is done by adding real part of the first complex number with real part of the second complex number.
  • And adding imaginary part of the first complex number with the second which results into the third complex number.
  • So that means our add() will return another complex number.


 

Ex. addition of two complex numbers

(a1) + (b1)i -----(1)

(a2)+ (b2)i -----(2)

adding (1) and (2) will look like

(a1+a2) + (b1+b2)i

Function Definition: 

ComplexNumber add(ComplexNumber n1, ComplexNumber n2){
    
  ComplexNumber res = new ComplexNumber(0,0); //creating blank complex number 
  
  // adding real parts of both complex numbers
  res.real = n1.real + n2.real;
  
  // adding imaginary parts
  res.image = n1.image + n2.image;
  
  // returning result
  return res;

}

 
 Code: 


Output
first Complex number: 4 +i5
Second Complex number: 10 +i5
Addition is :
14 +i10

Time Complexity: O(1)

Auxiliary Space: O(1)


 


Next Article

Similar Reads