Win a copy of Rust Web Development this week in the Other Languages forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

simple code

 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class Exercise1b {

public static void main(String[] args) {

int x = 5;
while(x > 1)
{
x = x - 1;
if(x < 3)
{
System.out.println("small x");
}

}
}

}

Output

small x
small x

my doubt is here x = 5 then why this condition

if(x < 3)
{
System.out.println("small x");
}

working and it is giving small x as output. i know this is a silly and simple doubt please dont mind please anyone answer me thank you.
 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Sony,

In this case, when you first enter the while loop, x = 4 since you have x = x - 1 in the beginning. When x becomes 2 in the loop, then the program hits the "if" statement which prints "small x". The program goes to the beginning of the while loop again, sees that x = 2 (so it passes), then it decrements x by 1 so now x = 1. The program would hit the "if" statement since x = 1 is less than 3 so it would print "small x" again. Since x = 1 now, the program would exit out of the while loop.

Hope that probably over-complicated explanation helps.

- Jason
 
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If you indent your loops it becomes easier to follow the program execution..

 
Marshal
Posts: 74687
335
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Jules Bach is quite right; we have code tags which preserve the indentation and ought to be used whenever you post code.

And that is not a silly question at all; lots of people get confused about that sort of loop.
 
reply
    Bookmark Topic Watch Topic
  • New Topic