-->

Hello,This is me!

ITEngineer8995

Professional Coder Coding is my passion

Saturday, May 9, 2020

Java Program to add two complex numbers

  • May 09, 2020
  • by


Java Program to add two complex numbers


In this Java Program, we perform addition of two complex numbers.


Complex numbers generally consists of two parts, real number and imaginary number. In this program, we add real number together and imaginary numbers together. The imaginary number has a letter i written after the number. Eg. 2i, 5i etc.


                                    2 + 5i  + 4 + 3i = 6 + 8i


Step 1 : Create two variables named real and img to store both the numbers.


Step 2 : Create a Constructor to initialize the complex number. 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.


Step 3 : Declare a method sum() to add the two numbers by adding their real and imaginary parts together.


Step 4 : Create a temporary complex number to hold the sum of the two numbers.


Step 5 : Return the output complex number.


Step 6 : Display the result by using System.out.printf.


Program :


public class AddTwoComplexNumbers

    {

        //for real and imaginary parts of complex numbers

        double real, img;

     

        //constructor to initialize the complex number

        AddTwoComplexNumbers(double r, double i)

        {

            this.real = r;

            this.img = i;

        }

     

        public static AddTwoComplexNumbers sum(AddTwoComplexNumbers a1, AddTwoComplexNumbers a2)

        {

            //creating a temporary complex number to hold the sum of two numbers

            AddTwoComplexNumbers temp = new AddTwoComplexNumbers(0,0);

         

            temp.real = a1.real + a2.real;

            temp.img = a1.img + a2.img;

         

            //returning the output complex number

            return temp;

        }

     

        public static void main(String [] args)

        {

            AddTwoComplexNumbers a1 = new AddTwoComplexNumbers(5.5,4);

            AddTwoComplexNumbers a2 = new AddTwoComplexNumbers(1.2,3.5);

            AddTwoComplexNumbers temp = sum(a1,a2);

            System.out.printf("Sum is:"+temp.real+" + "+temp.img+"i");

        }

}


Output: 


Sum is : 6.7 + 7.5i


For execution of the same do visit my YouTube Channel:


https://youtu.be/E7c50kFqlFE

A blog full of codes of various languages like Java, .net, C, C++ etc with their outputs and some other IT stuff.

0 comments:

Post a Comment

ITEngineer8995
India

SEND ME A MESSAGE

Search This Blog

Powered by Blogger.

Pages