![]() |
Counting and Looping |
|
|
The while Statement |
|
The while statement provides an effective mechanism to loop through code. Its syntax is: while(Condition) Statement To execute this loop, the interpreter tests the Condition. If the result of the comparison is true, then the Statement is executed. After the Statement is executed, the loop restarts. This continues UNTIL the test on the Condition renders false or AS LONG AS the test on the Condition is true. If the Statement to be executed covers more than one line of code, you should include it between an opening and a closing curly brackets. Here is an example:
Once again, if the Condition is never met, the Statement never executes. If the Condition is always met, then the Statement would never stop. Each of these two situations should be avoided. |
|
The do…while Statement |
|
The deal with the while statement is that it test the Condition first. If the test renders a false result, then the Statement doesn’t execute and the loop ends. If you want the Statement to be executed prior to testing the Condition, use the do…while loop. Its syntax is: do Statement while(Condition) When the interpreter encounters this loop, it first executes the Statement. After executing the Statement, the Condition is tested. If the test renders a true result, then the Statement executes again. This looping continues AS LONG AS the Condition is true. The main difference between a while loop and a do…while is that, in the while loop, the Condition is tested first before the Statement is considered; on the other hand, in the do…while loop, the Statement is first executed, then the Condition is tested. Here is an example:
|
|
|
||
| Previous | Copyright © 2002-2004 FunctionX, Inc. | Home |
|
|
||