Fact-checked by Grok 2 weeks ago

While loop

A while loop is a fundamental construct in that repeatedly executes a block of code as long as a specified condition evaluates to true. The condition is tested before each iteration; if true, the loop body executes, and the process repeats, but if false, execution proceeds to the statement following the loop. This structure is essential for implementing algorithms where the number of iterations is indeterminate at the outset, such as input until an marker is reached or continuing a until a criterion is met. While loops appear in nearly all imperative and languages, with syntax variations but consistent semantics. For example, in , the form is while <condition>: followed by an indented of statements, where the is an expression evaluated in a context. In C# and , it follows while (condition) { statements }, requiring parentheses around the and braces for the body if multi-statement. Unlike for loops, which typically iterate over a known range or collection, while loops emphasize -based repetition without built-in counters, making them suitable for tasks like event-driven processing or recursive simulations without explicit . They differ from do-while loops by checking the pre-iteration, potentially skipping the body entirely if initially false, whereas do-while ensures at least one execution. A key consideration in using while loops is avoiding loops, which occur if the condition never becomes false due to errors, such as failing to update variables inside the body; this can cause programs to hang or consume excessive resources. To mitigate this, programmers often include loop invariants—properties that hold true before and after each —or use tools to trace condition changes. While loops form the basis for more complex control patterns, including those in functional languages via or calls, and remain a cornerstone of introductory education for teaching and conditional .

Fundamentals

Definition

A while loop is a fundamental control flow structure in programming languages that enables the repeated execution of a block of code as long as a specified Boolean condition evaluates to true. This construct is essential for implementing iterative processes where the number of repetitions is not predetermined and depends on runtime conditions. Unlike fixed-iteration mechanisms, the while loop supports indefinite iteration, making it suitable for scenarios such as processing input until a sentinel value is encountered or continuing computation until convergence is achieved. The of a while loop involve an initial evaluation of the before any execution of the loop ; if the is false at the outset, the loop is skipped entirely, and control passes to the subsequent statements. Upon a true , the loop executes, after which the is re-evaluated, forming a that persists until the becomes false. This pre-test evaluation distinguishes the while loop from post-test variants and ensures that the executes zero or more times, provided the can be falsified through changes within the , such as updates or modifications. In , the structure of a while loop is typically expressed as:
while ([condition](/page/Condition)) {
    // loop body statements
}
Here, [condition](/page/Condition) is a , and the enclosed statements form the body that performs the iterative work. Proper design requires that the loop body includes mechanisms to alter the , preventing non-termination; failure to do so results in infinite loops, which can halt program execution. The while loop originated as a structured programming primitive in , where it was formalized as a "while-do" statement to promote clear, goto-free in algorithmic descriptions. This design influenced subsequent languages, establishing the while loop as a standard for conditional repetition in imperative and procedural paradigms. Its adoption underscores the emphasis on readability and maintainability in practices.

Basic Syntax

The basic syntax of a while loop features the keyword "while" followed by a condition enclosed in parentheses, and a body of statements delimited by braces or indentation, depending on the language convention. This structure ensures the loop body executes repeatedly only while the condition evaluates to true. In , the syntax is commonly expressed as:
while (condition is true)
    do something
end while
Here, the "condition" is a tested before each iteration, and the "do something" represents the , which must include logic to eventually falsify the condition to prevent execution. For instance, a simple example counts iterations while a is below a :
set count = 0
while (count < 5)
    print(count)
    increment count by 1
end while
This outputs values from 0 to 4 before terminating. The condition must be a well-formed boolean expression, such as a comparison (e.g., variable < limit) or logical combination, and the body can contain multiple statements or even nested structures, though the core syntax remains invariant across implementations. Proper indentation or block delimiters are essential for readability and to define the scope of the loop body clearly.

Execution and Semantics

Condition Evaluation

In a while loop, the condition is a boolean expression evaluated prior to each iteration to determine whether the loop body should execute. This pre-test evaluation ensures that the body runs zero or more times, depending on the initial and subsequent states of the program. If the condition evaluates to true, the body executes, potentially modifying variables that affect future evaluations; if false, the loop terminates immediately without executing the body. Formal models of condition evaluation appear in operational semantics for imperative programming languages. In big-step operational semantics, as defined for the WHILE language, the judgment E \vdash \texttt{while } P \texttt{ do } S \Downarrow E' evaluates the predicate P in environment E to a boolean value. If E \vdash P \Downarrow \texttt{true} and E \vdash S; \texttt{while } P \texttt{ do } S \Downarrow E', the loop reduces to the result after executing the body followed by the loop itself; if E \vdash P \Downarrow \texttt{false}, it terminates with E \vdash \texttt{while } P \texttt{ do } S \Downarrow E, leaving the environment unchanged. This recursive definition captures the repeated evaluation until falsity.
E ⊢ P ⇓ true    E ⊢ S ; while P do S ⇓ E'
---------------------------------------------  (WHILE-TRUE)
      E ⊢ while P do S ⇓ E'

E ⊢ P ⇓ false
---------------------  (WHILE-FALSE)
   E ⊢ while P do S ⇓ E
In contrast, small-step operational semantics model condition evaluation through stepwise reductions without committing to a final result in one rule. The while loop desugars in one step to an equivalent if statement, transforming the configuration \langle \texttt{while } b \texttt{ do } c, \sigma \rangle \to \langle \texttt{if } b \texttt{ then } (c; \texttt{while } b \texttt{ do } c) \texttt{ else } \texttt{skip}, \sigma \rangle, where b is the condition and \sigma the store. The condition b then reduces step-by-step via boolean expression rules (e.g., arithmetic subexpressions evaluate to numbers before comparison), feeding into the if's evaluation: if true, the body and loop execute; if false, skip terminates. This approach simulates machine-like execution, preserving the store until the condition resolves. In standardized languages, condition evaluation adheres to these principles with language-specific details on types and side effects. The C standard specifies that the controlling expression, of scalar type, evaluates to non-zero for continuation, performed before each body execution; side effects in the expression are sequenced such that the body sees updated values, but subexpression order is unspecified beyond that. The Java Language Specification requires the expression to be boolean (or unboxable to boolean), evaluated afresh before each iteration; if evaluation throws an exception or completes abruptly, the while statement propagates the abruptness without body execution. These evaluations enable dynamic loop control, where conditions often reference mutable state from prior iterations, but require careful design to guarantee termination.

Loop Body Execution

In a while loop, the loop body consists of one or more statements that are executed sequentially only if the preceding condition evaluates to true. Execution of the body commences immediately after the condition check succeeds, processing each statement in the order they appear, which may include assignments, function calls, or other control structures. Upon completing the body, program control returns to the condition for re-evaluation, potentially leading to another iteration if the condition remains true. This repeated execution allows the body to perform iterative tasks, such as accumulating results or processing data until a stopping criterion is met. Formally, the semantics of loop body execution are often defined using operational models, such as big-step semantics, where the while loop is evaluated recursively based on the current program state. If the condition P evaluates to true in state E, the body S is executed to yield a new state E', after which the entire while loop is re-evaluated in E'. This rule, known as reduce-whiletrue, ensures the body executes followed by a recursive call to the loop itself, continuing until the condition evaluates to false, at which point the body is skipped and the original state is preserved (reduce-whilefalse). Similar recursive evaluation applies in large-step operational semantics for imperative languages like IMP, where the body c transitions the state from σ to σ'' before re-applying the loop rule. These models capture the iterative nature without altering the state prematurely, emphasizing that body execution directly influences subsequent condition checks through side effects like variable modifications. A representative example illustrates this process in a Java-like syntax, where the body increments a counter and outputs its value:
int count = 1;
while (count <= 3) {
    System.out.println("count is: " + count);
    count = count + 1;
}
System.out.println("Done with the loop");
The body executes three times: first printing "count is: 1" and setting count to 2; then "count is: 2" and count to 3; finally "count is: 3" and count to 4. On the fourth condition check, count <= 3 is false, so the body is skipped, and execution proceeds to the post-loop statement. The body's assignment ensures termination by altering the condition-dependent variable. The loop body's potential to modify state variables critical to the condition is central to achieving termination, as unchecked execution could lead to non-termination if the condition never falsifies. Semantics guarantee that the body runs zero or more times, with each iteration isolated to its sequential statements, though nested structures within the body follow their own execution rules. This design supports reliable iterative computation in imperative programming paradigms.

Termination and Infinite Loops

In a while loop, execution terminates when the controlling condition evaluates to false, at which point control passes to the statement immediately following the loop construct. This pre-test mechanism ensures that the loop body may not execute at all if the condition is initially false. For instance, in Python, the while statement repeatedly executes its suite until the condition, an assignment expression, becomes false; if no iterations occur, an optional else clause may still execute. Similarly, in C++, the while loop evaluates its condition before each iteration, converting the result to bool, and terminates upon yielding false (or zero for integral types). Infinite loops arise in while constructs when the condition perpetually evaluates to true, preventing natural termination and potentially causing resource exhaustion or program unresponsiveness. Common causes include failure to modify variables involved in the condition within the loop body, leading to unchanged evaluation outcomes. For example, in a loop like while (i < 10) { /* no update to i */ }, the variable i remains unaltered, resulting in endless repetition. Another frequent issue is using a constant true condition, such as while (true) { ... } without an explicit exit mechanism, which is sometimes intentional for event-driven code but often stems from logical errors. To mitigate infinite loops, programmers must ensure the loop body includes operations that progress toward falsifying the condition, such as incrementing counters or reading external inputs. Early termination can be enforced using control statements like break, which exits the loop immediately upon execution, bypassing further condition checks. In Python, break skips any else clause, while in C++, it simply transfers control to the post-loop statement. Prevention also involves rigorous testing, such as tracing variable states or employing static analysis tools to detect potential non-termination paths. Accidental infinite loops, like those from off-by-one errors where a variable "accidentally stays" at a value satisfying the condition, underscore the need for careful condition design. From a formal semantics perspective, while loops model non-deterministic repetition until termination, but infinite execution represents a fixed point where the loop semantics denote divergence rather than a value. In operational semantics for imperative languages like While, termination requires the condition to eventually yield false after finite steps; otherwise, the computation sequence continues indefinitely. This aligns with axiomatic approaches, where proving termination often relies on loop invariants demonstrating progress toward a false condition.

Comparisons to Other Loops

Versus For Loop

The while loop and for loop are both iteration constructs in imperative programming languages, but they differ in structure, initialization, and typical use cases. The for loop typically integrates initialization, condition checking, and update operations into a single statement, making it suitable for scenarios where the number of iterations is predetermined or based on a countable sequence, such as traversing an array or generating a range of values. In contrast, the while loop separates the condition evaluation from any initialization or updates, which must be handled explicitly outside or within the loop body, allowing for more flexible control when the iteration count is unknown or depends on runtime conditions like user input or dynamic computations. In terms of syntax, a for loop in C-like languages follows the form for (initialization; condition; update) { body }, where the initialization occurs once before the loop starts, the condition is checked before each iteration, and the update executes after each body execution. This compact structure reduces boilerplate code for counter-based loops, as seen in an example iterating from 0 to 9:
c
for (int i = 0; i < 10; ++i) {
    printf("%d\n", i);
}
A , however, uses while (condition) { body }, requiring manual management of variables, such as:
c
int i = 0;
while (i < 10) {
    printf("%d\n", i);
    ++i;
}
This explicit control in while loops can lead to clearer intent for complex conditions but increases the risk of infinite loops if updates are omitted. In Python, the distinction is more pronounced: for loops iterate over iterables like lists or ranges (for i in range(10):), emphasizing sequence traversal, while while loops rely solely on a boolean condition (i = 0; while i < 10: i += 1). Use cases highlight their complementarity. For loops excel in fixed-iteration tasks, such as processing elements in a collection, where readability benefits from the built-in iteration mechanics; empirical studies on programmer cognition show that counter-based for loops align with "process/read" strategies for predictable data access. While loops are preferred for indefinite iterations, like waiting for an event or processing until a sentinel value is encountered, as in reading input until a specific string:
python
while input() != "quit":
    # process input
This flexibility suits algorithms where termination depends on evolving state, though it demands careful condition management to avoid non-termination.
AspectFor LoopWhile Loop
StructureCombines init, condition, update in headerCondition only; init/update manual
Best ForKnown iterations, sequencesUnknown iterations, dynamic conditions
ReadabilityHigh for counters; reduces code duplicationHigh for logic-heavy flows; explicit but verbose
RisksOverly rigid for variable countsInfinite loops if condition not updated
Overall, the choice between them promotes code clarity: for loops for enumerable tasks and while loops for conditional persistence, as standardized in languages like and to support structured programming principles.

Versus Do-While Loop

The primary distinction between a while loop and a do-while loop is the timing of condition evaluation, which affects the minimum number of executions of the loop body. In a while loop, the controlling expression is evaluated before the body executes; if it is false (or zero in languages like ), the body may not run at all, making it a pretest loop suitable for scenarios where iteration is conditional from the start. Conversely, a do-while loop is a posttest construct: the body executes at least once, followed by evaluation of the condition to determine continuation, ensuring guaranteed initial execution even if the condition would otherwise fail immediately. This difference influences syntax and semantics across languages. For instance, in C and C++, the while loop syntax is while (expression) statement;, where the expression must evaluate to a nonzero value for execution, while do-while uses do statement while (expression);, with the semicolon after the condition mandatory to close the loop. In Java, the structures mirror this: while (booleanExpression) { statements } for pretest and do { statements } while (booleanExpression); for posttest, where the boolean must be true to continue. Similar patterns appear in C#, where the do loop explicitly differs by requiring at least one iteration, unlike while which permits zero.
AspectWhile LoopDo-While Loop
Condition CheckBefore body execution (pretest)After body execution (posttest)
Minimum Iterations0 (if condition false initially)1 (body always runs first)
Use Case ExamplePolling until a resource is available, skipping if already readyInteractive menus or input prompts requiring at least one user response
Risk of Infinite LoopPossible if condition never falsifiesPossible, but initial execution always occurs
Do-while loops are particularly valuable in applications needing unconditional first-run behavior, such as validating user input in a loop until valid data is provided, as the prompt displays before any check. However, while loops offer more flexibility for avoiding unnecessary computations when the condition can be determined upfront, reducing overhead in conditional scenarios. Both support early termination via break and iteration skipping with continue, but the posttest nature of do-while can introduce subtle bugs if the body has side effects assuming multiple runs. For example, consider prompting for input in Java: While loop (may skip prompt if input valid initially):
java
String input = getInitialInput();  // Assume pre-fetched
while (!isValid(input)) {
    System.out.println("Invalid input. Try again:");
    input = readInput();
}
Do-while loop (always prompts at least once):
java
String input;
do {
    System.out.println("Enter input:");
    input = readInput();
} while (!isValid(input));
This illustrates how do-while ensures user interaction occurs, aligning with its design for bottom-tested control flow.

Language-Specific Implementations

In C-Like Languages

In C-like languages, such as C, C++, Java, and JavaScript, the while loop provides a mechanism for conditional repetition of a statement or block of code, originating from the syntax defined in the C programming language. The basic form evaluates a condition before each iteration; if the condition holds true, the loop body executes, and the process repeats until the condition becomes false. This pre-test structure ensures the body may execute zero or more times, distinguishing it from post-test loops like do-while. In C, the syntax is while (expression) statement, where expression must be of arithmetic or pointer type and is considered true if nonzero. The expression is evaluated first; if false (zero), execution proceeds to the next statement after the loop. If true, the statement (which may be a compound block { ... }) executes, after which the expression re-evaluates. Control statements like break terminate the loop normally, while continue skips the remainder of the body and re-evaluates the condition. For example, the following C code copies characters from one string to another in reverse until reaching the end:
c
int i = 3;
while (i >= 0) {
    string1[i] = string2[i];
    i--;
}
This loop may result in an infinite execution if the condition never falsifies, such as while (1) { ... }, unless interrupted by break or external factors. C++ inherits this syntax almost identically, as while (condition) statement, but extends the condition to support declarations since , such as while (int x = get_value()) { ... }, where the declared variable scopes to the loop body and re-initializes each iteration. The condition converts to bool; non-convertible types cause a compile-time . Like C, break and continue apply, and infinite loops invoke undefined behavior without observable side effects in modern standards. An example iterating over even numbers:
cpp
int j = 0;
while (j < 9) {
    std::cout << j << ' ';
    j += 2;
}
This outputs 0 2 4 6 8. In Java, the syntax is while (Expression) Statement, where Expression must evaluate to a boolean value (or unbox from Boolean), enforcing stricter type safety than C or C++. Execution mirrors C: evaluate the expression; if true, run the statement and loop; if false, complete normally without entering the body. Abrupt completions in the body (e.g., via break or return) propagate accordingly, and continue restarts the condition check. Java's while loop integrates seamlessly with its object-oriented features, often used for processing collections until a sentinel value. No direct example is in the specification, but it aligns with the C-like form for compatibility in mixed paradigms. JavaScript adopts a similar while (condition) statement syntax, where condition is an expression coerced to a (truthy/falsy). The loop executes the statement (block recommended for multiples) if truthy, re-checking after each . It supports break to exit and continue to advance, and is commonly used for dynamic iterations like inputs. For instance:
javascript
let n = 0;
while (n < 3) {
    n++;
}
console.log(n);  // Outputs: 3
Assignments in conditions, like while (node = nextNode()), require parentheses for clarity to avoid ambiguities. Across these languages, while loops emphasize efficiency for unknown counts, such as reading input or processing until exhaustion, but require careful management to avoid unintended loops, which can lead to resource exhaustion in production environments. Variations like declaration-based conditions in C++ highlight evolutionary adaptations, while Java's boolean strictness prevents common C pitfalls like implicit pointer checks.

In Scripting Languages

In scripting languages, the while loop serves as a fundamental control structure for executing code repeatedly based on a conditional test, commonly used for tasks like input , waiting for events, or iterating until a resource is exhausted. These languages, often interpreted and dynamically typed, adapt the while loop from C-like syntax but incorporate features suited to rapid development and , such as flexible evaluation and integration with built-in functions for handling or . Unlike in compiled languages, while loops in scripting environments emphasize and brevity, with indentation or keywords delineating blocks rather than braces in some cases. In Python, the while loop evaluates a boolean expression before each iteration, executing the indented block if true, and supports an else clause that runs when the condition becomes false without a break statement intervening. This else feature distinguishes Python's while from stricter implementations, allowing cleanup code after normal termination. The syntax is while condition:, followed by indented statements. For example, to compute Fibonacci numbers up to a limit:
python
a, b = 0, 1
while a < 10:
    print(a, end=' ')
    a, b = b, a + b
print()
This outputs 0 1 1 2 3 5 8, demonstrating indefinite based on the . Break and continue s further , with break exiting early and continue skipping to the next check. JavaScript's while loop, as defined in , checks the before executing the or block, making it suitable for browser-based event polling or asynchronous simulations in . The syntax is while ([condition](/page/Condition)) [statement](/page/Statement);, where the must coerce to a , and curly braces {} are optional for single s but recommended for clarity. An example iterates until a counter reaches five:
javascript
let i = 0;
while (i < 5) {
  console.log(i);
  i++;
}
This prints 0 through 4. The loop integrates seamlessly with 's event-driven model, often used in scripts for dynamic , and adheres to strict mode without special caveats for . Infinite loops are a common pitfall if the condition never falsifies, requiring careful . PHP employs a C-inspired while loop for , evaluating the expression at the start of each and executing the if it is truthy. The syntax is while (expr) statement;, supporting both single statements and blocks with braces. It mirrors while loops in procedural code for tasks like reading database results or form validation. A basic example prints numbers from 1 to 5:
php
$i = 1;
while ($i <= 5) {
    echo $i . "\n";
    $i++;
}
PHP's while lacks an else clause but pairs with break and continue for flow control, and it is often preferred over for loops when the count is unknown, such as in file uploads or polling. The loop's simplicity aids in embedding within for dynamic pages. Ruby's while loop checks the before , using do (optional) to introduce the ended by end, and returns nil unless broken. This syntax promotes Ruby's emphasis on expressiveness, with a modifier form expression while condition for concise post-condition checks. An example increments and prints until 10:
ruby
a = 0
while a < 10 do
  p a
  a += 1
end
p a  # Outputs 10
A begin block before while ensures at least one execution, akin to do-while. Modifiers enable idiomatic one-liners like print i; i += 1 while i < 5, useful in Rails controllers or scripts. Ruby's dynamic nature allows conditions involving objects or s without type restrictions. In and other shell scripting, the while loop tests commands for a zero before executing the body, ideal for process monitoring or log parsing in Unix environments. The is while test-commands; do consequent-commands; done, where test-commands often use [ ] for comparisons. For instance, to echo numbers 1 to 5:
bash
n=1
while [ &#36;n -le 5 ]; do
  echo $n
  n=$((n + 1))
done
This leverages shell builtins like true for loops or read for line-by-line input, with break and continue for . 's command-oriented makes while loops essential for pipelines and traps, differing from higher-level languages by treating conditions as executable code rather than expressions.

In Other Paradigms

In paradigms, traditional imperative while loops are typically avoided in favor of and higher-order functions to maintain immutability and pure functions. serves as the primary mechanism for iteration, where a function calls itself with modified arguments until a base case is met, effectively simulating conditional repetition without mutable state. For instance, in , a while loop equivalent can be implemented using tail-recursive functions or combinators like foldr, which process data declaratively. This approach aligns with the paradigm's emphasis on mathematical expressiveness over side effects; for example, computing a sum iteratively uses a recursive accumulator function rather than updating a loop variable. Languages like F# support imperative while loops for interoperability but prioritize recursive definitions for idiomatic functional code, such as defining factorial via let rec fact n = if n = 0 then 1 else n * fact (n - 1). The use of recursion prevents issues like stack overflows in optimized tail calls, which many functional compilers convert to efficient loops at runtime. In paradigms, such as , there are no built-in while loops; iteration is achieved through recursive and the language's inherent mechanism. A defines rules that recursively unfold until all solutions are enumerated or a failure condition halts execution, mimicking conditional looping declaratively. For example, generating a list of numbers up to N uses a recursive like nums(0, [], _) :- !. nums(N, [N|Ns], Max) :- N =< Max, N1 is N-1, nums(N1, Ns, Max)., where the base case terminates the . This recursive style leverages Prolog's search strategy for non-deterministic computation, avoiding explicit loop control in favor of logical inference. Extensions like tabling or definite clause grammars (DCGs) further optimize iterative tasks, such as parsing or constraint solving, by memoizing intermediate results to prevent redundant recursion. In multi-paradigm languages like Lisp, functional subsets employ recursion similarly, though macros like loop provide imperative-like syntax for convenience without altering the core paradigm.

References

  1. [1]
    8. Compound statements — Python 3.14.0 documentation
    8.2. The while statement¶ ... This repeatedly tests the expression and, if it is true, executes the first suite; if the expression is false (which may be the ...
  2. [2]
    The while and do-while Statements (The Java™ Tutorials ...
    The `while` statement executes while a condition is true, and the `do-while` executes at least once, evaluating the condition at the end of the loop.
  3. [3]
    Iteration statements -for, foreach, do, and while - C# reference
    Nov 14, 2023 · The while statement executes a statement or a block of statements while a specified Boolean expression evaluates to true . Because that ...
  4. [4]
    Programming - While Loop
    A 'While' loop repeats a code block an unknown number of times until a condition is met, going as often as necessary to accomplish its goal.
  5. [5]
    do-while Statement (C) - Microsoft Learn
    Jan 25, 2023 · A do-while statement repeats a statement until a condition is false, ensuring the body executes at least once. The condition is evaluated after ...
  6. [6]
    Javanotes 9, Section 3.1 -- Blocks, Loops, and Branches
    A while loop is used to repeat a given statement over and over. Of course, it's not likely that you would want to keep repeating it forever. That would be an ...<|control11|><|separator|>
  7. [7]
    Introduction to C / C++ Programming Looping Constructs
    Both while and do-while loops alternate between performing actions and testing for the stopping condition. While loops check for the stopping condition first, ...
  8. [8]
    While Loops - Python Programming And Numerical Methods
    A while loop or indefinite loop is a set of instructions that is repeated as long as the associated logical expression is true.
  9. [9]
    [PDF] Chapter 7
    Compound statements - introduced by ALGOL 60 in the form of begin...end. A ... logical loop statements (while-do and repeat-until). 2. C and C++ also ...
  10. [10]
    While Loop – Programming Fundamentals - Rebus Press
    A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition.
  11. [11]
    4.1. While Loops — CSAwesome v1 - Runestone Academy
    A while loop executes as long as a condition is true, repeating statements until the condition becomes false. The loop body is not executed if the condition is ...
  12. [12]
    [PDF] While Loops
    A while loop repeats actions until a condition is met. It checks a boolean expression, and if true, runs the loop body. The loop exits when the condition ...Missing: computer | Show results with:computer
  13. [13]
  14. [14]
    [PDF] Lecture Notes: Semantics of WHILE
    While loops work much like if statements. If the loop condition eval- uates to true, we replace the while loop with the loop body. However, because the loop ...
  15. [15]
    [PDF] IMP: a simple imperative language Lecture 5 Tuesday, February 5 ...
    Feb 5, 2024 · The small-step operational semantics suggest that the loop while b do c should be equivalent to the com- mand if b then (c; while b do c) else ...Missing: foundations | Show results with:foundations<|separator|>
  16. [16]
  17. [17]
    Semantics of the while statement
    When the condition is true, the loop body is exectued. · When the condition is false, the loop body is skipped, and the statment after the loop is executed.
  18. [18]
    [PDF] CS411 Notes 1: IMP and Large Step Operational Semantics
    Execution of a loop whose condition evaluates to true is equivalent to \un- rolling" the loop once { that is, executing the loop body c and then re-executing.<|control11|><|separator|>
  19. [19]
    [PDF] Semantics of while loop - Duke Computer Science
    The if statement and if/else statement allow a block of statements to be executed selectively: based on a guard/test if (area > 20.0).
  20. [20]
  21. [21]
    While Loop
    the variable i accidentally stays at the value 1 and the loop just goes forever.
  22. [22]
    [PDF] 1 A Denotational Semantics for IMP - Cornell: Computer Science
    3 Denotation for Loops. We can now write the correct denotation case for while loops as the fixed point of a higher-order function: C[[while b do c]] = fix(F).
  23. [23]
    [PDF] Chapter 11 AXIOMATIC SEMANTICS - University of Iowa
    This assertion captures the essence of the while loop: It must be true initially, it must be preserved after the loop body executes, and, combined with the exit ...
  24. [24]
  25. [25]
    4. More Control Flow Tools — Python 3.14.0 documentation
    In a for or while loop the break statement may be paired with an else clause. If the loop finishes without executing the break , the else clause executes. In a ...4. More Control Flow Tools · 4.3. The Range() Function · 4.5. Else Clauses On Loops
  26. [26]
  27. [27]
    Cognitive Strategies and Looping Constructs: An Empirical Study
    The study identified two looping strategies: READ/PROCESS (read and process on each pass) and PROCESS/READ (process and read on each pass).
  28. [28]
  29. [29]
  30. [30]
    while Statement (C) - Microsoft Learn
    Jan 25, 2023 · The while statement lets you repeat a statement until a specified expression becomes false. Syntax: iteration-statement: while ( expression ) statement.
  31. [31]
    while - JavaScript - MDN Web Docs - Mozilla
    Jul 8, 2025 · The while statement creates a loop that executes a specified statement as long as the test condition evaluates to true.
  32. [32]
    while - Manual - PHP
    while loops are the simplest type of loop in PHP. They behave just like their C counterparts. The basic form of a while statement is: while (expr) statement.
  33. [33]
    control_expressions - Documentation for Ruby 4.0
    The pattern matching syntax is described on its own page. while Loop¶ ↑. The while loop executes while a condition is true: a = 0 while a < 10 do p a a += 1 end ...
  34. [34]
    Bash Reference Manual
    Summary of each segment:
  35. [35]
    Data.List - Hackage - Haskell.org
    Lists are one of the most important data types as they are often used analogous to loops in imperative programming languages.<|separator|>
  36. [36]
    Beautiful functional programming - Page 3 - Haskell Discourse
    Aug 25, 2023 · Recursion is equivalent in power to while, and higher-order functions can be seen as replacements for for-loops. The advantage of higher ...
  37. [37]
    Functions - F#
    ### Summary on Loops and `while` in F#
  38. [38]
    Streamly.Prelude - Hackage
    This is a console echo program. It is an example of a declarative loop written using streaming combinators. Compare it with an imperative while loop. Hopefully, ...
  39. [39]
    Various ways to iterate in Prolog - SWISH
    Various ways to iterate in Prolog · Traditional top-down iteration · Traditional bottom-up, tail recursion using an accumulator · Difference List · Definite Clause ...
  40. [40]
    Six ways to iterate in Prolog - General
    Apr 2, 2019 · I worked through different ways to translate an input list into an output list, and to look at their efficiency using the time clause.
  41. [41]
    The Common Lisp Cookbook – Loop, iteration, mapping
    The keyword it , often used in functional constructs, can be recognized as a loop keyword. Don't use it inside a loop. (loop for i from 1 to 5 when (evenp i) ...Introduction: loop, iterate, for... · Iterate's for loop · Terminate the loop with a test...