Do while loop
View on WikipediaIt has been suggested that this article be merged with For loop and While loop to Loop (statement). (Discuss) Proposed since September 2025. |

| Loop constructs |
|---|
In computer programming, a do-while loop is a control flow statement that executes a block of code and then either repeats the block or exits the loop depending on a Boolean condition.
The do-while construct consists of a process symbol and a condition. First the code within the block is executed. Then the condition is evaluated. If the condition is true the code within the block is executed again. This repeats until the condition becomes false.
Do-while loops check the condition after the block of code is executed. This control structure can be known as a post-test loop. This means the do-while loop is an exit-condition loop. However a while loop will test the condition before the code within the block is executed.
This means that the code is always executed first and then the expression or test condition is evaluated. This process is repeated as long as the expression evaluates to true. If the expression is false the loop terminates. A while loop sets the truth of a statement as a necessary condition for the code's execution. A do-while loop provides for the action's ongoing execution until the condition is no longer true.
It is possible and sometimes desirable for the condition to always evaluate to be true. This creates an infinite loop. When an infinite loop is created intentionally there is usually another control structure that allows termination of the loop. For example, a break statement would allow termination of an infinite loop.
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. In contrast a "while" loop runs while the control expression is true and terminates once the expression becomes false.
Equivalent constructs
[edit]do {
do_work();
} while (condition);
is equivalent to
do_work();
while (condition) {
do_work();
}
In this manner, the do ... while loop saves the initial "loop priming" with do_work(); on the line before the while loop.
As long as the continue 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):
while (true) {
do_work();
if (!condition) {
break;
}
}
or
LOOPSTART:
do_work();
if (condition) goto LOOPSTART;
Examples
[edit]This section's factual accuracy is disputed. (November 2020) |
These example programs calculate the factorial of 5 using their respective languages' syntax for a do-while loop.
Ada
[edit]with Ada.Integer_Text_IO;
procedure Factorial is
Counter : Integer := 5;
Factorial : Integer := 1;
begin
loop
Factorial := Factorial * Counter;
Counter := Counter - 1;
exit when Counter = 0;
end loop;
Ada.Integer_Text_IO.Put (Factorial);
end Factorial;
BASIC
[edit]Early BASICs (such as GW-BASIC) used the syntax WHILE/WEND. Modern BASICs such as PowerBASIC provide both WHILE/WEND and DO/LOOP structures, with syntax such as DO WHILE/LOOP, DO UNTIL/LOOP, DO/LOOP WHILE, DO/LOOP UNTIL, and DO/LOOP (without outer testing, but with a conditional EXIT LOOP somewhere inside the loop). Typical BASIC source code:
Dim factorial As Integer
Dim counter As Integer
factorial = 1
counter = 5
Do
factorial = factorial * counter
counter = counter - 1
Loop While counter > 0
Print factorial
C, C++, D
[edit]The following function finds the first multiple of 7 greater than a given number.
int first_multiple_of_7(int n) {
do {
n += 1;
} while (n % 7 != 0);
return n;
}
Examples
printf("%d\n", first_multiple_of_7(10)); // 14
printf("%d\n", first_multiple_of_7(20)); // 21
printf("%d\n", first_multiple_of_7(28)); // 35
Do-while(0) statements are also commonly used in C macros as a way to wrap multiple statements into a regular (as opposed to compound) statement. It makes a semicolon needed after the macro, providing a more function-like appearance for simple parsers and programmers as well as avoiding the scoping problem with if. It is recommended in CERT C Coding Standard rule PRE10-C.[1]
Fortran
[edit]With legacy Fortran 77 there is no DO-WHILE construct but the same effect can be achieved with GOTO:
INTEGER CNT,FACT
CNT=5
FACT=1
1 CONTINUE
FACT=FACT*CNT
CNT=CNT-1
IF (CNT.GT.0) GOTO 1
PRINT*,FACT
END
Fortran 90 and later supports a DO-While construct:
program FactorialProg
integer :: counter = 5
integer :: factorial = 1
factorial = factorial * counter
counter = counter - 1
do while (counter /= 0)
factorial = factorial * counter
counter = counter - 1
end do
print *, factorial
end program FactorialProg
Java
[edit]int counter = 5;
int factorial = 1;
do {
factorial *= counter--; // Multiply, then decrement.
} while (counter > 0);
System.out.printf("The factorial of 5 is %d%n", factorial);
Kotlin
[edit]Source:[2]
var counter = 5
var factorial = 1
do {
factorial = factorial * counter
counter = counter - 1
} while (counter > 1)
println(factorial)
Pascal
[edit]Pascal uses repeat/until syntax instead of do-while.
factorial := 1;
counter := 5;
repeat
factorial := factorial * counter;
counter := counter - 1; // In Object Pascal one may use dec (counter);
until counter = 0;
PL/I
[edit]The PL/I DO statement subsumes the functions of the post-test loop (do-until), the pre-test loop (do-while), and the for loop. All functions can be included in a single statement. The example shows only the do-until syntax.
declare counter fixed initial(5);
declare factorial fixed initial(1);
do until(counter <= 0);
factorial = factorial * counter;
counter = counter - 1;
end;
put(factorial);
Python
[edit]Python does not have a DO-WHILE loop, but its effect can be achieved by an infinite loop with a breaking condition at the end.
The following function finds the first multiple of 7 greater than a given number.
def first_multiple_of_7(n):
while True:
n += 1
if n % 7 == 0:
break
return n
Examples
print(first_multiple_of_7(10)) # 14
print(first_multiple_of_7(20)) # 21
print(first_multiple_of_7(28)) # 35
Racket
[edit]In Racket, as in other Scheme implementations, a "named-let" is a popular way to implement loops:
#lang racket
(define counter 5)
(define factorial 1)
(let loop ()
(set! factorial (* factorial counter))
(set! counter (sub1 counter))
(when (> counter 0) (loop)))
(displayln factorial)
Compare this with the first example of the while loop example for Racket. Be aware that a named let can also take arguments.
Racket and Scheme also provide a proper do loop.
(define (factorial n)
(do ((counter n (- counter 1))
(result 1 (* result counter)))
((= counter 0) result) ; Stop condition and return value.
; The body of the do-loop is empty.
))
Smalltalk
[edit]| counter factorial |
counter := 5.
factorial := 1.
[counter > 0] whileTrue:
[factorial := factorial * counter.
counter := counter - 1].
Transcript show: factorial printString
See also
[edit]References
[edit]- ^ "C multi-line macro: do/while(0) vs scope block". Stack Overflow.
- ^ "Conditions and loops | Kotlin". Kotlin Help. Retrieved 21 October 2025.
External links
[edit]Do while loop
View on Grokipediado {
// loop body statements
} while (condition);
This form is also used in Java, JavaScript, and other derivatives, where the condition is a boolean expression evaluated after each iteration.[2][5] In contrast, languages like Python lack native do-while support and require emulation using while loops with additional logic.[6]
Do-while loops are commonly applied in iterative algorithms, menu-driven programs, and validation routines where the termination criterion depends on data generated or modified inside the loop itself.[7] Their design promotes cleaner code for bottom-tested conditions, reducing the need for separate initialization steps outside the loop, though overuse can lead to infinite loops if the condition lacks proper update mechanisms.[8]
Fundamentals
Definition and Purpose
A do while loop is a post-test control structure in programming that executes its body at least once before evaluating a condition (typically a boolean or equivalent expression) to determine whether to continue iterating.[3] This design distinguishes it from pre-test loops like the while loop, where the condition is checked prior to any execution.[5] The loop's body, which may consist of one or more statements, runs iteratively as long as the condition evaluates to true (or equivalent) after each iteration.[9] The primary purpose of a do while loop is to ensure that the loop body executes initially regardless of the condition's initial state, making it ideal for scenarios where an action must occur at least once.[3] For instance, it is commonly used in input validation, where a program prompts the user for data and re-prompts only if the input is invalid, guaranteeing the initial prompt appears.[9] Similarly, in menu-driven programs, it allows the menu to display and process user choices repeatedly until an exit option is selected.[10] Key characteristics include its reliance on an expression for the test condition, which must evaluate to true (or equivalent) for continuation and false to exit, and the flexibility of the body to encompass multiple statements for complex operations.[5] This structure promotes reliable iteration in situations where the condition depends on results generated within the loop itself.[3]Execution Flow
The execution flow of a do-while loop commences with the unconditional execution of the loop body, ensuring that the statements within it are performed at least once regardless of the initial state of the condition.[2] Upon completion of the body, the loop's condition—an expression that determines whether to continue (evaluating to true or equivalent)—is checked.[11] If the condition evaluates to true (or equivalent), control transfers back to the start of the loop, and the body executes again, repeating this cycle.[12] Conversely, if the condition is false, the loop terminates, and program execution continues with the statement immediately following the loop construct.[11] This post-test structure distinguishes the do-while loop from pre-test variants, as the condition evaluation occurs after the initial body execution, thereby guaranteeing one iteration even if the condition is initially false.[2][12] An infinite loop may arise if the condition perpetually evaluates to true due to unaltered variables or logical errors in the body, leading to continuous execution until external intervention, such as a break statement, halts it.[11] Conceptually, the flow can be represented as a flowchart: entry leads directly to the loop body execution, followed by a decision node for the condition; a "true" branch loops back to the body, while a "false" branch exits to subsequent code.[12][11]Comparisons to Other Loops
Versus While Loop
The primary distinction between a do-while loop and a while loop lies in the timing of the condition evaluation: a while loop tests its condition before executing the loop body, potentially resulting in zero iterations if the condition is initially false, whereas a do-while loop executes the body at least once before testing the condition at the end.[2][13] This post-test mechanism in do-while ensures the loop body runs unconditionally on the first iteration, making it suitable for scenarios where an initial execution is mandatory, such as prompting user input or performing setup actions that must occur regardless of the outcome.[14][15] In contrast, the while loop's pre-test approach is ideal for cases where entry into the loop depends strictly on the condition being true from the start, avoiding unnecessary computations when the loop might not be needed at all.[9] To illustrate this difference, consider pseudocode for a simple scenario where a value is read and checked against a threshold; if the initial value fails the check, the while loop skips the body entirely, while the do-while loop processes it once before deciding to continue or exit. While Loop Pseudocode:while (condition) {
// Loop body: perform actions
}
Do-While Loop Pseudocode:
do {
// Loop body: perform actions
} while (condition);
In the while example, if condition is false at the outset (e.g., input < threshold), no actions occur; in the do-while, the body executes once even if condition is false initially, then terminates.[16][13]
A common pitfall arises when developers mistakenly use a while loop in situations requiring at least one execution, leading to the loop body being skipped unexpectedly and causing logical errors, such as unprompted user input or uninitialized variables remaining unset.[14][17] To avoid this, programmers should select do-while when the loop's purpose demands an initial run, ensuring reliability in control flow.[9]
Versus Repeat-Until Loop
The do-while loop and the repeat-until loop share a fundamental similarity as post-test control structures, both ensuring that the loop body executes at least once before the termination condition is evaluated.[18] This design distinguishes them from pre-test loops like the while construct, where execution may be skipped entirely if the initial condition fails.[9] In both cases, the condition check occurs after the body, allowing scenarios where an action must occur regardless of the outcome, such as prompting user input or initializing a process. The primary difference between the two lies in their condition logic. A do-while loop repeats the body while the specified condition remains true, terminating only when it becomes false.[9] In contrast, a repeat-until loop repeats the body until the condition becomes true, which inherently employs the logical negation of a do-while's continuation criterion.[18] This inverted semantics means that the repeat-until form explicitly states the stopping condition, while do-while emphasizes the persistence condition. Despite the difference in phrasing, the constructs are logically equivalent when the repeat-until condition is the negation of the do-while condition.[18] For instance, the following pseudocode demonstrates the transformation:do {
// Perform some action
x = computeValue();
} while (x < 10);
is equivalent to:
repeat
// Perform some action
x = computeValue();
until (x >= 10);
Here, the negation (x >= 10 is not (x < 10)) preserves identical behavior, with the loop terminating after the first iteration if the condition holds initially.[18]
The repeat-until construct originated in the Pascal programming language, developed by Niklaus Wirth and formally defined in his 1975 revised report, where it serves as a post-test iteration mechanism.[19] Conversely, the do-while loop was introduced in the C programming language, as detailed in the 1978 book by Brian Kernighan and Dennis Ritchie, becoming a staple in C-family languages like C++ and Java.[20] This historical divergence reflects language design philosophies: Pascal's emphasis on clarity in termination, versus C's alignment with while-loop conventions.[18]
General Syntax and Variations
Pseudocode Representation
The do-while loop in pseudocode provides a language-independent way to express a control structure that executes its body at least once before evaluating a termination condition. The standard representation begins with a "DO" keyword to initiate the loop, followed by the body of statements, and concludes with "WHILE" followed by the condition in parentheses, often terminated by a semicolon or an "ENDDO"/"END WHILE" for clarity.[21][22] This structure ensures the body runs unconditionally on the first iteration, distinguishing it from top-tested loops.[23]DO
// One or more statements forming the loop body
WHILE (condition);
In this template, the body can consist of multiple statements, which are typically indented to denote their scope within the loop, allowing for sequential execution of operations like assignments, inputs, or computations.[21][24] Semicolons after statements or the entire construct are optional in pseudocode, as the notation prioritizes readability over strict syntax.[25]
The condition following "WHILE" is a boolean expression that determines whether to repeat the body; it evaluates to true to continue the loop or false to exit. Common types include simple boolean variables (e.g., moreRecordsExist), relational comparisons (e.g., x > 1), equality checks (e.g., userInput == "y"), or calls to functions returning a boolean value.[22][23] Complex conditions can incorporate logical operators such as AND or OR for multifaceted tests.[21]
Edge cases in pseudocode include an empty body, represented minimally as DO WHILE (condition);, which executes no operations but still evaluates the condition after the initial (empty) iteration—though such constructs are rare and often avoided for clarity. Another consideration is overly complex conditions that might lead to infinite loops if not properly mutable within the body, emphasizing the need for the condition to eventually falsify through body actions like counters or inputs.[23][24]
Common Keywords and Structure
The do-while loop commonly employs the keywords "do" to initiate the loop body and "while" to specify the continuation condition, ensuring the body executes at least once before the condition is evaluated.[26] In some variants, additional keywords such as "loop" or "end while" may delimit the structure, particularly in languages influenced by BASIC paradigms, though "do" and "while" remain the predominant pair in imperative contexts.[26] Structurally, the loop consists of a body block containing one or more statements, often enclosed by braces{} in C-style syntax or equivalent delimiters, followed by the "while" clause with the condition and typically terminated by a semicolon.[26] This arrangement guarantees initial execution regardless of the condition's initial value, distinguishing it from pre-test loops. As a base template, this aligns with pseudocode representations that abstract the flow without language-specific details.[26]
In imperative programming paradigms, do-while loops are natively supported as a core control structure for sequential, mutable execution.[26] Conversely, functional paradigms exhibit limited support, favoring recursion or higher-order functions over explicit loops to maintain immutability and avoid side effects.[27]
Do-while loops integrate with modification statements like "break" for immediate exit from the loop and "continue" to skip the remaining body and re-evaluate the condition for the next iteration.[26] These elements enhance control flow flexibility within the loop's post-test structure.[26]
Implementations in Programming Languages
C, C++, Java, and Similar
In languages such as C, C++, and Java, the do-while loop provides an exit-controlled iteration mechanism where the loop body executes at least once before the controlling condition is evaluated. The syntax follows the formdo { statement(s); } while (expression);, where the semicolon after the while clause is mandatory to terminate the statement properly.[2] This structure ensures the body—enclosed in curly braces for compound statements—is performed unconditionally first, after which the expression (which must evaluate to a boolean or convertible value) determines if the loop repeats. Compilation in these languages treats the do-while as a single statement, integrating seamlessly with block scoping rules from the respective standards (ISO/IEC 9899 for C, ISO/IEC 14882 for C++, and the Java Language Specification).
A simple example in C demonstrates a counter that prints values from 1 to 5:
#include <stdio.h>
int main() {
int i = 1;
do {
[printf](/page/Printf)("%d\n", i);
i++;
} while (i <= 5);
return 0;
}
This executes the body five times, as the condition i <= 5 is checked post-increment. In C++, the loop can incorporate input validation using std::cin, ensuring user input meets criteria before proceeding; for instance:
#include <iostream>
int main() {
int value;
do {
std::cout << "Enter a positive number: ";
std::cin >> value;
} while (value <= 0);
std::cout << "Valid input: " << value << std::endl;
return 0;
}
Here, the prompt and input occur at least once, looping until a positive integer is provided, handling potential std::cin failures via additional checks in practice. Java employs identical syntax, as in a menu-driven program that repeats until the user selects exit:
import java.util.Scanner;
public class Menu {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int choice;
do {
System.out.println("1. Option A\n2. Option B\n3. Exit");
choice = scanner.nextInt();
switch (choice) {
case 1: System.out.println("Executing A"); break;
case 2: System.out.println("Executing B"); break;
}
} while (choice != 3);
scanner.close();
}
}
The loop guarantees one menu display regardless of initial input.[2]
Variables declared within the do-while body adhere to block scope, limiting visibility to that enclosed block and excluding the while condition clause, which may require external declarations for condition-dependent variables.[28] This behavior aligns with C and C++ scoping rules, promoting encapsulation but necessitating careful placement for loop control variables. In Java, the scope is similarly confined to the body, with no access from the condition. The D programming language, syntactically akin to C++, supports a compatible form: do ScopeStatement while (Expression);, inheriting these scoping and termination behaviors from its C-family roots.[29]
A frequent compilation error arises from omitting the semicolon after the while clause, resulting in syntax errors as the parser interprets subsequent code as part of the unfinished statement, often manifesting as "expected ';' before..." diagnostics.[30] At runtime, these languages evaluate the condition efficiently post-body execution, with no inherent overhead beyond standard branching, though infinite loops can occur if the expression perpetually yields true—mitigated by break or continue statements.
Python and Scripting Languages
In Python, there is no native do-while loop construct, unlike some other languages that support post-test iteration directly. Instead, developers emulate do-while behavior using awhile True loop combined with a conditional break statement to exit after the first execution if the condition fails. This approach ensures the loop body runs at least once before checking the condition, mimicking the do-while semantics. For instance, consider a loop for validating user input where the body prompts and reads input initially, then breaks if valid:
user_input = input("Enter a positive number: ")
while True:
try:
value = int(user_input)
if value > 0:
break
except ValueError:
pass
user_input = input("Enter a positive number: ")
print(f"You entered: {value}")
This emulation is a standard idiom in Python, as documented in the official language reference.[31]
Scripting languages like JavaScript provide native support for do-while loops, allowing the body to execute at least once before evaluating the condition. The syntax is do { statements } while (condition);, which is useful for tasks requiring initial execution, such as menu-driven interfaces. In Ruby, a similar effect is achieved using loop do ... end with an internal conditional break, or more directly with the begin ... end while condition construct, which evaluates the condition after the block. These variations in scripting environments highlight adaptations for dynamic, interpreted execution models.
The emulation in Python introduces additional logic with the break statement, which can slightly increase code complexity compared to native do-while in languages like JavaScript, potentially affecting readability in simple cases. However, this method aligns with Python's emphasis on explicit control flow and is preferred over workarounds like function wrappers for its simplicity.
Other Languages
In the BASIC family of languages, such as Visual Basic, the do-while loop is realized through a post-test structure usingDo followed by statements and Loop While with the condition, ensuring the body executes at least once before the condition is evaluated at the end. This syntax allows repetition as long as the condition remains true. For instance:
Dim counter As [Integer](/page/Integer) = 0
Do
Console.WriteLine(counter)
counter += 1
Loop While counter < 5
This outputs values from 0 to 4, demonstrating the loop's execution until the condition fails.[32]
Fortran lacks a native post-test do-while construct in its early standards like Fortran 77, but an equivalent is achieved using a labeled DO loop combined with an IF statement and GOTO to simulate the post-evaluation check, often in fixed-form source code where statements align in specific columns (e.g., columns 7-72 for code). The structure involves initiating the loop, performing the body, and branching back if the condition holds. A representative example in fixed-form syntax is:
INTEGER I
I = 1
10 PRINT *, I
I = I + 1
IF (I .LE. 5) GOTO 10
This prints integers 1 through 5, with the condition checked after each iteration.[33]
Pascal provides no direct do-while loop but employs the repeat...until construct as a post-test equivalent, where the body executes at least once and repeats until the specified condition becomes true, effectively mirroring a do-while by negating the continuation condition. The syntax is repeat followed by statements and until condition;. An example is:
var
i: integer;
begin
i := 1;
repeat
writeln(i);
i := i + 1;
until i > 5;
end.
This outputs 1 to 5, halting when the condition i > 5 is true.[34]
In Ada, a do-while equivalent is implemented using an unlabeled loop...end loop with an exit when statement inside the body to check the condition after execution, ensuring at least one iteration occurs before potential exit. The syntax places the body statements before exit when condition;, where the condition triggers termination (thus, for do-while behavior, use exit when not continuation_condition). A simple example is:
declare
I : Integer := 1;
begin
loop
Put_Line (Integer'Image (I));
I := I + 1;
exit when I > 5;
end loop;
end;
This prints 1 to 5, exiting after the condition I > 5 holds.[35]
PL/I supports versatile DO groups that can emulate a post-test do-while through a conditional DO...END with an internal IF and LEAVE statement to check the condition at the end of the group, allowing the body to run initially without prior testing. The basic structure is DO; statements; IF (condition) THEN LEAVE; END;, where LEAVE exits the group. An example is:
DCL I FIXED BIN(31) INIT(1);
DO;
PUT SKIP LIST('I =', I);
I = I + 1;
IF (I > 5) THEN LEAVE;
END;
This outputs I = 1 to I = 5, continuing until the condition triggers leave.[36]
Smalltalk, being object-oriented and block-based, has no built-in do-while but emulates it by defining a block that performs the body actions and returns a boolean condition, then invoking whileTrue on that block to repeat as long as it evaluates to true, with the condition assessed post-body within the block itself. The syntax involves a block literal [body; ^condition] sent the whileTrue message. For example:
| n |
n := 1.
[ n := n * 2. n < 100 ] whileTrue
This doubles n starting from 1 (yielding 2, 4, 8, ..., 64) and stops after 64 since 128 >= 100, executing the body at least once.[37]