Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Help with while

 
sumaraghavi ragha
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 77
Android Chrome MyEclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Mark Vedder
Ranch Hand
Posts: 624
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 624
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks all
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic