Jump to content

Control flow

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Ed Poor (talk | contribs) at 14:00, 22 March 2002 (copied from April's disambiguating page). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

In computer science, a program loop (or loop is a sequence of commands that is carried out several times but written just once. A loop is a method of iteration. In general, a loop is made from a test for a certain condition, and a location inside the code to where the execution should move provided that the condition evaluates true. Two main types of loops exist:

  • "while" loops: a certain operation is carried out as long as a certain condition hold true. For example, a programmer might use a "while" loop to make an application process an input file until it comes to the End Of File (EOF) marker.
  • "for" loops: a certain operation is carried out with a variable moving in a given range. The variable is usually called a counter. A "for" loop is in effect a "while" loop with a condition regarding the counter and specifying its initial value.

Languages often provide different or extended types of loops: for example, the Bourne-Again shell (bash) scripting language has a foreach loop, which advances through the items inside a given list. Internally, it is implemented by a "while" loop going through a linked list. Tail recursion is equivalent to itteration and therefore the Scheme programming language, which lacks "traditional" loops, uses tail recursion instead. See also GOTO.

For all types of loops it might happen that the end condition is never met. An example of this is a "while" loop that waits for the system date to become January 1 2002. Because January 1 has already passed, the loop will never complete. This is an example of an endless loop. See also Halting problem.