Loops are a type of control flow structure in programming in which a series of statements may be executed repeatedly until some condition is met.
A loop is a fundamental programming idea that is commonly used in writing programs.
Types
A loop can be categorized in two different ways,
1. Entry Controlled Loops
A loop which checks for the condition before the iteration is known as Entry Controlled loops - for example
- while loop - iterates while a certain condition is true
- until loop - iterates while a certain condition is false
- for loop - iterates through numbers in a certain range. Note: not the same as C++
for
loop - foreach loop - iterates through the elements of a collections.
2. Exit Controlled Loops
A loop which checks the condition after the iteration is knows as Exit Controlled loop - for example
- do-while loop - iterates while a certain condition is true (the first iteration will run regardless of the condition)
- do-until loop - iterates while a certain condition is false (the first iteration will run regardless of the condition)
Most languages provide only a subset of loop types described above. For example: in Python there are only foreach (keyword for
) and while loops.
Break and continue
In some languages, there are two keywords that simplify the task of implementing a more advanced control flow: break
and continue
. The former allows you to jump to the operator immediately after the loop, the latter allows you to jump to the end of the current iteration.
Example: implementation of do-until loop in Python using the break
keyword:
while True:
// loop body
if condition:
break
Tag usage
The tag loops can be used for programming related problems in implementing loops feature of any programming language. Please avoid theoretical questions related to tag loops on stackoverflow.
See also: