Q:

Java program to add two complex numbers

belongs to collection: Java Basic Programs

0

Java program to add two complex numbers

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to extract the last two digits from a... >>
<< Java program to calculate the product of two binar...