a+bi is the common form of a complex number. Here number part ‘a’ is known as ‘real part’ and b is known as imaginary part. If a+bi and c+di are two complex numbers, then its sum is (a+c) + (b+d)i.
This is a java console program to add any two complex numbers by user.
Here class name is ‘complex’, so you should save your file with name ‘complex.java’.
Program Code:
import java.io.*;
class complex
{
int real1,imag1,real2,imag2;
void get() throws IOException
{
BufferedReader Br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("\n Enter the real part of first complex number: ");
real1=Integer.parseInt(Br.readLine());
System.out.print(" Enter the imaginary part of first complex number: ");
imag1=Integer.parseInt(Br.readLine());
System.out.print("\n Enter the real part of second complex number: ");
real2=Integer.parseInt(Br.readLine());
System.out.print(" Enter the imaginary part of second complex number : ");
imag2=Integer.parseInt(Br.readLine());
}
void display()
{
System.out.println(" \n Sum of complex numbers " + real1 + "+" + imag1 + "i and " + real2 + "+" + imag2 + "i is " + (real1+real2) + "+" + (imag1+imag2) + "i");
}
public static void main(String p[]) throws IOException
{
complex cmp = new complex();
cmp.get();
cmp.display();
}
}
Sample output:
Enter the real part of first complex number : 2
Enter the imaginary part of first complex number : 3
Enter the real part of second complex number : 5
Enter the imaginary part of second complex number : 7
Sum of complex numbers 2+3i and 5+7i is 7+10i

Be First to Comment