Need help in understanding a nested for loop. | Sololearn: Learn to code for FREE!
+ 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.

8th Apr 2017, 9:56 AM
ElricTheCoder
ElricTheCoder - avatar
7 Answers
+ 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.
8th Apr 2017, 10:07 AM
Ashwani Kumar
Ashwani Kumar - avatar
+ 16
@Ashwani,why does inner loop increments count by everytime..shouldn't it increment by 1 only?
8th Apr 2017, 10:14 AM
ElricTheCoder
ElricTheCoder - avatar
+ 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++??
8th Apr 2017, 10:26 AM
ElricTheCoder
ElricTheCoder - avatar
+ 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
8th Apr 2017, 1:45 PM
Shamima Yasmin
Shamima Yasmin - avatar
+ 7
@Tiyam : These are nested loops, here that means for every iteration of outer loop inner loop executes 3 times.
8th Apr 2017, 10:16 AM
Ashwani Kumar
Ashwani Kumar - avatar
+ 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.
8th Apr 2017, 10:35 AM
Ashwani Kumar
Ashwani Kumar - avatar
+ 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 */
8th Apr 2017, 10:16 AM
K.C. Leung
K.C. Leung - avatar