Java Program to Add Two Complex Numbers

by | Aug 22, 2021 | Java Programs

Home » Java » Java Programs » Java Program to Add Two Complex Numbers

Introduction

Complex Numbers are numbers that have two distinct components namely a real part and an imaginary part. Complex numbers are generally designated in the following form:

a1 + ib1 and a2+ib2

For the first number mentioned above, a1 is the real part of the number and b1 is the complex part of the number. For the second number mentioned above, a2 is the real part of the number and b2 is the imaginary part of the number.

The task at hand is to add two complex numbers in Java. To perform this calculation, you need to set up a parameterized constructor with the help of a default constructor. A default constructor is also commonly referred to as an empty constructor. Thereafter, you will have to pass the real and the imaginary parts of the number while calling said parameterized constructor. The program below is uses the method addComp to obtain the result of adding the two complex numbers.

Example

Input: a1 = 4, and b1 = 8
a2 = 5, and b2 = 7

Output Sum = 9 + i15

Explanation

(4 + i8) + (5 + i7)
= (4 + 5) + i(8 + 7)
= 9 + i15

Input: a1 = 9, b1 = 3
a2 = 6, b2 = 1

Output: Sum = 15 + i4

Sample Code

The following code given illustrates how to add two complex numbers using Java

import java.util.*;
class Complex
{
int real, imaginary;
Complex ()
{
}
Complex (int tempReal, int tempImaginary)
{
real = tempReal;
imaginary = tempImaginary;
}
Complex addComp (Complex C1, Complex C2)
{
Complex temp = new Complex();
temp.real = c1.real + c2.real;
temp.imaginary = c1.imaginary + c2.imaginary;
return temp;
}
}
public class Demo
{
public static void main (String args [])
{
Complex C1 = new Complex (3 , 2);
System.out.println (“Complex Number 1” :) + C1.real + “ + i” + C1.imaginary);
Complex c2 = new Complex (9 , 5);
System.out.println (“Complex Number 2 : ” + c2.real + “ + i” + c2.imaginary);
Complex C3 = new Complex();
C3 = C3.addComp(C1, C2);
System.out.println (“Sum of the complex numbers is : ” + C3.real + “ + i” + C3.imaginary);
}
}

 

Output

Complex Number 1 : 3 + i2
Complex Number 2 : 9 + i5
Sum of the complex numbers: 12 + i7

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author