In the following Java code....when does ds[2] get the value 7 and the other reta
ID: 3591114 • Letter: I
Question
In the following Java code....when does ds[2] get the value 7 and the other retain the value 9? please explain
public class D {
int d = 9;
D left;
public D(D left) {
this.left = left;
}
public int getD() {
return d;
}
public void decr() {
d--;
if (d == -1) {
d = 9;
if (left != null) {
left.decr();
}
}
}
public int c() {
if(left == null) {
return d;
} else {
return d + 10 * left.c();
}
}
public static void main(String[] args) {
D[] ds = new D[3];
ds[2] = new D(null);
ds[1] = new D(ds[2]);
ds[0] = new D(ds[1]);
for(int i = 0; i < 200; i++) {
ds[0].decr();
}
System.out.println("ds[2]: " + ds[2].c());
System.out.println("ds[1]: " + ds[1].c());
System.out.println("ds[0]: " + ds[0].c());
System.out.println("ds.length: " + ds.length);
}
}
Answer:
ds[2]: 7
ds[1]: 79
ds[0]: 799
ds.length: 3
Explanation / Answer
Hi,
This is a kind of tree recursion problem, hence i can understand why you got confused, let me explain it line by line
D[] ds = new D[3];
ds[2] = new D(null);
ds[1] = new D(ds[2]);
ds[0] = new D(ds[1]);
with these 3 lines, we established an array of 3 D objects like
ds[0]->left=ds[1]->left=ds[2]->left=null
now, we are calling the decr() operator on ds[0] 100 times, lets look at what its doing,
public void decr() {
d--;
if (d == -1)
{
d = 9;
if (left != null) {
left.decr();
}
}
}
in this, as long as d!=-1, we just decrement and return, hence if we iterate for less than 9 times, no other values are changed, things get interesting if we iterate for more, if d=9 and then we iterate for 10 times,
on the 10th time, d becomes -1 and then we assign 9 back to d and then go to left and start decrementing,
Now, we are iterating for 200 times, i.e we decrement d[0] 9 times and then decrement d[1] once for every 10 times and d[2] once for every 100 times,
therefore since no of iterations is 200, d[2] is reduced twice and becomes d[2]=7, where as we are always resetting value of ds[0] to 9 in the else statement, hence ds[0] is retained,
you can understand this by decreasing the number of iterations to say multiples of 10 and then multiples of 100,then we know what exactly the loop is doing.
Hope this was helpful,
Thumbs up if this was helpful, otherwise let me know in comments
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.