Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Loop (statement)

From Wikipedia, the free encyclopedia
(Redirected fromFor loop)
Control flow statement for executing code repeatedly
icon
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.

Overview

[edit]

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.

Conditional loop

[edit]

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]

Pre-test loop

[edit]

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)xx + 1repeat

Post-test loop

[edit]
Do-While loop flow diagram

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]

Three-part for loop

[edit]
Flow diagram of a for loop that prints five asterisks.

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);}

Equivalent constructs

[edit]
[icon]
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

Enumeration

[edit]
foreach loops are almost always used to iterate over items in a sequence of elements.

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]

Loops in functional programming

[edit]
[icon]
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.

Loop counter

[edit]

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]

Early exit and continuation

[edit]

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))

Infinite loop

[edit]
Main article:Infinite loop
[icon]
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]

See also

[edit]

References

[edit]
  1. ^Angelou, Alexandros; Dadaliaris, Antonios; Dossis, Michael; Dimitriou, Georgios (2021-11-26)."Branchless Code Generation for Modern Processor Architectures".25th Pan-Hellenic Conference on Informatics. New York, NY, USA: ACM:300–305.doi:10.1145/3503823.3503879.
  2. ^abSamanta, Debasis; Sarma, Monalisa (15 June 2023).Joy with Java: Fundamentals of Object Oriented Programming. Cambridge University Press. p. 124.ISBN 978-1-009-21190-1.
  3. ^ab"Conditional loops - Computational constructs - National 4 Computing Science Revision".BBC Bitesize. Archived fromthe original on 19 October 2021. Retrieved8 January 2026.
  4. ^abcMcConnell, Steve (9 June 2004).Code Complete. Pearson Education.ISBN 978-0-7356-3697-2.
  5. ^"while Statement (GNU C Language Manual)".www.gnu.org. Archived fromthe original on 12 July 2024. Retrieved8 January 2026.
  6. ^"3. An Informal Introduction to Python".Python documentation. Archived fromthe original on 31 December 2025. Retrieved8 January 2026.
  7. ^"do...while - JavaScript | MDN".MDN Web Docs. 2025-07-08. Retrieved2026-01-22.
  8. ^"DO WHILE (FORTRAN 77 Language Reference)".docs.oracle.com. Archived fromthe original on 14 March 2023. Retrieved8 January 2026.
  9. ^"DO command (PL/I)".www.ibm.com. Archived fromthe original on 2 March 2025. Retrieved22 January 2026.
  10. ^"do-while Statement (GNU C Language Manual)".www.gnu.org. Archived fromthe original on 13 July 2024. Retrieved8 January 2026.
  11. ^"The Repeat..until statement".www.freepascal.org. Archived fromthe original on 9 November 2025. Retrieved22 January 2026.
  12. ^"Programming in Lua : 4.3.3".www.lua.org. Archived fromthe original on 2 January 2026. Retrieved22 January 2026.
  13. ^Thompson, Ken.VCF East 2019 – Brian Kernighan interviews Ken Thompson.YouTube.Archived from the original on 2021-12-12. Retrieved2020-11-16.I saw Johnson's semicolon version of the for loop and I put that in [B], I stole it.
  14. ^McConnell, Steve (9 June 2004).Code Complete. Pearson Education. p. 367.ISBN 978-0-7356-3697-2.
  15. ^Wirth, Niklaus (1973). "Preface".Systematic Programming: An Introduction. Prentice-Hall. pp. xiii.ISBN 0138803692.
  16. ^"DO / END DO".www.ibm.com. 24 April 2018. Archived fromthe original on 8 January 2026. Retrieved8 January 2026.
  17. ^"PERFORM with VARYING Phrase".www.ibm.com. June 2012. Archived fromthe original on 8 January 2026. Retrieved8 January 2026.
  18. ^"Zig documentation".ziglang.org. Archived fromthe original on 4 January 2026. Retrieved8 January 2026.
  19. ^"Looping Through a Collection with for".rust-lang.org. Archived fromthe original on 19 December 2025. Retrieved8 January 2026.
  20. ^"TIOBE Index for September 2024". Archived fromthe original on January 4, 2026. Retrieved2025-12-16.
  21. ^"for Statement (GNU C Language Manual)".www.gnu.org. Archived fromthe original on 13 July 2024. Retrieved8 January 2026.
  22. ^"for statement (C++)".learn.microsoft.com. Archived fromthe original on 28 September 2025. Retrieved8 January 2026.
  23. ^"The for Statement (The Java™ Tutorials > Learning the Java Language > Language Basics)".docs.oracle.com. Archived fromthe original on 28 December 2025. Retrieved8 January 2026.
  24. ^"Iteration statements -for, foreach, do, and while - C# reference".learn.microsoft.com. Archived fromthe original on 28 December 2025. Retrieved8 January 2026.
  25. ^"Perl for Loop".Perl Tutorial. Archived fromthe original on 7 June 2025. Retrieved8 January 2026.
  26. ^"FORALL".Intel. Archived fromthe original on 1 January 2026. Retrieved8 January 2026.
  27. ^Hinsen, Konrad (2009)."The Promises of Functional Programming".Computing in Science & Engineering.11 (4):86–90.doi:10.1109/mcse.2009.129.ISSN 1521-9615.
  28. ^Clinger, William D. (1998)."Proper tail recursion and space efficiency".Proceedings of the ACM SIGPLAN 1998 conference on Programming language design and implementation. New York, NY, USA: ACM:174–185.doi:10.1145/277650.277719.
  29. ^http://www.knosof.co.uk/vulnerabilities/loopcntrl.pdf Analysis of loop control variables in C
  30. ^Lee, Sarah."Turing's Halting Problem Explained".www.numberanalytics.com. Retrieved2026-01-22.
  31. ^"What is an infinite loop (endless loop)?".WhatIs. Retrieved2026-01-22.
Retrieved from "https://en.wikipedia.org/w/index.php?title=Loop_(statement)&oldid=1335838413#Three-part_for_loop"
Category:
Hidden categories:

[8]ページ先頭

©2009-2026 Movatter.jp