• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question regarding "for" loops

 
Thomas Markl
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Whether I say „j++“ or „++j“ in the for-loop j is always increased after the loop is
finished. WHY?
Why is it the same to say „i++“ or „++i“ in the loop? The result is always that „i“
is increased ? WHY?


C:\Java\EigeneJavaProgramme>java Skip1
LOOP 1 0
LOOP 2 1
LOOP 3 2
LOOP 4 3
LOOP 5 4
LOOP 6 5
LOOP 7 6
LOOP 8 7
LOOP 9 8
LOOP 10 9
END 10 10



C:\Java\EigeneJavaProgramme>java Skip1a
LOOP 1 0
LOOP 2 1
LOOP 3 2
LOOP 4 3
LOOP 5 4
LOOP 6 5
LOOP 7 6
LOOP 8 7
LOOP 9 8
LOOP 10 9
END 10 10
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because that is what both the pre-increment and post-increment operator do - incrementing the variable. The only difference between them is the *value of the expression*.
The following code should make that clear:

Did that help?
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Whether I say �j++� or �++j� in the for-loop j is always increased after the loop is
finished. WHY?

Because that's how for-loops in Java work. First the declaration/initialization part is performed. Then the test is performed. If the test returns true, then the loop body is executed with the current value(s) of any identifiers declared/used in the initialization and increment sections of the for-loop declaration. Then any statements in the increment section of the loop declaration are performed. These statements typically increment some variable or otherwise cause the loop to get closer to termination. These statements are each executed in isolation any other statement. Then the test is performed again and the process repeats as necessary.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic