CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Nov 2008
    Posts
    2

    Talking 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.

  2. #2
    Join Date
    May 2006
    Location
    Norway
    Posts
    1,709

    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

  3. #3
    Join Date
    Nov 2008
    Posts
    2

    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
  •  





Click Here to Expand Forum to Full Width

Featured