-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomplex.java
More file actions
55 lines (46 loc) · 1.48 KB
/
complex.java
File metadata and controls
55 lines (46 loc) · 1.48 KB
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
48
49
50
51
52
53
54
55
public class complex {
public static void main(String args[]){
// Using the full constructor
ComplexNumber num1 = new ComplexNumber(3, 4);
// Using the overloaded constructor (only real part)
ComplexNumber num2 = new ComplexNumber(5);
// Using the copy constructor
ComplexNumber num3 = new ComplexNumber(num1);
// Adding num1 and num2
ComplexNumber sum = num1.add(num2);
// Displaying the numbers and their sum
num1.display(); // Output: 3 + 4i
num2.display(); // Output: 5 + 0i
num3.display(); // Output: 3 + 4i
sum.display(); // Output: 8 + 4i
}
}
class ComplexNumber{
int real;
int imag;
ComplexNumber(int real, int imag){
this.real=real;
this.imag=imag;
}
ComplexNumber(int real){
this.real = real;
this.imag = 0;
}
ComplexNumber(ComplexNumber obj){
this.real=obj.real;
this.imag=obj.imag;
}
ComplexNumber add(ComplexNumber obj){
int realSum = this.real + obj.real; // Add real parts
int imagSum = this.imag + obj.imag; // Add imaginary parts
return new ComplexNumber(realSum, imagSum);
}
ComplexNumber subtract(ComplexNumber obj){
int realsub=this.real - obj.real;
int imagsub=this.imag - obj.imag;
return new ComplexNumber(realsub, imagsub);
}
void display(){
System.out.println(this.real + " + " + this.imag + "i");
}
}