Pages

Sunday, March 29, 2015

Write a Program that Add Two Complex Number

Input

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package AddTwoComplexNumber;

public class complex {
// declare Instance Variable

    private int real;
    private int imaginary;

// constructor with parameter
    public complex(int realN, int imgN) {
        real = realN;
        imaginary = imgN;
    }

// constructor without parameter
    public complex() {
        real = 0;
        imaginary = 0;
    }

// setter method
    public void setReal(int realN) {
        real = realN;
    }

    public void setImgN(int imgN) {
        imaginary = imgN;
    }

// getter method
    public int getReal() {
        return real;
    }

    public int getImgN() {
        return imaginary;
    }

// Add complex Number
    public complex addCmplxNo(complex c) {
//create an object of complex
        complex temp = new complex();
        temp.setReal(this.getReal() + c.getReal());
        temp.setImgN(this.getImgN() + c.getImgN());
        return temp;
    }
}

Input (Driver File):


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package AddTwoComplexNumber;

public class ComplexTest{

    public static void main(String[] args) {

//create an object of complex
        complex a = new complex(8, 9);
        complex b = new complex(3, 4);
        complex c = a.addCmplxNo(b);

        System.out.println("(" + a.getReal() + "," + a.getImgN() + ")");
        System.out.println("(" + b.getReal() + "," + b.getImgN() + ")");


        System.out.print("The sum of  ");
        System.out.print("(" + a.getReal() + "," + a.getImgN() + ")");
        System.out.print("and (" + b.getReal() + "," + b.getImgN() + ")");

        System.out.println("is\n\t(" + c.getReal() + "," + c.getImgN() + ")");

    }
}

Output


(8,9)
(3,4)
The sum of  (8,9)and (3,4)is
 (11,13)

No comments:

Post a Comment