Can someone explain how the output of this question is as given? Q4. What is the
ID: 3593887 • Letter: C
Question
Can someone explain how the output of this question is as given?
Q4. What is the output when the following is executed? (20 marks) public class Decr i int d = 9; Decr lefti public Decr (Decr lefti ( this.left left public void decr if (-d 0) st d = 9; if (left != null), { left decr ) public int co t return (eft null) ? d (d10left.co) public static void main (String(l args) i Decr [ ds new Decr 13]i ds[2] new Decr ( null); ds [1 new Decr (ds 12]) ds [0] = new Decr (ds [1]); for (int i = 0; i = 0; i--) { System.out.printin ("dsi"" dsil.co) dsI2J 3 dsI1 SCExplanation / Answer
public class Decr {
int d = 9;
Decr left;
public Decr(Decr left) {
this.left = left;
}
public void decr() {
//
if (--d < 0) {
d = 9;
//System.out.println(left);
if (left != null) {
left.decr();
}
}
}
public int c() {
return (left == null) ? d : (d + 10 * left.c());
}
public int d() {
return d ;
}
public static void main(String[] args) {
Decr[] ds = new Decr[3];
// all DS are assigned to null
ds[2] = new Decr(null);
ds[1] = new Decr(ds[2]);
ds[0] = new Decr(ds[1]);
// loop for 100 time and change the each value of ds
// ds[2].d = 8
// ds[1].d = 9
// ds[0].d = 9
// where where when d is less then 0 then the value is set to 9 and move towards to another ds
for (int i = 0; i < 100; i++) {
ds[0].decr();
}
// loop for 3 time and print
// ds[2].d = 8 => 8
// ds[1].d = ds[2].c() + 9 => 89
// ds[0].d = ds[2].c() + ds[1].c() + 9 => 899
for (int i = 2; i >= 0; i--) {
System.out.println("Ds[" + i + "]: " + ds[i].c());
System.out.println();
}
}
}