In this tutorial you will learn about the Java Program to add two complex numbers and its application with practical example.
Java Program to add two complex numbers
In this tutorial, we will learn to create a Java program that will add two Complex Numbers using Java programming.
Prerequisites.
Before starting with this tutorial, we assume that you are the best aware of the following java programming topics:
- Operators in Java Programming.
- Basic Input and Output function in Java Programming.
- Basic Java programming.
- While loop in Java programming.
What is a Complex Number?
A number is said to be a complex number if it is in the form of x+yi, where x and y are real numbers, and i is an indeterminate satisfying the condition i2 = −1.
For example, 2 + 3i
Algorithm:-
1 2 3 4 5 6 7 8 9 |
1. Declare the variables for the program. 2. Taking the input numbers and exponential numbers by the user. 3. Calculating the complex number. 4. Print the Result. 5. End the program. |
Program to add two Complex Numbers:-
In this program, we will first declare the values of the variables. Then we will add two numbers using the functions in java. At last, we will print the output of the program to the user using a print function.
Program:-
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 |
import java.util.*; public class Complex { //Declaring the required variables for the program. double real; double imag; //Printing the sum of the complex number public Complex(double real, double imag) { this.real = real; this.imag = imag; } //Assigning the values to the variables public static void main(String[] args) { Complex n1 = new Complex(2.3, 4.5), n2 = new Complex(3.4, 5.0), temp; temp = add(n1, n2); System.out.printf("Sum = %.1f + %.1fi", temp.real, temp.imag); } //Calculating the sum of numbers public static Complex add(Complex n1, Complex n2) { Complex temp = new Complex(0.0, 0.0); temp.real = n1.real + n2.real; temp.imag = n1.imag + n2.imag; return(temp); } } |
Output:-
In the above program, we have first initialized the required variable.
- temp = it will hold the complex value.
- real = it will hold the float value.
- img = it will hold the integer value.
Taking the input integer number and exponent from the user.