Win a copy of Head First Agile this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Loop Question.... Again  RSS feed

 
Shaan Shar
Ranch Hand
Posts: 1249
Java Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got an unexpected results from this program could anyone give the resolution::

public class InTheLoop {
public static final int END = Integer.MAX_VALUE;
public static final int START = END - 100;

public static void main(String[] args) {
int count = 0;
for (int i = START; i <= END; i++)
count++;
System.out.println(count);
}
}



Early Replies will be Appreciated.....
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What were you expecting ? What did you get ?
 
Shaan Shar
Ranch Hand
Posts: 1249
Java Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was expecting that this loob will run only hundred times...

But it's going to be indefinate.......


it's not running as I was expecting as a definite loop.....


Now have you ran the code..what you think that how much times this loop will execute....???



 
Shaan Shar
Ranch Hand
Posts: 1249
Java Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
According to my understanding this loop should be run for only 100

times.........


AM I Correct??? or I am thinking anything silly??

I am mean to say that, whether I have thought anything else.........



 
Jass Singh
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Above loop will keep on excuting infintely. Reason being, in statement for (int i = START; i <= END; i++) after i reaches Integer.MAX_VALUE (2147483647) the test condition will pass. Then in next iteration further increment will make i's value Integer.MIN_VALUE
(-2147483648) which will again pass the test conditon and hence loop will continue.

to make it run exactly 100 time change for llop statement to for (int i = START; i < END; i++). Now loop will stop at 2147483646.

Regards,
Jass

[ April 28, 2006: Message edited by: Jass Singh ]
[ April 28, 2006: Message edited by: Jass Singh ]
 
Shaan Shar
Ranch Hand
Posts: 1249
Java Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry folks,

I really missed out this one.....


well anyways thankx a lot.... to remind me.......


  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!