Do while loop

Last updated
Do While loop flow diagram Do-while-loop-diagram.svg
Do While loop flow diagram

In many computer programming languages, 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 given boolean condition.

Contents

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

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

Demonstrating do while loops

These example programs calculate the factorial of 5 using their respective languages' syntax for a do-while loop.

Ada

withAda.Integer_Text_IO;procedureFactorialisCounter:Integer:=5;Factorial:Integer:=1;beginloopFactorial:=Factorial*Counter;Counter:=Counter-1;exitwhenCounter=0;endloop;Ada.Integer_Text_IO.Put(Factorial);endFactorial;

BASIC

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:

DimfactorialAsIntegerDimcounterAsIntegerfactorial=1counter=5Dofactorial=factorial*countercounter=counter-1LoopWhilecounter>0Printfactorial

C, C++, D

intcounter=5;intfactorial=1;do{factorial*=counter--;/* Multiply, then decrement. */}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 if. It is recommended in CERT C Coding Standard rule PRE10-C. [1]

Fortran

With legacy Fortran 77 there is no DO-WHILE construct but the same effect can be achieved with GOTO:

INTEGER CNT,FACTCNT=5FACT=11CONTINUEFACT=FACT*CNTCNT=CNT-1IF(CNT.GT.0)GOTO1PRINT*,FACTEND

Fortran 90 and later does not have a do-while construct either, but it does have a while loop construct which uses the keywords "do while" and is thus actually the same as the for loop. [2]

program FactorialProginteger::counter=5integer::factorial=1factorial=factorial*countercounter=counter-1do while(counter>0)! Truth value is tested before the loopfactorial=factorial*countercounter=counter-1end do    print*,factorialend program FactorialProg

Java

intcounter=5;intfactorial=1;do{factorial*=counter--;/* Multiply, then decrement. */}while(counter>0);System.out.println("The factorial of 5 is "+factorial);

Pascal

Pascal uses repeat/until syntax instead of do while.

factorial:=1;counter:=5;repeatfactorial:=factorial*counter;counter:=counter-1;// In Object Pascal one may use dec (counter);untilcounter=0;

PL/I

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.

declarecounterfixedinitial(5); declarefactorialfixedinitial(1);dountil(counter<=0);factorial=factorial*counter;counter=counter-1;end;  put(factorial);

Racket

In Racket, as in other Scheme implementations, a "named-let" is a popular way to implement loops:

#lang racket(definecounter5)(definefactorial1)(letloop()(set!factorial(*factorialcounter))(set!counter(sub1counter))(when(>counter0)(loop)))(displaylnfactorial)

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(factorialn)(do((countern(-counter1))(result1(*resultcounter)))((=counter0)result); Stop condition and return value.; The body of the do-loop is empty.))

Smalltalk

| counter factorial |counter:=5.factorial:=1.  [counter>0] whileTrue:     [factorial:=factorial*counter.counter:=counter-1].Transcriptshow:factorialprintString

See also

Related Research Articles

In computer science, control flow 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 imperative programming language from a declarative programming language.

Template metaprogramming (TMP) is a metaprogramming technique in which templates are used by a compiler to generate temporary source code, which is merged by the compiler with the rest of the source code and then compiled. The output of these templates can include compile-time constants, data structures, and complete functions. The use of templates can be thought of as compile-time polymorphism. The technique is used by a number of languages, the best-known being C++, but also Curl, D, Nim, and XL.

<span class="mw-page-title-main">F Sharp (programming language)</span> Microsoft programming language

F# is a general-purpose, strongly typed, multi-paradigm programming language that encompasses functional, imperative, and object-oriented programming methods. It is most often used as a cross-platform Common Language Infrastructure (CLI) language on .NET, but can also generate JavaScript and graphics processing unit (GPU) code.

<span class="mw-page-title-main">Conditional (computer programming)</span> Control flow statement that executes code according to some condition(s)

In computer science, conditionals are programming language commands for handling decisions. Specifically, conditionals perform different computations or actions depending on whether a programmer-defined Boolean condition evaluates to true or false. In terms of control flow, the decision is always achieved by selectively altering the control flow based on some condition . Although dynamic dispatch is not usually classified as a conditional construct, it is another way to select between alternatives at runtime. Conditional statements are the checkpoints in the programme that determines behaviour according to situation.

<span class="mw-page-title-main">While loop</span> Control flow statement for repeating execution until a condition is met

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.

<span class="mw-page-title-main">For loop</span> Control flow statement for repeated execution

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.

In computer science, a generator is a routine that can be used to control the iteration behaviour of a loop. All generators are also iterators. A generator is very similar to a function that returns an array, in that a generator has parameters, can be called, and generates a sequence of values. However, instead of building an array containing all the values and returning them all at once, a generator yields the values one at a time, which requires less memory and allows the caller to get started processing the first few values immediately. In short, a generator looks like a function but behaves like an iterator.

<span class="mw-page-title-main">Foreach loop</span> Control flow statement for traversing items in a collection

In computer programming, foreach loop is a control flow statement for traversing items in a collection. foreach is usually used in place of a standard for loop statement. Unlike other for loop constructs, however, foreach loops usually maintain no explicit counter: they essentially say "do this to everything in this set", rather than "do this x times". This avoids potential off-by-one errors and makes code simpler to read. In object-oriented languages, an iterator, even if implicit, is often used as the means of traversal.

In computer programming, the ternary conditional operator is a ternary operator that is part of the syntax for basic conditional expressions in several programming languages. It is commonly referred to as the conditional operator, ternary if, or inline if. An expression a ? b : c evaluates to b if the value of a is true, and otherwise to c. One can read it aloud as "if a then b otherwise c". The form a ? b : c is by far and large the most common, but alternative syntaxes do exist; for example, Raku uses the syntax a ?? b !! c to avoid confusion with the infix operators ? and !, whereas in Visual Basic .NET, it instead takes the form If(a, b, c).

The basic control structures of Perl are similar to those used in C and Java, but they have been extended in several ways.

<span class="mw-page-title-main">JavaScript syntax</span> Set of rules defining correctly structured programs

The syntax of JavaScript is the set of rules that define a correctly structured JavaScript program.

<span class="mw-page-title-main">Recursion (computer science)</span> Use of functions that call themselves

In computer science, recursion is a method of solving a computational problem where the solution depends on solutions to smaller instances of the same problem. Recursion solves such recursive problems by using functions that call themselves from within their own code. The approach can be applied to many types of problems, and recursion is one of the central ideas of computer science.

The power of recursion evidently lies in the possibility of defining an infinite set of objects by a finite statement. In the same manner, an infinite number of computations can be described by a finite recursive program, even if this program contains no explicit repetitions.

S-algol is a computer programming language derivative of ALGOL 60 developed at the University of St Andrews in 1979 by Ron Morrison and Tony Davie. The language is a modification of ALGOL to contain orthogonal data types that Morrison created for his PhD thesis. Morrison would go on to become professor at the university and head of the department of computer science. The S-algol language was used for teaching at the university at an undergraduate level until 1999. It was also the language taught for several years in the 1980s at a local school in St. Andrews, Madras College. The computer science text Recursive Descent Compiling describes a recursive descent compiler for S-algol, implemented in S-algol.

In computer programming, an anonymous function is a function definition that is not bound to an identifier. Anonymous functions are often arguments being passed to higher-order functions or used for constructing the result of a higher-order function that needs to return a function. If the function is only used once, or a limited number of times, an anonymous function may be syntactically lighter than using a named function. Anonymous functions are ubiquitous in functional programming languages and other languages with first-class functions, where they fulfil the same role for the function type as literals do for other data types.

In computing, compile-time function execution is the ability of a compiler, that would normally compile a function to machine code and execute it at run time, to execute the function at compile time. This is possible if the arguments to the function are known at compile time, and the function does not make any reference to or attempt to modify any global state.

In the C and C++ programming languages, the comma operator is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value ; there is a sequence point between these evaluations.

The syntax and semantics of PHP, a programming language, form a set of rules that define how a PHP program can be written and interpreted.

Nemerle is a general-purpose, high-level, statically typed programming language designed for platforms using the Common Language Infrastructure (.NET/Mono). It offers functional, object-oriented, aspect-oriented, reflective and imperative features. It has a simple C#-like syntax and a powerful metaprogramming system.

<span class="mw-page-title-main">Nim (programming language)</span> Programming language

Nim is a general-purpose, multi-paradigm, statically typed, compiled high-level systems programming language, designed and developed by a team around Andreas Rumpf. Nim is designed to be "efficient, expressive, and elegant", supporting metaprogramming, functional, message passing, procedural, and object-oriented programming styles by providing several features such as compile time code generation, algebraic data types, a foreign function interface (FFI) with C, C++, Objective-C, and JavaScript, and supporting compiling to those same languages as intermediate representations.

References

  1. "C multi-line macro: do/while(0) vs scope block". Stack Overflow.
  2. "Microsoft visual basic". msdn.microsoft.com. Retrieved 21 January 2016.