Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

FOR condition.

 
WeiJie Lim
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Why does the output look this way :
1
2
3
4
5
6
7
8
9
10
The final value of i is 11

Shouldn't the final value be 10 ?
 
Kemal Sokolovic
Bartender
Posts: 825
5
Java Python Ruby
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
After the value 10 is printed, i is increased once more. Since the new value, 11, doesn't satisfy the condition in for loop, the loop ends and in the next statement you get that value 11.
 
siva chaitanya
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Final value of i is 11 only because after the execution of System.out.println(i);//10
'i' value will be incremented which is 11 eventually.
 
WeiJie Lim
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kemal Sokolovic wrote:After the value 10 is printed, i is increased once more. Since the new value, 11, doesn't satisfy the condition in for loop, the loop ends and in the next statement you get that value 11.


Very clear answer. Thanks ^^
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15282
39
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Let's look at what exactly this line means:

Note that there are three parts in the for-statement.

1. The first one is executed at the start to initialize i: i = 1
2. The second one is the condition for the loop. This is checked at the beginning of each iteration of the loop. The loop will repeat as long as the condition is true.
3. The third one is executed at the end of each iteration.

So, what happens when you run this?

i = 1
check i <= 10: true, so run the body of the loop
i++: i becomes 2
check i <= 10: true, so run the body of the loop
i++: i becomes 3
...
check i <= 10: true, so run the body of the loop
i++: i becomes 9
check i <= 10: true, so run the body of the loop
i++: i becomes 10
check i <= 10: true, so run the body of the loop
i++: i becomes 11
check i <= 10: false, so stop, we're done
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic