for loop without braces in java

I wonder why this two following codes give different results;

for(i = 1, j = 0; i < 10; i++) {
    j += i;
    System.out.println(i);
}

This one gives the numbers between 1 included and 10 excluded.

for(i = 1, j = 0; i < 10; i++)
    j += i;
System.out.println(i);

However this one gives 10. I could not get the logic of this;

for()
do_something;
do_something_else;

Answer

That is because the default scope of an iteration in your case is the only line following it, something equivalent to –

for(i=1, j=0;i<10;i++) {
    j += i;
}
System.out.println(i);

Hence the entire loop is iterated and since after that the value of i==10, that is your output in the second case.


In the first case, it’s pretty obvious that the value is printed with each iteration and hence 1 to 9(less than 10) :

for(i=1, j=0;i<10;i++){
    j += i;
    System.out.println(i);
}

Leave a Reply

Your email address will not be published. Required fields are marked *