Are you searching for how to add two complex numbers in Java programming language, then this answer for you.
Copy the below java program and execute it to see the program output.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | /** * Java program to Add two complex numbers. */ import java.util.*; class Complex { // Declaring variables int real, imaginary; // Empty Constructor Complex() { } // Constructor to accept real and imaginary part Complex(int tempReal, int tempImaginary) { real = tempReal; imaginary = tempImaginary; } Complex addComp(Complex C1, Complex C2) { // creating temporary variable Complex temp = new Complex(); // adding real part of complex numbers temp.real = C1.real + C2.real; // adding Imaginary part of complex numbers temp.imaginary = C1.imaginary + C2.imaginary; // returning the sum return temp; } } public class AddTwoComplexNumbers { public static void main(String[] args) { Complex C1 = new Complex(3, 2); System.out.println("Complex number 1 : " + C1.real + " + i" + C1.imaginary); // Second Complex number Complex C2 = new Complex(9, 5); // printing second complex number System.out.println("Complex number 2 : " + C2.real + " + i" + C2.imaginary); // for Storing the sum Complex C3 = new Complex(); // calling addComp() method C3 = C3.addComp(C1, C2); // printing the sum System.out.println("Sum of complex number : " + C3.real + " + i" + C3.imaginary); } } |
Program Output
1 2 3 | Complex number 1 : 3 + i2 Complex number 2 : 9 + i5 Sum of complex number : 12 + i7 |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.