// while-loop
class Loop {
public static void main(String[] args) {
int i = 1;
while (i <= 10) {
System.out.println("Line " + i);
++i;
}
}
}
// do-while-loop
class Loop {
public static void main(String[] args) {
int i = 1;
do{
System.out.println("Line " + i);
++i;
}while (i <= 10);
}
}
//for-loop
class Loop {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
System.out.println("Line " + i);
}
}
}
while (testExpression) {
// codes inside the body of while loop
}
In the above syntax, the test expression inside parenthesis is a boolean expression. If the test expression is evaluated to true,
statements inside the while loop are executed.
then, the test expression is evaluated again.
This process goes on until the test expression is evaluated to false. If the test expression is evaluated to false,
the while loop is terminated.
The do...while loop is similar to while loop with one key difference. The body of do...while loop is executed for once before the test expression is checked.
Between a WHILE and FOR loop, you can use them interchangeably. To be a purist, you could make your decision base on the nature of the conditions. If you're performing a count-based loop, then a FOR loop would make the most sense.
Comments
Leave a comment