This document was written by CS 290W TA Joshua Kay and was last modified
Okay, we're back for more basic programming skills. We finished the for statement, so let's check out another cool way to do loops. It's called, appropriately enough, while(). Let's check out some code, okay?while(x<10); - This simply states that while x is less than ten, perform the actions inside the squiggly brackets. Note that there is *NO* semicolon between the arguments for the while() and the beginning of the squiggly brackets.
Inside of the brackets, it looks a lot like the for statements. Except for one thing - the x gets increased INSIDE of the brackets, and not inside the while statement itself. This isn't a huge difference most of the time, but sometimes very necessary, and it can also make your programs much easier to write, depending on what it is you need to do.
Finally, note that there is *NO* semicolon after the squiggly brackets - just like the for statement.
Let's try another cool loop style - this is called do...while -
Ex:
Too, notice here something is different. The while statement has a semicolon *AFTER* it. This is necessary JAVA syntax.
Why would you need this? Well consider washing your car, with soap. You have to rinse it *once*, right? Even if you don't think you can see the soap? Then, you check to see if you need to rinse again. Then you check again, and again, until your car is rinsed.
Look at the following:
The answer is YES. do...while statements *ALWAYS* perform the action the first time, before the condition is ever checked.