If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In Java, the do-while
loop is similar to the while
loop, but with one key difference: the do-while
loop guarantees that the block of code will be executed at least once, regardless of whether the condition is true or false. After the initial execution, the loop will continue to execute as long as the specified condition remains true. The basic syntax of the do-while
loop is as follows:
javaCopy code
do {
// Code to be executed at least once
} while (condition);
Here's an example of using a do-while
loop to take input from the user until a positive number is entered:
javaCopy code
import java.util.Scanner;
public class DoWhileLoopExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number;
do {
System.out.print("Enter a positive number: ");
number = scanner.nextInt();
} while (number <= 0);
System.out.println("You entered a positive number: " + number);
scanner.close();
}
}
Example usage:
lessCopy code
Enter a positive number: -5
Enter a positive number: 0
Enter a positive number: 10
You entered a positive number: 10
In the example above, the do-while
loop ensures that the prompt for user input (Enter a positive number:
) is displayed at least once. After the initial execution, the loop checks whether the entered number
is less than or equal to 0. If the condition is true (i.e., a non-positive number is entered), the loop continues to prompt for input until a positive number is entered.
The do-while
loop is particularly useful in situations where you want to execute a block of code at least once, regardless of the condition's initial value. Just like the while
loop, it's essential to ensure that the condition eventually becomes false to avoid an infinite loop.
Comments: 0