Integrative Programming Examples about Loops in Java
Output
Enter a number
25
Enter a number
9
Enter a number
5
Enter a number
-3
Sum = 39
In the above program, we have used the Scanner class to take input from the user.
Here, nextInt() takes integer input from the user.
The while loop continues until the user enters a negative number. During each iteration, the
number entered by the user is added to the sum variable.
When the user enters a negative number, the loop terminates. Finally, the total sum is displayed
-----------------********************-------------------
2. Java do…while loop
The do...while loop is similar to while loop. However, the body of do...while loop is
executed once before the test expression is checked. For example,
do {
// body of loop
} while(textExpression)
Here,
1. The body of the loop is executed at first. Then the textExpression is evaluated.
2. If the textExpression evaluates to true, the body of the loop inside the do statement is
executed again.
3. The textExpression is evaluated once again.
4. If the textExpression evaluates to true, the body of the loop inside the do statement is
executed again.
5. This process continues until the textExpression evaluates to false. Then the loop stops.