
Posted by Toby Choy on December 08, 1999 at 05:36:06:
LOOPS:
******For Loop
This loop is used when the number of times something is executed is known ahead of time.
For (I=0; I<20; j++)
// I=0 is the initialization express. Starts loop with 0.
// I<20 test expression. Loop will be run 20 times.
// Increment express. Adds one to loop each time it s ran.
Statement;
// One statement or multiple statements.
----------------------
OPERATION OF A FOR LOOP:
Initialization expression is ran. Test expression is ran. If result is false, loop exits. If results is true, then the loop runs the body (statement or statements in the loop). Lastly, it runs the increment expression and returns to the beginning to run the test expression.
----------------------
Multiple Initialization and Test Expressions
More than one expression could be put in the test expression by separating them with commas. There could also be more than one increment expression, but at any time, a “for loop” can only have one test expression.
For (j=0, alpha=100; j=50; j++, beta--)
{ body of the loop }
The j in the above example is the normal variable. Alpha is the added variable. Beta is another increment other than j. Note that alpha and beta does not have to have anything to do with each other.
Also this approach can make listing more concise, it is recommended to use stand=alone statements to achieve the same effect and making it more readable.
*********************************************************************
******While Loop
This loop is used when the number of times something is executed is not known. The while is loop’s body may not even be executed at all depending on the criteria.
while (n!=0)
// ^^^^
// text expression
statement;
-----------or -----------
while (number<100)
{
statement;
statement;
statement;
}
----------------------
OPERATION OF A WHILE LOOP:
Run through body of statement. At End, run expression. When false, loop exits. When true, loop goes back to beginning and runs through again.
*********************************************************************
*******Do Loop
This loop is used when the number of times something is executed is not known.
The do loop will for sure execute the body at least once.
do
{ statement; }
while ( ch~ = ‘n’ );
// ^^^^^^^^^
// text expression
---------or---------
do
{
statement;
statement;
statement;
}
while (numb<96);
// ^^^^^^^
// text expression
----------------------
OPERATION OF A DO LOOP:
Run through body of statement. At End, run expression. When false, loop exits. When true, loop goes back to beginning and runs through again.
*********************************************************************