+ 2
How does this for loop increment the last increment for j?
This for loop was taken from a challenge and I couldn't figure out how the var j was set to 11. Could someone explain please?? The code: What is the output of this code? var i=2; var k=1; var j=0; for(k=0;k<10;k++) j++; for(i=0;i<10;i++) continue ; j++; alert(j); Answer: 11 https://code.sololearn.com/czWMAkxFkW73/?ref=app
8 Respostas
+ 4
♨️♨️ I tested it out on the debugger. The reason why this is a tricky question is because the for loops are not encapsulated in any curly brackets ({}).
No curly brackets means only a single statement after a for loop will run. Java will ignore the indentation.
Basically it is doing this:
var i=2;
var k=1;
var j=0;
for(k=0;k<10;k++)
{
j++;
}
for(i=0;i<10;i++)
{
continue;
}
j++;
alert(j);
+ 7
var i=2;
var k=1;
var j=0;
for(k=0;k<10;k++)
j++;
Here this loop will run 10 times so j will increase 10 times so j will be 10 after that next loop
for(i=0;i<10;i++)
continue ;
j++;
The continue statement skips the current iteration of the loop and continues with the next iteration.
Here if condition will be true then condition will check again here when loop reach at 10<10 condition false then next statement is
j++ here j is increase before j was 10 here it will increase by 1 so j will be 11 so final Output is 11
alert(j);
+ 7
RIO-NOS read about continue statement
The continue statement skips the current iteration of the loop and continues with the next iteration.
For understanding see this example
int i=0;
For(i=0 ; i<10;i++)
{
if(i==5)
Continue;
alert (i);
}
Here first condition check
0<10 true then next step check if condition its false wo alert will print 0 then i++ here i will 1 and i<10 true then check if condition its false then alert will print 1 again .....again when i will be 5 we check condition in loop
5<10 true so inner part we check if condition
Here if(5==5)
Continue here continue will skip and it won't print 5 control will skip here and again i++ here i will 6 then check condition in loop same thing repeating.
So final Output will be
0 1 2 3 4 6 7 8 9 it wont print 5
+ 3
K = 0 in the first loop making j = 10 once its finished
J only increments once in the second loop making it 11
+ 2
The second for loop does not do anything. The first for loop does 9 iterations and the answer should be j == 9.
+ 1
Антонио copy and paste the code and test it yourself. It's 11
+ 1
♨️♨️ I'm still confused. How does the second for loop execute j++ if the continue statement is right before it?