Do While Loop

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 26:- Do While Loop

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.

 

Disclaimer:-

Under Section 107 of the copyright act 1976, allowance is made for fair use for purposes such as criticism, comment, news reporting, scholarship, and research. Fair use is a use permitted by copyright statute that might otherwise be infringing. Non-profit, educational, or personal use tips the balance in favor of fair use.

 

6. Loops

Comments: 0

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?