| Author |
Help with while
|
sumaraghavi ragha
Ranch Hand
Joined: Nov 17, 2006
Posts: 118
|
|
class NoBody { public static void main(String[] args) { int i,j; i=100; j=200; while(++i ==102) System.out.println("Mid point is" + i); } } Why their is no output?
|
 |
damodar kumar
Ranch Hand
Joined: May 19, 2008
Posts: 77
|
|
|
because at first i value is 100, in expression ++i its preincrementing i to 101 and checking with 102 whether it is equal or not , it is not equal so it comes put of loop ans again the i value is 100 only , so it wont print any output
|
<a href="http://stackoverflow.com/users/668970/user668970" rel="nofollow">
<img src="http://stackoverflow.com/users/flair/668970.png" >
</a>
|
 |
Mark Vedder
Ranch Hand
Joined: Dec 17, 2003
Posts: 624
|
|
Originally posted by damodar kumar: because at first i value is 100, in expression ++i its preincrementing i to 101 and checking with 102 whether it is equal or not , it is not equal so it comes put of loop ans again the i value is 100 only , so it wont print any output
Actually, when it comes out of the "loop", its value is still 101 since nothing else changes i's value or decrements it.
|
 |
Mark Vedder
Ranch Hand
Joined: Dec 17, 2003
Posts: 624
|
|
sumaraghavi, You are probably looking to do something more along the lines of this: but that would be an unusually construct. Generally, when using a counter or index, like i, a 'for' loop is used rather than a 'while' loop. While both a 'while' loop and a 'for' loop would be syntactically correct, the 'for' loop is more conventional, and easier to understand. So it will make your code easier for others to read and understand. if you need i to be in scope after the 'for' loop, you can do this: [ June 02, 2008: Message edited by: Mark Vedder ]
|
 |
sumaraghavi ragha
Ranch Hand
Joined: Nov 17, 2006
Posts: 118
|
|
|
Thanks all
|
 |
 |
|
|
subject: Help with while
|
|
|