Add Two Complex Number Program In Java - Free Web Development || UI Development || React JS || Angular

Latest

Free Web Development ||Free UI Development || React JS || HTML5 || CSS3 || JavaScript || Angular Learn Web Development || Frontend Developer || Full Stack Developer

1 / 3
Welcome to Shravan Ghanchi
2 / 3
3 / 3

Sunday, December 13, 2020

Add Two Complex Number Program In Java

Add Two  Complex Number Program  In Java 

Complex numbers have two parts real parts and imaginary part. We Will write a java program to add two complex numbers. When we add real parts together and the imaginary part together as shown in the below.

5+4i   +   5+6i   =   10+10i





In this program we have a class ComplexNumber. 

two instances variables real and img to hold the real and imaginary to hold the real and imaginary part of complex no.

We have declared a method sum() to add the two no. by adding their real and imaginary part together.

The constructer of the class is used for initialized the complex no. When we create an instance of this class like this complex number temp=new complex number(0,0);

It actually creates a complex number 0+0i;



package com;

 

public class ComplexNumber {

   

    double real,img;

    ComplexNumber(double r,double i)

    {

       this.real=r;

       this.img=i;

      

    }

    public static ComplexNumber sum(ComplexNumber c1,ComplexNumber c2)

    {

       ComplexNumber temp=new ComplexNumber(0,0); 

       temp.real=c1.real+c2.real;

       temp.img=c1.img+c2.img;

       return temp;

      

    }

    public static void main(String[] args)

    {

       ComplexNumber c1=new ComplexNumber(5,4);

       ComplexNumber c2=new ComplexNumber(5,6);

       ComplexNumber temp=sum(c1,c2);

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

      

    }

  }


Output:10+10i


1 comment:

Snow
Forest
Mountains
Snow
Forest
Mountains