Do While Loop
   HOME

TheInfoList



OR:

In most
computer programming Computer programming is the process of performing a particular computation (or more generally, accomplishing a specific computing result), usually by designing and building an executable computer program. Programming involves tasks such as ana ...
languages a do while loop is a
control flow In computer science, control flow (or flow of control) is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. The emphasis on explicit control flow distinguishes an ''imper ...
statement that executes a block of code and then either repeats the block or exits the loop depending on a given 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 True most commonly refers to truth, the state of being in congruence with fact or reality. True may also refer to: Places * True, West Virginia, an unincorporated community in the United States * True, Wisconsin, a town in the United States * ...
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 In most computer programming languages, a while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The ''while'' loop can be thought of as a repeating if statement. Overview The ' ...
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 In computer programming, an infinite loop (or endless loop) is a sequence of instructions that, as written, will continue endlessly, unless an external intervention occurs ("pull the plug"). It may be intentional. Overview This differs from: * ...
. When an infinite loop is created intentionally there is usually another control structure that allows termination of the loop. For example a
break statement In computer science, control flow (or flow of control) is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. The emphasis on explicit control flow distinguishes an ''imper ...
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 Lua or LUA may refer to: Science and technology * Lua (programming language) * Latvia University of Agriculture * Last universal ancestor, in evolution Ethnicity and language * Lua people, of Laos * Lawa people, of Thailand sometimes referred t ...
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

do while (condition); is equivalent to do_work(); while (condition) 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) or LOOPSTART: do_work(); if (condition) goto LOOPSTART;


Demonstrating do while loops

These example programs calculate the
factorial In mathematics, the factorial of a non-negative denoted is the product of all positive integers less than or equal The factorial also equals the product of n with the next smaller factorial: \begin n! &= n \times (n-1) \times (n-2) \t ...
of 5 using their respective languages' syntax for a do-while loop.


ActionScript 3 ActionScript is an object-oriented programming language originally developed by Macromedia Inc. (later acquired by Adobe). It is influenced by HyperTalk, the scripting language for HyperCard. It is now an implementation of ECMAScript (meaning ...

var counter: int = 5; var factorial: int = 1; do while (counter > 0); trace(factorial);


Ada Ada may refer to: Places Africa * Ada Foah, a town in Ghana * Ada (Ghana parliament constituency) * Ada, Osun, a town in Nigeria Asia * Ada, Urmia, a village in West Azerbaijan Province, Iran * Ada, Karaman, a village in Karaman Province, ...

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 BASIC (Beginners' All-purpose Symbolic Instruction Code) is a family of general-purpose, high-level programming languages designed for ease of use. The original version was created by John G. Kemeny and Thomas E. Kurtz at Dartmouth College ...

Early BASICs (such as
GW-BASIC GW-BASIC is a dialect of the BASIC programming language developed by Microsoft from IBM BASICA. Functionally identical to BASICA, its BASIC interpreter is a fully self-contained executable and does not need the Cassette BASIC ROM found in the or ...
) used the syntax WHILE/WEND. Modern BASICs such as
PowerBASIC PowerBASIC, formerly Turbo Basic, is the brand of several commercial compilers by PowerBASIC Inc. that compile a dialect of the BASIC programming language. There are both MS-DOS and Windows versions, and two kinds of the latter: Console and Wind ...
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#

int counter = 5; int factorial = 1; do while (counter > 0); System.Console.WriteLine(factorial);


C

int counter = 5; int factorial = 1; do while (counter > 0); printf("factorial of 5 is %d\n", factorial); 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 . It is recommended in
CERT C Coding Standard The SEI CERT Coding Standards are software coding standards developed by the CERT Coordination Center to improve the safety, reliability, and security of software systems. Individual standards are offered for C, C++, Java, Android OS, and Perl. G ...
rule PRE10-C.


C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...

int counter = 5; int factorial = 1; do while (counter > 0); std::cout << "factorial of 5 is "<< factorial << std::endl;


CFScript CFScript is an extension of CFML on the ColdFusion platform. CFScript resembles JavaScript. Some ColdFusion developers prefer it since it has less visual and typographical overhead than ordinary CFML. Usage Unless it's within a pure script-bas ...

factorial = 1; count = 10; do while (count > 1); writeOutput(factorial);


D

int counter = 5; int factorial = 1; do while (counter > 0); writeln("factorial of 5 is ", factorial);


Fortran

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 does not have a do-while construct either, but it does have a
while loop In most computer programming languages, a while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The ''while'' loop can be thought of as a repeating if statement. Overview The ' ...
construct which uses the keywords "do while" and is thus actually the same as the
for loop In computer science a for-loop or for loop is a control flow statement for specifying iteration. Specifically, a for loop functions by running a section of code repeatedly until a certain condition has been satisfied. For-loops have two par ...
. program FactorialProg integer :: counter = 5 integer :: factorial = 1 factorial = factorial * counter counter = counter - 1 do while (counter > 0) ! Truth value is tested before the loop factorial = factorial * counter counter = counter - 1 end do print *, factorial end program FactorialProg


Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...

int counter = 5; int factorial = 1; do while (counter > 0); System.out.println("The factorial of 5 is " + factorial); //

// // The below function does the same as above. // //

// int counter = 5; int factorial = 1; while (counter > 0) System.out.println("The factorial of 5 is " + factorial);


JavaScript JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of Website, websites use JavaScript on the Client (computing), client side ...

let counter = 5; // Declaring two variables, counter and factorial let factorial = 1; do while (counter > 0); //The looping conditions console.log(factorial); //Showing the result


Kotlin

var counter = 5 var factorial = 1 //These line of code is almost the same as the above JavaScript codes, the only difference is the keyword that shows the results do while (counter > 0) println("Factorial of 5 is $factorial")


Pascal

Pascal does not have a do/while; instead, it has a repeat/until. As mentioned in the introduction, one can consider a repeat/until to be equivalent to a 'do code while not expression' construct. factorial := 1; counter := 5; repeat factorial := factorial * counter; counter := counter - 1; // In Object Pascal one may use dec (counter); until counter = 0;


PHP PHP is a general-purpose scripting language geared toward web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementation is now produced by The PHP Group. ...

$counter = 5; $factorial = 1; do while ($counter > 0); echo $factorial;


PL/I PL/I (Programming Language One, pronounced and sometimes written PL/1) is a procedural, imperative computer programming language developed and published by IBM. It is designed for scientific, engineering, business and system programming. I ...

The
PL/I PL/I (Programming Language One, pronounced and sometimes written PL/1) is a procedural, imperative computer programming language developed and published by IBM. It is designed for scientific, engineering, business and system programming. I ...
DO statement subsumes the functions of the post-test loop (''do until''), the pre-test loop (''do while''), and the
for loop In computer science a for-loop or for loop is a control flow statement for specifying iteration. Specifically, a for loop functions by running a section of code repeatedly until a certain condition has been satisfied. For-loops have two par ...
. 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 Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...

Python lacks a specific do while flow control construct. However, the equivalent may be constructed out of a while loop with a break. counter = 5 factorial = 1 while True: factorial *= counter counter -= 1 if counter

0: break print(factorial)


Racket

In Racket, as in other
Scheme A scheme is a systematic plan for the implementation of a certain idea. Scheme or schemer may refer to: Arts and entertainment * ''The Scheme'' (TV series), a BBC Scotland documentary series * The Scheme (band), an English pop band * ''The Schem ...
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 In most computer programming languages, a while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The ''while'' loop can be thought of as a repeating if statement. Overview The ' ...
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. ))


Ruby A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sa ...

counter = 10 factorial = 2 begin factorial *= counter counter -= 2 end while counter > 1 puts factorial


Smalltalk Smalltalk is an object-oriented, dynamically typed reflective programming language. It was designed and created in part for educational use, specifically for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by Alan Ka ...

, counter factorial , counter := 5. factorial := 1. ounter > 0whileTrue: actorial := factorial * counter. counter := counter - 1 Transcript show: factorial printString


Swift Swift or SWIFT most commonly refers to: * SWIFT, an international organization facilitating transactions between banks ** SWIFT code * Swift (programming language) * Swift (bird), a family of birds It may also refer to: Organizations * SWIFT, ...

Swift 2.x and later: var counter = 5 var factorial = 1 repeat while counter > 0 print(factorial) Swift 1.x: var counter = 5 var factorial = 1 do while counter > 0 println(factorial)


Visual Basic .NET Visual Basic, originally called Visual Basic .NET (VB.NET), is a multi-paradigm, object-oriented programming language, implemented on .NET, Mono, and the .NET Framework. Microsoft launched VB.NET in 2002 as the successor to its original Visua ...

Dim counter As Integer = 5 Dim factorial As Integer = 1 Do factorial *= counter counter -= 1 Loop While counter > 0 Console.WriteLine(factorial)


See also

*
Control flow In computer science, control flow (or flow of control) is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. The emphasis on explicit control flow distinguishes an ''imper ...
*
For loop In computer science a for-loop or for loop is a control flow statement for specifying iteration. Specifically, a for loop functions by running a section of code repeatedly until a certain condition has been satisfied. For-loops have two par ...
*
Foreach In computer programming, foreach loop (or for each loop) is a control flow statement for traversing items in a collection. is usually used in place of a standard loop statement. Unlike other loop constructs, however, loops usually maintai ...
* Repeat loop (disambiguation) *
While loop In most computer programming languages, a while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The ''while'' loop can be thought of as a repeating if statement. Overview The ' ...


References


External links


do while (0) in C macros
{{DEFAULTSORT:Do While Loop Control flow Articles with example Ada code Articles with example C code Articles with example Fortran code Articles with example Pascal code Articles with example Racket code Articles with example Python (programming language) code de:Schleife (Programmierung)#Do-While-Schleife