//1
while (true)
{
System.out.println ("Hello World");
}
for (;;)
{
System.out.println ("Hello World");
}
do
{
System.out.println ("Hello World");
}
while (true);
//2
boolean flag = false;
do
{
System.out.println ("(Do) You shouldn't be here.");
}
while (flag);
for (; flag;)
{
System.out.println ("(For) You shouldn't be here.");
}
while (flag)
{
System.out.println ("(While) You shouldn't be here.");
}
//3
int[] a = new int[10];
for (int i = 0; i < a.length; i++)
{
a[i] = i;
}
int i = 0;
while (i < a.length)
{
a[i] = i++;
}
i = 0;
do
{
a[i] = i++;
}
while (i < a.length);
The main difference in the operation of loops is the condition check: for 'for' and 'while' the check occurs before the operation is performed, and for 'do while' after (example number 2, the 'for' and 'while' loop will not be executed, unlike ' do while '). Also in 'for' it is convenient to work with indices / counters (example number 3), therefore, it is most often used to work with an array.
for
Advantage:
Convenient work with indices / counters.
Disadvantages:
Not.
while
Advantage:
Not.
Disadvantages:
Not.
do while
Advantage:
Checking the condition after execution.
Disadvantages:
Checking the condition after execution.
Comments
Leave a comment