The state may be updated within the “Do something” process.
Question: What will happen if the state is never changed?
Answer: it will be an “infinite loop,” meaning the program will run forever until it crashes or is terminated by the user.
Note
You may have noticed the // next to the <do something> line. This identifies a comment left by the developer. You should use comments to annotate your code so it’s easier to understand for future readers (who could be you, so be kind to your future self). The compiler will ignore all comments when compiling your Java programs.
Example
Answer: ten times (when x = 1, 11, 21, 31, 41, 51, 61, 71, 81, 91)
Example
Answer: zero.
The do-while Loop
Lab Work
- 1.
Use the while loop to output “Hello!” 10 times.
- 2.
Use the while loop to print out all integers from 1 to 25, inclusively.
- 3.Explain what the following code snippet is trying to do.int n = 5;while (n == 5) {n = n + 1;System.out.println(n);n--;}
Problems
- 1.How many times will the loop execute its body?int x = 250;while (x % 3 != 0) {System.out.println(x);}
- 2.How many times will the loop execute its body?int x = 2;while (x < 200) {System.out.print(x + " ");x *= x;}
- 3.How many times will the loop execute its body?String word = "a";while (word.length() < 10) {word = "b" + word + "b";}System.out.println(word);
- 4.How many times will the loop execute its body?int x = 100;while (x > 1) {System.out.println(x / 10);x = x / 2;}
- 5.Given the static method runWhileLoop(), what is its output when x = 10? You may want to copy this method to your test class to try.public static void runWhileLoop(int x) {int y = 1;int z = 0;while (2 * y <= x) {y = y * 2;z++;}System.out.println(y + " " + z);}