# Java program to add two complex numbers

Given two complex numbers, we have to add two complex numbers.
Submitted by Nidhi, on March 01, 2022

Problem Solution:

In this program, we will read two complex numbers and add both complex numbers, and printed them.

Program/Source Code:

The source code to add two complex numbers is given below. The given program is compiled and executed successfully.

```// Java program to add two complex numbers

import java.util.Scanner;

class Complex {
int real;
int img;
}
public class Main {
public static void main(String[] args) {
Scanner SC = new Scanner(System.in);

Complex num1 = new Complex();
Complex num2 = new Complex();
Complex num3 = new Complex();

System.out.printf("Enter a first complex number (real and imaginary): ");
num1.real = SC.nextInt();
num1.img = SC.nextInt();

System.out.printf("Enter a second complex number (real and imaginary): ");
num2.real = SC.nextInt();
num2.img = SC.nextInt();

num3.real = num1.real + num2.real;
num3.img = num1.img + num2.img;

if (num3.img >= 0)
System.out.printf("Result is = %d + %di\n", num3.real, num3.img);
else
System.out.printf("Result is = %d %di\n", num3.real, num3.img);
}
}
```

Output:

```Enter a first complex number (real and imaginary): 13 23
Enter a second complex number (real and imaginary): 24 35
Result is = 37 + 58i
```

Explanation:

In the above program, we imported the "java.util.Scanner" package to read input from the user. And, created two classes Complex and Main. The Main class contains a static method main().

The main() method is an entry point for the program. Here, we created 3 objects of the Complex class. Then we read two complex numbers and add them. After that, we printed the result.

Preparation

What's New

Top Interview Coding Problems/Challenges!