+ 10
I don't understand why this results 3. Anyone please help!
int i=0,j=0,count=0; for(;i < 3; i++){ for(;j < 3;j++){ count++ } } alert(count);
6 Antworten
+ 12
Because after first loop j is 3 and in second and third loop condition j < 3 is not satisfied.
+ 10
The real output is error.
'int' should be 'var'.
Anywho, the problem is that j is declared outside the loop. I highly recommend you start declaring them in the loop.
These are the steps the program goes through:
i is 0.
j is 0.
count is 1.
j is 1.
count is 2.
j is 2.
count is 3.
j is 3.
3 < 3 is false, exit loop.
i is 2.
j is still 3, so the loop is still false.
i is 3.
3 < 3 is false.
exit loop.
Count is 3.
+ 6
@Rrestoring Faith, wow, talk about details! super cool! thank you very much, it was really kind, appreciate it. *clapping*
+ 5
@Rrestoring Faith, can you help me understand the for loop where it has no initial value like that example above? I found it confusing, how it works, help is appreciated.
Thanks.
+ 5
@lpang
for(;i < 3; i++)
This for loop will not declare a variable, but it will still run until i is larger than 2, and increment 'i' when the loop reaches the end each time.
for(int i = 0; i < 3; i++)
When the loop first begins, the variable 'i' is created and set to the value 0.
If we look in the example:
int i = 0, j = 0;
for(; i < 3; i++)
for(; j < 3; j++)
{
}
When the inner loop: 'j' finishes, the outer loop: 'i' starts it back up again.
The loops still use 'i' and 'j', but they do not create the variables when the loops first begin.
Instead, the variables were already created before the loops started.
Because of this, when the inner loop that uses 'j' is finished, the variable 'j' is not reset back to 0 when the loop starts all over again.
Hopefully that clears up the confusion, if not maybe provide another example problem that we can go over.
+ 4
Thank you guys! Now I understand it