Encyclopedia > Program loop

  Article Content

Program loop

In computer science, a program loop (or just loop) is a sequence of commands that is specified once but carried out several times in succession. A loop is a method of iteration. A loop executes the code "inside" the loop a specific number of times, or once for each of a collection of items, or until some condition is met, called the exit condition of the loop.

Modern programming languages provide many constructs for looping. Typically they will have something like a "for x = 1 to 10..." statement to execute a loop a fixed number of times (in this case 10, where the variable "x" is called a loop index) and statements like "repeat...until (condition)" or "while (condition)...", which repeat the loop until the specified condition becomes true (there are often two types of these, differing in whether the condition is tested before or after the loop). Many languages with collection data types (for example, Perl) also have something like "foreach" that causes a loop to execute once for each member of a collection. Many languages also provide something like a "break" instruction to exit from a loop before its normal exit condition is met; this is called early termination.

A common programming mistake is to code a loop whose exit condition is never met, either because the programmer specified it incorrectly or because the behavior of the program differs from the programmer's expectations. This creates an endless loop bug. An example of this is a loop that waits for the system date to become January 1, 2002. Because January 1 has already passed, the loop will never complete. See also Halting problem.

Tail recursion can be used equivalently to iteration, and therefore some languages such as Scheme programming language, which lacks "traditional" loops, use tail recursion instead.

See also GOTO.



All Wikipedia text is available under the terms of the GNU Free Documentation License

 
  Search Encyclopedia

Search over one million articles, find something about almost anything!
 
 
  
  Featured Article
Canadian Music Hall of Fame

... Complete list of Inductees 1978 Guy Lombardo 1978 Oscar Peterson 1979 Hank Snow 1980 Paul Anka 1981 Joni Mitchell 1982 Neil Young 1983 Glenn Gould 1986 ...

 
 
 
This page was created in 35.7 ms