Results 1 to 4 of 4
  1. #1
    sleshas is offline Interested in Java
    Join Date
    Mar 2012
    Location
    Lithuania
    Posts
    2
    Rep Power
    0

    Default Question about while loop

    Hello, I tested one program. Code is here:
    Java Code:
    public class asfd {
        
    	public static void main(String[] args) {
    		int x = 18;
    		System.out.println("Before loop x =  :"+x);
    		while (x>15){
    			System.out.println("Loop time");
    			System.out.println(x);
    			x--;
    		}
    		System.out.println("After the loop x =  : "+x);
    	}
    
    }
    Output:
    Java Code:
    Before loop x =  :18
    Loop time
    18
    Loop time
    17
    Loop time
    16
    After the loop x =  : 15
    Tell me, why after the loop x = 15 not 16?
    Am I right, that if x = 16, condition is false, ant code breaks? So, x-- couldn't touch x one more time?

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,535
    Blog Entries
    7
    Rep Power
    20

    Default Re: Question about while loop

    16 > 15 so the body of the while loop executes again and decrements the value of x (15).

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  3. #3
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,457
    Rep Power
    25

    Default Re: Question about while loop

    Add another println to show the value of x after it is changed, just before the end of the while loop. The printout will show you what the value of x is.
    If you don't understand my response, don't ignore it, ask a question.

  4. #4
    sleshas is offline Interested in Java
    Join Date
    Mar 2012
    Location
    Lithuania
    Posts
    2
    Rep Power
    0

    Default Re: Question about while loop

    Thank you. I realise, that it was changed, but wasn't showed.

Similar Threads

  1. Do....while Loop question
    By Roter in forum New To Java
    Replies: 10
    Last Post: 01-25-2012, 04:49 AM
  2. Loop question
    By rich123 in forum New To Java
    Replies: 6
    Last Post: 02-08-2011, 02:26 AM
  3. loop question
    By ccie007 in forum New To Java
    Replies: 22
    Last Post: 08-15-2010, 08:29 PM
  4. for Loop with Yes/No Question! help..please!
    By mastercrimson in forum New To Java
    Replies: 8
    Last Post: 06-02-2010, 05:08 PM
  5. Question about for loop..
    By sivakumar_sakam in forum New To Java
    Replies: 4
    Last Post: 05-15-2009, 11:23 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •