+ 2

How the ans is 12 ?

var b=0; for(var i=0;i<=2;i++){ for(var j=0;j<=3;j++){ b++} } alert(b);

11th Jan 2023, 12:56 PM
Mohammad Tausiful Alam
Mohammad Tausiful Alam - avatar
4 Respostas
+ 5
Outer loop runs the inner loop 3 times. Inner loop runs the b increment 4 times. b is incremented from 0 by 3 * 4 times, which is +12.
11th Jan 2023, 1:02 PM
Mozzy
Mozzy - avatar
+ 2
You can put console.log(i, j, b) in the line after b to better understand what happens
11th Jan 2023, 1:03 PM
Lisa
Lisa - avatar
+ 2
The reason as to why the answer is 12 is due to the second for loop being inside a for loop. The first loop is called with the variable i going from 0 - 2 because you used <=. Once this is called, the second for loop is called with the variable j going from 0 - 3 because you used <=. So, the b++ gets called 4 times from the second for loop and once that finishes, the first loop gets called again but now i is 1. This repeats for when i becomes 2 but then it ends. This results in the b++ getting called 4 times for the second loop and the second loop getting called 3 times from the first loop. 4 x 3 = 12. That is how the answer is 12. If you used < instead of <=, the answer would be 6.
11th Jan 2023, 1:08 PM
TRStrider
TRStrider - avatar
0
Thanks to all
11th Jan 2023, 3:34 PM
Mohammad Tausiful Alam
Mohammad Tausiful Alam - avatar