{{Short description|Control flow construct for executing code repeatedly}}{{More citations needed|date=January 2026}} In computer programming, a '''loop''' is a control flow construct 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 a collection, or to implement a long lived program.
==Overview== Loops are a feature of high-level programming languages. In low-level programming languages the same functionality is achieved using jumps. When a program is compiled to machine code, looping may be achieved using jumps; but some loops can be optimized to run without jumping.<ref>{{Cite book |last1=Angelou |first1=Alexandros |last2=Dadaliaris |first2=Antonios |last3=Dossis |first3=Michael |last4=Dimitriou |first4=Georgios |chapter=Branchless Code Generation for Modern Processor Architectures |date=2021-11-26 |title=25th Pan-Hellenic Conference on Informatics |chapter-url=https://doi.org/10.1145/3503823.3503879 |location=New York, NY, USA |publisher=ACM |pages=300–305 |doi=10.1145/3503823.3503879|isbn=978-1-4503-9555-7 |chapter-url-access=subscription }}</ref>
Usually, loops are expected to run for a finite number of iteration.{{citation needed|date=December 2025}} Without proper care, loops may accidentally be created that have no possibility of terminating. Such loops are called infinite loops. The problem of determining whether a program contains an infinite loop is known as the halting problem.
== Conditional loop == A '''conditional loop''' (also known as an '''indeterminate loop'''<ref name=joy>{{cite book |last1=Samanta |first1=Debasis |last2=Sarma |first2=Monalisa |title=Joy with Java: Fundamentals of Object Oriented Programming |date=15 June 2023 |publisher=Cambridge University Press |isbn=978-1-009-21190-1 |page=124 |url=https://books.google.com/books?id=34GyEAAAQBAJ |language=en}}</ref>) is a loop that determines whether to terminate based on a logical condition.<ref name=bbc1>{{cite web |title=Conditional loops - Computational constructs - National 4 Computing Science Revision |url=https://www.bbc.co.uk/bitesize/guides/zcg9kqt/revision/8 |website=BBC Bitesize |access-date=8 January 2026 |archive-url=https://web.archive.org/web/20211019111021/https://www.bbc.co.uk/bitesize/guides/zcg9kqt/revision/8 |archive-date=19 October 2021}}</ref> These loops are flexible, but their exact behavior can be difficult to reason about.<ref name=codecomplete></ref>{{rp|368}}
A conditional loop is usually composed of two parts: a ''condition'' and a ''body''. The ''condition'' is a logical statement depending on the state of the program and the ''body'' is a block of code that runs as long as the ''condition'' holds.<ref name=bbc1 />
A common misconception is that the execution of the ''body'' terminates as soon as the ''condition'' does not hold anymore; but this is usually not the case.<ref name=codecomplete>{{cite book |last1=McConnell |first1=Steve |title=Code Complete |date=9 June 2004 |publisher=Pearson Education |isbn=978-0-7356-3697-2 |url=https://books.google.com/books?id=LpVCAwAAQBAJ |language=en}}</ref>{{rp|368}} In most programming languages, the ''condition'' is checked once for every execution of the ''body''. When the ''condition'' is checked is not standardized and some programming languages contain multiple conditional looping structures with different rules about when the ''condition'' is assessed.{{citation needed|date=January 2026}}
=== Pre-test loop === A '''pre-test loop''' is a conditional loop where the ''condition'' is checked before the ''body'' is executed. More precisely, the ''condition'' is checked and if it holds the ''body'' is execute. Afterwards, the ''condition'' is checked again, and if it holds the ''body'' is executed again. This process repeats until the ''condition'' does not hold. Many programming languages call this loop a ''while loop'' and refer to it with the keyword ''while''. They are commonly formatted in manner similar to '''while''' ''condition'' '''do''' ''body'' '''repeat''' Instead of the keywords ''do'' and ''repeat'', other methods are sometimes used to indicate where the ''body'' begins and ends, such as curly braces<ref>{{cite web |title=while Statement (GNU C Language Manual) |url=https://www.gnu.org/software/c-intro-and-ref/manual/html_node/while-Statement.html |website=www.gnu.org |access-date=8 January 2026 |archive-url=https://web.archive.org/web/20240712235744/https://www.gnu.org/software/c-intro-and-ref/manual/html_node/while-Statement.html |archive-date=12 July 2024}}</ref> or whitespace.<ref>{{cite web |title=3. An Informal Introduction to Python |url=https://docs.python.org/3/tutorial/introduction.html |website=Python documentation |access-date=8 January 2026 |archive-url=https://web.archive.org/web/20251231204216/https://docs.python.org/3/tutorial/introduction.html |archive-date=31 December 2025 |language=en}}</ref>
For example, the following code fragment first checks whether ''x'' is less than five, which it is, so the ''body'' is entered. There, ''x'' is displayed and then incremented by one. After executing the statements in the ''body'', the ''condition'' is checked again, and the loop is executed again. This process repeats until ''x'' has the value five.
''x'' ← 0 '''while''' ''x'' < 5 '''do''' display(''x'') ''x'' ← ''x'' + 1 '''repeat'''
=== Post-test loop === thumb|upright|Do-While loop flow diagram A '''post-test loop''' is a conditional loop where the ''condition'' is checked after the ''body'' is executed. More precisely, the ''body'' is executed and afterwards the ''condition'' is checked. If it holds the ''body'' is run again and then the ''condition'' is checked. This is repeated until the ''condition'' does not hold. This is sometimes called a ''do-while loop'' due to the syntax used in various programming languages,<ref>{{Cite web |date=2025-07-08 |title=do...while - JavaScript {{!}} MDN |url=https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/do...while |access-date=2026-01-22 |website=MDN Web Docs |language=en-US}}</ref> although this can be confusing since Fortran and PL/I use the syntax "DO WHILE" for pre-test loops.<ref>{{cite web |title=DO WHILE (FORTRAN 77 Language Reference) |url=https://docs.oracle.com/cd/E19957-01/805-4939/6j4m0vn8e/index.html |website=docs.oracle.com |access-date=8 January 2026 |archive-url=https://web.archive.org/web/20230314015649/https://docs.oracle.com/cd/E19957-01/805-4939/6j4m0vn8e/index.html |archive-date=14 March 2023}}</ref><ref>{{cite web |title=DO command (PL/I) |url=https://www.ibm.com/docs/en/wdfrhcw/1.4.0?topic=commands-do-command-pli |website=www.ibm.com |access-date=22 January 2026 |archive-url=https://web.archive.org/web/20250302164825/https://www.ibm.com/docs/en/wdfrhcw/1.4.0?topic=commands-do-command-pli |archive-date=2 March 2025 |language=en-us}}</ref> Post-test loops are commonly formatted in manner similar to '''do''' ''body'' '''repeat''' '''while''' ''condition'' Instead of the keywords ''do'' and ''repeat'' others methods are sometime use to indicate where the ''body'' begins and ends, such as curly braces.<ref>{{cite web |title=do-while Statement (GNU C Language Manual) |url=https://www.gnu.org/software/c-intro-and-ref/manual/html_node/do_002dwhile-Statement.html |website=www.gnu.org |access-date=8 January 2026 |archive-url=https://web.archive.org/web/20240713012759/https://www.gnu.org/software/c-intro-and-ref/manual/html_node/do_002dwhile-Statement.html |archive-date=13 July 2024}}</ref>
Some languages may use a different naming convention for this type of loop. For example, the Pascal and Lua languages have a "''repeat until''" loop, which continues to run ''until'' the control expression is true and then terminates.<ref>{{cite web |title=The Repeat..until statement |url=https://www.freepascal.org/docs-html/ref/refsu60.html |website=www.freepascal.org |access-date=22 January 2026 |archive-url=https://web.archive.org/web/20251109225700/https://www.freepascal.org/docs-html/ref/refsu60.html |archive-date=9 November 2025}}</ref><ref>{{cite web |title=Programming in Lua : 4.3.3 |url=https://www.lua.org/pil/4.3.3.html |website=www.lua.org |access-date=22 January 2026 |archive-url=https://web.archive.org/web/20260102100039/https://www.lua.org/pil/4.3.3.html |archive-date=2 January 2026}}</ref>
=== Three-part for loop === thumb|right |Flow diagram of a for loop that prints five asterisks. A '''three-part for loop''', popularized by C, has two additional parts: ''initialization'' (loop variant), and ''increment'', both of which are blocks of code. The ''initialization'' is intended as code that prepares the loop and is run once in the beginning and ''increment'' 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 '''for''' ''initialization'', ''condition'', ''increment'' '''do''' ''body'' '''repeat'''
This syntax came from B and was originally invented by Stephen C. Johnson.<ref name="ken">{{cite AV media |last=Thompson |first=Ken |author-link=Ken Thompson |website=YouTube |url=https://www.youtube.com/watch?v=EY6q5dv_B-o&t=2330 |title=VCF East 2019 – Brian Kernighan interviews Ken Thompson |archive-url=https://ghostarchive.org/varchive/youtube/20211212/EY6q5dv_B-o |archive-date=2021-12-12 |url-status=live |quote=I saw Johnson's semicolon version of the for loop and I put that in [B], I stole it. |access-date=2020-11-16}}{{cbignore}}</ref> The following C code is an example of a three part loop that prints the numbers from 0 to 4.
<syntaxhighlight Lang="c"> for (int i = 0; i < 5; i++) { printf("%d\n", i); } </syntaxhighlight>
===Equivalent constructs=== {{Expand section|date=January 2026}} Assuming there is a properly declared function or method called <code>do_work()</code>, the following are equivalent in programming languages which support post-test loops.<ref>{{Cite web |title=The while and do-while Statements (The Java™ Tutorials > Learning the Java Language > Language Basics) |url=https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html |access-date=2026-05-16 |website=docs.oracle.com}}</ref>
{| class="wikitable" || '''do''' do_work() '''repeat while''' ''condition'' || do_work() '''while''' ''condition'' '''do''' do_work() '''repeat''' |}
Furthermore, given that a <code>continue</code> 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.<ref>Parlante, Nick. [https://cs.stanford.edu/people/nick/py/python-while.html "While Loop"]. Stanford University. Retrieved 16-05-26.</ref><ref>{{Cite web |title=3.12. Legitimate Uses For goto |url=https://icarus.cs.weber.edu/~dab/cs1410/textbook/3.Control/goto.html |access-date=2026-05-16 |website=icarus.cs.weber.edu}}</ref>
'''while''' ''true'' '''do''' do_work() '''if''' ''condition'' is not ''true'' '''then''' '''break''' '''end if''' '''repeat'''
or alternatively,
LOOPSTART: do_work() '''if''' ''condition'' '''then''' '''goto''' LOOPSTART '''end if'''
== Enumeration == thumb|{{mono|foreach}} loops are almost always used to iterate over items in a sequence of elements. An '''enumeration''' (also known as an '''determinate loop'''<ref name=joy />) is a loop intended to iterate over all the items of a collection.<ref>{{cite book |last1=McConnell |first1=Steve |title=Code Complete |date=9 June 2004 |publisher=Pearson Education |isbn=978-0-7356-3697-2 |pages=367 |url=https://books.google.com/books?id=LpVCAwAAQBAJ&q=code+complete |language=en}}</ref>{{pn|date=March 2026}} It is not as flexible as a conditional loop; but it is more predictable.{{citation needed|date=January 2026}} For example, it is easier to guarantee that enumerations terminate and they avoid potential off-by-one errors.{{citation needed|date=January 2026}} Enumerations can be implemented using an iterator, whether implicitly or explicitly.{{cn|date=March 2026}}
Depending on the programming language, various keywords are used to invoke enumerations. For example, descendants of ALGOL use {{code |for}},<ref>{{Cite book |last=Wirth |first=Niklaus |author-link=Niklaus Wirth |year=1973 |chapter=Preface |title=Systematic Programming: An Introduction |pages=xiii |publisher=Prentice-Hall |isbn=0138803692}}</ref> while descendants of Fortran use {{code |do}}<ref>{{cite web |title=DO / END DO |url=https://www.ibm.com/docs/en/xl-fortran-linux/16.1.0?topic=directives-do-end-do |website=www.ibm.com |access-date=8 January 2026 |archive-url=https://web.archive.org/web/20260108231419/https://www.ibm.com/docs/en/xl-fortran-linux/16.1.0?topic=directives-do-end-do |archive-date=8 January 2026 |language=en-us |date=24 April 2018}}</ref> and COBOL uses {{code |PERFORM VARYING}}.<ref>{{cite web |title=PERFORM with VARYING Phrase |url=https://www.ibm.com/docs/en/i/7.5.0?topic=statement-perform-varying-phrase |website=www.ibm.com |access-date=8 January 2026 |archive-url=https://web.archive.org/web/20260108231758/https://www.ibm.com/docs/en/i/7.5.0?topic=statement-perform-varying-phrase |archive-date=8 January 2026 |language=en-us |date=June 2012}}</ref>
Enumerations are sometimes called "for loops," for example in Zig and Rust.<ref>{{cite web |title=Zig documentation |url=https://ziglang.org/documentation/master/#for |website=ziglang.org |access-date=8 January 2026 |archive-url=https://web.archive.org/web/20260104121319/https://ziglang.org/documentation/master/#for |archive-date=4 January 2026}}</ref><ref>{{cite web |title=Looping Through a Collection with for |url=https://doc.rust-lang.org/stable/book/ch03-05-control-flow.html#looping-through-a-collection-with-for |website=rust-lang.org |access-date=8 January 2026 |archive-url=https://web.archive.org/web/20251219092527/https://doc.rust-lang.org/stable/book/ch03-05-control-flow.html#looping-through-a-collection-with-for |archive-date=19 December 2025}}</ref> This can be confusing since many of the most popular<ref>{{cite web|title=TIOBE Index for September 2024|url=https://www.tiobe.com/tiobe-index/|access-date=2025-12-16|archive-date=January 4, 2026|archive-url=https://web.archive.org/web/20260104151245/https://www.tiobe.com/tiobe-index/}}</ref> programming languages, such as C, C++, and Java, use that term for the three-part for loop,<ref>{{cite web |title=for Statement (GNU C Language Manual) |url=https://www.gnu.org/software/c-intro-and-ref/manual/html_node/for-Statement.html |website=www.gnu.org |access-date=8 January 2026 |archive-url=https://web.archive.org/web/20240713014231/https://www.gnu.org/software/c-intro-and-ref/manual/html_node/for-Statement.html |archive-date=13 July 2024}}</ref><ref>{{cite web |title=for statement (C++) |url=https://learn.microsoft.com/en-us/cpp/cpp/for-statement-cpp?view=msvc-170 |website=learn.microsoft.com |access-date=8 January 2026 |archive-url=https://web.archive.org/web/20250928185930/https://learn.microsoft.com/en-us/cpp/cpp/for-statement-cpp?view=msvc-170 |archive-date=28 September 2025 |language=en-us}}</ref><ref>{{cite web |title=The for Statement (The Java™ Tutorials > Learning the Java Language > Language Basics) |url=https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html |website=docs.oracle.com |access-date=8 January 2026 |archive-url=https://web.archive.org/web/20251228051928/https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html |archive-date=28 December 2025}}</ref> which is not an enumeration. Other programming languages, such as Perl and C#, avoid this confusion by using the term "foreach loop."<ref>{{cite web |title=Iteration statements -for, foreach, do, and while - C# reference |url=https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/iteration-statements |website=learn.microsoft.com |access-date=8 January 2026 |archive-url=https://web.archive.org/web/20251228021319/https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/iteration-statements |archive-date=28 December 2025 |language=en-us}}</ref><ref>{{cite web |title=Perl for Loop |url=https://www.perltutorial.org/perl-for-loop/ |website=Perl Tutorial |access-date=8 January 2026 |archive-url=https://web.archive.org/web/20250607160051/https://www.perltutorial.org/perl-for-loop/ |archive-date=7 June 2025}}</ref>
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 keyword {{code|FORALL}}, 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 in Fortran 2018.<ref>{{cite web |title=FORALL |url=https://www.intel.com/content/www/us/en/docs/fortran-compiler/developer-guide-reference/2025-2/forall.html |website=Intel |access-date=8 January 2026 |archive-url=https://web.archive.org/web/20260101223642/https://www.intel.com/content/www/us/en/docs/fortran-compiler/developer-guide-reference/2025-2/forall.html |archive-date=1 January 2026 |language=en}}</ref>
== Loops in functional programming == {{Expand section|date=January 2026}} In most functional programming languages, recursion is used instead of traditional loops. This is due to the fact that variables are immutable, and therefore the ''increment'' step of a loop cannot occur.<ref>{{Cite journal |last=Hinsen |first=Konrad |date=2009 |title=The Promises of Functional Programming |url=https://doi.org/10.1109/mcse.2009.129 |journal=Computing in Science & Engineering |volume=11 |issue=4 |pages=86–90 |doi=10.1109/mcse.2009.129 |bibcode=2009CSE....11d..86H |issn=1521-9615}}</ref>
To avoid running into stack overflow errors for long loops, functional programming languages implement tail call optimisation, which allows the same stack frame to be used for each iteration of the loop, compiling to effectively the same code as a ''while'' or ''for'' loop.<ref>{{Cite book |last=Clinger |first=William D. |chapter=Proper tail recursion and space efficiency |date=1998 |title=Proceedings of the ACM SIGPLAN 1998 conference on Programming language design and implementation |location=New York, NY, USA |publisher=ACM |pages=174–185 |doi=10.1145/277650.277719|doi-access=free |isbn=0-89791-987-4 }}</ref>
Some languages, such as Haskell, have a syntax known as a list comprehension, which is similar to enumeration, iterating over the contents of a list and transforming it into a new list.{{cn|date=March 2026}}
==<span class="anchor" id="Loop counters"></span>Loop counter== 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 common identifier naming convention is for the loop counter to use the variable names ''i'', ''j'', and ''k'' (and so on if needed),<ref>http://www.knosof.co.uk/vulnerabilities/loopcntrl.pdf Analysis of loop control variables in C</ref> where ''i'' 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|date=August 2009}}, 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 to mathematical notation where indices for sums and multiplications are often ''i'', ''j'', and ''k''.
Using terse names for loop counters, like ''i'' and ''j'', is discouraged by some since the purpose of the variables is not as clear as if they were given a longer more descriptive name.<ref name=codecomplete />{{rp|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 a compiler 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 counter immutable.{{Citation needed|date=January 2026}} 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 a subroutine, 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|date=January 2026}}
==Early exit and continuation== Some languages may also provide supporting statements for altering how a loop's iteration proceeds. Common among these are the ''break'' statement, which terminates the current loop the program is in, and the ''continue'' statement, which skips to the next iteration of the current loop.<ref name=codecomplete />{{rp|379}} These statements may have other names; For example in Fortran 90, they are called ''exit'' and ''cycle''.{{citation needed|date=December 2025}}
A loop can also be terminated by returning from the function within which it is being executed.
In the case of nested loops, the ''break'' and ''continue'' 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 ≤ 2 '''do''' '''for''' 1 ≤ j ≤ 2 '''do''' display(i, j) '''if''' i = 2 '''continue''' outer_loop '''end if''' '''repeat''' '''repeat''' ''(This nested loop displays the pairs (1, 1), (1, 2), and (2, 1))''
==Infinite loop== {{Main|Infinite loop}}{{Expand section|date=January 2026}} An infinite loop is a loop which never terminates. This can be intentional, or the result of a logic error.{{cn|date=March 2026}}
Systematically detecting infinite loops is known as the halting problem.
Infinite loops are useful in applications which need to perform a repeated calculation until a program terminates, such as web servers.<ref>{{Cite web |title=What is an infinite loop (endless loop)? |url=https://www.techtarget.com/whatis/definition/infinite-loop-endless-loop |access-date=2026-01-22 |website=WhatIs |language=en}}</ref>
== See also == * Primitive recursive function * General recursive function * Repeat loop (disambiguation) * LOOP (programming language) – a programming language with the property that the functions it can compute are exactly the primitive recursive functions
==References== {{Reflist}}
Category:Control flow