Slider

Do While Loop in Java.

The only difference between the do-while loop and the while loop is that the do-while loop executes the block of code at least once.

Java do-while loop is a control flow statement and is very similar to a while loop. It is also used to iterate a block of code repeatedly until the boolean condition is true. 

The only difference between the java do-while loop and the java while loop is that the do-while loop executes the block of code at least once even if the boolean condition is false but the while loop executes the block of code only when the boolean condition is true. 

do while loop syntax

Example: 1 Write a Java Program to print "Hello" four times using a do-while loop. 

public class Main
{
	public static void main(String[] args) {
		
		int i = 1;
		
		do {
		    System.out.println("Hello");
		    i++;
		} while(i < 5);
	}
}
Output:
Hello
Hello
Hello
Hello

Example: 2

public class Main
{
	public static void main(String[] args) {
		
		int i = 1;
		
		do {
		    System.out.println("Hello");
		    i++;
		} while(i > 5);
	}
}
Output:
Hello

Note: In the above second example, "Hello" is printed only one time because the boolean condition is false and when the boolean condition is false in the do-while loop, the block of code executes at least once

0

No comments

Post a Comment

both, mystorymag

DON'T MISS

Tech News
© all rights reserved
made with by AlgoLesson
Table of Contents