Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Do-while Loop

do-while

The do-while loop in Java is a post-test loop. This means that the loop condition is evaluated after the loop body has been executed at least once. If the loop condition is true, then the loop body is executed again. This process continues until the loop condition becomes false. The do-while loop is similar to the while loop, but the do-while loop will always execute the loop body at least once, even if the loop condition is false. The while loop, on the other hand, will only execute the loop body if the loop condition is true on the first iteration of the loop. The do-while loop is useful for situations where you need to execute a loop body at least once, regardless of the loop condition. For example, you might use a do-while loop to read input from the user until they enter a valid value. Here is an example of a do-while loop in Java:
do-while loop syntax
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int number = 0; do { System.out.print("Enter a number: "); number = scanner.nextInt(); } while (number <= 5); scanner.close(); } }
Enter a number: 4 Enter a number: 2 Enter a number: 6
This loop will prompt the user to enter a number and then store the number in the number variable. The loop will then check if the number variable is less than zero. If it is, then the loop will execute the body of the loop again. This process will continue until the user enters a number that is greater than or equal to zero. Once the user enters a number that is greater than or equal to zero, the loop condition will become false and the loop will terminate. Here is another example of a do-while loop in Java:
do-while loop example
public class Main{ public static void main(String[] args){ int count = 0; do { System.out.println("Count: " + count); count++; } while (count < 10); } }
Count: 1 Count: 2 Count: 3 Count: 4 Count: 5 Count: 6 Count: 7 Count: 8 Count: 9
This loop will print the value of the count variable to the console and then increment the count variable by one. The loop will then check if the count variable is less than ten. If it is, then the loop will execute the body of the loop again. This process will continue until the count variable is equal to or greater than ten. Once the count variable is equal to or greater than ten, the loop condition will become false and the loop will terminate. The do-while loop is a powerful tool that can be used to implement a variety of different algorithms. It is important to understand how to use the do-while loop effectively in order to write efficient and maintainable Java code.

  📌TAGS

★do-while ★for ★while ★loop ★for-each

Tutorials