New course! Every coder should learn Generative AI!
Try a free lesson+ 11
I need someone blessed to please explain why the result of this code is 30
var x=0; for(var i=0; i<10; i++) { for(var j=0; j<=2; j++) { ++x; } } alert(x);
16 Answers
+ 8
the first for loop runs exactly 10 times because the sign is "i<10"
the second runs 3 times because the sign is "i<=2" which is like saying "i<3"
since the loop that runs 3 times is inside the 10 times loop, it runs the 3 loop 10 times. basically the 3loop*10loop or 3*10 = 30
so x = 30
+ 11
i:0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Then i does not become less than 10.
j:0, 1, 2
Then j does not become less than or equal to 2.
10*3=30
Edit: The above numbers listed are the values i and j could possibly take.
+ 7
I am not exactly sure how to find a blessed person.
+ 6
Prometheus 🇸🇬 I'm afraid to say that I still don't understand
+ 5
Yeah, 10 times ( from 0 to 9) x 3 (0, 1 and 2)=30.
If you put j<2 then the result is 20.
+ 4
Hi Mofey. The answer is simply: in nested for(m.. (for(n..)), the result is the multiplication of m * n, in this case i=0 i<10 => i takes values 0 till 9, total 10
case j=0 j<=2 => j takes values 0, 1 & 2, therefore 3=> i=10 * j=3 => x = 30
+ 4
inner loop runs three time (j<=2 0,1,2) for each main loop which is 10 times (i<10)
when mainloop run first loop inner loop will run three time and it goes on until i <10
0 to 9 is 0123456789 which is 10 times.
+ 3
I want to know where is the output statement? Like system.out.println....
+ 3
whats the error message?
+ 2
Using the formula for series as the loop from 0-9 this is 10 numbers for 0-1, sum of the first number is 15 and this is repeated twice, so that's why the sum is 30. (Sum (0-9)) *2 = (5*(6/2))*2= 15*2 = 30 🤗🤩
+ 2
i would suggest not to apply equation to solve if you beginner go with logic you will get clear and later on you can apply any equation you want.
+ 1
Mofey It's a nested for loop. It runs the second for loop 10 times, which runs twice. 10 * 3 = 30
+ 1
The loop for (var j = 0; j <= 2; j++) {
++x
}
gives x = x + 3 each time.
The i loop runs 10 time.
so each time x = x + 3
so 30
+ 1
List of i to be looped: (1,2,3,4,5,6,7,8,9, 10)
List of j to be looped:
(1,2, 3)
NB: the values of i and j are incremented before their conditions are checked
For each value of i, the second for-loop evaluates 3 times(so x increases by 1 each time and will have a final value of 3) .
The first for-loop of i will be evaluated 10 times in all.
Since alert(x) is out of the loop it will return the cumulated value of x which will be 30.
So when {i =1, x=3}, {i=2, x=6},{i=3, x=9}, {i=4, x=12}, {i=5, x=15}, {i=6, x=18}...
+ 1
Loop increment... playing around with inner loop and creating a 3 times of the outer loop. ...great though ...thumbs up
0
Because you have <= sign befor 2 in the line with second FOR