|
-
November 27th, 2008, 12:35 AM
#1
Simple While Looping Question
Hello,
It's a very simple looping question but I want to figure it out why the result is this.
int y = 6;
while(y-- > 1){
System.out.println(y);
}
Output:
5
4
3
2
1
Why 1 is shown on output?
Thanks.
-
November 27th, 2008, 05:11 AM
#2
Re: Simple While Looping Question
because after you have written "2" to the console y==2.
Then the while loop checks if the condition is true -> 2>1 is true so it decrements y by 1, and continue to the loop. And now y==1.
Remember that y--, first uses the variable y in the expression, then it decrements it.
If you had used --y instead you would not have 1 written out, because you would have done the decrement before you check the condition.
Cheers
-
November 27th, 2008, 03:53 PM
#3
Re: Simple While Looping Question
Thank you so much! I totally understand why now.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|