Complex Number Addition

Aim:

This webpage demonstrates a simple Java program that performs addition of two complex numbers.

Algorithm:

The algorithm is as follows:

  1. Create a class complex to represent complex numbers.
  2. Create another class com with a main method to perform addition of two complex numbers.

Java Code:

import java.io.*;
import java.util.Scanner;

class complex {
    int real, img;

    complex() {}

    complex(int Treal, int Timg) {
        real = Treal;
        img = Timg;
    }

    complex addcomplex(complex c1, complex c2) {
        complex ctemp = new complex();
        ctemp.real = c1.real + c2.real;
        ctemp.img = c1.img + c2.img;
        return ctemp;
    }
}

class com {
    public static void main(String args[]) {
        Scanner ic = new Scanner(System.in);
        int a, b, c, d;
        System.out.println("Enter a,b value");
        a = ic.nextInt();
        b = ic.nextInt();
        System.out.println("Enter c,d value");
        c = ic.nextInt();
        d = ic.nextInt();
        complex c1 = new complex(a, b);
        complex c2 = new complex(c, d);
        complex c3 = new complex();
        c3 = c3.addcomplex(c1, c2);
        System.out.println("Real value: " + c3.real);
        System.out.println("Imaginary value: " + c3.img);
        System.out.println("Complex addition: " + c3.real + "+i" + c3.img);
    }
}
            

Output: