Ignora collegamentiHome / Blog

Blog


DoWhile loop in Java

To ensure that the instructions of the loop block are executed at least once, you should use the version do_while of a cycle. As shown in the example:

public class DoWhileExample
{
	public static void main(String[] args) 
	{
	int n = 1;
		do 
		{
		System.out.println("n = " + n++);
		} while(n<= 10);
	}
}

The program generates the following result:

n = 1
n = 2
n = 3
n = 4
n = 5
n = 6
n = 7
n = 8
n = 9
n = 10

In some cases the instructions of the loop body is executed only once, as in the following example:

public class DoWhileExample
{
	public static void main(String[] args) 
	{
	int n = 11;
		do 
		{
		System.out.println("n = " + n++);
		} while(n<= 10);
	}
}

The program generates the following result:

n = 11



Category: Java