;

Java Program to Add Two Complex Numbers


Tutorialsrack 19/04/2021 Java

In this Java program, you’ll learn how to add two complex numbers in java. Before starting this program, let us first know what the complex number is. 

What is a Complex Number?

A complex number is a number of the form a + bi, where a and b are real numbers, and i is a symbol called the imaginary unit, and satisfying the equation i2 = -1. For example, 2 + 3i is a complex number.

Complex Numbers can be added and subtracted like regular numbers. The real parts and imaginary parts are respectively added or subtracted or even multiplied and divided.

Java Program to Add Two Complex Numbers

Java Program to Add Two Complex Numbers
// Java Program to Add Two Complex Numbers

public class ComplexNumber {

	double real, img;

	// constructor to initialize the complex number
	ComplexNumber(double r, double i) {
		this.real = r;
		this.img = i;
	}

	public static ComplexNumber sum(ComplexNumber c1, ComplexNumber c2) {
		// creating a temporary complex number to hold the sum of two numbers
		ComplexNumber temp = new ComplexNumber(0, 0);

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

		// returning the output complex number
		return temp;
	}

	public static void main(String args[]) {
		ComplexNumber c1 = new ComplexNumber(5.5, 5);
		ComplexNumber c2 = new ComplexNumber(2.2, 2.2);
		ComplexNumber temp = sum(c1, c2);
		System.out.printf("Sum is: " + temp.real + " + " + temp.img + "i");
	}
}
Output

Sum is: 7.7 + 7.2i

Understanding the Program

  • In the above program, we created a class ComplexNumber with two member variables: real and img. As the name suggests, the real stores the real part of a complex number, and img stores the imaginary part.
  • The ComplexNumber class has a constructor which initializes the value of real and img.
  • We also created a new static function sum() that takes two complex numbers as parameters and returns the result as a complex number.
  • Inside the sum() method, we just add the real and imaginary parts of complex numbers c1 and c2, store it in a new variable temp and return temp.
  • Then, in the calling function main(), we print it using printf() function.


Related Posts



Comments

Recent Posts
Tags