Add Two Complex Numbers in Java

Exercise:

Write a Java Program to add two complex numbers by passing an object to a function.

Click Here to View the Solution!
public class Complex{
  
     double real;
     double imag;
  
     //Function to store complex number
     public Complex(double real, double imag) {
         this.real = real;
         this.imag = imag;
     }
        public static void main(String[] args) {
        Complex n1 = new Complex(6.7, 8.9),
                 n2 = new Complex(2.1, 3.0),
                 temp;
        temp = addition(n1, n2);
        System.out.printf("Sum = %.1f + %.1fi", temp.real, temp.imag);
     }
     
    //User defined function to add complex numbers
     public static Complex addition(Complex n1, Complex n2)
     {
         Complex temp = new Complex(0.0, 0.0);
         temp.real = n1.real + n2.real;
         temp.imag = n1.imag + n2.imag;
         return(temp);
     }
 } 
Click Here to View the Output!
Sum = 8.8 + 11.9i
Click Here to View the Explanation!
  • In this program, a class called Complex is created. It is constructed for the purpose of representing complex numbers which have a real and an imaginary part. Therefore, it contains two data members or variables namely real and imag which represent just the same.
  • This class also has a constructor which initializes values of the two data members.
  • A function called add() takes two arguments of the type Complex and returns a value of complex type as well.
  •  The working of the add() function is such that it adds the real part of the first argument n1 to the real part of the second argument n2. Similarly, it adds the imaginary parts of both the arguments. The results of these additions are stored in real and imag data members of a Complex type object called temp. At the end of the function, temp is returned.
  • So when the main function of the program is executed, after calling the add() function, the results of the real and imag part of temp are displayed on the screen using printf().

%d bloggers like this: