programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

a query regarding 'for' loop

Aafreen Moinuddin
Greenhorn
Posts: 20
hey guys ,
can anyone explain breifly on how does the the following loop execute prints i=10 n i=10 in the output... n it is said that it executes 10 times...

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

i do agree that the loop executes for 10 times however i dont understand how it prints 10

Alana Sparx
Ranch Hand
Posts: 121
From what I understand, it is down to the execution order of the loop:

First iteration:
j is intialised to 0;
0 is less than 10;
the body of the loop is executed, i is incremented to 1;
j is then incremented to one;
1 (value of j), is less than 10...

end of 8th / start of 9th iteration
j is incremented to 9
9 (value of j) is less than 10
i is incremented to 10
j incremented to 10
10 (value of j) is equal to 10, condition fails, loop terminates.

j reaches the value of 10 because it is incremented as the last stage of the loop, so it will reach the value 10 (which then fails the condition j < 10).

Succinctly, in your example, i is the first value incremented in the body of the loop, j is the last value incremented.

Arun Boraiah
Ranch Hand
Posts: 233
0+1=1
1+1=2
2+1=3
3+1=4
4+1=5
5+1=6
6+1=7
7+1=8
8+1=9
9+1=10

Aafreen Moinuddin
Greenhorn
Posts: 20
Thanks Alana !!! that really helps

Aafreen Moinuddin
Greenhorn
Posts: 20
how does a postfix increment operator differ from prefix increment operator in a loop?

Alana Sparx
Ranch Hand
Posts: 121
In your case it won't make any difference, as you are not assigning the value of j to anything (j must still at some point reach/exceed 10 to break the loop).

++j and
j++ would make a difference in a line of code such as:
as in one case you assign then increment, in the other you increment thenassign

Jeff Albertson
Ranch Hand
Posts: 1780
Originally posted by Aafreen Moinuddin:
how does a postfix increment operator differ from prefix increment operator in a loop?

The best way to understand expressions ++i and i++ is to realize that there are two important but separate aspects of any expression:

1. its value

2. its side effect

Both ++i and i++ have the same side effect -- incrementing the value of variable i -- but they have different values. Sometimes the value of an expression is ignored, for example, when you add() to a collection like this: