Using loops

You use a loop when you want to repeat some instructions several times. For example, if you were going to write a spell check program, you would not want to write a sequential list of instructions like:
1. check the first word in the document and correct it if necessary
2. check the second word in the document and correct it if necessary
3. check the third word in the document and correct it if necessary
4. check the fourth word in the document and correct it if necessary
etc.
A sequential spell check program would have two major problems: it would be very long and there would be no way to know in advance how many words it would need to check.

The following is a psuedocode loop that would solve both of those problems:

do until there are no more words in the document
   get the next word
   check its spelling and correct it if necessary
loop
Like all loops, this one has a body (the instructions to be repeated) and a termination condition. The instructions in the body check a word, correcting it if necessary. Since the loop begins with "get the next word," we are checking a different word with each iteration. The loop terminates when we have processed the last word.

This loop processes the words in the document one at a time. Loops often (though not always) have an index variable that is incremented or decremented each time the loop is executed. It is often helpful to think of the index variable as pointing to the item that is being processed during the current iteration of the loop.

In this case, the index variable would be a pointer to the word that is currently being checked. Each time through the loop, the index would be incremented by one, so as to point to the next word in the document. (That is the step "get the next word" in the above loop). The loop will terminate after the last word is processed.

This idea of a pointer is quite useful. For example, if a loop is stepping through a character string one letter at a time, you can think of the index variable as pointing to the character that is currently being processed. If a loop is stepping through an array or a data file, you can think of the index variable as pointing to the current array element or file record.


Disclaimer: The views and opinions expressed on unofficial pages of California State University, Dominguez Hills faculty, staff or students are strictly those of the page authors. The content of these pages has not been reviewed or approved by California State University, Dominguez Hills.