This articleneeds additional citations forverification. Please helpimprove this article byadding citations to reliable sources. Unsourced material may be challenged and removed. Find sources: "Loop" statement – news ·newspapers ·books ·scholar ·JSTOR(January 2026) (Learn how and when to remove this message) |
Incomputer programming, aloop is acontrol flowstatement that allows code to be executed repeatedly, usually with minor alterations between repetitions. Loops can be used to perform a repeated action on all items in acollection, or to implement a long lived program.
Loops are a feature ofhigh-level programming languages. Inlow-level programming languages the same functionality is achieved usingjumps. When a program iscompiled tomachine code, looping may be achieved using jumps; but some loops can beoptimized to run without jumping.[1]
Usually, loops are expected to run for a finite number of iteration.[citation needed] Without proper care, loops may accidentally be created that have no possibility of terminating. Such loops are calledinfinite loops. The problem of determining whether a program contains an infinite loop is known as thehalting problem.
Aconditional loop (also known as anindeterminate loop[2]) is a loop that determines whether to terminate based on a logical condition.[3] These loops are flexible, but there exact behavior can be difficult to reason about.[citation needed]
A conditional loop is usually composed of two parts: acondition and abody. Thecondition is a logical statement depending on the state of the program and thebody is a block of code that runs as long as thecondition holds.[3]
A common misconception is that the execution of thebody terminates as soon as thecondition does not hold anymore; but this is usually not the case.[4]: 368 In most programming languages, thecondition is checked once for every execution of thebody. When thecondition is checked is not standardized and some programming languages contain multiple conditional looping structures with different rules about when thecondition is assessed.[citation needed]
Apre-test loop is a conditional loop where thecondition is checked before thebody is executed. More precisely, thecondition is checked and if it holds thebody is execute. Afterwards, thecondition is checked again, and if it holds thebody is executed again. This process repeats until thecondition does not hold. Many programming languages call this loop awhile loop and refer to it with thekeywordwhile. They are commonly formatted in manner similar to
whileconditiondobodyrepeat
Instead of the keywordsdo andrepeat others methods are sometime use to indicate where thebody begins and ends, such ascurly braces[5] orwhitespace.[6]
For example, the following code fragment first checks whetherx is less than five, which it is, so thebody is entered. There,x is displayed and then incremented by one. After executing the statements in thebody, thecondition is checked again, and the loop is executed again. This process repeats untilx has the value five.
x ← 0whilex < 5do display(x)x ←x + 1repeat

Apost-test loop is a conditional loop where thecondition is checked after thebody is executed. More precisely, thebody is executed and afterwards thecondition is checked. If it holds thebody is run again and then thecondition is checked. This is repeated until thecondition does not hold. This is sometimes called ado-while loop due to the syntax used in various programming languages,[7] although this can be confusing sinceFortran andPL/I use the syntax "DO WHILE" for pre-test loops.[8][9] Post-test loops are commonly formatted in manner similar to
dobodyrepeatwhilecondition
Instead of the keywordsdo andrepeat others methods are sometime use to indicate where thebody begins and ends, such as curly braces.[10]
Somelanguages may use a different naming convention for this type of loop. For example, thePascal andLua languages have a "repeat until" loop, which continues to rununtil the control expression is true and then terminates.[11][12]

Athree-part for loop, popularized by C, has two additional parts:initialization (loop variant), andincrement, both of which are blocks of code. Theinitialization is intended as code that prepares the loop and is run once in the beginning andincrement is used to update the state of the program after each iteration of the loop. Otherwise, the three-part for loop is a pre-test loop.They are commonly formatted in manner similar to
forinitialization,condition,incrementdobodyrepeat
This syntax came fromB and was originally invented byStephen C. Johnson.[13] The following C code is an example of a three part loop that prints the numbers from 0 to 4.
for(inti=0;i<5;i++){printf("%d\n",i);}
This sectionneeds expansion. You can help byadding missing information.(January 2026) |
Assuming there is a function calleddo_work() that does some work, the following are equivalent.[citation needed]
do do_work()repeat whilecondition | do_work()whileconditiondo do_work()repeat |
As long as thecontinue statement is not used, the above is technically equivalent to the following (though these examples are not typical or modern style used in everyday computers):
whiletruedo do_work()ifcondition is nottruethenbreakend ifrepeat
or
LOOPSTART:do_work()ifconditionthengoto LOOPSTARTend if

Anenumeration (also known as andeterminate loop[2]) is a loop intended to iterate over all the items of a collection.[14] It is not as flexible as a conditional loop; but it is more predictable.[citation needed] For example, it is easier to guarantee that enumerationsterminate and they avoid potentialoff-by-one errors.[citation needed] Enumerations can be implemented using aniterator, whether implicitly or explicitly. They are commonly formatted in manner similar to
foritemincollectionbodyrepeat
Depending on the programming language, various keywords are used to invoke enumerations. For example, descendants ofALGOL usefor,[15] while descendants ofFortran usedo[16] andCOBOL usesPERFORM VARYING.[17]
Enumerations are sometimes called "for loops," for example inZig andRust.[18][19] This can be confusing since many of the most popular[20] programming languages, such as C,C++, andJava, use that term for the three-part for loop,[21][22][23] which is not an enumeration. Other programming languages, such asPerl andC#, avoid this confusion by using the term "foreach loop."[24][25]
The order in which the items in the collection are iterated through depends on the programming language.Fortran 95 has a loop, invoked using the keywordFORALL, that is independent of this order. It has the effect of executing each iteration of the loop at the same time. This feature was made obsolescent inFortran 2018.[26]
This sectionneeds expansion. You can help byadding missing information.(January 2026) |
In mostfunctional programming languages,recursion is used instead of traditional loops. This is due to the fact that variables areimmutable, and therefore theincrement step of a loop cannot occur.[27]
To avoid running intostack overflow errors for long loops, functional programming languages implementtail call optimisation, which allows the samestack frame to be used for each iteration of the loop, compiling to effectively the same code as awhile orfor loop.[28]
Some languages, such asHaskell, have a special syntax known as alist comprehension, which is similar to enumeration, iterating over the contents of a list and transforming it into a new list.
A loop counter is a control variable that controls the iterations of a loop. Loop counters change with each iteration of a loop, providing a unique value for each iteration. The loop counter is used to decide when the loop should terminate. It is so named because most uses of this construct result in the variable taking on a range of integer values.
A commonidentifier naming convention is for the loop counter to use the variable namesi,j, andk (and so on if needed),[29] wherei would be the most outer loop,j the next inner loop, etc. This style is generally agreed to have originated from the early programming of Fortran[citation needed], where these variable names beginning with these letters were implicitly declared as having an integer type, and so were obvious choices for loop counters that were only temporarily required. The practice dates back further tomathematical notation whereindices forsums andmultiplications are ofteni,j, andk.
Using terse names for loop counters, likei andj, is discouraged by some since the purpose of the variables is not as clear as if they were given a longer more descriptive name.[4]: 383–382
Different languages specify different rules for what value the loop counter will hold on termination of its loop, and indeed some hold that it becomes undefined. This permits acompiler to generate code that leaves any value in the loop counter, or perhaps even leaves it unchanged because the loop value was held in a register and never stored in memory. Actual behavior may even vary according to the compiler's optimization settings.
Modifying the loop counter within the body of the loop can lead to unexpected consequences. To prevent such problems, some languages make the loop counterimmutable.[citation needed] However, only overt changes are likely to be detected by the compiler. Situations where the address of the loop counter is passed as an argument to asubroutine, make it very difficult to check because the routine's behavior is in general unknowable to the compiler unless the language supports procedure signatures and argument intents.[citation needed]
Some languages may also provide supporting statements for altering how a loop's iteration proceeds. Common among these are thebreak statement, which terminates the current loop the program is in, and thecontinue statement, which skips to the next iteration of the current loop.[4]: 379 These statements may have other names; For example inFortran 90, they are calledexit andcycle.[citation needed]
A loop can also be terminated byreturning from the function within which it is being executed.
In the case of nested loops, thebreak andcontinue statements apply to the inner most loop. Some languages allow loops to be labelled. These statements can then be applied to any of the loops in which the program is nested.
outer_loop:(This is a label for the outermost loop)for 1 ≤ i ≤ 2dofor 1 ≤ j ≤ 2do display(i, j)if i = 2contine outer_loopend ifrepeatrepeat(This nested loop displays the pairs (1, 1), (1, 2), and (2, 1))
This sectionneeds expansion. You can help byadding missing information.(January 2026) |
An infinite loop is a loop which never terminates. This can be intentional, or the result of alogic error.
Systematically detecting infinite loops is known as thehalting problem.[30]
Infinite loops are useful in applications which need to perform a repeated calculation until a program terminates, such asweb servers.[31]
I saw Johnson's semicolon version of the for loop and I put that in [B], I stole it.