This is the Java Program to Add Two Complex Numbers.
Problem Description
Given two complex numbers, write a java program to add the two numbers.
Problem Solution
Add the real and imaginary parts of the numbers seperately and store them in a new variable.
Program/Source Code
Here is the source code of the Java Program to Add Two Complex Numbers. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.
//Java Program to Add Two Complex Numbers
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ComplexNumbers {
// Main function to read two complex numbers and add them
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
double i1,j1,i2,j2;
System.out.println("Enter the real part and
imaginary part of the first complex number");
try{
i1=Double.parseDouble(br.readLine());
j1=Double.parseDouble(br.readLine());
}catch (Exception e){
System.out.println("An error occurred");
return;
}
System.out.println("Enter the real part and
imaginary part of the second complex number");
try{
i2=Double.parseDouble(br.readLine());
j2=Double.parseDouble(br.readLine());
}catch (Exception e){
System.out.println("An error occurred");
return;
}
System.out.println("The first complex number is "
+ i1 + " + i(" + j1 + ")");
System.out.println("The second complex number is "
+ i2 + " + i(" + j2 + ")");
System.out.println("The sum of the two complex numbers is "
+ (i1 + i2) + " + i(" + (j1 + j2) + ")");
}
}
Program Explanation
1. In function main(), the real parts of the complex number are stored in i1 and i2 and the imaginary parts are stored in j1 and j2.
2. Then, in the third println statement real parts are added separately and imaginary parts are added separately.
advertisement
Time Complexity: O(1).
Runtime Test Cases
Case 1 (Simple Test Case): Enter the real part and imaginary part of the first complex number 4 6 Enter the real part and imaginary part of the second complex number -5 2 The first complex number is 4.0 + i(6.0) The second complex number is -5.0 + i(2.0) The sum of the two complex numbers is -1.0 + i(8.0)
Sanfoundry Global Education & Learning Series – Java Programs..
Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
Related Posts:
- Practice Programming MCQs
- Practice BCA MCQs
- Apply for Java Internship
- Apply for Computer Science Internship
- Check Java Books