Loops

<< Click to Display Table of Contents >>

Navigation:  Concordance Programming Fundamentals > Using Conditional Statements and Loops >

Loops

Loops are a programming tool that allow you to repeat a section of code over and over again. For example, if you wrote a piece of code that formatted a page in a particular manner, you could use a loop to format all pages in a document in that particular manner. You use conditional statements with loops in order to instruct your computer as to when they should loop, and how many times they should loop. The following topics discuss the two different styles of loops.

For Loops

A For loop is a looping technique that contains three elements: an initialization value, a test condition, and a loop increment expression. They use the following format:

for (initialization statement; test condition; loop increment expression)

{

   DoLoopCode();
}

The initialization value resets the test value you will use in the for loop.

The test condition is the check on the test value to see if the loop should continue: as long as the condition holds true, the loop will continue to run. The check is made after the loop runs.

The loop increment is the modification you make to the test value on each loop.

The following example uses a For-loop to represent a jogger running around a track 20 times:

for (laps = 0; laps < 20; laps = laps + 1) 

{

 Run();

}

While Loops

A while-loop is a loop that contains a single "while" text expression. In order for a loop to proceed, the test statement must be true. A while loop uses the following syntax:

while (test condition) 

{

   DoSomething();
}

In order for a while-loop to exit, the test condition must evaluate to false. What this means is that somewhere in your while-loop something must trigger this condition. For example, the following while-loop would run for 10 times, and then exit:

x = 10;

while (x > 0) 

{

   DoSomeStuff();

   x = x-1;
}

Note that it is very easy to create an infinite while-loop, simply by not modifying your test condition.