+ 13
Need help in understanding a nested for loop.
var count=0; for(var i=0;i<3;i++){ count--; for(var j=0;j<=2;j++){ count++; } } document.write(count); how is the answer 6?...would be glad if someone helped out.
7 odpowiedzi
+ 6
Outer loop decrements count by 1 every time
Inner loop increments count by 3 every time
Iteration by iteration in respect of outer loop:
Every iteration(i=0,1,2) count happens like this
count = -1
count = +3 //count becomes 2
And there are 3 iterations, so 2*3 becomes 6.
+ 16
@Ashwani,why does inner loop increments count by everytime..shouldn't it increment by 1 only?
+ 16
@Ashwani,thanks for clarifying...btw,if I do like this-
outer count decrement,then 3 times inner count increment.
again outer count decrement,then 3 times inner count increment....then also,the answer is right...
Is it ok to do the count-- first,and then the inner count++??
+ 16
The outer loop runs 3 times and for each iteration the inner loop runs 3 times.
The value of count changes as follows:
Outer loop 0: 0-1 = -1
inner loop 0: 0
inner loop 1: 1
inner loop 2: 2
Outer loop 1: 2-1 = 1
inner loop 0: 2
inner loop 1: 3
inner loop 2: 4
Outer loop 2: 4-1 = 3
inner loop 0: 4
inner loop 1: 5
inner loop 2: 6
+ 7
@Tiyam : These are nested loops, here that means for every iteration of outer loop inner loop executes 3 times.
+ 4
@Tiyam : This seems to be a challenge question just to test your nested loops understanding. Real logics will make more sense if you understand it properly.
+ 1
// You may debug by yourself
var writeBr = function ( v ) {
document.write ( v + "<br />" ) ;
}
var count=0;
for(var i=0;i<3;i++){
count--;
for(var j=0;j<=2;j++){
count++;
writeBr ( "i: " + i
+ ", j: " + j
+ ", count:" + count ) ;
}
}
document.write(count);
/* the result is...
i: 0, j: 0, count:0
i: 0, j: 1, count:1
i: 0, j: 2, count:2
i: 1, j: 0, count:2
i: 1, j: 1, count:3
i: 1, j: 2, count:4
i: 2, j: 0, count:4
i: 2, j: 1, count:5
i: 2, j: 2, count:6
6
*/