+ 4
Nested loop question
Hi Guys, I have a problem with this nested loop and how it works, whats the logic here... var count = 0; for(var i = 0; i < 3; i++){ count--; for(var j = 0; j <= 2; j++){ count++; } } console.log(count); // Outputs 6
5 odpowiedzi
+ 12
David
First iteration:
Count-- //which is post-operative i.e means value will decrement after use.
So value of count entering in j loop is 0
After complete iteration of j loop:
Final value of count = 3
But before next iteration of i loop it decreases by one according post-operative operation.
Count = 2
This cycle continues for next 2 iterations
And final value of count = 6.
+ 6
When ,outer for loop runs for 1st time , count =-1, then
Three time inner loop runs for , three time then
count = -1+1+1+1 =2
Then again outer for loop runs for second time then
Count =2-1=1
Then inner loop 3 times
Count=1+1+1+1=4
Then outer loop for last time
Count=4-1=3
Then inner loop 3 l of st time
Count=3+1+1+1=6
Is this clear
+ 4
the count first decremented once and then incremented thrice inside the inner loop..
and all of those repeated 3 times
so,
count in 1st loop = -1. 0, 1, 2
2nd loop = 1, 2, 3, 4
3rd loop = 3, 4, 5, 6
+ 4
David
📍The first loop is repeated 3 times.. (from i= 0 to 2)
📍For each i repetition count is decreased by 1 and the second loop is repeated 3 times (from j=0 to 2)
📍In each time count is increased by 1.
📍So count initial value is 0 then we go into the first loop (count become - 1) then enter the second loop and increase by 1 three times and become 2.. Go into the first loop again and repeart the steps decrease by one then increase by 1 three times and you get 4.. And in the last itration for the first loop you finally get count =6..
I hope my explanation is clear.. 😁
+ 3
Thank you all for your help! You all explained it pretty good