/* The Java Language provides the while and do-while
* loops to allow code to execute repeatedly until a
* condition is no longer true.
*
* The primary difference between while and do-while
* is the point at which the expression is evaluated.
*
* For while loops the expression is evaluated at the
* top of the loop. The beginning of the code block.
* So if the expression evaluates to false. The
* following statements will not run.
*
* do-while loops evaluate their expression at the bottom
* of the loop. The end of the code block. So do-while
* loops ALWAYS execute their statements at least once.
*/
public static void main(String[] args) {
int A = 0;
int B = 5;
/* The code in this while loop will only run
* because A is less than B.
*/
while(A < B) {
System.out.println("A = " + (A++));
}
// Now that A is = to B the code won't run any more.
while(A < B) {
System.out.println("A = " + (A++));
}
/* But if we use a do-while loop. The code should run at
* least once.
*/
do {
System.out.println("\nThis is a do-while loop.");
System.out.println("A = " + (A++));
} while (A < B);
}
}
No comments:
Post a Comment