Java do…while Loop
The loop is similar to loop with one key difference. The body of loop is executed for once before the test expression is checked.
Here is the syntax of the loop.
How do…while loop works?
The body of loop is executed once (before checking the test expression). Only then, the test expression is checked.
If the test expression is evaluated to , codes inside the body of the loop are executed, and the test expression is evaluated again. This process goes on until the test expression is evaluated to .
When the test expression is , the loop terminates.
Example 3: do…while Loop
The program below calculates the sum of numbers entered by the user until user enters 0.
To take input from the user, we have used the object. To learn more about , visit Java Scanner.
Enter a number: 2.5 Enter a number: 23.3 Enter a number: -4.2 Enter a number: 3.4 Enter a number: 0 Sum = 25.0
Infinite while Loop
We should be always careful while working with loops. It is because if we mistakenly set the test expression in such a way that it is never false, the and loop will run forever.
This is called infinite and loop. For example,
Let’s take another example,
The infinite loop works in a similar way as loop.
Java while Loop
The syntax of loop in Java is:
How while loop works?
In the above syntax, the test expression inside parenthesis is a boolean expression. If the test expression is evaluated to ,
- statements inside the while loop are executed.
- then, the test expression is evaluated again.
This process goes on until the test expression is evaluated to . If the test expression is evaluated to ,
the while loop is terminated.
Example 1: while Loop
Line 1 Line 2 Line 3 Line 4 Line 5 Line 6 Line 7 Line 8 Line 9 Line 10
In the above example, we have a test expression (). It checks whether the value of i is less than or equal to 10.
Here initially, the value of i is 1. So the test expression evaluates to for the first time. Hence, the print statement inside loop is executed.
Inside loop notice the statement
This statement increases the value of i by 1 in each iteration. After 10 iterations, the value of i will be 11. Then, the test expression () evaluates to and loop terminates.
To learn more about test expression and how it is evaluated, visit and .
Example 2: Java while Loop
Sum = 5050
Here, we have two variables named sum and i whose initial values are 0 and 100 respectively.
In each iteration of the loop,
- the sum variable is assigned value:
- the value of i is decreased by 1
The loop continues until the value of i is equal to 0. For better visualization,
С этим читают